diff --git a/.github/ci-task-matrix.json b/.github/ci-task-matrix.json index 7432f4adaed..067ab518009 100644 --- a/.github/ci-task-matrix.json +++ b/.github/ci-task-matrix.json @@ -7,107 +7,177 @@ "general_tests": [ { "group": "general-server-without-chat", - "group_label": "server (1/12)", + "group_label": "server (1/20)", "shard_index": 0, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (2/12)", + "group_label": "server (2/20)", "shard_index": 1, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (3/12)", + "group_label": "server (3/20)", "shard_index": 2, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (4/12)", + "group_label": "server (4/20)", "shard_index": 3, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (5/12)", + "group_label": "server (5/20)", "shard_index": 4, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (6/12)", + "group_label": "server (6/20)", "shard_index": 5, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (7/12)", + "group_label": "server (7/20)", "shard_index": 6, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (8/12)", + "group_label": "server (8/20)", "shard_index": 7, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (9/12)", + "group_label": "server (9/20)", "shard_index": 8, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (10/12)", + "group_label": "server (10/20)", "shard_index": 9, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (11/12)", + "group_label": "server (11/20)", "shard_index": 10, - "shard_count": 12, + "shard_count": 20, "task": "ci:server" }, { "group": "general-server-without-chat", - "group_label": "server (12/12)", + "group_label": "server (12/20)", "shard_index": 11, - "shard_count": 12, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (13/20)", + "shard_index": 12, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (14/20)", + "shard_index": 13, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (15/20)", + "shard_index": 14, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (16/20)", + "shard_index": 15, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (17/20)", + "shard_index": 16, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (18/20)", + "shard_index": 17, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (19/20)", + "shard_index": 18, + "shard_count": 20, + "task": "ci:server" + }, + { + "group": "general-server-without-chat", + "group_label": "server (20/20)", + "shard_index": 19, + "shard_count": 20, "task": "ci:server" }, { "group": "general-chat", - "group_label": "chat (1/3)", + "group_label": "chat (1/5)", "shard_index": 0, - "shard_count": 3, + "shard_count": 5, "task": "ci:chat" }, { "group": "general-chat", - "group_label": "chat (2/3)", + "group_label": "chat (2/5)", "shard_index": 1, - "shard_count": 3, + "shard_count": 5, "task": "ci:chat" }, { "group": "general-chat", - "group_label": "chat (3/3)", + "group_label": "chat (3/5)", "shard_index": 2, - "shard_count": 3, + "shard_count": 5, + "task": "ci:chat" + }, + { + "group": "general-chat", + "group_label": "chat (4/5)", + "shard_index": 3, + "shard_count": 5, + "task": "ci:chat" + }, + { + "group": "general-chat", + "group_label": "chat (5/5)", + "shard_index": 4, + "shard_count": 5, "task": "ci:chat" }, { @@ -149,6 +219,7 @@ { "lane_label": "static checks", "command": "check:static", + "release_crate": true, "task": "ci:runner-static" }, { @@ -158,19 +229,34 @@ "task": "ci:runner-rust" }, { - "lane_label": "vitest package (1/3)", - "command": "test:typescript:vitest --package-lane=1/3", - "task": "ci:runner-vitest" + "lane_label": "vitest package (1/6)", + "command": "test:typescript:vitest --package-lane=1/6", + "task": "ci:runner-package" }, { - "lane_label": "vitest package (2/3)", - "command": "test:typescript:vitest --package-lane=2/3", - "task": "ci:runner-vitest" + "lane_label": "vitest package (2/6)", + "command": "test:typescript:vitest --package-lane=2/6", + "task": "ci:runner-package" }, { - "lane_label": "vitest package (3/3)", - "command": "test:typescript:vitest --package-lane=3/3", - "task": "ci:runner-vitest" + "lane_label": "vitest package (3/6)", + "command": "test:typescript:vitest --package-lane=3/6", + "task": "ci:runner-package" + }, + { + "lane_label": "vitest package (4/6)", + "command": "test:typescript:vitest --package-lane=4/6", + "task": "ci:runner-package" + }, + { + "lane_label": "vitest package (5/6)", + "command": "test:typescript:vitest --package-lane=5/6", + "task": "ci:runner-package" + }, + { + "lane_label": "vitest package (6/6)", + "command": "test:typescript:vitest --package-lane=6/6", + "task": "ci:runner-package" }, { "lane_label": "vitest native server", diff --git a/.github/scripts/tests/ci-plan.test.mjs b/.github/scripts/tests/ci-plan.test.mjs index e27aa8d96d8..6eae69eeb9c 100644 --- a/.github/scripts/tests/ci-plan.test.mjs +++ b/.github/scripts/tests/ci-plan.test.mjs @@ -34,12 +34,94 @@ test("a UI component retains browser and build coverage without unrelated server assert.equal(selected(result, "build"), true); assert.equal(selected(result, "e2e_shards"), true); assert.equal(selected(result, "verify_serialized_server"), false); - // The Runner support suite imports UI modules and checks that catalog-listed - // UI files stay tracked, so UI source changes are its inputs too. - assert.deepEqual([...selectedTasks(result)].filter((task) => /server|chat|runner/.test(task)), ["ci:runner-e2e-support"]); + assert.equal(selected(result, "canary_dry_run"), false); + assert.equal(selected(result, "verify_runner_e2e_support"), false); + assert.equal(selected(result, "docker_context_integrity"), false); + assert.deepEqual([...selectedTasks(result)].filter((task) => /server|chat|runner/.test(task)), []); assert.equal(result.jobs.general_tests.selected, 2); }); +test("ordinary app PRs skip canary dry run, runner support, docker context and runner package lanes", () => { + const serverRoute = plan(["server/src/routes/issues.ts"]); + const tasks = selectedTasks(serverRoute); + for (const required of ["ci:server", "ci:chat", "ci:serialized", "ci:build", "ci:typecheck", "ci:e2e", "ci:workspaces-b", "ci:runner-static", "ci:runner-vitest"]) { + assert.ok(tasks.has(required), `expected ${required}`); + } + for (const skipped of ["ci:canary", "ci:runner-e2e-support", "ci:docker", "ci:workspaces-a", "ci:db", "ci:runner-package", "ci:runner-rust", "ci:sandbox-providers"]) { + assert.ok(!tasks.has(skipped), `unexpected ${skipped}`); + } + // Feature PR adding a table, route, and UI page still skips non-PR release/runner bloat. + const featurePr = plan(["packages/db/src/schema/issues.ts", "server/src/routes/issues.ts", "ui/src/pages/Issues.tsx"]); + assert.equal(selected(featurePr, "canary_dry_run"), false); + assert.equal(selected(featurePr, "verify_runner_e2e_support"), false); + assert.equal(selected(featurePr, "docker_context_integrity"), false); + assert.equal(selectedTasks(featurePr).has("ci:chat"), true); + assert.equal(selectedTasks(featurePr).has("ci:runner-package"), false); + assert.equal(selectedTasks(featurePr).has("ci:db"), true); + assert.equal(selectedTasks(featurePr).has("ci:workspaces-a"), true); +}); + +test("canary dry run, runner support, chat, docker and test-only edits select their exact owners", () => { + for (const file of ["scripts/release.sh", "package.json", "server/package.json", "cli/esbuild.config.mjs", + "server/scripts/bundle-runtime.mjs", "packages/paperclip-runner/scripts/stage-release-runner-binaries.mjs", + "packages/paperclip-runner/release-runner-targets.json"]) { + assert.equal(selected(plan([file]), "canary_dry_run"), true, `canary: ${file}`); + } + for (const file of ["tests/runner-e2e/catalog.test.ts", "packages/paperclip-runner/src/index.ts", + "packages/plugins/sdk/src/index.ts", "packages/adapters/codex-local/src/index.ts", + "packages/shared/src/constants.ts", "server/src/services/native-runtime/canonical.ts", + "server/src/services/ai-api-key-failures.ts", "server/src/services/activity.ts", + "ui/src/features/connections/ConnectionSetupFlow.tsx", ".github/workflows/pr-trusted.yml"]) { + assert.equal(selected(plan([file]), "verify_runner_e2e_support"), true, `runner-e2e-support: ${file}`); + } + for (const file of ["server/src/services/chat-channels/github/retry.ts", "server/src/services/connectors/slack-access.ts", + "packages/db/src/schema/chat_channels.ts", "server/src/routes/board-chat.ts", "server/src/services/heartbeat.ts"]) { + assert.equal(selectedTasks(plan([file])).has("ci:chat"), true, `chat: ${file}`); + } + for (const file of ["Dockerfile", ".dockerignore", "packages/paperclip-runner/src/index.ts"]) { + assert.equal(selected(plan([file]), "docker_context_integrity"), true, `docker: ${file}`); + } + assert.deepEqual([...selectedTasks(plan(["tests/e2e/smoke.spec.ts"]))].sort(), ["ci:e2e", "ci:typecheck"]); + assert.deepEqual([...selectedTasks(plan(["tests/runner-e2e/catalog.test.ts"]))].sort(), ["ci:runner-e2e-support", "ci:runner-package", "ci:runner-static", "ci:typecheck"]); + assert.equal(selectedTasks(plan(["packages/paperclip-runner/src/index.ts"])).has("ci:runner-package"), true); + assert.equal(selectedTasks(plan(["packages/adapter-utils/src/github-launcher.ts"])).has("ci:runner-package"), true); + assert.equal(selectedTasks(plan(["cli/src/commands/onboard.ts"])).has("ci:workspaces-a"), true); + assert.equal(selected(plan(["cli/src/commands/onboard.ts"]), "verify_paperclip_runner"), false); + assert.equal(selectedTasks(plan(["packages/db/src/schema/issues.ts"])).has("ci:workspaces-a"), true); + assert.equal(selectedTasks(plan(["packages/paperclip-runner/src/drivers/acpx/pi-extension-adapter.ts"])).has("ci:workspaces-a"), true); + assert.equal(selectedTasks(plan(["server/src/services/agent-conversations.ts"])).has("ci:workspaces-a"), true); + assert.equal(selectedTasks(plan(["packages/plugins/create-paperclip-plugin/src/index.ts"])).has("ci:workspaces-a"), true); + assert.equal(selectedTasks(plan(["announcements/examples/animated/assets/demo.html"])).has("ci:workspaces-a"), true); +}); + +test("PR workflow keeps Build fast and passes PR-mode context to typecheck and Vitest lanes", () => { + const workflow = readFileSync(new URL(".github/workflows/pr-trusted.yml", root), "utf8"); + const build = workflow.split("\n build:\n")[1].split("\n verify_serialized_server:\n")[0]; + assert.ok(!build.includes("node scripts/verify-grok-npm-install.mjs"), "PR Build must not run the 4-min public npm install verifier"); + assert.ok(!build.includes("warm-public-install-npm-cache.mjs"), "PR Build must not warm the unused public npm install cache"); + assert.ok(build.includes("pnpm --filter @paperclipai/server build:runtime"), "PR Build still verifies production runtime bundle"); + assert.match(build, /if \[ "\$\{PAPERCLIP_CI_FULL:-\}" = "1" \]; then\n\s+scripts\/server-boot-smoke\.sh/); + const typecheck = workflow.split("\n typecheck_release_registry:\n")[1].split("\n general_tests:\n")[0]; + assert.match(typecheck, /fetch-depth: 2/); + assert.match(typecheck, /CI_PLAN: \$\{\{ needs\.gate\.outputs\.plan \}\}/); + assert.match(typecheck, /PAPERCLIP_CI_BASE_SHA:/); + for (const job of ["typecheck_release_registry", "general_tests", "verify_paperclip_runner", "build", "verify_serialized_server"]) { + const block = workflow.split(`\n ${job}:\n`)[1].split(/\n [a-z0-9_]+:\n/)[0]; + const line = block.match(/PAPERCLIP_CI_FULL:.*/)?.[0]; + assert.ok(line, `${job} must forward PAPERCLIP_CI_FULL`); + assert.doesNotMatch(line, /profile_ci/, `${job} must keep profile-ci in PR mode rather than forcing PAPERCLIP_CI_FULL`); + } + const e2e = workflow.split("\n e2e_shards:\n")[1].split("\n e2e:\n")[0]; + const releaseVerify = readFileSync(new URL(".github/workflows/release-verify.yml", root), "utf8"); + const releaseBuild = releaseVerify.split("\n build:\n")[1].split("\n runner_binary_targets:\n")[0]; + const prKey = e2e.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; + const releaseKey = releaseBuild.match(/key: (e2e-ui-dist-v1-.+)/)?.[1]; + assert.ok(prKey && releaseKey, "both pr-trusted.yml and release-verify.yml must define the E2E UI dist cache key"); + assert.equal(prKey, releaseKey, "E2E UI dist reader and writer keys must match exactly"); + assert.doesNotMatch(e2e.split("Restore prebuilt UI assets")[1].split("Run e2e tests")[0], /restore-keys:/); + assert.match(e2e, /PAPERCLIP_E2E_SKIP_UI_BUILD: \$\{\{ steps\.e2e_ui_dist\.outputs\.cache-hit == 'true' && '1' \|\| '' \}\}/); +}); + test("source inspected across package boundaries selects its consumers", () => { for (const file of ["ui/src/lib/issue-execution-policy.ts", "ui/src/index.css", "ui/src/pages/CompanyExport.tsx", "ui/src/components/MarkdownBody.tsx"]) { @@ -292,7 +374,7 @@ else process.exit(3); else { assert.notEqual(value, "plan=", `${JSON.stringify(overrides)}: ${result.stderr}`); const resultPlan = JSON.parse(value.slice("plan=".length)); - assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 19 : 2); + assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 29 : 2); assert.equal(resultPlan.diff.base, base); assert.deepEqual(resultPlan.changed, ["ui/src/components/Sidebar.tsx"]); } diff --git a/.github/workflows/pr-trusted.yml b/.github/workflows/pr-trusted.yml index deb7d92060e..9963714fc9e 100644 --- a/.github/workflows/pr-trusted.yml +++ b/.github/workflows/pr-trusted.yml @@ -243,7 +243,10 @@ jobs: run: node "$CI_NODE_TEST" '.github/scripts/tests/*.test.mjs' - name: Test general-server shard partition - run: node "$CI_NODE_TEST" ./scripts/__tests__/run-vitest-stable-shard.test.mjs + run: | + tests=(./scripts/__tests__/run-vitest-stable-shard.test.mjs) + if [[ -f ./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs ]]; then tests+=(./scripts/__tests__/run-vitest-stable-pr-mode.test.mjs); fi + node "$CI_NODE_TEST" "${tests[@]}" - name: Test e2e shard partition run: node "$CI_NODE_TEST" ./scripts/__tests__/e2e-shard.test.mjs @@ -303,6 +306,9 @@ jobs: timeout-minutes: 20 env: + CI_PLAN: ${{ needs.gate.outputs.plan }} + PAPERCLIP_CI_BASE_SHA: ${{ needs.gate.outputs.plan != '' && fromJSON(needs.gate.outputs.plan).diff.base || github.event.pull_request.base.sha }} + PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_PROFILE: ${{ needs.gate.outputs.profile_ci }} PAPERCLIP_CI_PROFILE_JOB: Typecheck + Release Registry @@ -311,6 +317,7 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 with: persist-credentials: false + fetch-depth: 2 - name: Initialize CI profile continue-on-error: true @@ -514,9 +521,10 @@ jobs: strategy: fail-fast: false max-parallel: ${{ needs.gate.outputs.runner == 'ubuntu-latest' && 4 || 256 }} - matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/12)","shard_index":0,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/12)","shard_index":1,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/12)","shard_index":2,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/12)","shard_index":3,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/12)","shard_index":4,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/12)","shard_index":5,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/12)","shard_index":6,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/12)","shard_index":7,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/12)","shard_index":8,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/12)","shard_index":9,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/12)","shard_index":10,"shard_count":12,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/12)","shard_index":11,"shard_count":12,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/3)","shard_index":0,"shard_count":3,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/3)","shard_index":1,"shard_count":3,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/3)","shard_index":2,"shard_count":3,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b","task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} + matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.general_tests.matrix) || '{"include":[{"group":"general-server-without-chat","group_label":"server (1/20)","shard_index":0,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (2/20)","shard_index":1,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (3/20)","shard_index":2,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (4/20)","shard_index":3,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (5/20)","shard_index":4,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (6/20)","shard_index":5,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (7/20)","shard_index":6,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (8/20)","shard_index":7,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (9/20)","shard_index":8,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (10/20)","shard_index":9,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (11/20)","shard_index":10,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (12/20)","shard_index":11,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (13/20)","shard_index":12,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (14/20)","shard_index":13,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (15/20)","shard_index":14,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (16/20)","shard_index":15,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (17/20)","shard_index":16,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (18/20)","shard_index":17,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (19/20)","shard_index":18,"shard_count":20,"task":"ci:server"},{"group":"general-server-without-chat","group_label":"server (20/20)","shard_index":19,"shard_count":20,"task":"ci:server"},{"group":"general-chat","group_label":"chat (1/5)","shard_index":0,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/5)","shard_index":1,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (3/5)","shard_index":2,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (4/5)","shard_index":3,"shard_count":5,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (5/5)","shard_index":4,"shard_count":5,"task":"ci:chat"},{"group":"general-workspaces-a","group_label":"workspaces-a (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-a","group_label":"workspaces-a (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-a"},{"group":"general-workspaces-b","group_label":"workspaces-b","task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }} env: + PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_TEST_SELECTION: ${{ matrix.selection && '.ci-test-selection/manifest.json' || '' }} PAPERCLIP_CI_SELECTION_HASH: ${{ matrix.selection && fromJSON(needs.test_selection.outputs.plan).testSelection.hash || '' }} PAPERCLIP_CI_PROFILE: ${{ needs.gate.outputs.profile_ci }} @@ -849,9 +857,10 @@ jobs: strategy: fail-fast: false max-parallel: ${{ needs.gate.outputs.runner == 'ubuntu-latest' && 4 || 256 }} - matrix: ${{ fromJSON(needs.gate.outputs.plan != '' && toJSON(fromJSON(needs.gate.outputs.plan).jobs.verify_paperclip_runner.matrix) || '{"include":[{"lane_label":"static checks","command":"check:static","task":"ci:runner-static"},{"lane_label":"rust","command":"check:runner","release_crate":true,"task":"ci:runner-rust"},{"lane_label":"vitest package (1/3)","command":"test:typescript:vitest --package-lane=1/3","task":"ci:runner-vitest"},{"lane_label":"vitest package (2/3)","command":"test:typescript:vitest --package-lane=2/3","task":"ci:runner-vitest"},{"lane_label":"vitest package (3/3)","command":"test:typescript:vitest --package-lane=3/3","task":"ci:runner-vitest"},{"lane_label":"vitest native server","command":"test:typescript:vitest --native-server","release_crate":true,"task":"ci:runner-vitest"}]}') }} + matrix: ${{ fromJSON(needs.gate.outputs.plan != '' && toJSON(fromJSON(needs.gate.outputs.plan).jobs.verify_paperclip_runner.matrix) || '{"include":[{"lane_label":"static checks","command":"check:static","release_crate":true,"task":"ci:runner-static"},{"lane_label":"rust","command":"check:runner","release_crate":true,"task":"ci:runner-rust"},{"lane_label":"vitest package (1/6)","command":"test:typescript:vitest --package-lane=1/6","task":"ci:runner-package"},{"lane_label":"vitest package (2/6)","command":"test:typescript:vitest --package-lane=2/6","task":"ci:runner-package"},{"lane_label":"vitest package (3/6)","command":"test:typescript:vitest --package-lane=3/6","task":"ci:runner-package"},{"lane_label":"vitest package (4/6)","command":"test:typescript:vitest --package-lane=4/6","task":"ci:runner-package"},{"lane_label":"vitest package (5/6)","command":"test:typescript:vitest --package-lane=5/6","task":"ci:runner-package"},{"lane_label":"vitest package (6/6)","command":"test:typescript:vitest --package-lane=6/6","task":"ci:runner-package"},{"lane_label":"vitest native server","command":"test:typescript:vitest --native-server","release_crate":true,"task":"ci:runner-vitest"}]}') }} env: + PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_PROFILE: ${{ needs.gate.outputs.profile_ci }} PAPERCLIP_CI_PROFILE_JOB: Verify Paperclip Runner (${{ matrix.lane_label }}) @@ -1007,10 +1016,11 @@ jobs: # path list and the key live in scripts/runner-release-crate-cache.mjs # and must match the writer's; a guard test holds them together. # - # Only the lanes that build the release crate restore it: the Rust - # lane's release tests link the lib, and the final vitest shard hosts - # the server's native-runner suite, which builds the binary in its - # beforeAll. The static and first vitest lanes run no cargo at all. + # Only the lanes that build the release crate restore it: `static checks` + # runs `check:api-authority` (which builds `paperclip-runnerd` in release + # mode), the Rust lane's release tests link the lib, and `vitest native + # server` builds the binary in its beforeAll. The package vitest lanes + # only use the debug crate cache. - name: Compute the Runner release crate cache key id: runner_release_crate_key if: ${{ matrix.release_crate == true }} @@ -1090,6 +1100,7 @@ jobs: timeout-minutes: 20 env: + PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_PROFILE: ${{ needs.gate.outputs.profile_ci }} PAPERCLIP_CI_PROFILE_JOB: Build @@ -1154,25 +1165,6 @@ jobs: pnpm install --frozen-lockfile fi - # The public-install verifier at the end of this lane downloads the whole - # public registry graph into an empty npm cache: its consumer install - # took 119-129s of the 226-241s step, more than half of this ~415-446s - # lane, in runs 38426120144, 38432086560 and 38423713537 (2026-10-13). - # That graph is fixed by source manifests, so this fetches it in the - # background while the Rust restore, Evalbook and `pnpm build` run, about - # 150s before the verifier installs anything. Only the cache is handed - # over, and the verify step waits for this first. A failed or partial - # warm-up leaves the verifier to fetch what is missing as before. - - name: Start warming the public-install npm cache - if: ${{ hashFiles('scripts/warm-public-install-npm-cache.mjs') != '' }} - run: | - ( - # The default `bash -e` would skip the status line on a failure. - set +e - PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache" node scripts/warm-public-install-npm-cache.mjs - echo $? > "$RUNNER_TEMP/public-install-npm-cache.status" - ) > "$RUNNER_TEMP/public-install-npm-cache.log" 2>&1 & - # pnpm build reaches the Runner package's build:binary step; without the # shared Rust cache that is a ~3m40s cold compile of all third-party # crates (run 35036001734, 2026-09-15). Same restore-only contract as @@ -1290,41 +1282,19 @@ jobs: - name: Build run: pnpm build - # The production image starts the server from this bundle with plain - # node (Dockerfile CMD), so prove it boots before the image is built: - # bundle the `pnpm build` output, start it against a throwaway embedded - # instance, and wait for /api/health to report ok. - - name: Boot the production runtime bundle + # Always verify the production runtime bundle builds cleanly (~4s). + # Full embedded-Postgres boot smoke (~53s) runs on full-ci / release + # verification; ordinary PRs already boot the server in e2e_shards. + - name: Build production runtime bundle run: | pnpm --filter @paperclipai/server build:runtime - scripts/server-boot-smoke.sh node server/dist-runtime/index.mjs - - # This verification only needs `pnpm build` output (the verifier stages - # the public packages' dist and reuses ui/dist itself), yet it ran at the - # end of Canary Dry Run, serially after the ~210-295s release.sh dry run. - # That made Canary Dry Run the slowest check in every green PR run: - # 484s, 572s and 483s in runs 37310951026, 37309272947 and 37308895471 - # (2026-10-05), with this step alone at 210-223s of each. The Build lane - # finished its `pnpm build` in ~206s total in those same runs, so it - # absorbs the step at ~416s while Canary Dry Run drops to ~275-350s and - # neither remains the critical path (server 2/12 at ~437-467s is). - # docker-runner-check.yml runs the same verifier after `pnpm build`. - - name: Verify built-in Grok from a clean public npm install - if: ${{ hashFiles('scripts/verify-grok-npm-install.mjs') != '' }} - run: | - status="$RUNNER_TEMP/public-install-npm-cache.status" - if [ -f "$RUNNER_TEMP/public-install-npm-cache.log" ]; then - # Normally finished long before this; never let it hold the lane. - for _ in $(seq 180); do [ -f "$status" ] && break; sleep 1; done - if [ "$(cat "$status" 2>/dev/null)" = 0 ]; then - tail -n 1 "$RUNNER_TEMP/public-install-npm-cache.log" - else - echo '::notice title=Public-install npm cache::warm-up did not finish cleanly; the verifier fetches what is missing' - tail -n 20 "$RUNNER_TEMP/public-install-npm-cache.log" - fi - export PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache" + if [ "${PAPERCLIP_CI_FULL:-}" = "1" ]; then + scripts/server-boot-smoke.sh node server/dist-runtime/index.mjs fi - node scripts/verify-grok-npm-install.mjs + + # Clean public npm install verification (`verify-grok-npm-install.mjs`, + # ~231s) is covered by release-smoke.yml and docker-runner-check.yml + # rather than running on every pull request Build job. - name: Upload CI profile timings continue-on-error: true @@ -1349,6 +1319,7 @@ jobs: matrix: ${{ fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan) != '' && toJSON(fromJSON((needs.test_selection.outputs.plan || needs.gate.outputs.plan)).jobs.verify_serialized_server.matrix) || '{"include":[{"shard_index":0,"shard_count":9,"shard_label":"1/9","task":"ci:serialized"},{"shard_index":1,"shard_count":9,"shard_label":"2/9","task":"ci:serialized"},{"shard_index":2,"shard_count":9,"shard_label":"3/9","task":"ci:serialized"},{"shard_index":3,"shard_count":9,"shard_label":"4/9","task":"ci:serialized"},{"shard_index":4,"shard_count":9,"shard_label":"5/9","task":"ci:serialized"},{"shard_index":5,"shard_count":9,"shard_label":"6/9","task":"ci:serialized"},{"shard_index":6,"shard_count":9,"shard_label":"7/9","task":"ci:serialized"},{"shard_index":7,"shard_count":9,"shard_label":"8/9","task":"ci:serialized"},{"shard_index":8,"shard_count":9,"shard_label":"9/9","task":"ci:serialized"}]}') }} env: + PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_TEST_SELECTION: ${{ matrix.selection && '.ci-test-selection/manifest.json' || '' }} PAPERCLIP_CI_SELECTION_HASH: ${{ matrix.selection && fromJSON(needs.test_selection.outputs.plan).testSelection.hash || '' }} PAPERCLIP_CI_PROFILE: ${{ needs.gate.outputs.profile_ci }} @@ -1761,10 +1732,21 @@ jobs: } CONF + # Reuse master's exact UI build on non-UI PRs so all 8 E2E shards skip + # rebuilding Vite (~35s each). Exact key only (no restore-keys): a UI + # change misses and Playwright builds server/ui-dist inline. + - name: Restore prebuilt UI assets (read only) + id: e2e_ui_dist + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: server/ui-dist + key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + - name: Run e2e tests env: PAPERCLIP_E2E_SKIP_LLM: "true" PAPERCLIP_PLAYWRIGHT_CHANNEL: "chrome" + PAPERCLIP_E2E_SKIP_UI_BUILD: ${{ steps.e2e_ui_dist.outputs.cache-hit == 'true' && '1' || '' }} run: | # Playwright's own --shard balances by test count, and one spec # (smoke-lab) is ~40% of the lane's wall clock. Partition by recorded diff --git a/.github/workflows/release-verify.yml b/.github/workflows/release-verify.yml index 77d34faa0d3..55044cb9a1c 100644 --- a/.github/workflows/release-verify.yml +++ b/.github/workflows/release-verify.yml @@ -564,6 +564,28 @@ jobs: - name: Build run: pnpm build + # Exact-key master cache for PR e2e_shards (read-only restore in + # pr-trusted.yml). Only canonical master pushes write this entry. + - name: Check for prebuilt E2E UI assets cache + id: e2e_ui_dist + if: ${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' && inputs.ref == github.sha }} + uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + lookup-only: true + path: server/ui-dist + key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + + - name: Stage prebuilt UI assets for E2E cache + if: ${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' && inputs.ref == github.sha && steps.e2e_ui_dist.outputs.cache-hit != 'true' }} + run: PAPERCLIP_RELEASE_REUSE_UI_DIST=1 bash scripts/prepare-server-ui-dist.sh + + - name: Save prebuilt UI assets for PR E2E shards + if: ${{ github.repository == 'paperclipai/paperclip' && github.event_name == 'push' && github.ref == 'refs/heads/master' && inputs.ref == github.sha && steps.e2e_ui_dist.outputs.cache-hit != 'true' }} + uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: server/ui-dist + key: e2e-ui-dist-v1-${{ runner.os }}-${{ runner.arch }}-${{ hashFiles('pnpm-lock.yaml', 'tsconfig*.json', 'ui/package.json', 'ui/index.html', 'ui/vite.config.*', 'ui/tsconfig*.json', 'ui/src/**', 'ui/public/**', 'packages/shared/src/**', 'packages/adapter-utils/src/**', 'packages/adapters/*/src/**', 'packages/plugins/sdk/src/**') }} + runner_binary_targets: if: inputs.runner_binaries_only name: Read exact-source daemon targets diff --git a/maps/agent-access-map/onboarding.md b/maps/agent-access-map/onboarding.md index 096050ffa57..52f7211f9f2 100644 --- a/maps/agent-access-map/onboarding.md +++ b/maps/agent-access-map/onboarding.md @@ -114,9 +114,8 @@ test. This adds no installation API, account grant, environment authority or engine fallback. Cloud UI omits manual shell debugging and legacy operator hints while retaining check messages and details. Local, SSH and custom commands remain operator-managed. Controls: -[runtime](../../packages/adapters/claude-local/src/server/sandbox-cli-version.test.ts), -[probe](../../packages/adapters/claude-local/src/server/test.remote.test.ts), and -[wizard](../../ui/src/components/OnboardingWizard.test.tsx). Live managed +[runtime](../../packages/adapters/claude-local/src/server/sandbox-cli-version.test.ts) +and [probe](../../packages/adapters/claude-local/src/server/test.remote.test.ts) (mocked UI wizard unit tests were removed; verify wizard UI via [onboarding browser suite](../../tests/e2e/onboarding.spec.ts) or manual checks). Live managed authorization and subscription execution remain `not-run` for this change. For fresh managed Codex Auto setup, the wizard's explicit Connect path can call @@ -140,9 +139,8 @@ change instruction discovery for ordinary task execution. Scoped source review: 2026-10-13, exact baseline `1a0ca66242121e39d88455aa2b52a07acc4a07d9` plus the privately composed onboarding -correction. [Wizard controls](../../ui/src/components/OnboardingWizard.test.tsx) -and [existing Product E2E observer controls](../../tests/runner-e2e/first-task.test.ts) -exercise mocked allowed/denied setup and sticky unknown cost coverage. They do +correction. [Existing Product E2E observer controls](../../tests/runner-e2e/first-task.test.ts) +exercise mocked allowed/denied setup and sticky unknown cost coverage (mocked UI wizard component tests were removed; verify wizard UI manually or via browser checks). They do not prove live actor authorization or provider execution. The explicit manual `confirmation-replies.runner-codex.daytona.task-card-accept` case requires an eligible immutable OCI target and the existing probe authority, two identified @@ -301,8 +299,8 @@ and opening a saved Legacy agent does not apply new-agent defaults. The initial matching route opening preserves the authorized saved wizard step on bare and company-prefixed reloads. Explicit new-company or changed-company openings retain their navigation override and clear foreign company resource -IDs. [Existing component controls](../../ui/src/components/OnboardingWizard.test.tsx) -exercise these presentation and account boundaries. This scoped correction adds +IDs. No automated UI component tests cover these wizard presentation and account +boundaries (previously mocked wizard tests were removed; verify via [onboarding browser suite](../../tests/e2e/onboarding.spec.ts) or manual reload checks). This scoped correction adds no server draft API, agent grant or proof of live actor authorization. The managed first-task eval still reloads before Get started and remains a separate live acceptance gate. The existing mocked-login browser case also checks the diff --git a/maps/feature-map/activity.md b/maps/feature-map/activity.md index 76076f22ff7..689e3c611d4 100644 --- a/maps/feature-map/activity.md +++ b/maps/feature-map/activity.md @@ -43,7 +43,7 @@ Manual: Compare the dashboard with the known fixture tasks and runs. Start and f ### `activity-audit` -Automated: [activity service](../../server/src/__tests__/activity-service.test.ts), [audit runs](../../ui/src/pages/audit/AuditRuns.test.tsx), and [routine audit](../../ui/src/pages/audit/RoutineAuditActivity.test.tsx) cover these separate data/host layers. +Automated: [activity service](../../server/src/__tests__/activity-service.test.ts) covers the server data layer (UI component tests for audit runs and routine audit were removed; verify UI behavior manually or via Storybook). Manual: Find a known mutation by actor/resource and a known run by status. Change filters, load more, and follow the source links. Reload the chosen view and verify no company leakage or duplicate events. Inspect a routine run from its audit entry. @@ -56,10 +56,10 @@ events from `case_events` appear alongside the already recorded handoffs and document events, without duplicating those mirrored records. Combined history passes retained case access before cursor pagination. -Focused regressions: [Audit feed](../../ui/src/pages/audit/AuditFeed.test.tsx), -[Audit routing](../../ui/src/pages/audit/AuditHub.test.tsx), and -[Postgres audit routes](../../server/src/__tests__/agent-action-audit-routes.test.ts). -These prove the component/API boundaries separately; follow the case-to-Audit +Focused regressions: +[Postgres audit routes](../../server/src/__tests__/agent-action-audit-routes.test.ts) +cover the API boundary (mocked Audit feed and Audit routing UI tests were removed; +follow the case-to-Audit link in the actual app to verify the UI and assembled journey). link in the actual app to verify the assembled journey. Issue activity is also available through `GET /api/issues/{id}/activity`. @@ -106,4 +106,4 @@ Company run history defaults to 200 rows and caps explicit limits at 1,000. Summary contexts omit stored prompts and expand JSON once per returned row. The array response and run visibility/redaction checks remain in place. Agent detail links resolve older runs by ID outside the recent history page. -Sources: Source: [AuditRuns.tsx](../../ui/src/pages/audit/AuditRuns.tsx), [heartbeats.ts](../../ui/src/api/heartbeats.ts), [routines.ts](../../ui/src/api/routines.ts). Tests: [AuditRuns.test.tsx](../../ui/src/pages/audit/AuditRuns.test.tsx), [heartbeat-run-privacy-routes.test.ts](../../server/src/__tests__/heartbeat-run-privacy-routes.test.ts), [routines-service.test.ts](../../server/src/__tests__/routines-service.test.ts) +Sources: Source: [AuditRuns.tsx](../../ui/src/pages/audit/AuditRuns.tsx), [heartbeats.ts](../../ui/src/api/heartbeats.ts), [routines.ts](../../ui/src/api/routines.ts). Tests: [heartbeat-run-privacy-routes.test.ts](../../server/src/__tests__/heartbeat-run-privacy-routes.test.ts), [routines-service.test.ts](../../server/src/__tests__/routines-service.test.ts) diff --git a/maps/feature-map/agent-chat.md b/maps/feature-map/agent-chat.md index e2018600e3c..bb1af2be115 100644 --- a/maps/feature-map/agent-chat.md +++ b/maps/feature-map/agent-chat.md @@ -51,7 +51,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Enab ### `agent-conversation` -Automated: [chat landing](../../ui/src/pages/AgentChats.test.tsx) checks recent-chat routing; [conversation service](../../server/src/__tests__/agent-conversations.test.ts) covers persisted conversation behavior. +Automated: [conversation service](../../server/src/__tests__/agent-conversations.test.ts) covers persisted conversation behavior (mocked chat landing UI tests were removed; verify recent-chat routing manually or via browser checks). Automated: [proactive delivery](../../server/src/__tests__/agent-chat-messages.test.ts) exercises native/HTTP delivery, concurrency, retries, authority, privacy, active @@ -61,7 +61,7 @@ uses real app APIs and a deterministic process agent to verify first-chat discov unread state across reloads, source navigation and follow-up context. It does not qualify live PR retrieval or a model's editorial choices. -Automated: [composer picker](../../ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx) covers fixed-agent model/effort selection on desktop and mobile; [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. [Task detail](../../ui/src/pages/IssueDetail.test.tsx) verifies canonical first/existing-chat IDs, settings-before-comment ordering, and no comment submission when settings fail to save. These tests mock the API and do not prove provider execution with the chosen model. +Automated: [composer picker](../../ui/src/components/task-chat/ComposerRunSettingsPicker.test.tsx) covers fixed-agent model/effort selection on desktop and mobile; [composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers Coordinator gating and settings submission without reassignment. (Mocked `IssueDetail` UI tests for canonical first/existing-chat IDs and settings-before-comment ordering were removed; verify those page-level flows manually.) These tests mock the API and do not prove provider execution with the chosen model. Automated: [thread and composer](../../ui/src/components/TaskChatThread.test.tsx) keeps an in-flight attachment through first-chat creation on desktop and mobile, @@ -135,7 +135,7 @@ Capability ID: `agent-chat/conference-room`. Scope: ui Storybook: Conference-room flag disabled, empty/history/reply, busy and explicit failure states. Production: Exercise separate BoardChat route gate, local-trusted deployment and authenticated Claude CLI; send/reload real conversation with responding agent attribution. -Sources: Source: [BoardChat.tsx](../../ui/src/pages/BoardChat.tsx), [board-chat.ts](../../server/src/routes/board-chat.ts). Tests: [BoardChat.test.tsx](../../ui/src/pages/BoardChat.test.tsx), [board-chat-route-feature-flag.test.ts](../../server/src/__tests__/board-chat-route-feature-flag.test.ts) +Sources: Source: [BoardChat.tsx](../../ui/src/pages/BoardChat.tsx), [board-chat.ts](../../server/src/routes/board-chat.ts). Tests: [board-chat-route-feature-flag.test.ts](../../server/src/__tests__/board-chat-route-feature-flag.test.ts) ### Explicit output quality review (Coordinator functional slice) diff --git a/maps/feature-map/agents.md b/maps/feature-map/agents.md index 9e22cafb1d7..949ddfa48e3 100644 --- a/maps/feature-map/agents.md +++ b/maps/feature-map/agents.md @@ -173,7 +173,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `hire-agent` -Automated: [new agent page](../../ui/src/pages/NewAgent.test.tsx) and [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) cover mocked UI behavior. +Automated: [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) covers mocked configuration-form UI behavior (mocked `NewAgent` page tests were removed; verify the new-agent page flow manually). For an agent-owned plugin environment, verify preparation before connecting, same-agent probes, account preservation after an environment change, failed @@ -261,8 +261,7 @@ The notice must stay absent for native agents, other harnesses, and unsupported targets. Discovery failure must not imply that an upgrade is available. Navigate to another agent while an upgrade is pending. Its result must stay with the original agent, without showing success on the new page or redirecting back. -Focused coverage: [save receipt](../../ui/src/pages/AgentRunnerUpgrade.test.tsx) -and [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx). +Focused coverage: [configuration form](../../ui/src/components/AgentConfigForm.render.test.tsx) (mocked upgrade save-receipt UI tests were removed; verify upgrade save receipts manually). For an existing native agent on a Daytona snapshot or immutable sandbox image, use **Test** in its saved Harness or Runtime configuration after a managed @@ -282,7 +281,7 @@ or provider execution. ### `organization` -Automated: [org chart](../../ui/src/pages/OrgChart.test.tsx) is component evidence. Built-in setup also has [configuration modal tests](../../ui/src/components/ConfigureBuiltInAgentModal.test.tsx). +Automated: none (mocked org-chart and built-in agent configuration modal UI tests were removed; verify manually). Manual: Inspect a manager and report, change the relationship through the offered controls, and reload both views. Exercise a rejected invalid relationship. Configure a built-in agent and verify it retains its required identity and restrictions. diff --git a/maps/feature-map/app-permissions.md b/maps/feature-map/app-permissions.md index 0500e6d0335..2d44613dfbb 100644 --- a/maps/feature-map/app-permissions.md +++ b/maps/feature-map/app-permissions.md @@ -50,7 +50,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Prep ### `permissions` -Automated: [app detail](../../ui/src/pages/apps/AppDetail.test.tsx) covers agent/action controls, quarantined actions, and navigation using mocked requests. +Automated: none for mocked UI controls (`AppDetail` component tests were removed; see server tests below and verify UI controls manually or via Storybook). [Runtime assignment tests](../../server/src/__tests__/agent-runtime-assignments.test.ts) use PostgreSQL to verify committed assignment notifications, bounded snapshots, @@ -88,7 +88,7 @@ still need live account qualification. ### `test-and-maintain` -Automated: [app detail tests](../../ui/src/pages/apps/AppDetail.test.tsx) cover test-dialog/UI contracts. Real provider execution and revocation require the selected provider’s live check. +Automated: none for mocked UI test-dialog contracts (`AppDetail` component tests were removed; verify UI manually). Real provider execution and revocation require the selected provider’s live check. Manual: Run a read-only action with explicit inputs and inspect returned data and activity. Refresh discovery and review new actions. Revoke or disconnect only the disposable credential, then verify subsequent use fails with an actionable reconnect state. @@ -135,7 +135,7 @@ Capability ID: `app-permissions/catalog-change`. Scope: ui Storybook: Mount PermissionsPanel/AppDetail with quarantined actions, selection/review, refresh pending, empty and failed discovery states. Existing auto-allowed NewToolsAllowed examples are not quarantine review. Production: Exercise catalog refresh and new-tool review with permitted/denied actors; unreviewed actions stay quarantined, prior Off/Ask choices survive refresh, and approved review persists. -Sources: Source: [PermissionsPanel.tsx](../../ui/src/pages/apps/app-detail/PermissionsPanel.tsx), [AppDetail.tsx](../../ui/src/pages/apps/AppDetail.tsx), [tool-access.ts](../../server/src/routes/tool-access.ts). Tests: [AppDetail.test.tsx](../../ui/src/pages/apps/AppDetail.test.tsx), [tool-access-service.test.ts](../../server/src/__tests__/tool-access-service.test.ts), [tool-access-policy-service.test.ts](../../server/src/__tests__/tool-access-policy-service.test.ts) +Sources: Source: [PermissionsPanel.tsx](../../ui/src/pages/apps/app-detail/PermissionsPanel.tsx), [AppDetail.tsx](../../ui/src/pages/apps/AppDetail.tsx), [tool-access.ts](../../server/src/routes/tool-access.ts). Tests: [tool-access-service.test.ts](../../server/src/__tests__/tool-access-service.test.ts), [tool-access-policy-service.test.ts](../../server/src/__tests__/tool-access-policy-service.test.ts) ### `delegated-configuration` See the canonical [delegated configuration guidance and acceptance evidence](connection-setup.md#delegated-configuration). diff --git a/maps/feature-map/assistant-connections.md b/maps/feature-map/assistant-connections.md index 3ed734fd768..d8d74580911 100644 --- a/maps/feature-map/assistant-connections.md +++ b/maps/feature-map/assistant-connections.md @@ -48,7 +48,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `apps-setup` -Automated: [Assistant setup UI](../../ui/src/pages/apps/AssistantConnection.test.tsx) covers mocked invitation, setup, status, and revocation. [Client metadata](../../server/src/__tests__/public-mcp-client-metadata.test.ts) and [MCP routes](../../server/src/__tests__/public-mcp.test.ts) cover configured origins, metadata, and identity restrictions. They do not prove setup in an external client. +Automated: [Client metadata](../../server/src/__tests__/public-mcp-client-metadata.test.ts) and [MCP routes](../../server/src/__tests__/public-mcp.test.ts) cover configured origins, metadata, and identity restrictions (mocked `AssistantConnection` UI tests were removed; verify setup UI manually). They do not prove setup in an external client. Manual: Open the Apps card as the intended signed-in person, copy the invitation, and verify the exact configured resource and company hint without embedded credentials. Follow manual instructions in an owned MCP client and proceed through the separate consent journey. Reload Apps to inspect connection status. Check signed-out, unconfigured-origin, and disabled experimental states; never substitute a guessed server URL or local implicit identity. Verify public instructions and authenticated setup metadata have their documented access boundaries. @@ -80,7 +80,7 @@ Sources: [MCP capabilities](../../server/src/services/public-mcp/capabilities.ts ### `manage-connections` -Automated: [Apps management UI](../../ui/src/pages/apps/AssistantConnection.test.tsx) covers mocked current-company controls, and [public MCP integration](../../server/src/__tests__/public-mcp.test.ts) covers persisted own-grant/token revocation. These component tests do not cover the account-wide `/assistant-connections` page or a real remote assistant after revocation. +Automated: [public MCP integration](../../server/src/__tests__/public-mcp.test.ts) covers persisted own-grant/token revocation (mocked `AssistantConnection` UI tests were removed; neither current-company UI controls nor the account-wide `/assistant-connections` page or a real remote assistant after revocation are covered by UI unit tests). Manual: First prove a harmless read using a personal client grant. Revoke that grant in the browser, reload its list, and retry the exact same credential: the remote call must fail. As a second person, confirm their grant remains usable. Attempt removal using another person’s grant ID; the API may return a harmless no-op, so verify that person’s grant is unchanged rather than demanding a specific error. Disable Assistant connections and confirm tool calls stop while signed-in list/revoke management remains reachable. Observe any work already delegated before revocation through its ordinary task controls; revocation does not cancel it. diff --git a/maps/feature-map/budgets-costs.md b/maps/feature-map/budgets-costs.md index b1fa72cbc94..b1719334dc6 100644 --- a/maps/feature-map/budgets-costs.md +++ b/maps/feature-map/budgets-costs.md @@ -50,7 +50,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `cost-overview` -Automated: [costs service](../../server/src/__tests__/costs-service.test.ts) covers cost contracts; [embedded costs UI](../../ui/src/pages/Costs.test.tsx) has narrow Audit-host coverage. +Automated: [costs service](../../server/src/__tests__/costs-service.test.ts) covers cost contracts (mocked `Costs` UI tests were removed; verify Audit-host UI manually). Manual: Inspect a known fixture run and reconcile recorded spend with the chosen period and resource. Switch the report period/company and inspect the **By @@ -79,7 +79,7 @@ Sources: [Subscription card](../../ui/src/components/SubscriptionCostCard.tsx), ### `cost-recording` -Automated: [Cost notice](../../ui/src/components/CostDataQualityNotice.test.tsx), [quality report](../../server/src/__tests__/cost-data-quality.test.ts), and [quality routes](../../server/src/__tests__/cost-data-quality-routes.test.ts) cover UI explanations, report scope, viewer/agent denial, and retry contracts. They do not prove arrival of a real provider receipt. +Automated: [quality report](../../server/src/__tests__/cost-data-quality.test.ts) and [quality routes](../../server/src/__tests__/cost-data-quality-routes.test.ts) cover report scope, viewer/agent denial, and retry contracts (mocked `CostDataQualityNotice` UI tests were removed; verify UI explanations manually). They do not prove arrival of a real provider receipt. Manual: Use saved-cost fixtures for waiting-for-receipt, receipt-unavailable, unknown-billing, missing-model/price, and retryable states. Expand the notice, inspect the affected run, and verify the explanation matches its saved evidence. For a retryable entry, choose Retry cost recording, reload, and verify costs are recorded once while the run ID, transcript, task execution count, and original outcome stay unchanged. Repeat with no new receipt and with a failed recording attempt; neither may fabricate zero cost or start a model run. Sign in as a viewer and then an ordinary agent: check the read/mutation boundaries and denial. Keep unresolved budget holds visible until their own accounting obligations settle. @@ -104,4 +104,4 @@ Capability ID: `budgets-costs/resolution`. Scope: ui Storybook: Mount BudgetIncidentCard with entered raised limit, invalid limit, keep-paused, applying, authorized/blocked and error states wired through actual host. Existing matrix handlers are no-ops. Production: POST /companies/{id}/budget-incidents/{id}/resolve must authorize scope-specific raise, persist resolution and resume eligible work while retaining overlapping budget/manual holds. -Sources: Source: [BudgetIncidentCard.tsx](../../ui/src/components/BudgetIncidentCard.tsx), [Costs.tsx](../../ui/src/pages/Costs.tsx), [budgets.ts](../../ui/src/api/budgets.ts), [costs.ts](../../server/src/routes/costs.ts), [budgets.ts](../../server/src/services/budgets.ts). Tests: [budgets-service.test.ts](../../server/src/__tests__/budgets-service.test.ts), [Costs.test.tsx](../../ui/src/pages/Costs.test.tsx) +Sources: Source: [BudgetIncidentCard.tsx](../../ui/src/components/BudgetIncidentCard.tsx), [Costs.tsx](../../ui/src/pages/Costs.tsx), [budgets.ts](../../ui/src/api/budgets.ts), [costs.ts](../../server/src/routes/costs.ts), [budgets.ts](../../server/src/services/budgets.ts). Tests: [budgets-service.test.ts](../../server/src/__tests__/budgets-service.test.ts) diff --git a/maps/feature-map/cases.md b/maps/feature-map/cases.md index 4ba3bdadf29..1fdde76673c 100644 --- a/maps/feature-map/cases.md +++ b/maps/feature-map/cases.md @@ -48,7 +48,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Enab ### `case-list` -Automated: [case list](../../ui/src/pages/Cases.test.tsx) covers the four header controls, read-only column visibility, URL filters/view state, server sort/group queries before pagination, group headers, detail/back navigation and loading/failure with mocked data. +Automated: covered end-to-end by the browser regression below (mocked `Cases` page unit tests were removed). Provider-free browser regression: [cases read-only journey](../../tests/e2e/cases-read-only.spec.ts) seeds passive cases, nested objects, singleton/multiple object arrays, a related unassigned task and two document revisions through production APIs, then checks column visibility, server-backed title sorting/type grouping, Filter popover/count, semantic key/value table rows and dotted paths, Work-before-Details layout, document revision previews, case-scoped Audit history/action filtering and return navigation in Chromium. It creates no agents. Run `env -u DATABASE_URL -u DATABASE_MIGRATION_URL pnpm exec playwright test --config tests/e2e/playwright.config.ts tests/e2e/cases-read-only.spec.ts --project chromium` on an unused `PAPERCLIP_E2E_PORT`. The existing harness starts an isolated instance; this journey does not qualify agent handoffs or live agent avatars. @@ -56,7 +56,7 @@ Manual: Hide/show a field through Columns, choose a sort/direction, group by typ ### `case-record` -Automated: [case routes](../../server/src/__tests__/cases-routes.test.ts) covers API behavior; [case fields](../../ui/src/components/CaseFieldsPanel.test.tsx) covers field UI separately. +Automated: [case routes](../../server/src/__tests__/cases-routes.test.ts) covers API behavior (mocked `CaseFieldsPanel` UI unit tests were removed; see the browser regression above and Storybook stories for field UI coverage). Manual: Inspect Work above Details in one column. Read nested values as compact dotted key/value rows; a singleton item has `items.quantity`, while multiple items use `items[0].quantity` and `items[1].quantity`. Verify keys/values remain legible on mobile without horizontal page overflow and scalar references still link to their destinations. Preview a document, inspect its revisions, and close with Escape; focus returns to the document link. Follow View in Audit to the case's retained history; filter by Cases actions or Case entities in Audit and verify agents use their configured avatars. Read attachments, follow parent/child/task links, and inspect a passive case. Case pages have no editing controls, including status, labels, documents, or handoff retry/cancel. Verify inaccessible cases fail clearly and remain distinct from pipeline-owned items. @@ -80,7 +80,7 @@ Start a standalone case through the agent's `handoff_case` operation or the case The final agent may hand off to `done`. While ordinary task completion is pending, the case remains open and shows that it will close when the task completes. Accepted completion closes the case and records a completed terminal handoff. Review and user waits do not close it. Case pages remain read-only. -Automated: shared schema tests, case route privacy tests, case handoff service/delivery tests, native lifecycle tests, and `CaseDetail.test.tsx` exercise their individual boundaries. The registered explicit-only case-handoffs Product E2E suite covers the full native journey; registration is not a live pass. +Automated: shared schema tests, case route privacy tests, case handoff service/delivery tests, and native lifecycle tests exercise their individual boundaries (mocked `CaseDetail` UI component tests were removed; verify case-detail UI manually or via browser checks). The registered explicit-only case-handoffs Product E2E suite covers the full native journey; registration is not a live pass. Manual: hand the task through implementation, verification, and correction. Its ID, workspace, thread, and review gates must remain stable. Repeat a request and restart delivery; neither may duplicate work. Try private cases with an unauthorized actor and verify documents, assets, activity, and handoff history remain inaccessible. @@ -136,7 +136,7 @@ Capability ID: `cases/browse`. Scope: ui Storybook: Mount the production Cases page in its real shell: Columns/Filter/Sort/Group header controls, URL view state, search/status/type/project filters, No project, result paging, list-to-detail return, keyboard navigation and empty/loading/error recovery. The ListControls story changes columns, title sorting and type grouping using fixture query responses. Production: GET /companies/{id}/cases and /cases/types scope/filter behavior and ordering before pagination require production evidence; rendered fixtures establish presentation only. Mutation/permission scenarios need real API checks separately. -Sources: Source: [Cases.tsx](../../ui/src/pages/Cases.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [Cases.test.tsx](../../ui/src/pages/Cases.test.tsx), [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts) +Sources: Source: [Cases.tsx](../../ui/src/pages/Cases.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts), [cases-read-only.spec.ts](../../tests/e2e/cases-read-only.spec.ts) #### `structure` @@ -145,7 +145,7 @@ Capability ID: `cases/structure`. Scope: ui Storybook: Mount read-only CaseDetail and CaseFieldsTable with nested objects, singleton/multiple object arrays and scalar reference links in a compact monospace key/value table, alongside documents, attachments, parent/children and unavailable references. Dotted leaf paths omit the index for a singleton object array and retain it for multiple entries. CaseDetail shows Work above Details in one column. The older CaseFieldsPanel arbitrary/empty examples retain their generic component scope. Do not invent a general field editor or typed field validation. Production: GET /cases/{id} and the parent-filtered case list must return permitted company records and correct relationships; changes/persistence require route tests separately. -Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [CaseFieldsPanel.tsx](../../ui/src/components/CaseFieldsPanel.tsx), [Cases.tsx](../../ui/src/pages/Cases.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [CaseFieldsPanel.test.tsx](../../ui/src/components/CaseFieldsPanel.test.tsx), [Cases.test.tsx](../../ui/src/pages/Cases.test.tsx), [CaseDetail.test.tsx](../../ui/src/pages/CaseDetail.test.tsx), [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts) +Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [CaseFieldsPanel.tsx](../../ui/src/components/CaseFieldsPanel.tsx), [Cases.tsx](../../ui/src/pages/Cases.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts), [cases-read-only.spec.ts](../../tests/e2e/cases-read-only.spec.ts) #### `history` @@ -154,7 +154,7 @@ Capability ID: `cases/history`. Scope: ui Storybook: Mount CaseDetail's View in Audit link with the case UUID query scope, and document revisions. Preserve the historical ActivityHistory export/ID for its Audit-navigation example. The destination Audit feed is a separate production surface, not reproduced in the case fixture shell. Production: The case-scoped Audit query must include retained historical case events, enforce the same case access boundary, and deduplicate events also recorded in the activity log. Case/Case action filters and configured agent avatars need real Audit/browser checks. GET /cases/{id}/events and /cases/{id}/documents/{key}/revisions still require company/access filtering; fixtures do not establish durable creation, privacy or restoration. -Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [CaseDetail.test.tsx](../../ui/src/pages/CaseDetail.test.tsx), [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts) +Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts), [cases-read-only.spec.ts](../../tests/e2e/cases-read-only.spec.ts) #### `task-links` @@ -163,7 +163,7 @@ Capability ID: `cases/task-links`. Scope: ui Storybook: Mount CaseDetail and IssueCasesPanel related-task/case links in both directions, missing links and unavailable targets. Production: GET /issues/{id}/cases and /cases/{id}/issue-links must enforce permitted task/case relationships; production browser cold links verify destination and company context. -Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [IssueCasesPanel.tsx](../../ui/src/components/IssueCasesPanel.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [IssueCasesPanel.test.tsx](../../ui/src/components/IssueCasesPanel.test.tsx), [CaseDetail.test.tsx](../../ui/src/pages/CaseDetail.test.tsx), [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts) +Sources: Source: [CaseDetail.tsx](../../ui/src/pages/CaseDetail.tsx), [IssueCasesPanel.tsx](../../ui/src/components/IssueCasesPanel.tsx), [cases.ts](../../server/src/routes/cases.ts). Tests: [cases-routes.test.ts](../../server/src/__tests__/cases-routes.test.ts) #### `handoffs` @@ -172,4 +172,4 @@ Capability ID: `cases/handoffs`. Scope: ui Storybook: Read-only pages and CaseWorkSummary mount production task/phase/history with waiting and paused-recipient API fixtures. No handoff mutation controls are exposed on these pages. Production: POST /companies/{id}/case-handoffs and GET /cases/{id}/handoffs require company/task authorization, retained-source privacy, observed revisions, and durable admission. Retry/cancel retain task-control authority. Native and legacy provider/workspace settlement require runtime evidence. -Sources: Source: [CaseWorkSummary.tsx](../../ui/src/components/cases/CaseWorkSummary.tsx), [case-handoffs.ts](../../server/src/services/case-handoffs.ts), [case-handoff-delivery.ts](../../server/src/services/case-handoff-delivery.ts). Tests: [CaseDetail.test.tsx](../../ui/src/pages/CaseDetail.test.tsx) +Sources: Source: [CaseWorkSummary.tsx](../../ui/src/components/cases/CaseWorkSummary.tsx), [case-handoffs.ts](../../server/src/services/case-handoffs.ts), [case-handoff-delivery.ts](../../server/src/services/case-handoff-delivery.ts) diff --git a/maps/feature-map/chat-channels.md b/maps/feature-map/chat-channels.md index dfb8e215947..e6f6ca6d7ca 100644 --- a/maps/feature-map/chat-channels.md +++ b/maps/feature-map/chat-channels.md @@ -251,7 +251,7 @@ Capability ID: `chat-channels/attachments`. Scope: ui Storybook: Mount TaskChatBubble attachments and ChatEndpointDetail provider-specific consent/upload/delivery failure and unknown-outcome states. Local email attachment dialog remains a prototype. Production: Transfer a disposable supported file through each affected provider; verify recipient delivery, read scope, duplicate/replay handling and failure/unknown state without treating notification as file-upload proof. -Sources: Source: [TaskChatBubble.tsx](../../ui/src/components/task-chat/TaskChatBubble.tsx), [ChatEndpointDetail.tsx](../../ui/src/pages/apps/chat/ChatEndpointDetail.tsx), [chatEndpoints.ts](../../ui/src/api/chatEndpoints.ts), [chat-channels.ts](../../server/src/routes/chat-channels.ts). Tests: [TaskChatBubble.test.tsx](../../ui/src/components/task-chat/TaskChatBubble.test.tsx), [task-chat-attachments.test.ts](../../ui/src/components/task-chat/task-chat-attachments.test.ts), [chat-channels.integration.test.ts](../../server/src/__tests__/chat-channels.integration.test.ts), [issue-attachment-routes.test.ts](../../server/src/__tests__/issue-attachment-routes.test.ts) +Sources: Source: [TaskChatBubble.tsx](../../ui/src/components/task-chat/TaskChatBubble.tsx), [ChatEndpointDetail.tsx](../../ui/src/pages/apps/chat/ChatEndpointDetail.tsx), [chatEndpoints.ts](../../ui/src/api/chatEndpoints.ts), [chat-channels.ts](../../server/src/routes/chat-channels.ts). Tests: [task-chat-attachments.test.ts](../../ui/src/components/task-chat/task-chat-attachments.test.ts), [chat-channels.integration.test.ts](../../server/src/__tests__/chat-channels.integration.test.ts), [issue-attachment-routes.test.ts](../../server/src/__tests__/issue-attachment-routes.test.ts) ### Documentation scope: Chat and email channel setup diff --git a/maps/feature-map/companies.md b/maps/feature-map/companies.md index c10d3ead5df..33d3889d6b0 100644 --- a/maps/feature-map/companies.md +++ b/maps/feature-map/companies.md @@ -46,7 +46,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `company-switcher` -Automated: [company list](../../ui/src/pages/Companies.test.tsx) and [archive UI](../../ui/src/pages/CompanySettingsArchive.test.tsx) cover UI behavior with mocks. +Automated: none for mocked UI pages (mocked `Companies` and `CompanySettingsArchive` component tests were removed; see [CompanyContext.test.tsx](../../ui/src/context/CompanyContext.test.tsx) and server tests in Storybook/Production entries below). Manual: Create or select a company, rename it, and reload. Switch to the second company and back; verify tasks, agents, and settings follow the selection. Archive the disposable company and verify its visibility and offered restoration path. @@ -58,11 +58,10 @@ Manual: Export a small company, inspect the package preview, and import into a d ### `company-ai-services` -Automated: [decision settings](../../ui/src/components/decision-models/DecisionModelSettings.test.tsx), -[decision history](../../ui/src/components/decision-models/DecisionHistory.test.tsx), -[fast-response settings](../../ui/src/components/fast-responses/FastResponseSettings.test.tsx), -[decision service](../../server/src/__tests__/decision-models.test.ts), and +Automated: +[decision service](../../server/src/__tests__/decision-models.test.ts) and [fast-response service](../../server/src/__tests__/fast-responses.test.ts) cover +server behavior (mocked UI tests for decision settings, decision history, and fast-response settings were removed; verify settings UI manually). component and service contracts with simulated providers. Manual: As an authorized connection manager, select a disposable shared AI @@ -95,7 +94,7 @@ Capability ID: `companies/selection`. Scope: ui Storybook: Company list/create/switcher; empty, loading, error, unavailable company and switched navigation. Production: Switch and reload between companies; verify tasks/agents/cache/routes remain scoped and unauthorized company requests fail. -Sources: Source: [Companies.tsx](../../ui/src/pages/Companies.tsx), [CompanySwitcher.tsx](../../ui/src/components/CompanySwitcher.tsx), [CompanyContext.tsx](../../ui/src/context/CompanyContext.tsx). Tests: [Companies.test.tsx](../../ui/src/pages/Companies.test.tsx), [CompanyContext.test.tsx](../../ui/src/context/CompanyContext.test.tsx), [companies-route-cross-company-authz.test.ts](../../server/src/__tests__/companies-route-cross-company-authz.test.ts) +Sources: Source: [Companies.tsx](../../ui/src/pages/Companies.tsx), [CompanySwitcher.tsx](../../ui/src/components/CompanySwitcher.tsx), [CompanyContext.tsx](../../ui/src/context/CompanyContext.tsx). Tests: [CompanyContext.test.tsx](../../ui/src/context/CompanyContext.test.tsx), [companies-route-cross-company-authz.test.ts](../../server/src/__tests__/companies-route-cross-company-authz.test.ts) #### `archive` @@ -104,7 +103,7 @@ Capability ID: `companies/archive`. Scope: ui Storybook: Archive confirmation, pending/error and departure navigation; archived list entry and Unarchive action. Production: Archive eligible agents/runs without deleting history; restoration handles archival-specific pause and navigates to correct company. -Sources: Source: [CompanySettings.tsx](../../ui/src/pages/CompanySettings.tsx), [Companies.tsx](../../ui/src/pages/Companies.tsx), [companies.ts](../../ui/src/api/companies.ts). Tests: [CompanySettingsArchive.test.tsx](../../ui/src/pages/CompanySettingsArchive.test.tsx), [Companies.test.tsx](../../ui/src/pages/Companies.test.tsx), [companies-service.test.ts](../../server/src/__tests__/companies-service.test.ts) +Sources: Source: [CompanySettings.tsx](../../ui/src/pages/CompanySettings.tsx), [Companies.tsx](../../ui/src/pages/Companies.tsx), [companies.ts](../../ui/src/api/companies.ts). Tests: [companies-service.test.ts](../../server/src/__tests__/companies-service.test.ts) #### `portability` @@ -113,7 +112,7 @@ Capability ID: `companies/portability`. Scope: ui Storybook: Import/export preview, conflict choice, warnings, async progress/failure/success and restricted managed deployment. Production: Apply real small package to disposable target; inspect counts/references/conflicts, source immutability and credential exclusions; imported task requires separate runnable-account proof. -Sources: Source: [CompanyImport.tsx](../../ui/src/pages/CompanyImport.tsx), [CompanyExport.tsx](../../ui/src/pages/CompanyExport.tsx), [companies.ts](../../ui/src/api/companies.ts). Tests: [CompanyImport.test.tsx](../../ui/src/pages/CompanyImport.test.tsx), [CompanyExport.test.tsx](../../ui/src/pages/CompanyExport.test.tsx), [company-portability-routes.test.ts](../../server/src/__tests__/company-portability-routes.test.ts), [company-import-export-e2e.test.ts](../../cli/src/__tests__/company-import-export-e2e.test.ts) +Sources: Source: [CompanyImport.tsx](../../ui/src/pages/CompanyImport.tsx), [CompanyExport.tsx](../../ui/src/pages/CompanyExport.tsx), [companies.ts](../../ui/src/api/companies.ts). Tests: [company-portability-routes.test.ts](../../server/src/__tests__/company-portability-routes.test.ts), [company-import-export-e2e.test.ts](../../cli/src/__tests__/company-import-export-e2e.test.ts) ### Documentation scope: Company and instance administration diff --git a/maps/feature-map/connection-setup.md b/maps/feature-map/connection-setup.md index 532cf1a1b59..797b2725338 100644 --- a/maps/feature-map/connection-setup.md +++ b/maps/feature-map/connection-setup.md @@ -101,15 +101,14 @@ do not establish OAuth registration, public callbacks, or production provider ac ### `apps-catalog` -Automated: [Browse](../../ui/src/pages/apps/Browse.test.tsx), -[unconnected app](../../ui/src/pages/apps/AppNotConnected.test.tsx), and -[AppsConnect](../../ui/src/pages/apps/AppsConnect.test.tsx) cover catalog entry, -access selection, provider-specific method choices, and setup failures with -mocked APIs. [Connection intents](../../tests/e2e/connection-intents.spec.ts) +Automated: [Browse](../../ui/src/pages/apps/Browse.test.tsx) covers catalog entry +with mocked APIs (mocked `AppNotConnected` and `AppsConnect` component tests were +removed; coverage for access selection, method choices, and setup failures now relies +on browser/manual checks). [Connection intents](../../tests/e2e/connection-intents.spec.ts) drives store and task setup against one fake provider through a useful continuation: ```sh -pnpm exec vitest run ui/src/pages/apps/Browse.test.tsx ui/src/pages/apps/AppsConnect.test.tsx +pnpm exec vitest run ui/src/pages/apps/Browse.test.tsx pnpm exec playwright test -c tests/e2e/playwright.config.ts tests/e2e/connection-intents.spec.ts ``` @@ -197,10 +196,11 @@ task does not grant the right to resolve the request. ### `resume-connection` -Automated: AppsConnect tests cover exact-draft resume, declined OAuth, reconnect -lookup failure/retry, response-lost creation, archived connection revival, and -saved account reuse. [App detail](../../ui/src/pages/apps/AppDetail.test.tsx) covers -the connection host. These tests do not complete a real provider login. +Automated: none for mocked UI flows (`AppsConnect` and `AppDetail` component tests +covering draft resume, declined OAuth, reconnect retry, archived connection revival, +saved account reuse, and the connection host were removed; rely on +[Connection intents](../../tests/e2e/connection-intents.spec.ts) and manual checks +below). None of these checks complete a real provider login. Manual: leave setup through its footer, reload Apps, choose Finish setup, and confirm the same connection is resumed. Decline provider login and recover from @@ -209,11 +209,12 @@ action afterwards. Count connections before/after to catch accidental duplicates ### `chat-channel` -Automated: [setup routing](../../ui/src/pages/apps/chat/ChatEndpointSetup.routing.test.tsx), -[saved setup state](../../ui/src/pages/apps/chat/ChatEndpointSetup.state.test.ts), -[email setup](../../ui/src/pages/apps/chat/EmailEndpointSetup.test.tsx), and -[identity confirmation](../../ui/src/pages/apps/chat/ChatIdentityConfirm.test.tsx) -cover shared UI logic with fixtures. Provider-specific live setup is not implied. +Automated: +[saved setup state](../../ui/src/pages/apps/chat/ChatEndpointSetup.state.test.ts) +covers saved setup-state logic with fixtures (mocked UI tests for setup routing, +email setup, and identity confirmation were removed; verify those UI flows via +[chat adapters E2E](../../tests/e2e/chat-adapters-ui-providers.spec.ts) and manual +checks). Provider-specific live setup is not implied. [Channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) also covers bounded Telegram subscription recovery at startup and after committed diff --git a/maps/feature-map/developer-labs.md b/maps/feature-map/developer-labs.md index 93ff71d70af..f198e43fb38 100644 --- a/maps/feature-map/developer-labs.md +++ b/maps/feature-map/developer-labs.md @@ -35,13 +35,13 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `preview-lab` -Automated: [onboarding variant](../../ui/src/components/OnboardingWizardVariant.test.tsx) is an example component contract. There is no claim of full automated acceptance coverage for every lab page. +Automated: none (the mocked onboarding-variant component test was removed; there is no automated acceptance coverage for lab pages — verify manually). Manual: Open the specific fixture state, inspect controls and layout, then repeat the affected interaction in the actual product host. Report fixture results separately from persisted task/company results. ### `performance-fixture` -Automated: [task thread component](../../ui/src/components/IssueChatThread.test.tsx) does not establish a performance budget. Timing/scroll measurements need a dedicated browser run. +Automated: none (mocked `IssueChatThread` component tests were removed and did not establish a performance budget). Timing/scroll measurements need a dedicated browser run. Manual: Record browser/build/data size, exercise scrolling and rendering in the long-thread fixture, and retain timing or trace evidence. Its composer is diff --git a/maps/feature-map/documents-artifacts.md b/maps/feature-map/documents-artifacts.md index 979c6ae72c5..59c40226a58 100644 --- a/maps/feature-map/documents-artifacts.md +++ b/maps/feature-map/documents-artifacts.md @@ -70,9 +70,9 @@ desktop, mobile, and Classic document views with real uploaded images and saved document revisions. It covers keyboard/button navigation, image URLs and reload, focus return, focus containment, scroll locking, dismissal, and revision links. -[Exact revision panel](../../ui/src/components/task-side-panel/TaskDocumentPanel.test.tsx) -checks pinned content and missing-revision behavior; this component test does not -prove end-to-end conversation scrolling. Open a resolved receipt after making a +Mocked `TaskDocumentPanel` component tests for pinned content and missing-revision +behavior were removed (verify pinned revisions manually alongside the browser +gallery suite above). Open a resolved receipt after making a new revision and verify the earlier body plus matching interaction in the browser. Manual: Edit a paragraph, save, reload, and compare revisions. Add an annotation to a specific selection and inspect it after another edit. Resolve it through the supported action. Restore a disposable revision and confirm the new current document and history agree. @@ -91,7 +91,7 @@ Test an inaccessible user/company and explicit missing workspace-only resources. ### `artifact-library` -Automated: [artifact page](../../ui/src/pages/Artifacts.test.tsx) covers grouping, search requests, and pagination using mocks. +Automated: none for mocked UI (`Artifacts` page component tests were removed; verify grouping, search, and pagination manually). Manual: Find the task’s output through search and grouping, open its stack, page through results, and reload a direct stack link. Confirm the same file/content appears as from the task. @@ -110,7 +110,7 @@ Capability ID: `documents-artifacts/documents`. Scope: ui Storybook: Writable/read-only document, save pending/failure/conflict, revision history/historical preview and restore confirmation. Production: Persist edited body and reload; append-only restore creates new revision; reject stale writes and inaccessible company/task. -Sources: Source: [IssueDocumentsSection.tsx](../../ui/src/components/IssueDocumentsSection.tsx), [TaskDocumentPanel.tsx](../../ui/src/components/task-side-panel/TaskDocumentPanel.tsx), [documents.ts](../../server/src/services/documents.ts). Tests: [IssueDocumentsSection.test.tsx](../../ui/src/components/IssueDocumentsSection.test.tsx), [document-revisions.test.ts](../../ui/src/lib/document-revisions.test.ts), [documents-service.test.ts](../../server/src/__tests__/documents-service.test.ts), [issue-document-restore-routes.test.ts](../../server/src/__tests__/issue-document-restore-routes.test.ts) +Sources: Source: [IssueDocumentsSection.tsx](../../ui/src/components/IssueDocumentsSection.tsx), [TaskDocumentPanel.tsx](../../ui/src/components/task-side-panel/TaskDocumentPanel.tsx), [documents.ts](../../server/src/services/documents.ts). Tests: [document-revisions.test.ts](../../ui/src/lib/document-revisions.test.ts), [documents-service.test.ts](../../server/src/__tests__/documents-service.test.ts), [issue-document-restore-routes.test.ts](../../server/src/__tests__/issue-document-restore-routes.test.ts) ### Documentation scope: Artifacts and work products diff --git a/maps/feature-map/execution-environments.md b/maps/feature-map/execution-environments.md index 7ab182c020d..e9584bc1684 100644 --- a/maps/feature-map/execution-environments.md +++ b/maps/feature-map/execution-environments.md @@ -40,7 +40,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `environment-settings` -Automated: [environment UI](../../ui/src/pages/CompanyEnvironments.test.tsx), [driver configuration UI](../../ui/src/pages/CompanySettings.test.tsx), and [environment service](../../server/src/__tests__/environment-service.test.ts) cover configuration behavior. +Automated: [environment service](../../server/src/__tests__/environment-service.test.ts) covers server configuration behavior (mocked `CompanyEnvironments` and `CompanySettings` UI tests were removed; verify settings UI via Storybook/manual checks). Manual: Save a disposable target, reload it, and run its available probe. Verify both success and missing-credential/reachability errors identify the target. Confirm unavailable providers are not offered as working run targets. @@ -140,7 +140,7 @@ Capability ID: `execution-environments/configuration`. Scope: ui Storybook: Local/SSH/sandbox editors; unavailable providers, missing credentials, save pending/error and restricted operator. Production: Persist target configuration and enforce instance-admin/local-operator mutation boundary; target catalog is instance-scoped. -Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environments.ts](../../server/src/routes/environments.ts). Tests: [CompanyEnvironments.test.tsx](../../ui/src/pages/CompanyEnvironments.test.tsx), [environment-service.test.ts](../../server/src/__tests__/environment-service.test.ts) +Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environments.ts](../../server/src/routes/environments.ts). Tests: [environment-service.test.ts](../../server/src/__tests__/environment-service.test.ts) #### `capabilities` @@ -158,7 +158,7 @@ Capability ID: `execution-environments/probe`. Scope: ui Storybook: Remote Test pending, success, reachability/auth failure and platform qualification absent/invalidated notice. Production: Probe actual owned target; verify selected saved immutable config/image/company qualification plus lease cleanup; local API probe proves host/cwd only and has no UI Test button. -Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environment-probe.ts](../../server/src/services/environment-probe.ts). Tests: [CompanyEnvironments.test.tsx](../../ui/src/pages/CompanyEnvironments.test.tsx), [environment-probe.test.ts](../../server/src/__tests__/environment-probe.test.ts), [environment-live-ssh.test.ts](../../server/src/__tests__/environment-live-ssh.test.ts) +Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environment-probe.ts](../../server/src/services/environment-probe.ts). Tests: [environment-probe.test.ts](../../server/src/__tests__/environment-probe.test.ts), [environment-live-ssh.test.ts](../../server/src/__tests__/environment-live-ssh.test.ts) #### `images` @@ -167,7 +167,7 @@ Capability ID: `execution-environments/images`. Scope: ui Storybook: Custom-image setup/capture/progress, terminal connect/disconnect/failure, unsupported capability and active-image drift. Production: Execute owned provider setup/capture/probe/terminal transport with correct saved image identity, authority, cleanup and shutdown; terminal screenshot cannot prove operation. -Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environment-custom-images.ts](../../server/src/services/environment-custom-images.ts). Tests: [CompanyEnvironments.test.tsx](../../ui/src/pages/CompanyEnvironments.test.tsx), [environment-custom-images-service.test.ts](../../server/src/__tests__/environment-custom-images-service.test.ts) +Sources: Source: [CompanyEnvironments.tsx](../../ui/src/pages/CompanyEnvironments.tsx), [environment-custom-images.ts](../../server/src/services/environment-custom-images.ts). Tests: [environment-custom-images-service.test.ts](../../server/src/__tests__/environment-custom-images-service.test.ts) Managed account transfer requires `projectAuthCheckVersion: 1` and a successful `check_project_auth` result for the exact prepared configuration, provider, and diff --git a/maps/feature-map/gateways-profiles.md b/maps/feature-map/gateways-profiles.md index 94726ade27a..9f1e130a982 100644 --- a/maps/feature-map/gateways-profiles.md +++ b/maps/feature-map/gateways-profiles.md @@ -41,7 +41,7 @@ endpoint authorization independently of whether the admin UI is visible. ### `gateway-client` -Automated: [gateway service](../../server/src/__tests__/tool-gateway-service.test.ts), [connect client dialog](../../ui/src/pages/apps/gateways/ConnectClientDialog.test.tsx), and [token panel](../../ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx) cover service/UI contracts. +Automated: [gateway service](../../server/src/__tests__/tool-gateway-service.test.ts) and [token panel](../../ui/src/pages/apps/gateways/panels/TokensPanel.test.tsx) cover service and token-panel contracts (mocked `ConnectClientDialog` UI tests were removed; verify the connect-client dialog manually). Gateway regressions also cover a failed remote call followed by a successful sibling tool call. Transient failures preserve the catalog. Authentication @@ -53,7 +53,7 @@ Manual: Create a disposable gateway with one harmless tool, connect a client usi ### `access-profile` -Automated: [profile wizard](../../ui/src/pages/tools/profiles/ProfileWizard.test.tsx) and [profile detail](../../ui/src/pages/tools/profiles/ProfileDetail.test.tsx) cover component behavior with mocks. +Automated: none for mocked UI (`ProfileWizard` and `ProfileDetail` component tests were removed; see backend test below and verify UI manually). Backend: [profile entry validation](../../server/src/__tests__/tool-profile-entry-validation.test.ts) uses isolated PostgreSQL to create and replace a 518-selector assignment with diff --git a/maps/feature-map/goals.md b/maps/feature-map/goals.md index f95f28fea05..5b44840464f 100644 --- a/maps/feature-map/goals.md +++ b/maps/feature-map/goals.md @@ -34,7 +34,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Prep ### `goal-detail` -Automated: [project-goal validation](../../server/src/__tests__/project-goal-validation.test.ts) covers relationship validation; [goal detail control](../../ui/src/pages/GoalDetail.test.tsx) only tests the properties toggle, not the whole creation journey. +Automated: [project-goal validation](../../server/src/__tests__/project-goal-validation.test.ts) covers relationship validation (mocked `GoalDetail` UI tests were removed; verify goal detail UI manually). Manual: Choose **Add Goal/New Goal**, enter **Goal title**, select the level, and create a parent. Open it and choose **Sub Goal** to create a child with the @@ -72,7 +72,7 @@ Capability ID: `goals/navigation`. Scope: ui Storybook: Parent/child goal and project/task context links, empty/unavailable context and permitted destination. Production: Follow actual goal/project/task records and compare explicit versus inherited context; ensure reload and inaccessible destination behavior. -Sources: Source: [GoalDetail.tsx](../../ui/src/pages/GoalDetail.tsx), [GoalProperties.tsx](../../ui/src/components/GoalProperties.tsx). Tests: [GoalDetail.test.tsx](../../ui/src/pages/GoalDetail.test.tsx), [issues-goal-context-routes.test.ts](../../server/src/__tests__/issues-goal-context-routes.test.ts), [issue-goal-fallback.test.ts](../../server/src/__tests__/issue-goal-fallback.test.ts) +Sources: Source: [GoalDetail.tsx](../../ui/src/pages/GoalDetail.tsx), [GoalProperties.tsx](../../ui/src/components/GoalProperties.tsx). Tests: [issues-goal-context-routes.test.ts](../../server/src/__tests__/issues-goal-context-routes.test.ts), [issue-goal-fallback.test.ts](../../server/src/__tests__/issue-goal-fallback.test.ts) ### Documentation scope: Goals, dashboards, costs, and activity diff --git a/maps/feature-map/inbox-search.md b/maps/feature-map/inbox-search.md index 7568c7ac505..112f5178910 100644 --- a/maps/feature-map/inbox-search.md +++ b/maps/feature-map/inbox-search.md @@ -165,10 +165,10 @@ company/private-task isolation, and private v1 targets. [Attention service regressions](../../server/src/__tests__/attention-service.test.ts) cover pending question forms and confirmations in persistent agent chats, removal after an answer with retained history, and company/task-visibility/addressee checks. -Idle chats without structured requests remain absent. The -[Inbox component test](../../ui/src/components/coordinator/CoordinatorNeedsYou.test.tsx) -checks that a chat-sourced canonical question reaches its original resolver and context. -Idle chats without structured requests remain absent. +Idle chats without structured requests remain absent. (Mocked +`CoordinatorNeedsYou` UI component tests for chat-sourced canonical question +routing were removed; verify Inbox card routing manually alongside the server +tests above.) [Audience, badge and claim tests](../../server/src/__tests__/attention-audience-service.test.ts) cover the view partition, the For you badge with per-view counts, the personal `view=archived` list and its tab count, and the claim service and route @@ -195,17 +195,13 @@ route tests cover the active-member 422 and board-only writes. [Obligation tests](../../server/src/__tests__/attention-obligations.test.ts) cover the approval/review, budget-stop/override-approval and blocked-task/failed-run joins, the separate human review gate, placement with the blocked task's person, one count per obligation, -evidence that hides and restores with its lead, and the split after an answer. The -[Needs You component test](../../ui/src/components/coordinator/CoordinatorNeedsYou.test.tsx) -checks that a chat-sourced canonical question reaches its original resolver and context, -and the view switch, banner, Why me?, For @name and Claim, and Everyone for a board member only (with the withdraw confirmation for another person's card); the -[classic page view test](../../ui/src/pages/WhatNeedsMe.views.test.tsx) checks the same on Decisions, -plus the Archived view with Restore, Change time and Decision history on both pages. +evidence that hides and restores with its lead, and the split after an answer. +(Mocked UI component tests for `CoordinatorNeedsYou`, `WhatNeedsMe`, and +`CoordinatorTaskCommitment` were removed; UI view switching, Archived/Restore, +and reduced-motion card behavior are demonstrated in the Storybook stories below +and should be verified manually.) The [Decisions views stories](../../ui/storybook/stories/inbox-search/needs-you-views.stories.tsx) show For you, Unassigned, Company, Archived, Everyone, a different person's cards, one card for each obligation and the escalation owners (including the budget owner's hard stop in another person's Company view). -It also checks simultaneous resize/light and delayed movement to Recent Decisions. -[Shared card-motion tests](../../ui/src/components/coordinator/CoordinatorTaskCommitment.test.tsx) -cover reduced-motion settlement and returning to a resolved card without replay. The [decision-motion stories](../../ui/storybook/stories/design-proposals/coordinator-decision-motion.stories.tsx) exercise real Inbox/resolver components with isolated approval, question, and failed-save responses. [Projection helpers](../../ui/src/lib/coordinator-attention.test.ts) cover distinct @@ -216,7 +212,7 @@ task context on receipt click. Turning the setting off restores the classic surf ### `search` -Automated: [search page](../../ui/src/pages/Search.test.tsx) and [company search service](../../server/src/__tests__/company-search-service.test.ts) cover UI and server search separately. +Automated: [company search service](../../server/src/__tests__/company-search-service.test.ts) covers server search contracts (mocked `Search` page UI tests were removed; verify search page UI manually). Manual: Search a unique task title and content phrase, open the result, and compare the actual record. Test filters, no results, and a second company. Verify stale results do not expose inaccessible data. diff --git a/maps/feature-map/instance-operations.md b/maps/feature-map/instance-operations.md index 6ff9a9b0633..13aa0e8b63b 100644 --- a/maps/feature-map/instance-operations.md +++ b/maps/feature-map/instance-operations.md @@ -69,7 +69,7 @@ unfinished application write must still prevent sleep after its client leaves. ### `settings-backup` -Automated: [experimental settings](../../ui/src/pages/InstanceExperimentalSettings.test.tsx) and [database backup routes](../../server/src/__tests__/instance-database-backups-routes.test.ts) cover their UI/API contracts. +Automated: [database backup routes](../../server/src/__tests__/instance-database-backups-routes.test.ts) covers API backup contracts (mocked `InstanceExperimentalSettings` UI tests were removed; verify settings UI via Storybook/manual checks). Cloud migration: in one maintenance window, stop legacy file writers and run the [configuration/package qualification command](../../doc/cloud-configuration-migration.md). @@ -135,7 +135,7 @@ Capability ID: `instance-operations/backup`. Scope: ui Storybook: Mount shipped InstanceGeneralSettings in CompanySettings with daily/weekly/monthly retention presets, selected values, saving/error/loading and cloud-hidden controls. Backup creation and restore remain separate CLI/operator checks. Production: PATCH /api/instance/settings/general must enforce instance settings authority and managed hidden fields, persist retention and survive reload. Separately inspect a real backup and restore a known record into a second disposable target; a successful write does not prove restoration. -Sources: Source: [InstanceGeneralSettings.tsx](../../ui/src/pages/InstanceGeneralSettings.tsx), [CompanySettings.tsx](../../ui/src/pages/CompanySettings.tsx), [instance-settings.ts](../../server/src/routes/instance-settings.ts), [db-backup.ts](../../cli/src/commands/db-backup.ts). Tests: [InstanceGeneralSettings.test.tsx](../../ui/src/pages/InstanceGeneralSettings.test.tsx), [instance-settings-routes.test.ts](../../server/src/__tests__/instance-settings-routes.test.ts), [instance-settings-managed-overlay.test.ts](../../server/src/__tests__/instance-settings-managed-overlay.test.ts), [instance-database-backups-routes.test.ts](../../server/src/__tests__/instance-database-backups-routes.test.ts) +Sources: Source: [InstanceGeneralSettings.tsx](../../ui/src/pages/InstanceGeneralSettings.tsx), [CompanySettings.tsx](../../ui/src/pages/CompanySettings.tsx), [instance-settings.ts](../../server/src/routes/instance-settings.ts), [db-backup.ts](../../cli/src/commands/db-backup.ts). Tests: [instance-settings-routes.test.ts](../../server/src/__tests__/instance-settings-routes.test.ts), [instance-settings-managed-overlay.test.ts](../../server/src/__tests__/instance-settings-managed-overlay.test.ts), [instance-database-backups-routes.test.ts](../../server/src/__tests__/instance-database-backups-routes.test.ts) #### `install-update` diff --git a/maps/feature-map/navigation-preferences.md b/maps/feature-map/navigation-preferences.md index 92c03bc2cb0..0cafcd33680 100644 --- a/maps/feature-map/navigation-preferences.md +++ b/maps/feature-map/navigation-preferences.md @@ -41,7 +41,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `sidebar-deep-links` -Automated: [sidebar](../../ui/src/components/Sidebar.test.tsx) and [sidebar preference routes](../../server/src/__tests__/sidebar-preferences-routes.test.ts) cover UI/server behavior. +Automated: [sidebar preference routes](../../server/src/__tests__/sidebar-preferences-routes.test.ts) covers server preference contracts (mocked `Sidebar` component tests were removed; verify sidebar UI via Storybook/manual checks). Manual: Star and reorder supported resources, collapse a section, navigate and reload. Switch company/user and inspect the intended preference scope. Open an unavailable resource and a legacy route; verify clear fallback or correct redirect without leaking another company’s state. @@ -52,13 +52,13 @@ ordering are saved server-side. Local-trusted mode does not prove two-user isola ### `profile-announcements` -Automated: [profile page](../../ui/src/pages/ProfileSettings.test.tsx), [announcement hook](../../ui/src/hooks/useAnnouncement.test.tsx), and [announcement routes](../../server/src/__tests__/announcements-routes.test.ts) cover separate UI/persistence layers. +Automated: [announcement hook](../../ui/src/hooks/useAnnouncement.test.tsx) and [announcement routes](../../server/src/__tests__/announcements-routes.test.ts) cover hook and server persistence layers (mocked `ProfileSettings` page tests were removed; verify profile UI manually). Manual: Change a disposable user’s display details, reload, and inspect an attributed profile link. Dismiss a fixture announcement, switch companies, and verify it remains dismissed for that user; check another user still has their own dismissal state. ### `palette-shortcuts` -Automated: [Command palette](../../ui/src/components/CommandPalette.test.tsx), [shortcut hook](../../ui/src/hooks/useKeyboardShortcuts.test.tsx), [shortcut rules](../../ui/src/lib/keyboardShortcuts.test.ts), and [cheatsheet](../../ui/src/components/KeyboardShortcutsCheatsheet.test.tsx) test components and keyboard rules. [Company search](../../server/src/__tests__/company-search-service.test.ts) covers search contracts; browser focus and identity transitions still need a live check. +Automated: [shortcut hook](../../ui/src/hooks/useKeyboardShortcuts.test.tsx) and [shortcut rules](../../ui/src/lib/keyboardShortcuts.test.ts) test keyboard rules (mocked `CommandPalette` and `KeyboardShortcutsCheatsheet` component tests were removed; verify those dialogs manually). [Company search](../../server/src/__tests__/company-search-service.test.ts) covers search contracts; browser focus and identity transitions still need a live check. Manual: Use uniquely named visible and private task/project fixtures. Open the palette, find a permitted result, follow it, and reload the destination. Enter text with quick-filter chips such as `assignee:me`, `is:open`, and `updated:>7d`; use Search all and Cmd/Ctrl+Enter in separate attempts and verify the resulting query and filters. Switch person/company and confirm private results do not leak. Test `/` on a page with search and a page without it; inspect `?`, `c`, and `g i`. Type those keys inside an editor and a modal: they must not unexpectedly navigate or create work. Test a create action through its normal dialog and inspect the actual saved resource separately. @@ -81,7 +81,7 @@ Capability ID: `navigation-preferences/preferences`. Scope: ui Storybook: Mount Sidebar using real preference boundary with stars/order/collapse/recents state. Clearly distinguish in-memory section collapse, browser-local recents and server-saved stars/order. Production: GET/PUT /sidebar-preferences/me and /companies/{id}/sidebar-preferences/me plus stars must retain intended user/company isolation across reload and switch. Section collapse reopens after reload; global collapse is disabled. -Sources: Source: [Sidebar.tsx](../../ui/src/components/Sidebar.tsx), [sidebar-preferences.ts](../../server/src/routes/sidebar-preferences.ts), [sidebar-preferences.ts](../../server/src/services/sidebar-preferences.ts). Tests: [Sidebar.test.tsx](../../ui/src/components/Sidebar.test.tsx), [sidebar-preferences-routes.test.ts](../../server/src/__tests__/sidebar-preferences-routes.test.ts) +Sources: Source: [Sidebar.tsx](../../ui/src/components/Sidebar.tsx), [sidebar-preferences.ts](../../server/src/routes/sidebar-preferences.ts), [sidebar-preferences.ts](../../server/src/services/sidebar-preferences.ts). Tests: [sidebar-preferences-routes.test.ts](../../server/src/__tests__/sidebar-preferences-routes.test.ts) #### `fallbacks` @@ -90,7 +90,7 @@ Capability ID: `navigation-preferences/fallbacks`. Scope: browser Storybook: A NotFound rendering story can help polish, but missing-resource/legacy-deep-link capability principally needs real App/router/browser scenarios preserving company and query intent. Production: Cold-open invalid company/resource and retired URL; verify explicit fallback or correct canonical redirect without silently targeting a different resource/company. -Sources: Source: [NotFound.tsx](../../ui/src/pages/NotFound.tsx), [App.tsx](../../ui/src/App.tsx), [company-routes.ts](../../ui/src/lib/company-routes.ts). Tests: [App.activity-routing.test.tsx](../../ui/src/App.activity-routing.test.tsx), [App.cases-routing.test.tsx](../../ui/src/App.cases-routing.test.tsx), [App.test.tsx](../../ui/src/App.test.tsx), [company-routes.test.ts](../../ui/src/lib/company-routes.test.ts) +Sources: Source: [NotFound.tsx](../../ui/src/pages/NotFound.tsx), [App.tsx](../../ui/src/App.tsx), [company-routes.ts](../../ui/src/lib/company-routes.ts). Tests: [App.test.tsx](../../ui/src/App.test.tsx), [company-routes.test.ts](../../ui/src/lib/company-routes.test.ts) ### Recent task refresh performance @@ -111,9 +111,9 @@ Agent Chat is available to everyone independently of this personal workspace choice. Its retired instance flag and historical managed off values are ignored. Automated: [preference hook](../../ui/src/hooks/useCoordinatorWorkspaceEnabled.test.tsx), -[Classic settings card](../../ui/src/components/ClassicWorkspaceSetting.test.tsx), [authorization](../../server/src/__tests__/workspace-preferences-routes.test.ts), and -[database persistence](../../server/src/__tests__/workspace-preferences.test.ts). +[database persistence](../../server/src/__tests__/workspace-preferences.test.ts) +(mocked `ClassicWorkspaceSetting` card UI tests were removed; verify card UI manually). Manual: toggle on/off, reload, switch companies/accounts, and simulate failed reads and saves. Confirm existing work is unchanged and a failed save keeps the current choice. The [Settings card story](../../ui/storybook/stories/navigation-preferences/coordinator-workspace-setting.stories.tsx) @@ -126,9 +126,9 @@ existing company-aware routes. Unpin from either the flyout or the pinned row. The list is personal to the current user in this browser, shared across companies; it does not sync across devices. Only known route names are rendered. Storage failures show a save error. -The [pin hook](../../ui/src/hooks/usePinnedNavigation.ts) owns browser persistence; -[sidebar tests](../../ui/src/components/CoordinatorSidebar.test.tsx) cover pin/unpin, -remount persistence, account separation, unknown routes and cross-tab updates. +The [pin hook](../../ui/src/hooks/usePinnedNavigation.ts) owns browser persistence +(mocked `CoordinatorSidebar` UI tests for pin/unpin, remount persistence, account +separation, and cross-tab updates were removed; verify via the manual checks below). Manual: pin with mouse and keyboard, reload, follow a pinned link, unpin from both locations, and check the mobile drawer. Local-trusted checks do not prove two-user authenticated browser isolation. diff --git a/maps/feature-map/onboarding.md b/maps/feature-map/onboarding.md index 56f7f03b898..9a64773adb7 100644 --- a/maps/feature-map/onboarding.md +++ b/maps/feature-map/onboarding.md @@ -50,7 +50,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `web-wizard` -Automated: [wizard tests](../../ui/src/components/OnboardingWizard.test.tsx) cover mocked wizard behavior; [onboarding browser suite](../../tests/e2e/onboarding.spec.ts) supplies its own test environment. Live model execution is a separate check. +Automated: [onboarding browser suite](../../tests/e2e/onboarding.spec.ts) supplies its own test environment (mocked `OnboardingWizard` component tests were removed). Live model execution is a separate check. - **Create company and resume.** Start a fresh empty instance and run doctor using the [verification skill](../../.agents/skills/verify-paperclip/SKILL.md). Run @@ -92,9 +92,8 @@ selected model and account stay unchanged and that the compatible executable is actually used. A failed installation still blocks hiring. Cloud failures must not display Manual debug shell commands or legacy operator hints; self-hosted failures retain that help. -[Wizard controls](../../ui/src/components/OnboardingWizard.test.tsx) and -[runtime controls](../../packages/adapters/claude-local/src/server/sandbox-cli-version.test.ts) -cover these boundaries. They do not establish live Cloud onboarding success. +[Runtime controls](../../packages/adapters/claude-local/src/server/sandbox-cli-version.test.ts) +cover the adapter runtime boundary (mocked `OnboardingWizard` component tests were removed; verify wizard error help manually). They do not establish live Cloud onboarding success. For a new Claude agent on an explicit immutable sandbox image or a Daytona named snapshot, use Connect to @@ -191,7 +190,7 @@ Capability ID: `onboarding/resume`. Scope: ui Storybook: Restored incomplete wizard; invalid or unauthorized saved company; temporarily withheld draft; account switch; storage failure. Production: Reload company-prefixed onboarding without duplicating company; restore only authorized account/company draft and retain input after recoverable loading failure. -Sources: Source: [OnboardingWizard.tsx](../../ui/src/components/OnboardingWizard.tsx), [onboarding-state.ts](../../ui/src/lib/onboarding-state.ts). Tests: [OnboardingWizard.test.tsx](../../ui/src/components/OnboardingWizard.test.tsx), [onboarding-state.test.ts](../../ui/src/lib/onboarding-state.test.ts), [onboarding.spec.ts](../../tests/e2e/onboarding.spec.ts) +Sources: Source: [OnboardingWizard.tsx](../../ui/src/components/OnboardingWizard.tsx), [onboarding-state.ts](../../ui/src/lib/onboarding-state.ts). Tests: [onboarding-state.test.ts](../../ui/src/lib/onboarding-state.test.ts), [onboarding.spec.ts](../../tests/e2e/onboarding.spec.ts) #### `instance` diff --git a/maps/feature-map/plugins.md b/maps/feature-map/plugins.md index abc295f409b..113ea769629 100644 --- a/maps/feature-map/plugins.md +++ b/maps/feature-map/plugins.md @@ -35,13 +35,13 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `plugin-administration` -Automated: [install authorization](../../server/src/__tests__/plugin-install-route-security.test.ts) and [plugin settings](../../ui/src/pages/PluginSettings.test.tsx) cover route/UI contracts. +Automated: [install authorization](../../server/src/__tests__/plugin-install-route-security.test.ts) covers route contracts (mocked `PluginSettings` UI tests were removed; verify plugin settings UI via Storybook/manual checks). Manual: Install the fixture, supply its configuration, activate it, and inspect status. Save an invalid configuration and verify a useful error. Disable/remove the disposable plugin and check its tools and managed resources no longer behave as active. ### `plugin-contribution` -Automated: [static plugin UI](../../server/src/__tests__/plugin-ui-static.test.ts) and [company settings contribution](../../ui/src/pages/CompanySettingsPluginPage.test.tsx) cover serving/host behavior. +Automated: [static plugin UI](../../server/src/__tests__/plugin-ui-static.test.ts) covers static asset serving (mocked `CompanySettingsPluginPage` UI tests were removed; verify contributed pages via Storybook/manual checks). Manual: Open the contributed page by navigation and cold deep link, perform a harmless plugin action, and inspect its real outcome. Switch company and test an actor without the capability. Reload with the plugin unavailable and verify the host reports that state. @@ -77,7 +77,7 @@ Capability ID: `plugins/configuration`. Scope: ui Storybook: Mount PluginSettings valid/invalid schema inputs, saved configuration, pending/failure and unavailable plugin. Production: GET/POST /plugins/{id}/config and POST config/test must preserve validation/company scope and deliver saved config to real plugin worker/startup. -Sources: Source: [PluginSettings.tsx](../../ui/src/pages/PluginSettings.tsx), [plugins.ts](../../server/src/routes/plugins.ts), [plugin-config-validator.ts](../../server/src/services/plugin-config-validator.ts). Tests: [PluginSettings.test.tsx](../../ui/src/pages/PluginSettings.test.tsx), [plugin-config-startup-delivery.test.ts](../../server/src/__tests__/plugin-config-startup-delivery.test.ts), [plugin-routes-authz.test.ts](../../server/src/__tests__/plugin-routes-authz.test.ts) +Sources: Source: [PluginSettings.tsx](../../ui/src/pages/PluginSettings.tsx), [plugins.ts](../../server/src/routes/plugins.ts), [plugin-config-validator.ts](../../server/src/services/plugin-config-validator.ts). Tests: [plugin-config-startup-delivery.test.ts](../../server/src/__tests__/plugin-config-startup-delivery.test.ts), [plugin-routes-authz.test.ts](../../server/src/__tests__/plugin-routes-authz.test.ts) #### `contributions` @@ -86,7 +86,7 @@ Capability ID: `plugins/contributions`. Scope: ui Storybook: Mount PluginPage and CompanySettingsPluginPage contributed routes/tabs, loading, missing/unavailable plugin and action failures with a known fixture plugin. Production: Serve real static plugin UI; enforce bridge data/action host capabilities and company boundaries; exercise a harmless action and cold deep link. -Sources: Source: [PluginPage.tsx](../../ui/src/pages/PluginPage.tsx), [CompanySettingsPluginPage.tsx](../../ui/src/pages/CompanySettingsPluginPage.tsx), [plugins.ts](../../server/src/routes/plugins.ts), [plugin-ui-static.ts](../../server/src/routes/plugin-ui-static.ts). Tests: [PluginPage.test.tsx](../../ui/src/pages/PluginPage.test.tsx), [CompanySettingsPluginPage.test.tsx](../../ui/src/pages/CompanySettingsPluginPage.test.tsx), [plugin-ui-static.test.ts](../../server/src/__tests__/plugin-ui-static.test.ts), [plugin-tenant-isolation.test.ts](../../server/src/__tests__/plugin-tenant-isolation.test.ts) +Sources: Source: [PluginPage.tsx](../../ui/src/pages/PluginPage.tsx), [CompanySettingsPluginPage.tsx](../../ui/src/pages/CompanySettingsPluginPage.tsx), [plugins.ts](../../server/src/routes/plugins.ts), [plugin-ui-static.ts](../../server/src/routes/plugin-ui-static.ts). Tests: [plugin-ui-static.test.ts](../../server/src/__tests__/plugin-ui-static.test.ts), [plugin-tenant-isolation.test.ts](../../server/src/__tests__/plugin-tenant-isolation.test.ts) #### `lifecycle` diff --git a/maps/feature-map/projects.md b/maps/feature-map/projects.md index ade1a4e0eeb..58962efff1b 100644 --- a/maps/feature-map/projects.md +++ b/maps/feature-map/projects.md @@ -43,13 +43,13 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `project-list` -Automated: [projects UI](../../ui/src/pages/Projects.test.tsx) and [project detail](../../ui/src/pages/ProjectDetail.test.tsx) are component tests. +Automated: none for mocked UI pages (`Projects` and `ProjectDetail` component tests were removed; verify project list and detail flows manually). Manual: Create a project, add a task from its view, and reload. Verify the task belongs to that project, list counts are plausible, and links preserve company scope. Archive only the disposable project and inspect list/task behavior. ### `repository-settings` -Automated: [provider defaults and API overrides](../../server/src/__tests__/project-workspace-provider.integration.test.ts) and [storage selection UI](../../ui/src/components/ProjectProperties.concurrency.test.tsx) cover saved storage, explicit overrides, and configuration errors. These offline checks do not qualify live provider storage. +Automated: [provider defaults and API overrides](../../server/src/__tests__/project-workspace-provider.integration.test.ts) covers saved storage, explicit overrides, and configuration errors (mocked `ProjectProperties` concurrency UI tests were removed; verify storage selection UI manually). These offline checks do not qualify live provider storage. Automated: [repository persistence](../../server/src/__tests__/project-repositories-persistence.test.ts) and [repository browser suite](../../tests/e2e/project-repositories.spec.ts) cover configured repository workflows. diff --git a/maps/feature-map/questions-and-approvals.md b/maps/feature-map/questions-and-approvals.md index b3a06880c68..3648347be4a 100644 --- a/maps/feature-map/questions-and-approvals.md +++ b/maps/feature-map/questions-and-approvals.md @@ -132,9 +132,9 @@ history remains and the conversation does not close as a completed task. ### `attention` -Automated: [attention resolver](../../ui/src/components/AttentionInteractionResolver.test.tsx) -covers preparing-request refresh without accepting it. The resolution-route -tests above cover the API, not every Decisions or Inbox navigation path. +Automated: the resolution-route tests above cover the API (mocked +`AttentionInteractionResolver` UI component tests were removed; verify +preparing-request refresh and Decisions/Inbox navigation manually). Manual: open the same pending request in an attention row and task tab. Resolve from the row; both surfaces must settle after refresh. Check an empty queue, diff --git a/maps/feature-map/recovery.md b/maps/feature-map/recovery.md index 4505b7f89d3..5d307ef91a5 100644 --- a/maps/feature-map/recovery.md +++ b/maps/feature-map/recovery.md @@ -303,8 +303,8 @@ and the revised behavior still needs live qualification. ### `run-detail` -Automated: [run workspace recovery](../../ui/src/components/RunWorkspaceRecoverySurface.test.tsx) -tests this host; it is component coverage, not an end-to-end repair. +Automated: none for mocked UI (`RunWorkspaceRecoverySurface` component tests were +removed; verify the run workspace recovery host manually). Manual: prepare a failed run with error code `workspace_validation_failed`, a linked source task, and a live `workspace_validation` recovery action on that @@ -335,11 +335,10 @@ provider stop reply, and verifies that HTTP Retry cannot admit a successor until the real temporary files are restored. Duplicate requests then admit one queued turn. GitHub and Telegram admission also retain the exact pending recovery. -Automated: [disposition notices](../../ui/src/components/DispositionRecoveryNotice.test.tsx) -tests pending/error/gated states and waiting for the real retry acknowledgement. -The recovery-card suite covers workspace divergence, reissue, reconcile, and -confirmation. [Workspace export](../../ui/src/components/WorkspaceExportRecovery.test.tsx) -covers quiet restoration, legacy/operator assistance and resolved states. +Automated: [IssueRecoveryActionCard](../../ui/src/components/IssueRecoveryActionCard.test.tsx) +covers workspace divergence, reissue, reconcile, and confirmation (mocked UI tests +for `DispositionRecoveryNotice` and `WorkspaceExportRecovery` were removed; verify +those notice and export states via Storybook/manual checks). For a retained legacy or native file hold, open the source task after its recovery action has resolved but its files still need recovery. The shared task projection @@ -348,10 +347,9 @@ infrastructure attention card. Unknown external outcomes remain fenced internall An authorized board operator can use the resolution API to record verified files and a backup link without changing task status or starting another run. The server independently validates the original stopped-execution receipt. Agent -Chat retains the hold rather than suggesting another message. The -[notice](../../ui/src/components/ExecutionBlockerNotice.test.tsx) and -[repair route](../../server/src/__tests__/workspace-restore-repair-route.test.ts) -cover quiet live recovery, read-only access, stale or missing stop proof, +Chat retains the hold rather than suggesting another message. The [repair route](../../server/src/__tests__/workspace-restore-repair-route.test.ts) +covers quiet live recovery, read-only access, stale or missing stop proof, +(mocked `ExecutionBlockerNotice` UI tests were removed; verify notice UI manually) and source-only repair, and preserved task status. These tests use fixtures; separately verify original files and their attached artifact before recording a real repair. @@ -430,8 +428,7 @@ while the second cannot use the operator API. Automated: [legacy continuation](../../server/src/services/recovery/legacy-continuation.test.ts), [queue routes](../../server/src/__tests__/issue-queued-comments-routes.test.ts), and [native restart recovery](../../server/src/services/native-runtime/native-restart-recovery.test.ts) -cover their respective recovery paths. [Legacy failure continuation](../../tests/e2e/legacy-failure-continuation.spec.ts) -adds a browser journey; it is not native runtime proof. +cover their respective recovery paths. [Queued Stop database regressions](../../server/src/modules/wake-queue/adapters/queued-operator-stop-postgres.test.ts) verify that an operator cancellation before runtime selection releases its own @@ -479,7 +476,7 @@ Capability ID: `recovery/exhaustion`. Scope: ui Storybook: Exhausted/overdue attempts, operator retry pending/error, blocked authority/gate and specific escalation. Production: Inspect durable attempt bounds and actual eligible retry/repair; acknowledgment alone does not prove continued execution. -Sources: Source: [IssueRecoveryActionCard.tsx](../../ui/src/components/IssueRecoveryActionCard.tsx), [DispositionRecoveryNotice.tsx](../../ui/src/components/DispositionRecoveryNotice.tsx), [issue-recovery-actions.ts](../../server/src/services/issue-recovery-actions.ts). Tests: [IssueRecoveryActionCard.test.tsx](../../ui/src/components/IssueRecoveryActionCard.test.tsx), [DispositionRecoveryNotice.test.tsx](../../ui/src/components/DispositionRecoveryNotice.test.tsx), [issue-recovery-actions.test.ts](../../server/src/__tests__/issue-recovery-actions.test.ts), [recovery.spec.ts](../../tests/e2e/execution-recovery/recovery.spec.ts) +Sources: Source: [IssueRecoveryActionCard.tsx](../../ui/src/components/IssueRecoveryActionCard.tsx), [DispositionRecoveryNotice.tsx](../../ui/src/components/DispositionRecoveryNotice.tsx), [issue-recovery-actions.ts](../../server/src/services/issue-recovery-actions.ts). Tests: [IssueRecoveryActionCard.test.tsx](../../ui/src/components/IssueRecoveryActionCard.test.tsx), [issue-recovery-actions.test.ts](../../server/src/__tests__/issue-recovery-actions.test.ts), [recovery.spec.ts](../../tests/e2e/execution-recovery/recovery.spec.ts) #### `unknown-outcome` @@ -497,4 +494,4 @@ Capability ID: `recovery/user-continuation`. Scope: ui Storybook: Saved follow-up waiting on stop cleanup, pause/budget gate, one eligible continuation and result/failure. Production: Confirm previous execution stopped before delivery, preserve message, avoid duplicate wakes and honor actual task/ancestor/budget gate in separate legacy/native paths. -Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [legacy-continuation.ts](../../server/src/services/recovery/legacy-continuation.ts), [native-restart-recovery.ts](../../server/src/services/native-runtime/native-restart-recovery.ts). Tests: [legacy-continuation.test.ts](../../server/src/services/recovery/legacy-continuation.test.ts), [native-restart-recovery.test.ts](../../server/src/services/native-runtime/native-restart-recovery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts), [legacy-failure-continuation.spec.ts](../../tests/e2e/legacy-failure-continuation.spec.ts) +Sources: Source: [TaskChatQueuedMessages.tsx](../../ui/src/components/task-chat/TaskChatQueuedMessages.tsx), [legacy-continuation.ts](../../server/src/services/recovery/legacy-continuation.ts), [native-restart-recovery.ts](../../server/src/services/native-runtime/native-restart-recovery.ts). Tests: [legacy-continuation.test.ts](../../server/src/services/recovery/legacy-continuation.test.ts), [native-restart-recovery.test.ts](../../server/src/services/native-runtime/native-restart-recovery.test.ts), [issue-queued-comments-routes.test.ts](../../server/src/__tests__/issue-queued-comments-routes.test.ts) diff --git a/maps/feature-map/routines.md b/maps/feature-map/routines.md index 95fd016333e..d4292dfc660 100644 --- a/maps/feature-map/routines.md +++ b/maps/feature-map/routines.md @@ -42,7 +42,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `routine-editor` -Automated: [routed routine page tests](../../ui/src/pages/RoutineDetail.test.tsx) cover old-address redirects, History paging, the status switch, saving edits against the opened revision, the save-conflict state, webhook test mode and the responsibility flag gate; [routine form tests](../../ui/src/components/routine-page/routine-form.test.ts) cover schedule and responsibility sync. [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts. Running a routine through the page remains a manual check. +Automated: [routine form tests](../../ui/src/components/routine-page/routine-form.test.ts) cover schedule and responsibility sync, and [Routine service](../../server/src/__tests__/routines-service.test.ts) covers server contracts (mocked `RoutineDetail` page tests were removed; verify page redirects, History paging, status switch, save conflicts, and running a routine manually). Manual: Save an agent, request, project, and a required variable. Reload and inspect the saved definition. Run now with a distinguishable input, follow the resulting task, and verify its output and history entry. Check a missing required input. @@ -89,7 +89,7 @@ Capability ID: `routines/run-now`. Scope: ui Storybook: Mount RoutineRunVariablesDialog through actual RoutineDetail with required/default inputs, project/workspace overrides, pending, blocked and failed submission. RunButton-only no-op examples do not supply/run inputs. Production: POST /routines/{id}/run must validate variables, create one attributed execution/task and obey pause/access/budget gates; inspect actual task outcome separately. -Sources: Source: [RoutineRunVariablesDialog.tsx](../../ui/src/components/RoutineRunVariablesDialog.tsx), [RoutineDetail.tsx](../../ui/src/pages/RoutineDetail.tsx), [routines.ts](../../server/src/routes/routines.ts). Tests: [RoutineRunVariablesDialog.test.tsx](../../ui/src/components/RoutineRunVariablesDialog.test.tsx), [routines-service.test.ts](../../server/src/__tests__/routines-service.test.ts), [routines-e2e.test.ts](../../server/src/__tests__/routines-e2e.test.ts) +Sources: Source: [RoutineRunVariablesDialog.tsx](../../ui/src/components/RoutineRunVariablesDialog.tsx), [RoutineDetail.tsx](../../ui/src/pages/RoutineDetail.tsx), [routines.ts](../../server/src/routes/routines.ts). Tests: [routines-service.test.ts](../../server/src/__tests__/routines-service.test.ts), [routines-e2e.test.ts](../../server/src/__tests__/routines-e2e.test.ts) ### Documentation scope: Routines, cases, and status cards diff --git a/maps/feature-map/runs-adapters.md b/maps/feature-map/runs-adapters.md index a03ce83c1d8..6090f8b8614 100644 --- a/maps/feature-map/runs-adapters.md +++ b/maps/feature-map/runs-adapters.md @@ -62,9 +62,9 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Reco Automated: [actual-auth connection integration](../../server/src/__tests__/connection-management.integration.test.ts) exercises account/pool persistence, responsible-user ownership, agent attribution, -saved local-login access and native secret-response protection with provider fixtures. -[Saved handoff UI tests](../../ui/src/pages/apps/AppsConnect.test.tsx) -exercise setup routing with mocked APIs. Neither establishes live provider sign-in. +saved local-login access and native secret-response protection with provider fixtures +(mocked `AppsConnect` UI tests for setup routing were removed; verify setup routing +manually). This does not establish live provider sign-in. Manual: Start delegated managed-account setup, reload the exact saved human handoff, finish the required login, and inspect the saved account and original diff --git a/maps/feature-map/secrets.md b/maps/feature-map/secrets.md index 36bb8f13d04..88a43ad4bc3 100644 --- a/maps/feature-map/secrets.md +++ b/maps/feature-map/secrets.md @@ -54,7 +54,7 @@ Manual: Create a dummy secret reference, bind it through a supported field, and ### `proposal-import` -Automated: [proposal routes](../../server/src/__tests__/secret-proposals-routes.test.ts) and [vault import dialog](../../ui/src/pages/secrets/ImportFromVaultDialog.test.tsx) cover route/UI layers; a real vault integration needs live validation. +Automated: [proposal routes](../../server/src/__tests__/secret-proposals-routes.test.ts) covers route contracts (mocked `ImportFromVaultDialog` UI tests were removed; verify the vault import dialog manually); a real vault integration needs live validation. Manual: Review a dummy proposal, reject one and accept another, then inspect the resulting reference state and history. Preview a vault import, select only disposable entries, and verify imported references and denied-access errors after reload. @@ -77,7 +77,7 @@ Capability ID: `secrets/proposals`. Scope: ui Storybook: Mount ProposalsTab pending secret/binding proposals, blocked authority, expired/resolved proposal, approval/rejection pending/error, and redacted metadata. Production: GET /companies/{id}/secret-proposals and POST approve/reject must enforce company/admin/target authority, durable resolution and redaction; verified run-bound agent proposal creation is separate. -Sources: Source: [ProposalsTab.tsx](../../ui/src/pages/secrets/ProposalsTab.tsx), [secrets.ts](../../server/src/routes/secrets.ts), [secret-proposal-authorization.ts](../../server/src/services/secret-proposal-authorization.ts). Tests: [ProposalsTab.render.test.tsx](../../ui/src/pages/secrets/ProposalsTab.render.test.tsx), [secret-proposals-routes.test.ts](../../server/src/__tests__/secret-proposals-routes.test.ts) +Sources: Source: [ProposalsTab.tsx](../../ui/src/pages/secrets/ProposalsTab.tsx), [secrets.ts](../../server/src/routes/secrets.ts), [secret-proposal-authorization.ts](../../server/src/services/secret-proposal-authorization.ts). Tests: [secret-proposals-routes.test.ts](../../server/src/__tests__/secret-proposals-routes.test.ts) ### Documentation scope: Secrets and secret proposals diff --git a/maps/feature-map/skills.md b/maps/feature-map/skills.md index 170b16cbb9b..8a56ad7a845 100644 --- a/maps/feature-map/skills.md +++ b/maps/feature-map/skills.md @@ -49,19 +49,19 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Use ### `library-sources` -Automated: [library UI](../../ui/src/pages/CompanySkills.test.tsx) and [source service](../../server/src/__tests__/skill-sources.test.ts) cover their respective layers. +Automated: [source service](../../server/src/__tests__/skill-sources.test.ts) covers server source handling (mocked `CompanySkills` UI tests were removed; verify library UI manually). Manual: Install a fixture, locate it in Installed, inspect its source and files, and reload. Import a source update and compare versions before accepting it. Check a source requiring unavailable repository access and verify the failure is explicit. ### `studio` -Automated: [Studio](../../ui/src/pages/SkillStudio.test.tsx) covers UI behavior; model-driven skill testing remains a separate manual result. +Automated: none for mocked UI (`SkillStudio` component tests were removed; verify Studio UI via Storybook/manual checks); model-driven skill testing remains a separate manual result. Manual: Create or fork a disposable skill, edit instructions, save, and reload. Run a bounded test, respond to any question, and inspect the output. Verify the saved version matches what was tested and failed saves retain the draft. ### `agent-enablement` -Automated: [policy service](../../server/src/__tests__/company-skill-policy-service.test.ts) and [agent skills state](../../ui/src/pages/agent-skills/AgentSkillsTab.test.ts) cover policy/state contracts. +Automated: [policy service](../../server/src/__tests__/company-skill-policy-service.test.ts) covers server policy contracts (mocked `AgentSkillsTab` UI tests were removed; verify agent skills UI manually). The [version-cache regression](../../server/src/__tests__/skill-version-cache.test.ts) checks that listing assignments does not create repository caches, validate every @@ -142,7 +142,7 @@ Capability ID: `skills/testing`. Scope: ui Storybook: Studio test inputs/configuration, running, question/approval, result and failed test states. Production: Run bounded test of actual saved version with correct selected account/environment; inspect persisted test detail and eligible interaction response. -Sources: Source: [SkillStudio.tsx](../../ui/src/pages/SkillStudio.tsx), [companySkills.ts](../../ui/src/api/companySkills.ts). Tests: [SkillStudio.test.tsx](../../ui/src/pages/SkillStudio.test.tsx), [company-skill-test-runs-service.test.ts](../../server/src/__tests__/company-skill-test-runs-service.test.ts) +Sources: Source: [SkillStudio.tsx](../../ui/src/pages/SkillStudio.tsx), [companySkills.ts](../../ui/src/api/companySkills.ts). Tests: [company-skill-test-runs-service.test.ts](../../server/src/__tests__/company-skill-test-runs-service.test.ts) ### Documentation scope: Skills, Skill Studio, and teams diff --git a/maps/feature-map/status-cards.md b/maps/feature-map/status-cards.md index d43f9eac4e6..a66e71e6d6c 100644 --- a/maps/feature-map/status-cards.md +++ b/maps/feature-map/status-cards.md @@ -35,13 +35,13 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Enab ### `status-board` -Automated: [status-card service/routes](../../server/src/__tests__/status-cards.test.ts) covers gated lifecycle and generation contracts; [tile UI](../../ui/src/pages/StatusCards/StatusCardTile.test.tsx) covers rendering. +Automated: [status-card service/routes](../../server/src/__tests__/status-cards.test.ts) covers gated lifecycle and generation contracts (mocked `StatusCardTile` UI rendering tests were removed; verify tile UI via Storybook/manual checks). Manual: Create a bounded card, inspect its generation task, and wait for a saved summary. Change a watched task, refresh, and verify both the summary and update history reflect the source change. Exercise a failed generation and confirm it is not presented as fresh. ### `card-settings` -Automated: [settings form](../../ui/src/pages/StatusCards/StatusCardSettingsForm.test.tsx) and [update engine](../../server/src/__tests__/status-card-update-engine.test.ts) cover separate UI/engine layers. +Automated: [update engine](../../server/src/__tests__/status-card-update-engine.test.ts) covers engine behavior (mocked `StatusCardSettingsForm` UI tests were removed; verify settings form UI via Storybook/manual checks). Manual: Change a disposable card’s prompt or summarizer, run the offered rebuild/refresh, and inspect the resulting query and summary. Archive and restore it, reload its direct link, and check the actual new generation outcome. @@ -60,7 +60,7 @@ Capability ID: `status-cards/authoring`. Scope: ui Storybook: Mount CreateStatusCardDialog and StatusCardSettingsForm prompt, summarizer, refresh options, required/invalid inputs and save errors. Production: POST /companies/{id}/status-cards and PATCH /status-cards/{id} must enforce gate/author authority, save configuration and start expected compile task when prompt changes. -Sources: Source: [CreateStatusCardDialog.tsx](../../ui/src/pages/StatusCards/CreateStatusCardDialog.tsx), [StatusCardSettingsForm.tsx](../../ui/src/pages/StatusCards/StatusCardSettingsForm.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts). Tests: [StatusCardSettingsForm.test.tsx](../../ui/src/pages/StatusCards/StatusCardSettingsForm.test.tsx), [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts) +Sources: Source: [CreateStatusCardDialog.tsx](../../ui/src/pages/StatusCards/CreateStatusCardDialog.tsx), [StatusCardSettingsForm.tsx](../../ui/src/pages/StatusCards/StatusCardSettingsForm.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts). Tests: [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts) #### `generation` @@ -69,7 +69,7 @@ Capability ID: `status-cards/generation`. Scope: ui Storybook: Mount card tile/drawer compiling, refreshing, failed, stale existing summary and successful new-summary states with linked task. Production: POST /status-cards/{id}/recompile and /refresh plus update/finalization engine must persist actual new output/history; compare saved summary with source tasks, not merely successful task status. -Sources: Source: [StatusCardTile.tsx](../../ui/src/pages/StatusCards/StatusCardTile.tsx), [StatusCardDetailDrawer.tsx](../../ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts), [status-card-update-engine.ts](../../server/src/services/status-card-update-engine.ts). Tests: [StatusCardTile.test.tsx](../../ui/src/pages/StatusCards/StatusCardTile.test.tsx), [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts), [status-card-update-engine.test.ts](../../server/src/__tests__/status-card-update-engine.test.ts) +Sources: Source: [StatusCardTile.tsx](../../ui/src/pages/StatusCards/StatusCardTile.tsx), [StatusCardDetailDrawer.tsx](../../ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts), [status-card-update-engine.ts](../../server/src/services/status-card-update-engine.ts). Tests: [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts), [status-card-update-engine.test.ts](../../server/src/__tests__/status-card-update-engine.test.ts) #### `inspection` @@ -78,7 +78,7 @@ Capability ID: `status-cards/inspection`. Scope: ui Storybook: Mount StatusCardDetailDrawer summary, watched work, update/revision history, query debug, empty/loading/error and stale summary disclosure. Production: GET /status-cards/{id}, /updates, /summary-revisions and /dry-run must filter accessible card/source records; fixtures cannot establish summary truth or query authorization. -Sources: Source: [StatusCardDetailDrawer.tsx](../../ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts). Tests: [StatusCardTile.test.tsx](../../ui/src/pages/StatusCards/StatusCardTile.test.tsx), [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts) +Sources: Source: [StatusCardDetailDrawer.tsx](../../ui/src/pages/StatusCards/StatusCardDetailDrawer.tsx), [status-cards.ts](../../server/src/routes/status-cards.ts). Tests: [status-cards.test.ts](../../server/src/__tests__/status-cards.test.ts) #### `archive` diff --git a/maps/feature-map/steering.md b/maps/feature-map/steering.md index 0cfbf604075..2605e60ea48 100644 --- a/maps/feature-map/steering.md +++ b/maps/feature-map/steering.md @@ -72,8 +72,8 @@ cover durable ordering, authorization, steering acknowledgements, interrupt recovery, and concurrent dispatch. [Composer](../../ui/src/components/task-chat/TaskChatComposer.test.tsx) covers drafts and uncertain saves. -[Task-detail delivery races](../../ui/src/pages/IssueDetail.test.tsx) cover a -consumed message whose send response and queue snapshot arrive late. A started +Mocked `IssueDetail` delivery-race UI tests were removed (verify late send-response +and queue-snapshot races manually). Expected behavior: a started run's input receipt removes that message from pending, while a separate unsent message stays queued. Admission to a run that has not started is not delivery. A later retry of the same message remains visible in its new authoritative queue. diff --git a/maps/feature-map/task-coordination.md b/maps/feature-map/task-coordination.md index f6fae0e04ae..32916d24795 100644 --- a/maps/feature-map/task-coordination.md +++ b/maps/feature-map/task-coordination.md @@ -66,9 +66,9 @@ A closed panel can be reopened from the launcher. Implementation: [panel discovery](../../ui/src/hooks/useTaskPluginPanels.ts) and [task panel](../../ui/src/components/task-side-panel/TaskSidePanel.tsx). -Automated: [discovery tests](../../ui/src/hooks/useTaskPluginPanels.test.tsx) and -[task panel tests](../../ui/src/components/task-side-panel/TaskSidePanel.test.tsx) -cover availability, task/agent changes, failures, inactivity and dismissal. +Automated: [discovery tests](../../ui/src/hooks/useTaskPluginPanels.test.tsx) +cover hook discovery, task/agent changes, and failures (mocked `TaskSidePanel` +component tests were removed; verify panel dismissal UI manually). These mocks do not establish a particular plugin's live transport behavior. ## Gotchas diff --git a/maps/feature-map/tasks.md b/maps/feature-map/tasks.md index f566c388a9f..0e77ee47fde 100644 --- a/maps/feature-map/tasks.md +++ b/maps/feature-map/tasks.md @@ -74,7 +74,7 @@ Use these checks alongside the entry-point recipes below and the operation recor ### `new-task` -Automated: [board dialogs](../../ui/src/components/BoardDialogs.test.tsx) checks that the task form appears on the first synchronous open and retains its draft across reopen. [Creation dialog](../../ui/src/components/NewIssueDialog.test.tsx) covers typing while agent/project requests are pending and retaining that text when defaults arrive. These are component checks with mocked requests. +Automated: none for mocked creation dialogs (`BoardDialogs` and `NewIssueDialog` component tests were removed; verify draft retention and pending-defaults behavior manually). Manual: Create a uniquely named task with an agent and project. Open its resulting link and reload. Confirm text, attachment, assignment, and project persisted, and verify execution started only when the task and agent are eligible. @@ -96,7 +96,7 @@ Manual: Filter by status and assignee, change grouping/sort, open a task, and re Manual: Open a long task with slow historical requests. Read the instruction and recent reply before those requests finish. Edit the title/status while enrichment is pending and verify saves and rollbacks. Expand **More messages**, verify scroll position and no duplicate replies, return to the task, and follow an older comment link. Leave a task open across new messages and runs and confirm none disappear. Reconnect after several turns and verify watched runs settle. Reopen after steering with more than 50 newer activity rows; the delivered message must not reappear in the queue. -Automated: [cold-open reads](../../server/src/__tests__/task-cold-open.test.ts) cover bounded reads, event filtering and company denial. [Task detail](../../ui/src/pages/IssueDetail.test.tsx) covers component behavior, while [issue service](../../server/src/__tests__/issues-service.test.ts) covers server contracts. +Automated: [cold-open reads](../../server/src/__tests__/task-cold-open.test.ts) cover bounded reads, event filtering and company denial, and [issue service](../../server/src/__tests__/issues-service.test.ts) covers server contracts (mocked `IssueDetail` page tests were removed; verify task-detail UI via E2E/manual checks). Failure markers have no dashed divider rules. An adjacent run error and no-live-execution-path notice show only the last error, with its details and @@ -106,9 +106,10 @@ text, and credential-access denials stay visible. Explicit non-recovery titles stop grouping. Saved stranded-recovery action metadata plus a known recovery statement also identify recovery notices with a default or source-run title. Only known recovery statements use the legacy text fallback. -[Grouping tests](../../ui/src/components/task-chat/adjacent-errors.test.ts) and -[marker tests](../../ui/src/components/task-chat/TaskChatMarker.test.tsx) cover -the presentation. The [Failure notices stories](../../ui/storybook/stories/tasks/failure-notices.stories.tsx) +[Grouping tests](../../ui/src/components/task-chat/adjacent-errors.test.ts) cover +adjacent-error grouping (mocked `TaskChatMarker` unit tests were removed; marker +presentation is covered by the Storybook stories and visual browser suite below). +The [Failure notices stories](../../ui/storybook/stories/tasks/failure-notices.stories.tsx) mount the production thread view with fixture data. The focused [browser suite](../../tests/storybook-visual/failure-notices.spec.ts) checks play assertions, disclosure, retry callbacks, themes and phone width. These @@ -156,7 +157,7 @@ cover these boundaries locally; deployed runner acceptance remains separate. ### `task-sharing` -Automated: [Share sheet](../../ui/src/components/IssueShareSheet.test.tsx), [privacy controls](../../ui/src/components/PrivateTaskPrivacyControls.test.tsx), [grant routes](../../server/src/__tests__/issue-access-grants-routes.test.ts), and [privacy production review](../../server/src/__tests__/privacy-production-review.test.ts) cover component actions, persisted grants, inheritance, and actor/resource denials. They do not establish a live two-person browser journey. +Automated: [privacy controls](../../ui/src/components/PrivateTaskPrivacyControls.test.tsx), [grant routes](../../server/src/__tests__/issue-access-grants-routes.test.ts), and [privacy production review](../../server/src/__tests__/privacy-production-review.test.ts) cover privacy controls, persisted grants, inheritance, and actor/resource denials (mocked `IssueShareSheet` UI tests were removed; verify share-sheet actions manually). They do not establish a live two-person browser journey. Manual: Use authenticated mode with two ordinary operators, an eligible agent, and disposable parent/child/sibling tasks. Create private work as the first person; confirm the second person cannot discover or cold-open it. Share only the child, reload both sessions, and verify child/descendant access without exposing the private parent, sibling, or unreadable project metadata. Inspect direct and inherited rows in Share; inherited rows must identify access managed at its source and offer no local revoke action. Confirm a shared reader cannot manage the task’s grants. Revoke the direct grant as its manager, reload, and retry list and direct reads; change inherited access at its ancestor or project source separately. Inspect blocked Make public actions under a private parent or nonpersonal private project; separately confirm the offered personal-project publish action removes that project binding while private descendants remain private. With an actual granted agent, test the responsible user’s access intersection and the allowed restriction to private; agent access must not permit sharing or publishing. diff --git a/maps/feature-map/teams.md b/maps/feature-map/teams.md index d6bbefcb08d..8f026de6fd0 100644 --- a/maps/feature-map/teams.md +++ b/maps/feature-map/teams.md @@ -41,7 +41,7 @@ Manual: List an entry, preview its proposed agents and resources, install it int ### `catalog-components` -Automated: [catalog component](../../ui/src/pages/TeamCatalog.test.tsx) and [install hook](../../ui/src/pages/useInstallTeamCatalogEntry.test.tsx) cover preview and install UI logic with mocks. +Automated: none for mocked UI (`TeamCatalog` and `useInstallTeamCatalogEntry` tests were removed; verify preview and install UI manually). Manual: When changing or mounting these components, exercise preview, manager/source options, cancellation, failed install, and success. Follow created agents in the actual company. Record whether this was a component harness or a real product entry point. diff --git a/maps/feature-map/workspaces.md b/maps/feature-map/workspaces.md index 60f0edb8ca0..454d2dc5327 100644 --- a/maps/feature-map/workspaces.md +++ b/maps/feature-map/workspaces.md @@ -53,7 +53,7 @@ Preconditions: follow the [baseline](./README.md#before-driving-a-journey). Enab ### `task-workspace` -Automated: [workspace card](../../ui/src/components/IssueWorkspaceCard.test.tsx) and [task binding](../../server/src/__tests__/issue-runtime-workspace-binding.test.ts) cover host/binding contracts. +Automated: [task binding](../../server/src/__tests__/issue-runtime-workspace-binding.test.ts) covers binding contracts (mocked `IssueWorkspaceCard` UI tests were removed; verify the workspace card UI manually). Manual: Run a task that writes a small file, follow the bound workspace, and inspect the file and revision. Reload and verify links still refer to the same workspace, not another checkout or a stale run. @@ -173,7 +173,7 @@ For a child created by an admitted agent with an explicit existing workspace, ve ### `workspace-management` -Automated: [workspace detail](../../ui/src/pages/ExecutionWorkspaceDetail.test.tsx) and [runtime service](../../server/src/__tests__/workspace-runtime.test.ts) cover UI and runtime contracts separately. +Automated: [runtime service](../../server/src/__tests__/workspace-runtime.test.ts) covers runtime contracts (mocked `ExecutionWorkspaceDetail` UI tests were removed; verify workspace detail UI manually). Manual: Provision a disposable workspace, wait for readiness, start an available service, open its endpoint, and inspect a real response and logs. Stop it and verify it actually stops. Exercise close/reopen only after inspecting pending changes and active runs. diff --git a/packages/db/src/__fixtures__/muse-preview-migrations/0344_perpetual_eternity.sql b/packages/db/src/__fixtures__/muse-preview-migrations/0344_perpetual_eternity.sql deleted file mode 100644 index 4d6d52b54ef..00000000000 --- a/packages/db/src/__fixtures__/muse-preview-migrations/0344_perpetual_eternity.sql +++ /dev/null @@ -1,188 +0,0 @@ -CREATE TABLE "external_agent_holds" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "provider" text NOT NULL, - "assignment_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "run_id" uuid NOT NULL, - "worker_unknown" boolean DEFAULT true NOT NULL, - "native_effects_unknown" boolean DEFAULT false NOT NULL, - "stop_boundary" jsonb, - "worker_reported_at" timestamp with time zone, - "operator_attested_at" timestamp with time zone, - "released_at" timestamp with time zone, - "created_at" timestamp with time zone DEFAULT now() NOT NULL, - "updated_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_agent_bindings" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "operator_id" text NOT NULL, - "generation" integer DEFAULT 1 NOT NULL, - "revision" integer DEFAULT 1 NOT NULL, - "status" text DEFAULT 'pairing' NOT NULL, - "ticket_hash" text, - "ticket_expires_at" timestamp with time zone, - "paired_at" timestamp with time zone, - "challenge_hash" text, - "challenge_expires_at" timestamp with time zone, - "verified_reply_at" timestamp with time zone, - "receiver_contact_at" timestamp with time zone, - "worker_activity_at" timestamp with time zone, - "client_version" text, - "worker_cursor" integer DEFAULT 0 NOT NULL, - "qualification_id" uuid, - "qualification_expires_at" timestamp with time zone, - "cleanup_expires_at" timestamp with time zone, - "detector_removed_at" timestamp with time zone, - "revoked_at" timestamp with time zone, - "created_at" timestamp with time zone DEFAULT now() NOT NULL, - "updated_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_credentials" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "kind" text NOT NULL, - "family_id" uuid NOT NULL, - "token_hash" text NOT NULL, - "expires_at" timestamp with time zone NOT NULL, - "consumed_at" timestamp with time zone, - "revoked_at" timestamp with time zone, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_idle_receipts" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "request_id" uuid NOT NULL, - "digest" text NOT NULL, - "outcome" jsonb NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_input_deliveries" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "assignment_id" uuid NOT NULL, - "request_id" text NOT NULL, - "turn_id" text NOT NULL, - "input_digest" text NOT NULL, - "response" jsonb NOT NULL, - "source_event_id" text NOT NULL, - "consumed_at" timestamp with time zone, - "continuation_receipt_id" uuid, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_mailbox_items" ( - "id" bigserial PRIMARY KEY NOT NULL, - "company_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "assignment_id" uuid, - "kind" text NOT NULL, - "source_event_id" text NOT NULL, - "references" jsonb NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_receiver_contact_buckets" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "replica_id" uuid NOT NULL, - "bucket_at" timestamp with time zone NOT NULL, - "first_at" timestamp with time zone NOT NULL, - "last_at" timestamp with time zone NOT NULL, - "contacts" integer NOT NULL, - "gaps_at_most_seven_seconds" integer NOT NULL, - "max_gap_ms" integer NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_runner_assignments" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "binding_id" uuid NOT NULL, - "binding_generation" integer NOT NULL, - "run_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "normalized_session_id" text NOT NULL, - "turn_id" text NOT NULL, - "revision" integer DEFAULT 1 NOT NULL, - "controller_generation" integer NOT NULL, - "catalog_digest" text NOT NULL, - "status" text NOT NULL, - "projection" jsonb NOT NULL, - "accept_by" timestamp with time zone NOT NULL, - "expires_at" timestamp with time zone NOT NULL, - "offered_at" timestamp with time zone DEFAULT now() NOT NULL, - "claimed_at" timestamp with time zone, - "native_accepted_at" timestamp with time zone, - "accepted_result_at" timestamp with time zone, - "finalized_at" timestamp with time zone, - "last_activity_at" timestamp with time zone DEFAULT now() NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -CREATE TABLE "muse_runner_operations" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "assignment_id" uuid NOT NULL, - "request_id" uuid NOT NULL, - "digest" text NOT NULL, - "command" jsonb NOT NULL, - "status" text DEFAULT 'reserved' NOT NULL, - "outcome" jsonb, - "source_event_id" text, - "created_at" timestamp with time zone DEFAULT now() NOT NULL, - "updated_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -ALTER TABLE "external_agent_holds" ADD CONSTRAINT "external_agent_holds_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "external_agent_holds" ADD CONSTRAINT "external_agent_holds_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_agent_bindings" ADD CONSTRAINT "muse_agent_bindings_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_agent_bindings" ADD CONSTRAINT "muse_agent_bindings_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_credentials" ADD CONSTRAINT "muse_credentials_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_credentials" ADD CONSTRAINT "muse_credentials_binding_id_muse_agent_bindings_id_fk" FOREIGN KEY ("binding_id") REFERENCES "public"."muse_agent_bindings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_idle_receipts" ADD CONSTRAINT "muse_idle_receipts_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_idle_receipts" ADD CONSTRAINT "muse_idle_receipts_binding_id_muse_agent_bindings_id_fk" FOREIGN KEY ("binding_id") REFERENCES "public"."muse_agent_bindings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_input_deliveries" ADD CONSTRAINT "muse_input_deliveries_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_input_deliveries" ADD CONSTRAINT "muse_input_deliveries_assignment_id_muse_runner_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."muse_runner_assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_mailbox_items" ADD CONSTRAINT "muse_mailbox_items_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_mailbox_items" ADD CONSTRAINT "muse_mailbox_items_binding_id_muse_agent_bindings_id_fk" FOREIGN KEY ("binding_id") REFERENCES "public"."muse_agent_bindings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_mailbox_items" ADD CONSTRAINT "muse_mailbox_items_assignment_id_muse_runner_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."muse_runner_assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_receiver_contact_buckets" ADD CONSTRAINT "muse_receiver_contact_buckets_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_receiver_contact_buckets" ADD CONSTRAINT "muse_receiver_contact_buckets_binding_id_muse_agent_bindings_id_fk" FOREIGN KEY ("binding_id") REFERENCES "public"."muse_agent_bindings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_assignments" ADD CONSTRAINT "muse_runner_assignments_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_assignments" ADD CONSTRAINT "muse_runner_assignments_binding_id_muse_agent_bindings_id_fk" FOREIGN KEY ("binding_id") REFERENCES "public"."muse_agent_bindings"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_assignments" ADD CONSTRAINT "muse_runner_assignments_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_assignments" ADD CONSTRAINT "muse_runner_assignments_agent_id_agents_id_fk" FOREIGN KEY ("agent_id") REFERENCES "public"."agents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_operations" ADD CONSTRAINT "muse_runner_operations_company_id_companies_id_fk" FOREIGN KEY ("company_id") REFERENCES "public"."companies"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "muse_runner_operations" ADD CONSTRAINT "muse_runner_operations_assignment_id_muse_runner_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."muse_runner_assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE UNIQUE INDEX "external_holds_assignment_uq" ON "external_agent_holds" USING btree ("provider","assignment_id");--> statement-breakpoint -CREATE INDEX "external_holds_agent_idx" ON "external_agent_holds" USING btree ("company_id","agent_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_bindings_active_agent_uq" ON "muse_agent_bindings" USING btree ("company_id","agent_id") WHERE "muse_agent_bindings"."revoked_at" IS NULL;--> statement-breakpoint -CREATE UNIQUE INDEX "muse_bindings_ticket_uq" ON "muse_agent_bindings" USING btree ("ticket_hash");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_credentials_hash_uq" ON "muse_credentials" USING btree ("token_hash");--> statement-breakpoint -CREATE INDEX "muse_credentials_binding_idx" ON "muse_credentials" USING btree ("binding_id","binding_generation");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_idle_receipts_request_uq" ON "muse_idle_receipts" USING btree ("binding_id","binding_generation","request_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_input_request_uq" ON "muse_input_deliveries" USING btree ("assignment_id","request_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_input_source_uq" ON "muse_input_deliveries" USING btree ("assignment_id","source_event_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_mailbox_event_uq" ON "muse_mailbox_items" USING btree ("binding_id","binding_generation","source_event_id");--> statement-breakpoint -CREATE INDEX "muse_mailbox_cursor_idx" ON "muse_mailbox_items" USING btree ("binding_id","binding_generation","id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_contact_bucket_uq" ON "muse_receiver_contact_buckets" USING btree ("binding_id","binding_generation","replica_id","bucket_at");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_assignments_turn_uq" ON "muse_runner_assignments" USING btree ("run_id","turn_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_assignments_live_binding_uq" ON "muse_runner_assignments" USING btree ("binding_id") WHERE "muse_runner_assignments"."status" IN ('offered','claimed','accepted');--> statement-breakpoint -CREATE INDEX "muse_assignments_company_idx" ON "muse_runner_assignments" USING btree ("company_id");--> statement-breakpoint -CREATE UNIQUE INDEX "muse_operations_request_uq" ON "muse_runner_operations" USING btree ("assignment_id","request_id"); \ No newline at end of file diff --git a/packages/db/src/__fixtures__/muse-preview-migrations/0345_lumpy_celestials.sql b/packages/db/src/__fixtures__/muse-preview-migrations/0345_lumpy_celestials.sql deleted file mode 100644 index fa9e50645fc..00000000000 --- a/packages/db/src/__fixtures__/muse-preview-migrations/0345_lumpy_celestials.sql +++ /dev/null @@ -1,5 +0,0 @@ -ALTER TABLE "muse_agent_bindings" ADD COLUMN "qualification_started_at" timestamp with time zone;--> statement-breakpoint -ALTER TABLE "muse_agent_bindings" ADD COLUMN "deadline_enforced_at" timestamp with time zone;--> statement-breakpoint -ALTER TABLE "muse_agent_bindings" ADD COLUMN "cadence_evidence_incomplete_at" timestamp with time zone;--> statement-breakpoint -ALTER TABLE "muse_receiver_contact_buckets" ADD COLUMN "timestamps" jsonb DEFAULT '[]'::jsonb NOT NULL;--> statement-breakpoint -ALTER TABLE "muse_receiver_contact_buckets" ADD COLUMN "incomplete" boolean DEFAULT false NOT NULL; \ No newline at end of file diff --git a/packages/db/src/__fixtures__/muse-preview-migrations/0346_powerful_epoch.sql b/packages/db/src/__fixtures__/muse-preview-migrations/0346_powerful_epoch.sql deleted file mode 100644 index 468c8dba147..00000000000 --- a/packages/db/src/__fixtures__/muse-preview-migrations/0346_powerful_epoch.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE "muse_agent_bindings" ADD COLUMN "detector_removal_requested_at" timestamp with time zone;--> statement-breakpoint -ALTER TABLE "muse_mailbox_items" ADD COLUMN "signal_attempt" integer DEFAULT 0 NOT NULL;--> statement-breakpoint -ALTER TABLE "muse_mailbox_items" ADD COLUMN "signal_notified_at" timestamp with time zone; \ No newline at end of file diff --git a/packages/db/src/__fixtures__/muse-preview-migrations/0347_big_meggan.sql b/packages/db/src/__fixtures__/muse-preview-migrations/0347_big_meggan.sql deleted file mode 100644 index 2d277aa0864..00000000000 --- a/packages/db/src/__fixtures__/muse-preview-migrations/0347_big_meggan.sql +++ /dev/null @@ -1 +0,0 @@ -ALTER TABLE "muse_runner_operations" ADD COLUMN "continuation_receipt_id" uuid; \ No newline at end of file diff --git a/packages/db/src/__fixtures__/muse-preview-migrations/0348_foamy_lightspeed.sql b/packages/db/src/__fixtures__/muse-preview-migrations/0348_foamy_lightspeed.sql deleted file mode 100644 index 8d586b197ca..00000000000 --- a/packages/db/src/__fixtures__/muse-preview-migrations/0348_foamy_lightspeed.sql +++ /dev/null @@ -1,3 +0,0 @@ -ALTER TABLE "muse_agent_bindings" ADD COLUMN "grant_id" uuid;--> statement-breakpoint -ALTER TABLE "muse_agent_bindings" ADD CONSTRAINT "muse_agent_bindings_grant_id_mcp_oauth_grants_id_fk" FOREIGN KEY ("grant_id") REFERENCES "public"."mcp_oauth_grants"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint -CREATE UNIQUE INDEX "muse_bindings_active_grant_uq" ON "muse_agent_bindings" USING btree ("grant_id") WHERE "muse_agent_bindings"."revoked_at" IS NULL AND "muse_agent_bindings"."grant_id" IS NOT NULL; \ No newline at end of file diff --git a/packages/db/src/agent-chat-messages-migration.test.ts b/packages/db/src/agent-chat-messages-migration.test.ts deleted file mode 100644 index 7fa25643dbf..00000000000 --- a/packages/db/src/agent-chat-messages-migration.test.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const indexName = "issue_comments_agent_client_request_uq"; -const migrationFile = "0419_slippery_impossible_man.sql"; - -(support.supported ? describe : describe.skip)("agent chat message migration", () => { - it("repairs an interrupted index build and backfills old chat owners only once", async () => { - const database = await startEmbeddedPostgresTestDatabase("agent-chat-message-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash=${hash}`; - await sql.unsafe(`ALTER TABLE issue_comments DROP CONSTRAINT ${indexName}`); - const companies = await sql`INSERT INTO companies (name,issue_prefix) VALUES ('Chat migration','CMI1'),('Other company','CMI2') RETURNING id`; - const companyId = companies[0]!.id; - const [agent] = await sql`INSERT INTO agents (company_id,name,adapter_type) VALUES (${companyId},'Kodi','process') RETURNING id`; - const chats = await sql`INSERT INTO issues (company_id,title,conversation_agent_id,conversation_user_id,conversation_state,assignee_agent_id) - VALUES (${companyId},'Missing read state',${agent!.id},'legacy-owner','waiting',${agent!.id}), - (${companyId},'Existing read state',${agent!.id},'existing-owner','waiting',${agent!.id}) RETURNING id,conversation_user_id`; - for (const chat of chats) { - await sql`INSERT INTO issue_comments (company_id,issue_id,author_agent_id,body,created_at) - VALUES (${companyId},${chat.id},${agent!.id},'Existing message','2026-01-02T00:00:00Z')`; - } - await sql`INSERT INTO issue_read_states (company_id,issue_id,user_id,last_read_at) - VALUES (${companyId},${chats[1]!.id},'existing-owner','2026-01-01T00:00:00Z')`; - await expect(sql.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON companies ((true))`)).rejects.toThrow(); - await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]); - const [index] = await sql`SELECT indisvalid,indisunique FROM pg_index WHERE indexrelid=${indexName}::regclass`; - expect(index).toEqual({ indisvalid: true, indisunique: true }); - const [constraint] = await sql`SELECT count(*)::int count FROM pg_constraint WHERE conname=${indexName} AND conrelid='issue_comments'::regclass`; - expect(constraint!.count).toBe(1); - const readStates = await sql`SELECT user_id,last_read_at FROM issue_read_states WHERE company_id=${companyId} ORDER BY user_id`; - expect(readStates.map(row => [row.user_id, row.last_read_at.toISOString()])).toEqual([ - ["existing-owner", "2026-01-01T00:00:00.000Z"], - ["legacy-owner", "2026-01-02T00:00:00.000Z"], - ]); - const [newChat] = await sql`INSERT INTO issues (company_id,title,conversation_agent_id,conversation_user_id,conversation_state,assignee_agent_id) - VALUES (${companyId},'New unread chat',${agent!.id},'new-owner','waiting',${agent!.id}) RETURNING id`; - await sql`INSERT INTO issue_comments (company_id,issue_id,author_agent_id,body) - VALUES (${companyId},${newChat!.id},${agent!.id},'New digest')`; - for (let replay = 0; replay < 2; replay++) { - for (const statement of content.split("--> statement-breakpoint").filter(statement => statement.trim())) { - await sql.unsafe(statement); - } - } - expect(await sql`SELECT id FROM issue_read_states WHERE issue_id=${newChat!.id}`).toEqual([]); - const afterReplay = await sql`SELECT user_id,last_read_at FROM issue_read_states WHERE company_id=${companyId} ORDER BY user_id`; - expect(afterReplay).toEqual(readStates); - const [history] = await sql`SELECT count(*)::int count FROM drizzle.__drizzle_migrations WHERE hash=${hash}`; - expect(history!.count).toBe(1); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 120_000); -}); diff --git a/packages/db/src/agent-chat-migration.test.ts b/packages/db/src/agent-chat-migration.test.ts deleted file mode 100644 index dcd7a448eff..00000000000 --- a/packages/db/src/agent-chat-migration.test.ts +++ /dev/null @@ -1,113 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const migrationFile = "0274_agent_chat.sql"; -const migrationSql = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); -const migrationHash = createHash("sha256").update(migrationSql).digest("hex"); -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length) await cleanups.pop()?.(); -}); - -async function seed(sql: postgres.Sql) { - const companyId = randomUUID(); - const agentId = randomUUID(); - const issueId = randomUUID(); - const commentId = randomUUID(); - const userId = `chat-user-${randomUUID()}`; - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Chat migration', 'CHM')`; - await sql`INSERT INTO agents (id, company_id, name, role, adapter_type) VALUES (${agentId}, ${companyId}, 'Chat agent', 'engineer', 'process')`; - await sql`INSERT INTO "user" (id, name, email, email_verified, created_at, updated_at) - VALUES (${userId}, 'Chat user', ${`${userId}@example.test`}, true, now(), now())`; - await sql`INSERT INTO issues (id, company_id, title, assignee_agent_id, status, - conversation_agent_id, conversation_user_id, conversation_state, conversation_session_generation, conversation_boundary_comment_id) - VALUES (${issueId}, ${companyId}, 'Preserved chat', ${agentId}, 'in_review', - ${agentId}, ${userId}, 'waiting', 7, ${commentId})`; - await sql`INSERT INTO issue_comments (id, company_id, issue_id, author_user_id, body, client_request_id, conversation_session_generation) - VALUES (${commentId}, ${companyId}, ${issueId}, ${userId}, 'Preserved conversation history', 'first-message', 7)`; - return { companyId, agentId, issueId, commentId, userId }; -} - -async function assertConstraints(sql: postgres.Sql, row: Awaited>) { - for (const update of [ - { conversation_state: null }, - { status: "done" }, - { status: "cancelled" }, - { assignee_agent_id: null }, - { conversation_user_id: null }, - ]) { - await expect(sql`UPDATE issues SET ${sql(update)} WHERE id = ${row.issueId}`) - .rejects.toMatchObject({ code: "23514", constraint_name: "issues_conversation_identity_check" }); - } - await expect(sql`INSERT INTO issues (company_id, title, assignee_agent_id, status, conversation_agent_id, conversation_user_id, conversation_state) - VALUES (${row.companyId}, 'Duplicate conversation', ${row.agentId}, 'in_review', ${row.agentId}, ${row.userId}, 'waiting')`) - .rejects.toMatchObject({ code: "23505", constraint_name: "issues_conversation_identity_idx" }); - await expect(sql`INSERT INTO issue_comments (company_id, issue_id, author_user_id, body, client_request_id) - VALUES (${row.companyId}, ${row.issueId}, ${row.userId}, 'Duplicate message', 'first-message')`) - .rejects.toMatchObject({ code: "23505", constraint_name: "issue_comments_client_request_uq" }); - await sql`INSERT INTO issues (company_id, title, assignee_agent_id, status, conversation_agent_id, conversation_user_id, conversation_state) - VALUES (${row.companyId}, 'Other person conversation', ${row.agentId}, 'in_review', ${row.agentId}, 'other-person', 'waiting')`; - await sql`INSERT INTO issues (company_id, title, status) VALUES (${row.companyId}, 'Ordinary completed task', 'done')`; -} - -describePostgres("persistent agent chat migration", () => { - it("applies to a fresh database and enforces conversation identity and message retry uniqueness", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-chat-migration-fresh-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - await assertConstraints(sql, await seed(sql)); - } finally { - await sql.end(); - } - }, 30_000); - - it("replays over pre-release columns and constraints without losing history or weakening the state guard", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-chat-migration-replay-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const row = await seed(sql); - const beforeIssue = await sql`SELECT * FROM issues WHERE id = ${row.issueId}`; - const beforeComment = await sql`SELECT * FROM issue_comments WHERE id = ${row.commentId}`; - // The original pre-release guard omitted the explicit state null check. - // Keep every column, index and FK to model an already-upgraded development DB. - await sql`ALTER TABLE issues DROP CONSTRAINT issues_conversation_identity_check`; - const legacyGuard = migrationSql.slice(migrationSql.lastIndexOf('ALTER TABLE "issues" ADD CONSTRAINT')) - .replace(' and "issues"."conversation_state" is not null', ""); - await sql.unsafe(legacyGuard); - const legacyNullIds = [randomUUID(), randomUUID()]; - for (const [index, status] of ["in_review", "in_progress"].entries()) { - await sql`INSERT INTO issues (id, company_id, title, assignee_agent_id, status, conversation_agent_id, conversation_user_id, conversation_state) - VALUES (${legacyNullIds[index]!}, ${row.companyId}, 'Legacy null state', ${row.agentId}, ${status}, ${row.agentId}, ${`legacy-null-${index}`}, NULL)`; - } - - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${migrationHash}`; - expect(await inspectMigrations(database.connectionString)).toMatchObject({ - status: "needsMigrations", pendingMigrations: [migrationFile], - }); - await applyPendingMigrations(database.connectionString); - // Exercise the SQL itself a second time, even with every new object present. - await sql.begin(async (tx) => { - for (const statement of migrationSql.split("--> statement-breakpoint")) { - if (statement.trim()) await tx.unsafe(statement); - } - }); - expect(await sql`SELECT * FROM issues WHERE id = ${row.issueId}`).toEqual(beforeIssue); - expect(await sql`SELECT * FROM issue_comments WHERE id = ${row.commentId}`).toEqual(beforeComment); - const repaired = await sql`SELECT id, conversation_state FROM issues WHERE id IN ${sql(legacyNullIds)}`; - expect(repaired.find((item) => item.id === legacyNullIds[0])?.conversation_state).toBe("waiting"); - expect(repaired.find((item) => item.id === legacyNullIds[1])?.conversation_state).toBe("active"); - await assertConstraints(sql, row); - } finally { - await sql.end(); - } - }, 30_000); -}); diff --git a/packages/db/src/agent-config-read-grants-migration.test.ts b/packages/db/src/agent-config-read-grants-migration.test.ts deleted file mode 100644 index 7030eedee3b..00000000000 --- a/packages/db/src/agent-config-read-grants-migration.test.ts +++ /dev/null @@ -1,94 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const migrationFile = "0423_agent_config_read_defaults.sql"; - -(support.supported ? describe : describe.skip)("agent configuration read default migration", () => { - it("adds only read access to existing standard agents and preserves restrictions and later revocation", async () => { - const database = await startEmbeddedPostgresTestDatabase("agent-config-read-defaults-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const [company] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Read defaults', 'RD1') RETURNING id`; - const [otherCompany] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Other company', 'RD2') RETURNING id`; - const candidates = [ - { name: "Legacy" }, - { name: "Paused", status: "paused", lifecycleState: "paused", lifecycleHolds: ["manual"], pauseReason: "manual" }, - { name: "Pausing", status: "paused", lifecycleState: "pausing", lifecycleHolds: ["manual"], pauseReason: "manual" }, - { name: "Resuming", status: "paused", lifecycleState: "resuming" }, - { name: "Configured" }, - { name: "Scoped configure" }, - { name: "Scoped suggest" }, - { name: "Scoped read" }, - { name: "Low trust", permissions: { trustPreset: "low_trust_review" } }, - { name: "Nested low trust", permissions: { authorizationPolicy: { trustPreset: "low_trust_review" } } }, - { name: "Review preset", permissions: { reviewPreset: { id: "low_trust_review" } } }, - { name: "Nested review preset", permissions: { authorizationPolicy: { reviewPreset: { id: "low_trust_review" } } } }, - { name: "Boundary", permissions: { authorizationPolicy: { trustBoundary: { mode: "low_trust_review" } } } }, - { name: "Unknown preset", permissions: { trustPreset: "unknown" } }, - { name: "Built in", metadata: { paperclipBuiltInAgent: { key: "summarizer", featureKeys: [] } } }, - { name: "Pending", status: "pending_approval" }, - { name: "Terminated", status: "terminated" }, - { name: "Setup", status: "paused", lifecycleState: "paused", lifecycleHolds: ["setup"], pauseReason: "setup" }, - { name: "Legacy setup", status: "paused", lifecycleState: "paused", pauseReason: "setup" }, - { name: "Inactive membership", membershipStatus: "inactive" }, - { name: "No membership", membershipStatus: "absent" }, - { name: "Wrong company membership", membershipStatus: "other_company" }, - ]; - const ids = new Map(); - for (const candidate of candidates) { - const id = randomUUID(); - ids.set(candidate.name, id); - await sql`INSERT INTO agents (id, company_id, name, status, lifecycle_state, lifecycle_holds, pause_reason, permissions, metadata) - VALUES (${id}, ${company!.id}, ${candidate.name}, ${candidate.status ?? "idle"}, - ${candidate.lifecycleState ?? "ready"}, ${sql.json(candidate.lifecycleHolds ?? [])}, ${candidate.pauseReason ?? null}, - ${sql.json(candidate.permissions ?? {})}, ${sql.json(candidate.metadata ?? {})})`; - if (candidate.membershipStatus === "absent") continue; - await sql`INSERT INTO company_memberships (company_id, principal_type, principal_id, status, membership_role) - VALUES (${candidate.membershipStatus === "other_company" ? otherCompany!.id : company!.id}, 'agent', ${id}, - ${candidate.membershipStatus === "inactive" ? "inactive" : "active"}, 'member')`; - } - const scope = { agentIds: [ids.get("Legacy")!] }; - for (const [name, permissionKey, grantScope] of [ - ["Configured", "agents:configure", null], - ["Scoped configure", "agents:configure", scope], - ["Scoped suggest", "agents:suggest-changes", scope], - ["Scoped read", "agents:read", scope], - ] as const) { - await sql`INSERT INTO principal_permission_grants (company_id, principal_type, principal_id, permission_key, scope) - VALUES (${company!.id}, 'agent', ${ids.get(name)!}, ${permissionKey}, ${grantScope ? sql.json(grantScope) : null})`; - } - const before = await sql`SELECT principal_id, permission_key, scope FROM principal_permission_grants ORDER BY principal_id, permission_key`; - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await applyPendingMigrations(database.connectionString); - - const after = await sql`SELECT principal_id, permission_key, scope FROM principal_permission_grants ORDER BY principal_id, permission_key`; - const added = after.filter(row => !before.some(previous => previous.principal_id === row.principal_id && previous.permission_key === row.permission_key)); - expect(added).toEqual(expect.arrayContaining(["Legacy", "Paused", "Pausing", "Resuming", "Configured"].map(name => ({ - principal_id: ids.get(name), permission_key: "agents:read", scope: null, - })))); - expect(added).toHaveLength(5); - expect(after.filter(row => row.permission_key !== "agents:read")).toEqual(before.filter(row => row.permission_key !== "agents:read")); - expect(after.find(row => row.principal_id === ids.get("Scoped read"))).toMatchObject({ scope }); - const audit = await sql`SELECT entity_id, details FROM activity_log WHERE actor_id = 'migration:agent-config-read-defaults'`; - expect(audit).toHaveLength(5); - expect(audit.every(row => row.details.added.length === 1 && row.details.added[0] === "agents:read")).toBe(true); - await sql.unsafe(content); - expect(await sql`SELECT id FROM activity_log WHERE actor_id = 'migration:agent-config-read-defaults'`).toHaveLength(5); - - await sql`DELETE FROM principal_permission_grants WHERE principal_id = ${ids.get("Legacy")!} AND permission_key = 'agents:read'`; - await applyPendingMigrations(database.connectionString); - expect(await sql`SELECT id FROM principal_permission_grants WHERE principal_id = ${ids.get("Legacy")!}`).toHaveLength(0); - expect(await sql`SELECT id FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(1); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 120_000); -}); diff --git a/packages/db/src/agent-instruction-migration.test.ts b/packages/db/src/agent-instruction-migration.test.ts deleted file mode 100644 index 6def7b7e884..00000000000 --- a/packages/db/src/agent-instruction-migration.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -// Exact SQL from PR #14325 before master assigned 0285/0286 to API response storage. -// Exercise real preview tables/receipts, not a second application of the new schema. -const previewMigrations = [ - { when: 1790474441205, sql: `CREATE TABLE "agent_instruction_heads" ( - "company_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "entry_file" text NOT NULL, - "revision_id" uuid NOT NULL, - "updated_at" timestamp with time zone DEFAULT now() NOT NULL, - CONSTRAINT "agent_instruction_heads_identity_uq" UNIQUE("company_id","agent_id","entry_file") -); ---> statement-breakpoint -CREATE TABLE "agent_instruction_revisions" ( - "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, - "company_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "entry_file" text NOT NULL, - "content_base64" text NOT NULL, - "content_hash" text NOT NULL, - "byte_length" integer NOT NULL, - "parent_revision_id" uuid, - "base_revision_id" uuid, - "restored_from_revision_id" uuid, - "actor_agent_id" uuid, - "actor_user_id" text, - "responsible_user_id" text, - "source_run_id" uuid, - "source" text NOT NULL, - "created_at" timestamp with time zone DEFAULT now() NOT NULL, - CONSTRAINT "agent_instruction_revisions_identity_uq" UNIQUE("company_id","agent_id","entry_file","id") -); ---> statement-breakpoint -ALTER TABLE "agent_instruction_heads" ADD CONSTRAINT "agent_instruction_heads_company_id_agent_id_entry_file_revision_id_agent_instruction_revisions_company_id_agent_id_entry_file_id_fk" FOREIGN KEY ("company_id","agent_id","entry_file","revision_id") REFERENCES "public"."agent_instruction_revisions"("company_id","agent_id","entry_file","id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "agent_instruction_revisions" ADD CONSTRAINT "agent_instruction_revisions_company_id_agent_id_agents_company_id_id_fk" FOREIGN KEY ("company_id","agent_id") REFERENCES "public"."agents"("company_id","id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE INDEX "agent_instruction_revisions_history_idx" ON "agent_instruction_revisions" USING btree ("company_id","agent_id","entry_file","created_at","id");` }, - { when: 1790543348340, sql: `CREATE TABLE "agent_instruction_working_copies" ( - "run_id" uuid PRIMARY KEY NOT NULL, - "company_id" uuid NOT NULL, - "agent_id" uuid NOT NULL, - "responsible_user_id" text NOT NULL, - "entry_file" text NOT NULL, - "base_revision_id" uuid, - "base_hash" text NOT NULL, - "local_root" text NOT NULL, - "execution_root" text NOT NULL, - "location" text NOT NULL, - "state" text DEFAULT 'prepared' NOT NULL, - "candidate_base64" text, - "candidate_hash" text, - "error_code" text, - "error_message" text, - "receipt" jsonb, - "process_stopped_at" timestamp with time zone, - "attempts" integer DEFAULT 0 NOT NULL, - "next_attempt_at" timestamp with time zone, - "created_at" timestamp with time zone DEFAULT now() NOT NULL, - "updated_at" timestamp with time zone DEFAULT now() NOT NULL -); ---> statement-breakpoint -ALTER TABLE "agent_instruction_working_copies" ADD CONSTRAINT "agent_instruction_working_copies_run_id_heartbeat_runs_id_fk" FOREIGN KEY ("run_id") REFERENCES "public"."heartbeat_runs"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -ALTER TABLE "agent_instruction_working_copies" ADD CONSTRAINT "agent_instruction_working_copies_company_id_agent_id_agents_company_id_id_fk" FOREIGN KEY ("company_id","agent_id") REFERENCES "public"."agents"("company_id","id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint -CREATE INDEX "agent_instruction_copies_pending_idx" ON "agent_instruction_working_copies" USING btree ("state","next_attempt_at");--> statement-breakpoint -CREATE INDEX "agent_instruction_copies_agent_idx" ON "agent_instruction_working_copies" USING btree ("company_id","agent_id","created_at");` }, -]; -const migration = await readFile(new URL("./migrations/0287_serious_tinkerer.sql", import.meta.url), "utf8"); -const migrationHash = createHash("sha256").update(migration).digest("hex"); - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -describePostgres("instruction revision migrations", () => { - it("keeps applied migration receipts, revisions, and pending copies intact on repeated upgrades", async () => { - const database = await startEmbeddedPostgresTestDatabase("instruction-migration-upgrade-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - await sql`DROP TABLE agent_instruction_heads, agent_instruction_working_copies, agent_instruction_revisions`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${migrationHash}`; - for (const preview of previewMigrations) { - for (const statement of preview.sql.split("--> statement-breakpoint")) await sql.unsafe(statement); - await sql`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) - VALUES (${createHash("sha256").update(preview.sql).digest("hex")}, ${preview.when})`; - } - const companyId = randomUUID(), otherCompanyId = randomUUID(), agentId = randomUUID(); - const runId = randomUUID(), revisionId = randomUUID(); - const bytes = Buffer.from("\uFEFF# Saved\r\nExact bytes ☃\n"); - const contentBase64 = bytes.toString("base64"); - const contentHash = createHash("sha256").update(bytes).digest("hex"); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES - (${companyId}, 'Instructions', 'INS'), (${otherCompanyId}, 'Other', 'OTH')`; - await sql`INSERT INTO agents (id, company_id, name) VALUES (${agentId}, ${companyId}, 'Writer')`; - await sql`INSERT INTO heartbeat_runs (id, company_id, agent_id) VALUES (${runId}, ${companyId}, ${agentId})`; - await sql`INSERT INTO agent_instruction_revisions - (id, company_id, agent_id, entry_file, content_base64, content_hash, byte_length, source, source_run_id) - VALUES (${revisionId}, ${companyId}, ${agentId}, 'AGENTS.md', ${contentBase64}, ${contentHash}, ${bytes.length}, 'cleanup', ${runId})`; - await sql`INSERT INTO agent_instruction_heads (company_id, agent_id, entry_file, revision_id) - VALUES (${companyId}, ${agentId}, 'AGENTS.md', ${revisionId})`; - await sql`INSERT INTO agent_instruction_working_copies - (run_id, company_id, agent_id, responsible_user_id, entry_file, base_revision_id, base_hash, local_root, execution_root, location, state, candidate_base64, candidate_hash) - VALUES (${runId}, ${companyId}, ${agentId}, 'editor', 'AGENTS.md', ${revisionId}, ${contentHash}, '/private/copy', '/private/copy', 'local', 'pending_commit', ${contentBase64}, ${contentHash})`; - const snapshot = async () => ({ - journal: await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`, - relations: await sql`SELECT oid::text, relname FROM pg_class WHERE relname IN - ('agent_instruction_revisions', 'agent_instruction_heads', 'agent_instruction_working_copies') ORDER BY relname`, - constraints: await sql`SELECT oid::text, conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint - WHERE conrelid IN ('agent_instruction_revisions'::regclass, 'agent_instruction_heads'::regclass, - 'agent_instruction_working_copies'::regclass) ORDER BY conname`, - revisions: await sql`SELECT * FROM agent_instruction_revisions`, - heads: await sql`SELECT * FROM agent_instruction_heads`, - copies: await sql`SELECT * FROM agent_instruction_working_copies`, - }); - const before = await snapshot(); - expect(before.relations).toHaveLength(3); - expect(await inspectMigrations(database.connectionString)).toMatchObject({ - status: "needsMigrations", pendingMigrations: ["0287_serious_tinkerer.sql"], - }); - await applyPendingMigrations(database.connectionString); - const upgraded = await snapshot(); - expect(upgraded).toEqual({ ...before, journal: expect.arrayContaining(before.journal) }); - expect(upgraded.journal).toHaveLength(before.journal.length + 1); - for (let attempt = 0; attempt < 2; attempt += 1) { - expect(await inspectMigrations(database.connectionString)).toMatchObject({ status: "upToDate" }); - await applyPendingMigrations(database.connectionString); - expect(await snapshot()).toEqual(upgraded); - } - await expect(sql`UPDATE agent_instruction_heads SET company_id = ${otherCompanyId} WHERE revision_id = ${revisionId}`) - .rejects.toMatchObject({ code: "23503" }); - await expect(sql`UPDATE agent_instruction_working_copies SET company_id = ${otherCompanyId} WHERE run_id = ${runId}`) - .rejects.toMatchObject({ code: "23503" }); - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/better-auth-account-issuer-migration.test.ts b/packages/db/src/better-auth-account-issuer-migration.test.ts index ed260aa9a15..47466f37076 100644 --- a/packages/db/src/better-auth-account-issuer-migration.test.ts +++ b/packages/db/src/better-auth-account-issuer-migration.test.ts @@ -1,32 +1,6 @@ -import { randomUUID } from "node:crypto"; -import fs from "node:fs"; import { getTableConfig } from "drizzle-orm/pg-core"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; +import { describe, expect, it } from "vitest"; import { authAccounts } from "./schema/auth.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0230_better_auth_account_issuer.sql"; -const UNIQUE_INDEX = "account_issuer_account_id_uq"; - -const CREDENTIAL_ISSUER = "local:credential"; -const OAUTH_ISSUER_PREFIX = "local:oauth:"; - -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function applySqlMigration(sql: postgres.Sql, file: string) { - const content = await fs.promises.readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8"); - await sql.begin(async (transaction) => { - for (const statement of content.split("--> statement-breakpoint")) { - if (statement.trim()) await transaction.unsafe(statement); - } - }); -} describe("account issuer schema", () => { it("keeps issuer nullable and identifies accounts by provider and account ID", () => { @@ -43,125 +17,3 @@ describe("account issuer schema", () => { ]); }); }); - -describeEmbeddedPostgres("historical issuer migration and patched provider identity upgrade", () => { - // Reverse registration order, one at a time. The raw `postgres` client is not - // registered with the module's client registry, so the cluster teardown does - // not close it. Stopping the cluster while that client is still draining kills - // the backend socket under a queued write and can crash the runner. - afterEach(async () => { - for (const cleanup of cleanups.splice(0).reverse()) { - await cleanup(); - } - }); - - it("backfills every pre-upgrade row before the column goes NOT NULL", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-account-issuer-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - await sql`DROP INDEX IF EXISTS "account_provider_account_id_uq"`; - await sql`DROP INDEX IF EXISTS ${sql(UNIQUE_INDEX)}`; - await sql`ALTER TABLE "account" DROP COLUMN IF EXISTS "issuer"`; - - const credentialUserId = `user-${randomUUID()}`; - const socialUserId = `user-${randomUUID()}`; - const credentialAccountId = `account-${randomUUID()}`; - const githubAccountId = `account-${randomUUID()}`; - const googleAccountId = `account-${randomUUID()}`; - - await sql` - INSERT INTO "user" ("id", "name", "email", "created_at", "updated_at") - VALUES - (${credentialUserId}, 'Credential User', 'credential@example.com', now(), now()), - (${socialUserId}, 'Social User', 'social@example.com', now(), now()) - `; - await sql` - INSERT INTO "account" - ("id", "account_id", "provider_id", "user_id", "password", "created_at", "updated_at") - VALUES - (${credentialAccountId}, ${credentialUserId}, 'credential', ${credentialUserId}, 'hashed', now(), now()), - (${githubAccountId}, 'github-subject-1', 'github', ${socialUserId}, NULL, now(), now()), - (${googleAccountId}, 'google-subject-1', 'google', ${socialUserId}, NULL, now(), now()) - `; - - await applySqlMigration(sql, MIGRATION_FILE); - - const rows = await sql<{ id: string; issuer: string }[]>` - SELECT "id", "issuer" FROM "account" ORDER BY "id" - `; - const issuerById = new Map(rows.map((row) => [row.id, row.issuer])); - expect(issuerById.get(credentialAccountId)).toBe(CREDENTIAL_ISSUER); - // A backfill restricted to `provider_id = 'credential'` leaves these NULL, - // and SET NOT NULL then aborts the upgrade. - expect(issuerById.get(githubAccountId)).toBe(`${OAUTH_ISSUER_PREFIX}github`); - expect(issuerById.get(googleAccountId)).toBe(`${OAUTH_ISSUER_PREFIX}google`); - - const [issuerColumn] = await sql<{ is_nullable: string }[]>` - SELECT "is_nullable" FROM "information_schema"."columns" - WHERE "table_name" = 'account' AND "column_name" = 'issuer' - `; - expect(issuerColumn?.is_nullable).toBe("NO"); - - const indexes = await sql<{ indexname: string }[]>` - SELECT "indexname" FROM "pg_indexes" - WHERE "tablename" = 'account' AND "indexname" = ${UNIQUE_INDEX} - `; - expect(indexes).toHaveLength(1); - - // The restored index rejects a second account under the same key. - await expect( - sql` - INSERT INTO "account" - ("id", "issuer", "account_id", "provider_id", "user_id", "created_at", "updated_at") - VALUES (${`account-${randomUUID()}`}, ${CREDENTIAL_ISSUER}, ${credentialUserId}, 'credential', ${credentialUserId}, now(), now()) - `, - ).rejects.toMatchObject({ code: "23505", constraint_name: UNIQUE_INDEX }); - - await applySqlMigration(sql, "0465_better_auth_account_identity.sql"); - const preserved = await sql`SELECT "id", "issuer" FROM "account" ORDER BY "id"`; - expect(preserved).toEqual(rows); - const [nullable] = await sql` - SELECT "is_nullable" FROM "information_schema"."columns" - WHERE "table_schema" = 'public' AND "table_name" = 'account' AND "column_name" = 'issuer' - `; - expect(nullable?.is_nullable).toBe("YES"); - await expect(sql` - INSERT INTO "account" ("id", "account_id", "provider_id", "user_id", "created_at", "updated_at") - VALUES (${randomUUID()}, ${credentialUserId}, 'credential', ${credentialUserId}, now(), now()) - `).rejects.toMatchObject({ code: "23505", constraint_name: "account_provider_account_id_uq" }); - await sql` - INSERT INTO "account" ("id", "account_id", "provider_id", "user_id", "created_at", "updated_at") - VALUES (${randomUUID()}, 'new-subject', 'credential', ${credentialUserId}, now(), now()) - `; - }, 30_000); -}); - -describeEmbeddedPostgres("provider identity migration with duplicate legacy keys", () => { - it("rejects ambiguous provider/account keys without changing legacy rows", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-account-duplicates-"); - const sql = postgres(database.connectionString, { max: 1 }); - try { - await sql`DROP INDEX "account_provider_account_id_uq"`; - await sql`ALTER TABLE "account" ALTER COLUMN "issuer" SET NOT NULL`; - await sql`CREATE UNIQUE INDEX "account_issuer_account_id_uq" ON "account" ("issuer", "account_id")`; - const userId = randomUUID(); - await sql`INSERT INTO "user" ("id", "name", "email", "created_at", "updated_at") - VALUES (${userId}, 'Legacy User', 'legacy@example.com', now(), now())`; - await sql`INSERT INTO "account" ("id", "issuer", "account_id", "provider_id", "user_id", "created_at", "updated_at") - VALUES (${randomUUID()}, 'issuer-a', 'same-subject', 'credential', ${userId}, now(), now()), - (${randomUUID()}, 'issuer-b', 'same-subject', 'credential', ${userId}, now(), now())`; - const before = await sql`SELECT "id", "issuer" FROM "account" ORDER BY "id"`; - await expect(applySqlMigration(sql, "0465_better_auth_account_identity.sql")) - .rejects.toMatchObject({ code: "23505" }); - expect(await sql`SELECT "id", "issuer" FROM "account" ORDER BY "id"`).toEqual(before); - const [column] = await sql`SELECT "is_nullable" FROM "information_schema"."columns" - WHERE "table_schema" = 'public' AND "table_name" = 'account' AND "column_name" = 'issuer'`; - expect(column?.is_nullable).toBe("NO"); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 30_000); -}); diff --git a/packages/db/src/built-in-agent-unique-marker-migration.test.ts b/packages/db/src/built-in-agent-unique-marker-migration.test.ts deleted file mode 100644 index 9364149f7ed..00000000000 --- a/packages/db/src/built-in-agent-unique-marker-migration.test.ts +++ /dev/null @@ -1,119 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0195_built_in_agent_unique_marker.sql"; -const UNIQUE_INDEX = "agents_company_built_in_agent_key_unique_idx"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash() { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -function markerObj(key: string) { - // Return a plain object (not a JSON string) so `sql.json` stores it as a jsonb - // object; a JSON string param + `::jsonb` would double-encode into a scalar. - return { paperclipBuiltInAgent: { key, featureKeys: [key] } }; -} - -describeEmbeddedPostgres("built-in agent unique marker migration", () => { - afterEach(async () => { - await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); - }); - - it("resolves pre-existing duplicates and enforces uniqueness going forward", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-built-in-unique-marker-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - // Rewind the migration so we can seed the pre-index (duplicate) state. - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - await sql`DROP INDEX IF EXISTS ${sql(UNIQUE_INDEX)}`; - - const affectedCompanyId = randomUUID(); - const cleanCompanyId = randomUUID(); - const olderId = randomUUID(); - const newerId = randomUUID(); - const terminatedDupeId = randomUUID(); - const cleanSummarizerId = randomUUID(); - const approvalId = randomUUID(); - const apiKeyId = randomUUID(); - - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES - (${affectedCompanyId}, 'Affected', 'AFF'), - (${cleanCompanyId}, 'Clean', 'CLN') - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "status", "created_at", "metadata") - VALUES - (${olderId}, ${affectedCompanyId}, 'Summarizer One', 'idle', '2026-07-18T00:00:00.000Z', ${sql.json(markerObj("summarizer"))}), - (${newerId}, ${affectedCompanyId}, 'Summarizer Two', 'pending_approval', '2026-07-18T00:00:00.025Z', ${sql.json(markerObj("summarizer"))}), - (${terminatedDupeId}, ${affectedCompanyId}, 'Summarizer Old', 'terminated', '2026-07-17T00:00:00.000Z', ${sql.json(markerObj("summarizer"))}), - (${cleanSummarizerId}, ${cleanCompanyId}, 'Summarizer', 'idle', '2026-07-18T00:00:00.000Z', ${sql.json(markerObj("summarizer"))}) - `; - await sql` - INSERT INTO "approvals" ("id", "company_id", "type", "status", "payload") - VALUES (${approvalId}, ${affectedCompanyId}, 'hire_agent', 'pending', ${sql.json({ agentId: newerId, sourceBuiltInAgentKey: "summarizer" })}) - `; - await sql` - INSERT INTO "agent_api_keys" ("id", "agent_id", "company_id", "name", "key_hash") - VALUES (${apiKeyId}, ${newerId}, ${affectedCompanyId}, 'dupe-key', 'hash') - `; - - // Re-run the migration: it should clean up the duplicates, then recreate the index. - await applyPendingMigrations(database.connectionString); - - const agentRows = await sql<{ id: string; status: string }[]>` - SELECT "id", "status" FROM "agents" - WHERE "company_id" IN (${affectedCompanyId}, ${cleanCompanyId}) - `; - const statusById = new Map(agentRows.map((row) => [row.id, row.status])); - // Oldest active row kept; newer duplicate terminated; the clean company untouched. - expect(statusById.get(olderId)).toBe("idle"); - expect(statusById.get(newerId)).toBe("terminated"); - expect(statusById.get(cleanSummarizerId)).toBe("idle"); - - const activeMarked = await sql<{ count: string }[]>` - SELECT count(*)::text AS count FROM "agents" - WHERE "company_id" = ${affectedCompanyId} - AND "status" <> 'terminated' - AND ("metadata" -> 'paperclipBuiltInAgent' ->> 'key') = 'summarizer' - `; - expect(activeMarked[0]!.count).toBe("1"); - - // The newer duplicate's orphan approval was cancelled and its API key revoked. - const [approval] = await sql<{ status: string }[]>` - SELECT "status" FROM "approvals" WHERE "id" = ${approvalId} - `; - expect(approval!.status).toBe("cancelled"); - const [apiKey] = await sql<{ revoked_at: Date | null }[]>` - SELECT "revoked_at" FROM "agent_api_keys" WHERE "id" = ${apiKeyId} - `; - expect(apiKey!.revoked_at).not.toBeNull(); - - // The partial unique index exists again and now rejects a second active row. - const indexes = await sql<{ indexname: string }[]>` - SELECT "indexname" FROM "pg_indexes" - WHERE "tablename" = 'agents' AND "indexname" = ${UNIQUE_INDEX} - `; - expect(indexes).toHaveLength(1); - await expect( - sql` - INSERT INTO "agents" ("id", "company_id", "name", "status", "metadata") - VALUES (${randomUUID()}, ${affectedCompanyId}, 'Summarizer Dupe', 'idle', ${sql.json(markerObj("summarizer"))}) - `, - ).rejects.toMatchObject({ code: "23505", constraint_name: UNIQUE_INDEX }); - }, 30_000); -}); diff --git a/packages/db/src/case-handoff-migration.test.ts b/packages/db/src/case-handoff-migration.test.ts deleted file mode 100644 index cf1e93f9f01..00000000000 --- a/packages/db/src/case-handoff-migration.test.ts +++ /dev/null @@ -1,214 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const migrationNames = [ - "0363_steady_storm.sql", "0364_clear_maria_hill.sql", "0365_naive_shatterstar.sql", - "0366_superb_adam_warlock.sql", "0367_noisy_lilandra.sql", "0368_abandoned_bucky.sql", -]; -const migrations = await Promise.all(migrationNames.map(async name => { - const body = await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8"); - return { name, body, hash: createHash("sha256").update(body).digest("hex") }; -})); -// Receipts written by feature checkouts before these migrations were renumbered -// to follow master. Keep them as historical receipts, rather than rewriting them. -const legacyHashes = [ - "aff5773e553ed3f698bf068ebe65703dfbb1572961986eeb1dfb3654632e8277", - "7029364157e542096c254b628a76bbe38f50b081f0ff390f399d46d88fa2900a", - "c7249783638bddaa9c86cf5e1d5139ee832063394fec000d3a47b84fdcb2e924", - "99f7d24f4b8db5ae2b718112ead427d94ebf302031ef9bde50e522e894b1c3db", - "343a69c1f20fea11adf9a9cddd77dced125c673522ed50a6615a67a87096689e", -]; -// These byte-identical SQL receipts were written before master added its own -// 0362 migration. Renaming our files must not replay or rewrite those receipts. -const previousFeatureReceipts = [ - { hash: "b9270a6d233463f808aba4360f4478f30eba4604e0d105ecc53970191671c6d8", createdAt: 1792498810598 }, - { hash: "aa979e1f432aed46873d5e94465bb134f8aa171c6f3a6c0a2704961e602af3cb", createdAt: 1792498810599 }, - { hash: "1a44b0f62f4bb617a16295378b48412da9baf1684bb31fa7a71dca5bc421e0a2", createdAt: 1792498810600 }, - { hash: "13006eb46e3a1b91389abd71301f03471207297ac0208f07911ac60e27930f59", createdAt: 1792498810601 }, - { hash: "6339672e38d852726eae64478250e0bc3628c248d8419c65aeced0431f0c86e5", createdAt: 1792498810602 }, - { hash: "ed8849bb66aac03150a1414db4485fc086aab6608c8e838b9621efb062d0b0cb", createdAt: 1792507212651 }, -]; -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -afterEach(async () => { while (cleanups.length) await cleanups.pop()?.(); }); - -async function database() { - const temporary = await startEmbeddedPostgresTestDatabase("paperclip-case-migration-"); - cleanups.push(temporary.cleanup); - const sql = postgres(temporary.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(() => sql.end()); - return { ...temporary, sql }; -} - -async function seed(sql: postgres.Sql) { - const companyId = randomUUID(), agentId = randomUUID(), projectId = randomUUID(); - const issueId = randomUUID(), doneIssueId = randomUUID(), caseId = randomUUID(), doneCaseId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Case migration', 'CMG')`; - await sql`INSERT INTO agents (id, company_id, name, role, adapter_type) VALUES (${agentId}, ${companyId}, 'Case agent', 'engineer', 'process')`; - await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES (${projectId}, ${companyId}, 'Private research', 'private')`; - await sql`INSERT INTO issues (id, company_id, title, status, assignee_agent_id) VALUES - (${issueId}, ${companyId}, 'Retained source', 'todo', ${agentId}), - (${doneIssueId}, ${companyId}, 'Completed work', 'done', ${agentId})`; - await sql`INSERT INTO cases (id, company_id, project_id, case_number, identifier, case_type, title, fields) VALUES - (${caseId}, ${companyId}, ${projectId}, 1, 'CMG-C1', 'receipt', 'Saved receipt', '{"items":[{"quantity":2,"unitPrice":3}]}'), - (${doneCaseId}, ${companyId}, null, 2, 'CMG-C2', 'receipt', 'Completed receipt', '{"total":6}')`; - await sql`INSERT INTO case_issue_links (company_id, case_id, issue_id, role) VALUES (${companyId}, ${caseId}, ${issueId}, 'work')`; - await sql`INSERT INTO case_events (company_id, case_id, kind, actor_type, payload) VALUES (${companyId}, ${caseId}, 'created', 'system', '{"saved":true}')`; - const documentId = randomUUID(); - await sql`INSERT INTO documents (id, company_id, title, latest_body) VALUES (${documentId}, ${companyId}, 'Research', 'Preserved findings')`; - await sql`INSERT INTO case_documents (company_id, case_id, document_id, key) VALUES (${companyId}, ${caseId}, ${documentId}, 'research')`; - return { companyId, agentId, projectId, issueId, doneIssueId, caseId, doneCaseId }; -} - -async function contents(sql: postgres.Sql) { - const tables = ["cases", "case_access_sources", "case_handoffs", "case_issue_links", "case_events", "case_documents", "documents", "issue_comments"]; - const rows = await Promise.all(tables.map(table => sql.unsafe(`SELECT * FROM "${table}" ORDER BY id`))); - return Object.fromEntries(tables.map((table, index) => [table, rows[index]])); -} - -async function guards(sql: postgres.Sql) { - return { - constraints: await sql`SELECT conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint - WHERE conrelid IN ('cases'::regclass, 'case_access_sources'::regclass, 'case_handoffs'::regclass, 'case_events'::regclass) ORDER BY conname`, - indexes: await sql`SELECT indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' - AND tablename IN ('cases', 'case_access_sources', 'case_handoffs', 'case_events') ORDER BY indexname`, - }; -} - -async function expectActorContextColumn(sql: postgres.Sql) { - expect(await sql`SELECT data_type, is_nullable, column_default FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'case_handoffs' AND column_name = 'actor_context'`) - .toEqual([{ data_type: "jsonb", is_nullable: "YES", column_default: null }]); -} - -describePostgres("case handoff migration upgrades", () => { - it("preserves passive case data and backfills every retained source on a first upgrade", async () => { - const { sql, connectionString } = await database(); - await sql`DROP TABLE case_handoffs, case_access_sources`; - await sql`ALTER TABLE cases DROP COLUMN work_issue_id, DROP COLUMN phase, DROP COLUMN handoff_version`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash IN ${sql(migrations.map(row => row.hash))}`; - const row = await seed(sql); - const before = await contentsWithoutRouting(sql); - await applyPendingMigrations(connectionString); - expect(await contentsWithoutRouting(sql)).toEqual(before); - expect(await sql`SELECT work_issue_id, phase, handoff_version FROM cases WHERE id = ${row.caseId}`) - .toEqual([{ work_issue_id: null, phase: null, handoff_version: 0 }]); - expect(await sql`SELECT source_kind, source_id FROM case_access_sources WHERE case_id = ${row.caseId} ORDER BY source_kind`) - .toEqual([{ source_kind: "issue", source_id: row.issueId }, { source_kind: "project", source_id: row.projectId }]); - expect(await sql`SELECT count(*)::int AS count FROM case_handoffs`).toEqual([{ count: 0 }]); - await expectActorContextColumn(sql); - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "upToDate" }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("adds nullable actor context without inventing authority for existing handoffs", async () => { - const { sql, connectionString } = await database(); - const actorContextMigration = migrations.find(migration => migration.name === "0368_abandoned_bucky.sql")!; - await sql`ALTER TABLE case_handoffs DROP COLUMN actor_context`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${actorContextMigration.hash}`; - const row = await seed(sql); - await sql`UPDATE cases SET work_issue_id = ${row.issueId}, phase = 'verification', handoff_version = 1 WHERE id = ${row.caseId}`; - const handoffId = randomUUID(); - await sql`INSERT INTO case_handoffs (id, company_id, case_id, issue_id, version, from_agent_id, destination_kind, - to_agent_id, phase, instructions, actor_type, actor_id, wakeup_request_id, idempotency_key, input_fingerprint, state) VALUES - (${handoffId}, ${row.companyId}, ${row.caseId}, ${row.issueId}, 1, ${row.agentId}, 'agent', ${row.agentId}, - 'verification', 'Preserve legacy intent', 'agent', ${row.agentId}, ${randomUUID()}, 'legacy-context', 'fingerprint', 'pending_dispatch')`; - const [before] = await sql`SELECT * FROM case_handoffs WHERE id = ${handoffId}`; - expect(await sql`SELECT column_name FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'case_handoffs' AND column_name = 'actor_context'`).toEqual([]); - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "needsMigrations", pendingMigrations: [actorContextMigration.name] }); - - await applyPendingMigrations(connectionString); - - await expectActorContextColumn(sql); - expect(await sql`SELECT * FROM case_handoffs WHERE id = ${handoffId}`).toEqual([{ ...before, actor_context: null }]); - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "upToDate" }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("replays over old feature receipts without losing records, terminal rows, or schema guards", async () => { - const { sql, connectionString } = await database(); - const row = await seed(sql); - await sql`UPDATE cases SET work_issue_id = ${row.issueId}, phase = 'verification', handoff_version = 2 WHERE id = ${row.caseId}`; - await sql`UPDATE cases SET work_issue_id = ${row.doneIssueId}, phase = 'done', handoff_version = 1, status = 'done', completed_at = now() WHERE id = ${row.doneCaseId}`; - await sql`INSERT INTO case_access_sources (company_id, case_id, source_kind, source_id) VALUES - (${row.companyId}, ${row.caseId}, 'issue', ${row.issueId}), (${row.companyId}, ${row.caseId}, 'project', ${row.projectId})`; - await sql`INSERT INTO case_handoffs (company_id, case_id, issue_id, version, from_agent_id, destination_kind, to_agent_id, - phase, instructions, actor_type, actor_id, wakeup_request_id, idempotency_key, input_fingerprint, state, completed_at) VALUES - (${row.companyId}, ${row.caseId}, ${row.issueId}, 2, ${row.agentId}, 'agent', ${row.agentId}, 'verification', 'Verify saved receipt', 'agent', ${row.agentId}, ${randomUUID()}, 'pending', 'fingerprint', 'pending_dispatch', null), - (${row.companyId}, ${row.doneCaseId}, ${row.doneIssueId}, 1, ${row.agentId}, 'done', null, 'done', 'Receipt completed', 'agent', ${row.agentId}, ${randomUUID()}, 'done', 'fingerprint', 'completed', now())`; - await sql`INSERT INTO case_events (company_id, case_id, kind, actor_type) VALUES (${row.companyId}, ${row.doneCaseId}, 'handoff_completed', 'system')`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash IN ${sql(migrations.map(item => item.hash))}`; - for (const [index, hash] of legacyHashes.entries()) { - await sql`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES (${hash}, ${1792415648299 + index})`; - } - const before = await contents(sql), beforeGuards = await guards(sql); - const beforeHistory = await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`; - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "needsMigrations", pendingMigrations: migrationNames }); - await applyPendingMigrations(connectionString); - expect(await contents(sql)).toEqual(before); - expect(await guards(sql)).toEqual(beforeGuards); - await expectActorContextColumn(sql); - const afterHistory = await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`; - expect(afterHistory).toEqual(expect.arrayContaining(beforeHistory)); - expect(afterHistory).toHaveLength(beforeHistory.length + migrations.length); - await applyPendingMigrations(connectionString); - expect(await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`).toEqual(afterHistory); - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "upToDate" }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("recognizes every already-applied receipt from the previous feature numbering", async () => { - const { sql, connectionString } = await database(); - const row = await seed(sql); - await sql`UPDATE cases SET work_issue_id = ${row.issueId}, phase = 'verification', handoff_version = 1 WHERE id = ${row.caseId}`; - await sql`INSERT INTO case_handoffs (company_id, case_id, issue_id, version, from_agent_id, destination_kind, - to_agent_id, phase, instructions, actor_type, actor_id, actor_context, wakeup_request_id, idempotency_key, input_fingerprint, state) VALUES - (${row.companyId}, ${row.caseId}, ${row.issueId}, 1, ${row.agentId}, 'agent', ${row.agentId}, - 'verification', 'Keep the existing authority context', 'agent', ${row.agentId}, '{"preserved":true}', - ${randomUUID()}, 'previous-numbering', 'fingerprint', 'pending_dispatch')`; - expect(migrations.map(migration => migration.hash)).toEqual(previousFeatureReceipts.map(receipt => receipt.hash)); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash IN ${sql(migrations.map(migration => migration.hash))}`; - for (const receipt of previousFeatureReceipts) { - await sql`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES (${receipt.hash}, ${receipt.createdAt})`; - } - const before = await contents(sql), beforeGuards = await guards(sql); - const beforeHistory = await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`; - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "upToDate" }); - await applyPendingMigrations(connectionString); - expect(await contents(sql)).toEqual(before); - expect(await guards(sql)).toEqual(beforeGuards); - expect(await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`).toEqual(beforeHistory); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("rolls back the complete migration and its receipt when a replacement guard fails", async () => { - const { sql, connectionString } = await database(); - const row = await seed(sql); - await sql`ALTER TABLE case_handoffs DROP CONSTRAINT case_handoffs_destination_check, DROP CONSTRAINT case_handoffs_destination_state_check`; - await sql`INSERT INTO case_handoffs (company_id, case_id, issue_id, version, destination_kind, phase, instructions, - actor_type, actor_id, wakeup_request_id, idempotency_key, input_fingerprint, state) VALUES - (${row.companyId}, ${row.caseId}, ${row.issueId}, 1, 'invalid', 'triage', 'Legacy invalid destination', - 'system', 'system', ${randomUUID()}, 'invalid', 'fingerprint', 'delivered')`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${migrations[3]!.hash}`; - const before = await contents(sql), beforeGuards = await guards(sql); - const beforeHistory = await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`; - await expect(applyPendingMigrations(connectionString)).rejects.toMatchObject({ code: "23514", constraint_name: "case_handoffs_destination_check" }); - expect(await contents(sql)).toEqual(before); - expect(await guards(sql)).toEqual(beforeGuards); - expect(await sql`SELECT * FROM drizzle.__drizzle_migrations ORDER BY id`).toEqual(beforeHistory); - expect(await inspectMigrations(connectionString)).toMatchObject({ status: "needsMigrations", pendingMigrations: [migrationNames[3]] }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); - -async function contentsWithoutRouting(sql: postgres.Sql) { - return { - cases: await sql`SELECT id, company_id, project_id, case_number, identifier, case_type, title, fields, status FROM cases ORDER BY id`, - links: await sql`SELECT * FROM case_issue_links ORDER BY id`, - events: await sql`SELECT * FROM case_events ORDER BY id`, - documents: await sql`SELECT * FROM documents ORDER BY id`, - caseDocuments: await sql`SELECT * FROM case_documents ORDER BY id`, - }; -} diff --git a/packages/db/src/chat-github-migration.test.ts b/packages/db/src/chat-github-migration.test.ts deleted file mode 100644 index 65ce3791c2e..00000000000 --- a/packages/db/src/chat-github-migration.test.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -describePostgres("GitHub preview migration replay", () => { - it("preserves existing relations and constraints when the renumbered migration runs again", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-github-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const relations = () => sql`SELECT oid::text, relname FROM pg_class WHERE relname IN ('chat_github_configurations', 'chat_github_registrations', 'chat_github_reviews') ORDER BY relname`; - const constraints = () => sql`SELECT oid::text, conname, pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conrelid IN ('chat_github_configurations'::regclass, 'chat_github_registrations'::regclass, 'chat_github_reviews'::regclass) ORDER BY conname`; - const beforeRelations = await relations(); - const beforeConstraints = await constraints(); - expect(beforeRelations).toHaveLength(3); - expect(beforeConstraints.some((row) => row.definition.includes("FOREIGN KEY (company_id, endpoint_id)"))).toBe(true); - const migration = await readFile(new URL("./migrations/0283_jittery_psynapse.sql", import.meta.url), "utf8"); - for (let attempt = 0; attempt < 2; attempt += 1) { - for (const statement of migration.split("--> statement-breakpoint")) { - if (statement.trim()) await sql.unsafe(statement); - } - expect(await relations()).toEqual(beforeRelations); - expect(await constraints()).toEqual(beforeConstraints); - } - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/chat-identity-migration-reconciliation.test.ts b/packages/db/src/chat-identity-migration-reconciliation.test.ts deleted file mode 100644 index d06e7153496..00000000000 --- a/packages/db/src/chat-identity-migration-reconciliation.test.ts +++ /dev/null @@ -1,731 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { mkdir, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { drizzle } from "drizzle-orm/postgres-js"; -import { migrate } from "drizzle-orm/postgres-js/migrator"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { - applyPendingMigrations, - closeRegisteredClients, - ensurePostgresDatabase, - inspectMigrations, -} from "./client.js"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -// The deployed chat branch used 0240–0249 before master added its independent -// 0240–0245 execution-identity chain. These are the exact original SQL hashes, -// not hashes of regenerated DDL: the interaction migration also repairs data -// and must never run again just because its filename moved. -// The next upstream chain occupies0246–0254. Chat files now use0255–0268; -// historical data-repair audit labels remain byte-identical. -const chatMigrations = [ - [ - "0255_previous_captain_america", - "2cbd1eb88d3bf4c82b72fdfd78dce72ecd7899f85607a76fb7e40b2749fffa00", - 1788580015986, - ], - [ - "0256_married_king_cobra", - "f352a8769496412df3be35050df02110714af3a189d92b3c2ac8d097e2612c7b", - 1788581746772, - ], - [ - "0257_bizarre_the_hunter", - "4e4636a22fb06aac55a998a0c98d043ec70083c198c94a0f5e0a99f18a1debac", - 1788582768429, - ], - [ - "0258_typical_sauron", - "f3cb8b9d3bb3691d98a830c7ba8b4f49bbe9bb01ce2e899583d0b5c9b84d423c", - 1788585030341, - ], - [ - "0259_tan_chat", - "91012c36bfcf66615b537ce808c9cb2f1311bc6efa6aab3ed8afd0d01298af75", - 1788673647823, - ], - [ - "0260_chat_interaction_wakeup_idempotency", - "5e181169a724173d17865d537bd84c385e97e6f78e71aa795cad91734cd37ea0", - 1788688205087, - ], - [ - "0261_faulty_iceman", - "dd7a7571e080471148cff98d1138ddd046e8c1e3c256fa5bc11564d5f4766c28", - 1788704871875, - ], - [ - "0262_lying_avengers", - "59909e4edae56117c7fe0af28aa10fe30a64d151e83fe6e06debcec90658ff09", - 1788708784607, - ], - [ - "0263_nebulous_iron_lad", - "858eb11c0863e361c1ae6995e78ca365f8002e35dcb1e89dbcc8bf65dea879e3", - 1788714691806, - ], - [ - "0264_cynical_hellcat", - "d9aeacc58ae3c52d34bf50f8ea38f55435a6f8f66dc6ee87d3b78e105a86602a", - 1788793844054, - ], - [ - "0265_chat_interaction_wakeup_provenance", - "1547e6e597b50c621691ead1d25624c4bf94ca3259cf24ea4480f3fb915dd849", - 1788880065244, - ], - [ - "0266_brave_living_mummy", - "7c38ccd2fa6a9bde19d62b111f892bcabae9a8eabe5f8bf438f73a407016b56a", - 1788930085103, - ], - [ - "0267_warm_wild_child", - "6902ea71d481a26d6359c6c9b149ff0c8a388e65356b066b2fbaa33622a6c9b8", - 1788934048647, - ], - [ - "0268_lively_runaways", - "20ebd2ac15d9b467abcc5552901ecf592b38499942b3eae7d593c79fd89bd0a8", - 1788942847296, - ], -] as const; - -const identityMigrations = [ - "0240_pink_fantastic_four.sql", - "0241_conscious_adam_destine.sql", - "0242_wide_lightspeed.sql", - "0243_sleepy_metal_master.sql", - "0244_organic_meltdown.sql", - "0245_misty_nightshade.sql", -]; - -const provenanceMigration = "0265_chat_interaction_wakeup_provenance.sql"; -const legacyProvenance = "0245_chat_interaction_wakeup_idempotency"; -const canonicalProvenance = "0251_chat_interaction_wakeup_idempotency"; - -async function executeMigration(sql: postgres.Sql, file: string) { - const content = await readFile( - new URL(`./migrations/${file}`, import.meta.url), - "utf8", - ); - for (const statement of content.split("--> statement-breakpoint")) { - if (statement.trim()) await sql.unsafe(statement); - } -} - -async function migrationHash(file: string) { - const content = await readFile( - new URL(`./migrations/${file}`, import.meta.url), - ); - return createHash("sha256").update(content).digest("hex"); -} - -describe("chat and execution identity migration reconciliation", () => { - it("preserves all fourteen deployed chat SQL hashes after renumbering", async () => { - for (const [tag, hash] of chatMigrations) { - expect(await migrationHash(`${tag}.sql`), tag).toBe(hash); - } - }); - - it("keeps the identity and chat migrations in their reconciled journal order", async () => { - const journal = JSON.parse( - await readFile( - new URL("./migrations/meta/_journal.json", import.meta.url), - "utf8", - ), - ); - expect( - journal.entries - .filter( - (entry: { idx: number }) => entry.idx >= 240 && entry.idx <= 245, - ) - .map((entry: { tag: string }) => `${entry.tag}.sql`), - ).toEqual(identityMigrations); - expect( - journal.entries - .filter( - (entry: { idx: number }) => entry.idx >= 255 && entry.idx <= 268, - ) - .map((entry: { tag: string }) => entry.tag), - ).toEqual(chatMigrations.map(([tag]) => tag)); - }); -}); - -const support = await getEmbeddedPostgresTestSupport(); -(support.supported ? describe : describe.skip)( - "chat wake migration provenance", - () => { - it( - "repairs deployed provenance without replaying historical SQL or changing wake execution state", - async () => { - const database = await startEmbeddedPostgresTestDatabase( - "paperclip-chat-provenance-", - ); - const sql = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - try { - const companyId = randomUUID(), - agentId = randomUUID(), - retainedId = randomUUID(); - await sql`INSERT INTO companies (id,name,issue_prefix) VALUES (${companyId},'Provenance upgrade','PRV')`; - await sql`INSERT INTO agents (id,company_id,name) VALUES (${agentId},${companyId},'Upgrade agent')`; - const originalKey = `interaction:${randomUUID()}`; - const oldLine = `Safely retired duplicate by migration 0245; retained wake request ${retainedId}`; - const newLine = `Safely retired duplicate by migration 0251; retained wake request ${retainedId}`; - const retired = { - migration: legacyProvenance, - retainedWakeRequestId: retainedId, - originalIdempotencyKey: originalKey, - previousStatus: "queued", - linkedRunId: null, - resolution: "retired_unstarted_duplicate", - futureAuditField: { preserved: true }, - }; - const cases: Array<{ - name: string; - dedupe: postgres.JSONValue; - key?: string; - status?: string; - error?: string | null; - correct?: boolean; - correctedError?: string | null; - id?: string; - }> = [ - { - name: "retired first UUID", - id: "00000000-0000-0000-0000-000000000000", - dedupe: retired, - error: oldLine, - correct: true, - correctedError: newLine, - }, - { - name: "preserves unrelated audit prefix", - dedupe: retired, - error: `Unrelated migration 0245 note\n${oldLine}`, - correct: true, - correctedError: `Unrelated migration 0245 note\n${newLine}`, - }, - { - name: "preserves non-final generated line", - dedupe: retired, - error: `${oldLine}\nLater operator note`, - correct: true, - }, - { - name: "does not replace arbitrary suffix", - dedupe: retired, - error: `Operator quoted: ${oldLine}`, - correct: true, - }, - { - name: "does not replace another retained ID", - dedupe: retired, - error: oldLine.replace(retainedId, randomUUID()), - correct: true, - }, - { - name: "later terminalized rekeyed wake", - dedupe: { - ...retired, - previousStatus: "running", - linkedRunId: randomUUID(), - resolution: "rekeyed_preserving_execution_history", - }, - key: "historical", - status: "failed", - error: oldLine, - correct: true, - }, - { - name: "already canonical", - dedupe: { ...retired, migration: canonicalProvenance }, - error: oldLine, - }, - { - name: "unrelated migration", - dedupe: { ...retired, migration: "0245_misty_nightshade" }, - error: oldLine, - }, - { name: "array metadata", dedupe: [retired] }, - { name: "null metadata", dedupe: null }, - { name: "string metadata", dedupe: legacyProvenance }, - { - name: "unknown resolution", - dedupe: { ...retired, resolution: "unknown" }, - }, - { - name: "missing linked-run field", - dedupe: { ...retired, linkedRunId: undefined }, - }, - { - name: "malformed retained ID", - dedupe: { ...retired, retainedWakeRequestId: "not-a-uuid" }, - }, - { - name: "malformed linked-run ID", - dedupe: { - ...retired, - linkedRunId: "not-a-uuid", - resolution: "rekeyed_preserving_execution_history", - }, - key: "historical", - }, - { - name: "non-interaction source key", - dedupe: { ...retired, originalIdempotencyKey: "timer:unrelated" }, - }, - { - name: "non-string previous status", - dedupe: { ...retired, previousStatus: ["queued"] }, - }, - { - name: "inconsistent retired resolution", - dedupe: { ...retired, previousStatus: "running" }, - }, - { - name: "inconsistent rekeyed resolution", - dedupe: { - ...retired, - resolution: "rekeyed_preserving_execution_history", - }, - key: "historical", - }, - { - name: "unrelated current key", - dedupe: retired, - key: "timer:unrelated", - }, - ]; - // More than one keyset batch, including an unrelated-only middle batch. - await sql`INSERT INTO agent_wakeup_requests (id,company_id,agent_id,source,payload) - SELECT ('00000000-0000-0000-0001-' || lpad(n::text,12,'0'))::uuid, ${companyId}, ${agentId}, 'timer', '{"unrelated":true}'::jsonb - FROM generate_series(1,1001) AS n`; - const expectedChanges = new Map< - string, - { error: string | null; payload: Record } - >(); - for (const fixture of cases) { - const id = fixture.id ?? randomUUID(); - const key = - fixture.key === "historical" - ? `historical-interaction-wake-duplicate:${id}` - : (fixture.key ?? originalKey); - const payload = { - unrelated: { preserved: true }, - migrationDedupe: fixture.dedupe, - }; - const error = fixture.error ?? null; - await sql`INSERT INTO agent_wakeup_requests - (id,company_id,agent_id,source,reason,status,idempotency_key,run_id,payload,error,requested_at,claimed_at,finished_at,created_at,updated_at) - VALUES (${id},${companyId},${agentId},'automation',${fixture.name},${fixture.status ?? "skipped"},${key},${fixture.status === "failed" ? randomUUID() : null},${sql.json(payload)},${error},'2026-09-01T00:00:00Z','2026-09-01T00:00:01Z','2026-09-01T00:00:02Z','2026-09-01T00:00:00Z','2026-09-01T00:00:02Z')`; - if (fixture.correct) - expectedChanges.set(id, { - payload: { - ...payload, - migrationDedupe: { - ...(fixture.dedupe as object), - migration: canonicalProvenance, - }, - }, - error: fixture.correctedError ?? error, - }); - } - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${await migrationHash(provenanceMigration)}`; - const legacyHash = chatMigrations[5][1]; - await sql`UPDATE drizzle.__drizzle_migrations SET created_at = ${chatMigrations[5][2]} WHERE hash = ${legacyHash}`; - const historyBefore = - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - expect( - historyBefore.filter((row) => row.hash === legacyHash), - ).toHaveLength(1); - const rowsBefore = - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`; - const expected = rowsBefore.map(({ row }) => ({ - row: { ...row, ...expectedChanges.get(row.id) }, - })); - expect( - await inspectMigrations(database.connectionString), - ).toMatchObject({ - status: "needsMigrations", - pendingMigrations: [provenanceMigration], - }); - await applyPendingMigrations(database.connectionString); - expect( - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`, - ).toEqual(expected); - expect( - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations WHERE id <= ${historyBefore.at(-1)!.id} ORDER BY id`, - ).toEqual(historyBefore); - const historyAfter = - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - expect(historyAfter).toHaveLength(historyBefore.length + 1); - await executeMigration(sql, provenanceMigration); - await applyPendingMigrations(database.connectionString); - expect( - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`, - ).toEqual(expected); - expect( - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`, - ).toEqual(historyAfter); - } finally { - await sql.end(); - await database.cleanup(); - } - }, - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - ); - - it( - "corrects both original repair resolutions on a fresh migration path", - async () => { - const database = await startEmbeddedPostgresTestDatabase( - "paperclip-chat-provenance-fresh-", - ); - const sql = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - try { - const companyId = randomUUID(), - agentId = randomUUID(), - retainedId = randomUUID(), - queuedId = randomUUID(), - activeId = randomUUID(); - await sql`INSERT INTO companies (id,name,issue_prefix) VALUES (${companyId},'Fresh provenance','FPV')`; - await sql`INSERT INTO agents (id,company_id,name) VALUES (${agentId},${companyId},'Fresh agent')`; - await sql`DROP INDEX agent_wakeup_requests_question_response_delivery_idempotency_uq`; - const key = `interaction:${randomUUID()}`; - for (const [id, status, runId] of [ - [retainedId, "succeeded", randomUUID()], - [queuedId, "queued", null], - [activeId, "running", randomUUID()], - ] as const) { - await sql`INSERT INTO agent_wakeup_requests (id,company_id,agent_id,source,status,run_id,idempotency_key,payload,error) - VALUES (${id},${companyId},${agentId},'automation',${status},${runId},${key},'{"preserved":true}'::jsonb,'Prior audit')`; - } - await executeMigration(sql, `${chatMigrations[5][0]}.sql`); - const before = - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`; - expect( - before.filter( - ({ row }) => - row.payload.migrationDedupe?.migration === legacyProvenance, - ), - ).toHaveLength(2); - expect( - before.find(({ row }) => row.id === queuedId)!.row.status, - ).toBe("skipped"); - expect( - before.find(({ row }) => row.id === activeId)!.row.status, - ).toBe("running"); - await executeMigration(sql, provenanceMigration); - const expected = before.map(({ row }) => - row.id === retainedId - ? { row } - : { - row: { - ...row, - payload: { - ...row.payload, - migrationDedupe: { - ...row.payload.migrationDedupe, - migration: canonicalProvenance, - }, - }, - error: - row.id === queuedId - ? `Prior audit\nSafely retired duplicate by migration 0251; retained wake request ${retainedId}` - : row.error, - }, - }, - ); - expect( - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`, - ).toEqual(expected); - await executeMigration(sql, provenanceMigration); - expect( - await sql`SELECT row_to_json(w) AS row FROM agent_wakeup_requests w WHERE company_id = ${companyId} ORDER BY id`, - ).toEqual(expected); - } finally { - await sql.end(); - await database.cleanup(); - } - }, - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - ); - }, -); - -(support.supported ? describe : describe.skip)( - "chat identity migration upgrade", - () => { - it( - "upgrades the actual prior chat schema through the new upstream chain without replaying chat effects", - async () => { - const database = await startEmbeddedPostgresTestDatabase( - "paperclip-chat-upstream-upgrade-", - ); - const source = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - const directory = await mkdtemp( - join(tmpdir(), "paperclip-chat-old-migrations-"), - ); - const name = `legacy_chat_${randomUUID().replaceAll("-", "")}`; - const legacyUrl = new URL(database.connectionString); - legacyUrl.pathname = `/${name}`; - let legacy: postgres.Sql | null = null; - try { - expect( - await ensurePostgresDatabase(database.connectionString, name), - ).toBe("created"); - legacy = postgres(legacyUrl.href, { max: 1, onnotice: () => {} }); - const journal = JSON.parse( - await readFile( - new URL("./migrations/meta/_journal.json", import.meta.url), - "utf8", - ), - ); - const entries = journal.entries as Array<{ - idx: number; - tag: string; - when: number; - version: string; - breakpoints: boolean; - }>; - const priorEntries = entries - .filter( - (entry) => entry.idx < 246 || (entry.idx >= 255 && entry.idx <= 268), - ) - .map((entry, index) => ({ - ...entry, - idx: index, - // Exact immutable007 chat-history timestamps. Filenames are not - // persisted by Drizzle; the SQL hash and applied time are. - when: entry.idx < 255 ? entry.when : [ - 1788832469741, 1788832471197, 1788832472637, - 1788832474071, 1788832475492, 1788832476957, - 1788832478340, 1788832479792, 1788832481237, - 1788832482645, 1788880065244, 1788930085103, - 1788934048647, 1788942847296, - ][entry.idx - 255]!, - })); - expect(priorEntries.every((entry) => Number.isFinite(entry.when))).toBe(true); - await mkdir(join(directory, "meta")); - for (const entry of priorEntries) { - await writeFile( - join(directory, `${entry.tag}.sql`), - await readFile( - new URL(`./migrations/${entry.tag}.sql`, import.meta.url), - ), - ); - } - await writeFile( - join(directory, "meta/_journal.json"), - JSON.stringify({ ...journal, entries: priorEntries }), - ); - // Run the real migration engine over the prior schema, not a current - // schema with fabricated applied-history rows or dropped columns. - await migrate(drizzle(legacy), { migrationsFolder: directory }); - const companyId = randomUUID(), - agentId = randomUUID(), - applicationId = randomUUID(), - connectionId = randomUUID(), - endpointId = randomUUID(), - issueId = randomUUID(), - conversationId = randomUUID(), - publicationId = randomUUID(); - await legacy`INSERT INTO companies (id,name,issue_prefix) VALUES (${companyId},'Prior chat schema','OLD')`; - await legacy`INSERT INTO agents (id,company_id,name) VALUES (${agentId},${companyId},'Prior agent')`; - await legacy`INSERT INTO tool_applications (id,company_id,name,type) VALUES (${applicationId},${companyId},'Slack','rest_api')`; - await legacy`INSERT INTO tool_connections (id,company_id,application_id,name,uid,connection_purpose,transport) VALUES (${connectionId},${companyId},${applicationId},'Slack','old-chat','channel','chat_sdk')`; - await legacy`INSERT INTO chat_endpoints (id,company_id,connection_id,provider,public_id,assigned_agent_id) VALUES (${endpointId},${companyId},${connectionId},'slack',${randomUUID()},${agentId})`; - await legacy`INSERT INTO issues (id,company_id,title) VALUES (${issueId},${companyId},'Retained source')`; - await legacy`INSERT INTO chat_conversations (id,company_id,endpoint_id,issue_id,external_conversation_id,external_thread_id,external_label) VALUES (${conversationId},${companyId},${endpointId},${issueId},'COLD','slack:COLD:1700.1','Retained thread')`; - await legacy`INSERT INTO chat_publications (id,company_id,endpoint_id,conversation_id,issue_id,idempotency_key,payload,state,attempts) VALUES (${publicationId},${companyId},${endpointId},${conversationId},${issueId},'retained-unknown','{"text":"Do not resend"}'::jsonb,'delivery_unknown',1)`; - const before = - await legacy`SELECT row_to_json(p) AS row FROM chat_publications p ORDER BY id`; - const historyBefore = - await legacy`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - const pending = entries - .filter( - (entry) => (entry.idx >= 246 && entry.idx <= 254) || entry.idx > 268, - ) - .map((entry) => `${entry.tag}.sql`); - expect(pending).toHaveLength(9 + entries.filter((entry) => entry.idx > 268).length); - expect(await inspectMigrations(legacyUrl.href)).toMatchObject({ - status: "needsMigrations", - pendingMigrations: pending, - }); - await applyPendingMigrations(legacyUrl.href); - expect((await inspectMigrations(legacyUrl.href)).status).toBe( - "upToDate", - ); - expect( - await legacy`SELECT row_to_json(p) AS row FROM chat_publications p ORDER BY id`, - ).toEqual(before); - const historyAfter = - await legacy`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - expect(historyAfter.slice(0, historyBefore.length)).toEqual( - historyBefore, - ); - expect(historyAfter).toHaveLength( - historyBefore.length + pending.length, - ); - for (const [, hash] of chatMigrations) - expect( - historyAfter.filter((row) => row.hash === hash), - ).toHaveLength(1); - const schema = async (sql: postgres.Sql) => ({ - columns: - await sql`SELECT table_name,column_name,data_type,is_nullable,column_default FROM information_schema.columns WHERE table_schema='public' ORDER BY table_name,column_name`, - indexes: - await sql`SELECT tablename,indexname,indexdef FROM pg_indexes WHERE schemaname='public' ORDER BY tablename,indexname`, - constraints: - await sql`SELECT c.relname,k.conname,pg_get_constraintdef(k.oid) AS definition FROM pg_constraint k JOIN pg_class c ON c.oid=k.conrelid JOIN pg_namespace n ON n.oid=c.relnamespace WHERE n.nspname='public' ORDER BY c.relname,k.conname`, - }); - expect(await schema(legacy)).toEqual(await schema(source)); - await applyPendingMigrations(legacyUrl.href); - expect( - await legacy`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`, - ).toEqual(historyAfter); - expect( - await legacy`SELECT row_to_json(p) AS row FROM chat_publications p ORDER BY id`, - ).toEqual(before); - } finally { - try { - await legacy?.end(); - } finally { - try { - await source.end(); - } finally { - try { - await closeRegisteredClients(legacyUrl.href); - } finally { - try { - await database.cleanup(); - } finally { - await rm(directory, { recursive: true, force: true }); - } - } - } - } - } - }, - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - ); - - it( - "migrates a fresh database and upgrades deployed chat history without replaying chat SQL", - async () => { - const database = await startEmbeddedPostgresTestDatabase( - "paperclip-chat-identity-migration-", - ); - const sql = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - try { - expect( - (await inspectMigrations(database.connectionString)).status, - ).toBe("upToDate"); - expect( - ( - await sql`SELECT to_regclass('public.run_identity_contexts')::text AS identity, to_regclass('public.chat_publications')::text AS publications` - )[0], - ).toEqual({ - identity: "run_identity_contexts", - publications: "chat_publications", - }); - - // Restore the schema/history shape of a deployed pre-identity chat DB. - // This disposable database is owned solely by this test; no live fixture - // is modified. Its already-applied chat SQL retains the original hashes - // and timestamps, even though the checkout now uses new filenames. - await sql`ALTER TABLE heartbeat_runs DROP COLUMN active_identity_context_id`; - await sql`ALTER TABLE issues DROP COLUMN origin_identity_context_id, DROP COLUMN continuation_identity_context_id`; - await sql`ALTER TABLE issue_thread_interactions DROP COLUMN source_identity_context_id`; - await sql`DROP TABLE run_identity_contexts`; - for (const file of identityMigrations) { - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${await migrationHash(file)}`; - } - for (const [, hash, timestamp] of chatMigrations) { - await sql`UPDATE drizzle.__drizzle_migrations SET created_at = ${timestamp} WHERE hash = ${hash}`; - } - - const companyId = randomUUID(), - agentId = randomUUID(), - applicationId = randomUUID(), - connectionId = randomUUID(), - endpointId = randomUUID(), - issueId = randomUUID(), - conversationId = randomUUID(), - publicationId = randomUUID(); - await sql`INSERT INTO companies (id,name,issue_prefix) VALUES (${companyId},'Chat upgrade','CUP')`; - await sql`INSERT INTO agents (id,company_id,name) VALUES (${agentId},${companyId},'Chat agent')`; - await sql`INSERT INTO tool_applications (id,company_id,name,type) VALUES (${applicationId},${companyId},'Slack','rest_api')`; - await sql`INSERT INTO tool_connections (id,company_id,application_id,name,uid,connection_purpose,transport) VALUES (${connectionId},${companyId},${applicationId},'Slack','slack-upgrade','channel','chat_sdk')`; - await sql`INSERT INTO chat_endpoints (id,company_id,connection_id,provider,public_id,assigned_agent_id) VALUES (${endpointId},${companyId},${connectionId},'slack',${randomUUID()},${agentId})`; - await sql`INSERT INTO issues (id,company_id,title) VALUES (${issueId},${companyId},'Existing chat task')`; - await sql`INSERT INTO chat_conversations (id,company_id,endpoint_id,issue_id,external_conversation_id,external_thread_id,external_label) VALUES (${conversationId},${companyId},${endpointId},${issueId},'CUPGRADE','slack:CUPGRADE:1700.1','Existing Slack thread')`; - await sql`INSERT INTO chat_publications (id,company_id,endpoint_id,conversation_id,issue_id,idempotency_key,payload,state,attempts) VALUES (${publicationId},${companyId},${endpointId},${conversationId},${issueId},'existing-unknown-file','{"attachmentIds":["existing-attachment"]}'::jsonb,'delivery_unknown',1)`; - const rowsBefore = - await sql`SELECT row_to_json(p) AS row FROM chat_publications p WHERE id = ${publicationId}`; - const historyBefore = - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - expect( - await inspectMigrations(database.connectionString), - ).toMatchObject({ - status: "needsMigrations", - pendingMigrations: identityMigrations, - }); - - await applyPendingMigrations(database.connectionString); - expect( - (await inspectMigrations(database.connectionString)).status, - ).toBe("upToDate"); - expect( - await sql`SELECT row_to_json(p) AS row FROM chat_publications p WHERE id = ${publicationId}`, - ).toEqual(rowsBefore); - expect( - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations WHERE id <= ${historyBefore.at(-1)!.id} ORDER BY id`, - ).toEqual(historyBefore); - expect( - ( - await sql`SELECT count(*)::integer AS count FROM drizzle.__drizzle_migrations` - )[0].count, - ).toBe(historyBefore.length + identityMigrations.length); - expect( - ( - await sql`SELECT origin_identity_context_id,continuation_identity_context_id FROM issues WHERE id = ${issueId}` - )[0], - ).toEqual({ - origin_identity_context_id: null, - continuation_identity_context_id: null, - }); - const historyAfter = - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`; - await applyPendingMigrations(database.connectionString); - expect( - await sql`SELECT id,hash,created_at::text FROM drizzle.__drizzle_migrations ORDER BY id`, - ).toEqual(historyAfter); - } finally { - await sql.end(); - await database.cleanup(); - } - }, - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - ); - }, -); diff --git a/packages/db/src/client.test.ts b/packages/db/src/client.test.ts index 31a095b604f..07b4d7f7865 100644 --- a/packages/db/src/client.test.ts +++ b/packages/db/src/client.test.ts @@ -1,49 +1,24 @@ -import { createHash, randomUUID } from "node:crypto"; +import { createHash } from "node:crypto"; import fs from "node:fs"; -import { tmpdir } from "node:os"; -import { join } from "node:path"; -import { drizzle } from "drizzle-orm/postgres-js"; -import { migrate } from "drizzle-orm/postgres-js/migrator"; import { afterEach, describe, expect, it } from "vitest"; import postgres from "postgres"; import { DEFAULT_DATABASE_APPLICATION_NAME, applyPendingMigrations, - closeRegisteredClients, createDb, - ensurePostgresDatabase, inspectMigrations, resetPostgresDatabase, } from "./client.js"; import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase, } from "./test-embedded-postgres.js"; const cleanups: Array<() => Promise> = []; -const historyExternalVariables = { - master0346: ["PAPERCLIP_DB_HISTORY_MASTER_REFERENCE_URL", "PAPERCLIP_DB_HISTORY_MASTER_TARGET_URL"], - muse0348: ["PAPERCLIP_DB_HISTORY_MUSE_REFERENCE_URL", "PAPERCLIP_DB_HISTORY_MUSE_TARGET_URL"], -} as const; -const anyHistoryExternal = Object.values(historyExternalVariables).flat().some(name => process.env[name]); -const historyExternal = anyHistoryExternal ? Object.fromEntries(Object.entries(historyExternalVariables).map(([baseline, names]) => { - const values = names.map(name => { - const raw = process.env[name]; - if (!raw) throw new Error(`Supply all explicit retained-history fixture URLs: missing ${name}`); - const url = new URL(raw); - if (!["postgres:", "postgresql:"].includes(url.protocol) || !/^[A-Za-z0-9_]+_test$/.test(decodeURIComponent(url.pathname.slice(1))) - || url.search || url.hash) throw new Error(`${name} requires an explicit dedicated *_test database without overrides`); - return raw; - }); - return [baseline, { reference: values[0]!, target: values[1]! }]; -})) : undefined; -if (historyExternal && new Set(Object.values(historyExternal).flatMap(pair => [new URL(pair.reference).pathname, new URL(pair.target).pathname])).size !== 4) throw new Error("Retained-history fixture databases must be distinct"); -const embeddedPostgresSupport: Awaited> = historyExternal ? { supported: true } : await getEmbeddedPostgresTestSupport(); +const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; async function createTempDatabase(): Promise { - if (historyExternal) throw new Error("Explicit retained-history mode permits only its two selected migration cases"); const db = await startEmbeddedPostgresTestDatabase("paperclip-db-client-"); cleanups.push(db.cleanup); return db.connectionString; @@ -186,279 +161,7 @@ describeEmbeddedPostgres("resetPostgresDatabase", () => { }, 30_000); }); -type MergedHistoryEntry = { idx: number; version: string; when: number; tag: string; breakpoints: boolean }; -const mergedMasterTail = [ - { file: "0344_wide_blue_marvel.sql", when: 1791930226792, hash: "2df2e0b867f9ed65eb931b342e7f31fe8c59901da3108466c069b68cb3892f16" }, - { file: "0345_luxuriant_carmella_unuscione.sql", when: 1791978393174, hash: "d1b360d9e6acf060a67e91b5d6dc3952f9804da3d512c7097a928b30360f6426" }, - { file: "0346_cloudy_whiplash.sql", when: 1791989860950, hash: "a77d0b71eb96b4de14bbc60f5e5f00043bffacc09905ffc782f5f0cb818c4252" }, -] as const; -const canonicalMasterTail = [ - { file: "0347_flippant_imperial_guard.sql", when: 1792100545989, hash: "e159aba238be8e27e16adec236adee0febe29191ff1b4cf9cbb8d254910f4f8f" }, - { file: "0348_agent_skill_runtime_hooks.sql", when: 1792101163248, hash: "22115f83622ba83f2f494a4637f3ce404afbdf8717a5dea106421223e64d0b93" }, -] as const; -const mergedMuseTail = [ - { file: "0349_oval_dragon_lord.sql", oldFile: "0344_perpetual_eternity.sql", when: 1791904391794, hash: "5c422698d40da1d6cdc587134553e371f7c807ce9617e07d7ff77eb05810ae49" }, - { file: "0350_friendly_rhodey.sql", oldFile: "0345_lumpy_celestials.sql", when: 1791904404725, hash: "a9373b52e02fa985bf10c15da91f6681c49d8726d94d5d68fd77e5802fd47a68" }, - { file: "0351_hard_albert_cleary.sql", oldFile: "0346_powerful_epoch.sql", when: 1791904422315, hash: "65f4f08c6a8fed7396db491e0691e693636f48c4ca4fa63cd2057af38039861a" }, - { file: "0352_special_warbound.sql", oldFile: "0347_big_meggan.sql", when: 1791904430408, hash: "1d2d5834fd499b60a43778d6d14b2520e3e2980258b8c0997d80cb95465f4abf" }, - { file: "0353_skinny_gamma_corps.sql", oldFile: "0348_foamy_lightspeed.sql", when: 1791905947460, hash: "1a379bc03d80c34815546bb9f50bf1408ccf156f4a1df2d86edb0a01acdc55c0" }, -] as const; - -describeEmbeddedPostgres("merged Muse migration histories", () => { - async function schemaShape(sql: ReturnType) { - const columns = await sql` - SELECT table_name, column_name, data_type, udt_name, is_nullable, column_default - FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, ordinal_position - `; - const indexes = await sql` - SELECT tablename, indexname, indexdef FROM pg_indexes WHERE schemaname = 'public' ORDER BY tablename, indexname - `; - const constraints = await sql` - SELECT t.relname AS table_name, c.conname, pg_get_constraintdef(c.oid, true) AS definition - FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid - JOIN pg_namespace n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' ORDER BY t.relname, c.conname - `; - return { columns: Array.from(columns), indexes: Array.from(indexes), constraints: Array.from(constraints) }; - } - - async function historyRows(sql: ReturnType) { - return Array.from(await sql`SELECT id, hash, created_at::text AS created_at FROM drizzle.__drizzle_migrations ORDER BY id`); - } - - async function replayHistoricalSchema(sql: ReturnType, entries: Array<{ file: string; oldFile?: string; when: number; hash: string }>) { - await sql`CREATE SCHEMA drizzle`; - await sql`CREATE TABLE drizzle.__drizzle_migrations (id SERIAL PRIMARY KEY, hash text NOT NULL, created_at bigint)`; - let createdAt = 0; - for (const entry of entries) { - const content = await fs.promises.readFile(new URL(entry.oldFile ? `./__fixtures__/muse-preview-migrations/${entry.oldFile}` : `./migrations/${entry.file}`, import.meta.url), "utf8"); - expect(createHash("sha256").update(content).digest("hex")).toBe(entry.hash); - createdAt = Math.max(createdAt + 1, entry.when); - const applyMigration = async (executor: Pick, "unsafe">) => { - for (const statement of content.split("--> statement-breakpoint")) { - if (!statement.trim()) continue; - await executor.unsafe(statement.replace(/^(\s*ALTER TABLE "[^"]+" DROP CONSTRAINT) (?!IF EXISTS\b)/i, "$1 IF EXISTS ")); - } - await executor.unsafe("INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES ($1, $2)", [entry.hash, createdAt]); - }; - const requiresTopLevel = /\bCREATE\s+(?:UNIQUE\s+)?INDEX\s+CONCURRENTLY\b/i.test(content) - || /^\s*COMMIT\s*;/im.test(content); - if (requiresTopLevel) await applyMigration(sql); - else await sql.begin(async transaction => { await applyMigration(transaction); }); - } - } - - // Later migrations may add columns; retained rows must keep every earlier value. - function retainedColumns | null>>(after: T, before: T): T { - return Object.fromEntries(Object.entries(after).map(([table, row]) => { - const earlier = before[table]; - return [table, row && earlier ? Object.fromEntries(Object.keys(earlier).map(key => [key, row[key]])) : row]; - })) as T; - } - - async function seedRetainedRows(sql: ReturnType, withMuse: boolean) { - const userId = randomUUID(), clientId = `migration-client-${randomUUID()}`; - const [company] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Retained migration company', 'MRG') RETURNING id`; - const [agent] = await sql` - INSERT INTO agents (company_id, name, adapter_type, adapter_config) - VALUES (${company.id}, 'Retained Muse', 'paperclip_runner', '{"provider":"muse"}'::jsonb) RETURNING id - `; - const [task] = await sql` - INSERT INTO issues (company_id, title, assignee_agent_id) - VALUES (${company.id}, 'Retained task', ${agent.id}) RETURNING id - `; - const [run] = await sql` - INSERT INTO heartbeat_runs (company_id, agent_id, invocation_source, trigger_detail, status, runtime_mode, native_issue_id, context_snapshot) - VALUES (${company.id}, ${agent.id}, 'assignment', 'system', 'failed', 'native', ${task.id}, - ${JSON.stringify({ paperclipIssue: { id: task.id }, issueId: task.id })}::jsonb) RETURNING id - `; - await sql`INSERT INTO "user" (id, name, email, created_at, updated_at) VALUES (${userId}, 'Migration operator', ${`${userId}@example.test`}, now(), now())`; - await sql`INSERT INTO mcp_oauth_clients (id, name, redirect_uris) VALUES (${clientId}, 'Synthetic migration client', '["https://example.test/callback"]'::jsonb)`; - const [grant] = await sql` - INSERT INTO mcp_oauth_grants (company_id, user_id, client_id, resource, purpose, agent_id, scopes) - VALUES (${company.id}, ${userId}, ${clientId}, 'https://example.test/api/muse/v1', 'agent', ${agent.id}, '["paperclip:agent","offline_access"]'::jsonb) RETURNING id - `; - const [binding] = withMuse ? await sql` - INSERT INTO muse_agent_bindings (company_id, agent_id, operator_id, grant_id, status) - VALUES (${company.id}, ${agent.id}, ${userId}, ${grant.id}, 'connected') RETURNING id - ` : []; - return async () => { - const [companyRow] = await sql`SELECT to_jsonb(c) AS row FROM companies c WHERE id = ${company.id}`; - const [taskRow] = await sql`SELECT to_jsonb(t) AS row FROM issues t WHERE id = ${task.id}`; - const [runRow] = await sql`SELECT to_jsonb(r) AS row FROM heartbeat_runs r WHERE id = ${run.id}`; - const [grantRow] = await sql`SELECT to_jsonb(g) AS row FROM mcp_oauth_grants g WHERE id = ${grant.id}`; - const [bindingRow] = binding ? await sql`SELECT to_jsonb(b) AS row FROM muse_agent_bindings b WHERE id = ${binding.id}` : []; - return { company: companyRow.row, task: taskRow.row, run: runRow.row, grant: grantRow.row, binding: bindingRow?.row ?? null }; - }; - } - - it.each(["fresh", "master0346", "muse0348"] as const)("migrates %s through the normal loader without rewriting historical receipts", async baseline => { - const externalPair = historyExternal?.[baseline]; - const referenceUrl = externalPair?.reference ?? await createTempDatabase(); - if (externalPair) await applyPendingMigrations(referenceUrl); - const adminUrl = new URL(referenceUrl), databaseName = `merged_muse_${baseline.toLowerCase()}`; - if (!externalPair) { - adminUrl.pathname = "/postgres"; - await ensurePostgresDatabase(adminUrl.toString(), databaseName); - adminUrl.pathname = `/${databaseName}`; - } - const connectionString = externalPair?.target ?? adminUrl.toString(); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - const reference = postgres(referenceUrl, { max: 1, onnotice: () => {} }); - try { - const journal = JSON.parse(await fs.promises.readFile(new URL("./migrations/meta/_journal.json", import.meta.url), "utf8")) as { entries: MergedHistoryEntry[] }; - const common = await Promise.all(journal.entries.filter(entry => entry.idx <= 343).map(async entry => ({ - entry, file: `${entry.tag}.sql`, when: entry.when, hash: await migrationHash(`${entry.tag}.sql`), - }))); - const prefixIdentity = common.map(({ entry, hash }) => [entry.idx, entry.version, entry.when, entry.tag, entry.breakpoints, hash]); - expect(createHash("sha256").update(JSON.stringify(prefixIdentity)).digest("hex")).toBe("18063d01d91c172c556ee0bc7e84eaa35dc7c4b00b07e817c471cdf392393454"); - for (const entry of [...mergedMasterTail, ...canonicalMasterTail]) { - expect(await migrationHash(entry.file)).toBe(entry.hash); - expect(journal.entries.find(candidate => `${candidate.tag}.sql` === entry.file)?.when).toBe(entry.when); - } - for (const entry of mergedMuseTail) { - expect(await migrationHash(entry.file)).not.toBe(entry.hash); - expect(journal.entries.some(candidate => `${candidate.tag}.sql` === entry.file)).toBe(true); - } - if (baseline !== "fresh") await replayHistoricalSchema(sql, [...common, ...(baseline === "master0346" ? mergedMasterTail : mergedMuseTail)]); - const beforeHistory = baseline === "fresh" ? [] : await historyRows(sql); - const retainedRows = baseline === "fresh" ? null : await seedRetainedRows(sql, baseline === "muse0348"); - const beforeRows = await retainedRows?.(); - const expectedRetainedRows = beforeRows - ? { ...beforeRows, run: { ...beforeRows.run, legacy_process_settlement: null }, grant: { ...beforeRows.grant, revocation_index_receipt: null, revocation_revision: 0 } } - : beforeRows; - const state = await inspectMigrations(connectionString); - expect(state.status).toBe("needsMigrations"); - const laterMigrations = journal.entries.filter(entry => entry.idx > 353).map(entry => `${entry.tag}.sql`); - const expectedPending = baseline === "master0346" ? [...[...canonicalMasterTail, ...mergedMuseTail].map(entry => entry.file), ...laterMigrations] - : baseline === "muse0348" ? [...[...mergedMasterTail, ...canonicalMasterTail, ...mergedMuseTail].map(entry => entry.file), ...laterMigrations] - : journal.entries.map(entry => `${entry.tag}.sql`); - expect(state).toMatchObject({ pendingMigrations: expectedPending }); - if (baseline === "muse0348") { - expect(Number(beforeHistory.at(-1)!.created_at)).toBeGreaterThan(mergedMuseTail.at(-1)!.when); - expect(beforeHistory.slice(-5).map(row => row.hash)).toEqual(mergedMuseTail.map(entry => entry.hash)); - expect(mergedMuseTail.map(entry => entry.oldFile)).toEqual([ - "0344_perpetual_eternity.sql", "0345_lumpy_celestials.sql", "0346_powerful_epoch.sql", "0347_big_meggan.sql", "0348_foamy_lightspeed.sql", - ]); - } - await applyPendingMigrations(connectionString); - expect((await inspectMigrations(connectionString)).status).toBe("upToDate"); - const afterHistory = await historyRows(sql); - expect(afterHistory).toHaveLength(journal.entries.length + (baseline === "muse0348" ? mergedMuseTail.length : 0)); - expect(afterHistory.slice(0, beforeHistory.length)).toEqual(beforeHistory); - for (const entry of [...mergedMasterTail, ...canonicalMasterTail]) expect(afterHistory.filter(row => row.hash === entry.hash)).toHaveLength(1); - for (const entry of mergedMuseTail) { - expect(afterHistory.filter(row => row.hash === entry.hash)).toHaveLength(baseline === "muse0348" ? 1 : 0); - const currentHash = await migrationHash(entry.file); - expect(afterHistory.filter(row => row.hash === currentHash)).toHaveLength(1); - } - if (retainedRows) { - const afterRows = await retainedRows(); - expect(retainedColumns(afterRows, expectedRetainedRows!)).toEqual(expectedRetainedRows); - expect(afterRows).toMatchObject({ - run: { legacy_process_settlement: null }, - grant: { revocation_index_receipt: null, revocation_revision: 0 }, - }); - } - const indexes = await sql` - SELECT c.relname, i.indisvalid, i.indisready, pg_get_indexdef(c.oid) AS definition - FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid JOIN pg_namespace n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' AND c.relname IN ( - 'heartbeat_runs_company_ctx_paperclip_issue_created_idx', 'heartbeat_runs_company_origin_issue_idx', 'grok_dispatch_assignment_kind_idx' - ) ORDER BY c.relname - `; - expect(indexes).toHaveLength(3); - for (const index of indexes) expect(index).toMatchObject({ indisvalid: true, indisready: true }); - expect(indexes.find(index => index.relname === "heartbeat_runs_company_origin_issue_idx")!.definition).toContain("COALESCE"); - const finalShape = await schemaShape(sql); - expect(finalShape).toEqual(await schemaShape(reference)); - await applyPendingMigrations(connectionString); - expect((await inspectMigrations(connectionString)).status).toBe("upToDate"); - expect(await historyRows(sql)).toEqual(afterHistory); - expect(await schemaShape(sql)).toEqual(finalShape); - if (retainedRows) { - const afterRows = await retainedRows(); - expect(retainedColumns(afterRows, expectedRetainedRows!)).toEqual(expectedRetainedRows); - expect(afterRows).toMatchObject({ - run: { legacy_process_settlement: null }, - grant: { revocation_index_receipt: null, revocation_revision: 0 }, - }); - } - } finally { - await Promise.all([sql.end(), reference.end()]); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); - describeEmbeddedPostgres("applyPendingMigrations", () => { - it("upgrades an older clone whose replaced connection constraint is already absent", async () => { - const clusterUrl = new URL(await createTempDatabase()); - const databaseName = "missing_connection_constraint"; - clusterUrl.pathname = "/postgres"; - await ensurePostgresDatabase(clusterUrl.toString(), databaseName); - clusterUrl.pathname = "/" + databaseName; - const connectionString = clusterUrl.toString(); - const prefixFolder = await fs.promises.mkdtemp(join(tmpdir(), "paperclip-migration-prefix-")); - cleanups.push(() => fs.promises.rm(prefixFolder, { recursive: true, force: true })); - await fs.promises.mkdir(join(prefixFolder, "meta")); - const journal = JSON.parse(await fs.promises.readFile(new URL("./migrations/meta/_journal.json", import.meta.url), "utf8")); - journal.entries = journal.entries.filter((entry: { idx: number }) => entry.idx < 255); - await fs.promises.writeFile(join(prefixFolder, "meta/_journal.json"), JSON.stringify(journal)); - for (const entry of journal.entries) { - await fs.promises.copyFile(new URL(`./migrations/${entry.tag}.sql`, import.meta.url), join(prefixFolder, `${entry.tag}.sql`)); - } - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await migrate(drizzle(sql), { migrationsFolder: prefixFolder }); - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT "tool_connections_transport_check"`; - await applyPendingMigrations(connectionString); - expect((await inspectMigrations(connectionString)).status).toBe("upToDate"); - const [constraint] = await sql<{ definition: string }[]>` - SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint - WHERE conrelid = 'tool_connections'::regclass AND conname = 'tool_connections_transport_check' - `; - expect(constraint?.definition).toContain("chat_sdk"); - expect(constraint?.definition).toContain("runtime_auth"); - } finally { await sql.end(); } - }, 30_000); - - it("upgrades renumbered recovery migrations and replays their schema idempotently", async () => { - const connectionString = await createTempDatabase(); - const recoveryFiles = [ - "0250_exotic_dakota_north.sql", "0251_narrow_mastermind.sql", - "0252_friendly_kate_bishop.sql", "0253_real_firebrand.sql", - "0254_military_calypso.sql", - ]; - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - // An instance may have applied this identical SQL under the pre-rebase - // numbers, before the new session-goal and tool-action migrations existed. - for (const file of recoveryFiles) { - const hash = await migrationHash(file); - await sql`UPDATE "drizzle"."__drizzle_migrations" SET created_at = 1788825600000 WHERE hash = ${hash}`; - const source = await fs.promises.readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8"); - for (const statement of source.split("--> statement-breakpoint")) { - if (statement.trim()) await sql.unsafe(statement); - } - } - for (const file of ["0248_small_manta.sql", "0249_fast_silverclaw.sql"]) { - const hash = await migrationHash(file); - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = ${hash}`; - } - await applyPendingMigrations(connectionString); - expect((await inspectMigrations(connectionString)).status).toBe("upToDate"); - for (const file of recoveryFiles) { - const hash = await migrationHash(file); - const rows = await sql`SELECT id FROM "drizzle"."__drizzle_migrations" WHERE hash = ${hash}`; - expect(rows).toHaveLength(1); - } - const indexes = await sql`SELECT indexname FROM pg_indexes WHERE indexname = 'heartbeat_runs_native_replacement_predecessor_uq'`; - expect(indexes).toHaveLength(1); - } finally { - await sql.end(); - } - }, 30_000); - it("rejects unallowlisted migration backfills that bump updated_at on user-visible tables", async () => { const entries = await fs.promises.readdir(new URL("./migrations", import.meta.url), { withFileTypes: true, @@ -493,7 +196,6 @@ describeEmbeddedPostgres("applyPendingMigrations", () => { async () => { const connectionString = await createTempDatabase(); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); try { const richMagnetoHash = await migrationHash("0030_rich_magneto.sql"); @@ -539,1790 +241,4 @@ describeEmbeddedPostgres("applyPendingMigrations", () => { }, 20_000, ); - - it( - "replays migration 0044 safely when its schema changes already exist", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const illegalToadHash = await migrationHash("0044_illegal_toad.sql"); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${illegalToadHash}'`, - ); - - const columns = await sql.unsafe<{ column_name: string }[]>( - ` - SELECT column_name - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'instance_settings' - AND column_name = 'general' - `, - ); - expect(columns).toHaveLength(1); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0044_illegal_toad.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - }, - 20_000, - ); - - it( - "enforces a unique board_api_keys.key_hash after migration 0044", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await sql.unsafe(` - INSERT INTO "user" ("id", "name", "email", "email_verified", "created_at", "updated_at") - VALUES ('user-1', 'User One', 'user@example.com', true, now(), now()) - `); - await sql.unsafe(` - INSERT INTO "board_api_keys" ("id", "user_id", "name", "key_hash", "created_at") - VALUES ('00000000-0000-0000-0000-000000000001', 'user-1', 'Key One', 'dup-hash', now()) - `); - await expect( - sql.unsafe(` - INSERT INTO "board_api_keys" ("id", "user_id", "name", "key_hash", "created_at") - VALUES ('00000000-0000-0000-0000-000000000002', 'user-1', 'Key Two', 'dup-hash', now()) - `), - ).rejects.toThrow(); - } finally { - await sql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0046 safely when document revision columns already exist", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const smoothSentinelsHash = await migrationHash("0046_smooth_sentinels.sql"); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${smoothSentinelsHash}'`, - ); - - const columns = await sql.unsafe<{ column_name: string; is_nullable: string; column_default: string | null }[]>( - ` - SELECT column_name, is_nullable, column_default - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'document_revisions' - AND column_name IN ('title', 'format') - ORDER BY column_name - `, - ); - expect(columns).toHaveLength(2); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0046_smooth_sentinels.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const columns = await verifySql.unsafe<{ column_name: string; is_nullable: string; column_default: string | null }[]>( - ` - SELECT column_name, is_nullable, column_default - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'document_revisions' - AND column_name IN ('title', 'format') - ORDER BY column_name - `, - ); - expect(columns).toEqual([ - expect.objectContaining({ - column_name: "format", - is_nullable: "NO", - }), - expect.objectContaining({ - column_name: "title", - is_nullable: "YES", - }), - ]); - expect(columns[0]?.column_default).toContain("'markdown'"); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0047 safely when feedback tables and run columns already exist", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const overjoyedGrootHash = await migrationHash("0047_overjoyed_groot.sql"); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${overjoyedGrootHash}'`, - ); - - const tables = await sql.unsafe<{ table_name: string }[]>( - ` - SELECT table_name - FROM information_schema.tables - WHERE table_schema = 'public' - AND table_name IN ('feedback_exports', 'feedback_votes') - ORDER BY table_name - `, - ); - expect(tables.map((row) => row.table_name)).toEqual([ - "feedback_exports", - "feedback_votes", - ]); - - const columns = await sql.unsafe<{ table_name: string; column_name: string }[]>( - ` - SELECT table_name, column_name - FROM information_schema.columns - WHERE table_schema = 'public' - AND ( - (table_name = 'companies' AND column_name IN ( - 'feedback_data_sharing_enabled', - 'feedback_data_sharing_consent_at', - 'feedback_data_sharing_consent_by_user_id', - 'feedback_data_sharing_terms_version' - )) - OR (table_name = 'document_revisions' AND column_name = 'created_by_run_id') - OR (table_name = 'issue_comments' AND column_name = 'created_by_run_id') - ) - ORDER BY table_name, column_name - `, - ); - expect(columns).toHaveLength(6); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0047_overjoyed_groot.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const constraints = await verifySql.unsafe<{ conname: string }[]>( - ` - SELECT conname - FROM pg_constraint - WHERE conname IN ( - 'feedback_exports_company_id_companies_id_fk', - 'feedback_exports_feedback_vote_id_feedback_votes_id_fk', - 'feedback_exports_issue_id_issues_id_fk', - 'feedback_votes_company_id_companies_id_fk', - 'feedback_votes_issue_id_issues_id_fk' - ) - ORDER BY conname - `, - ); - expect(constraints.map((row) => row.conname)).toEqual([ - "feedback_exports_company_id_companies_id_fk", - "feedback_exports_feedback_vote_id_feedback_votes_id_fk", - "feedback_exports_issue_id_issues_id_fk", - "feedback_votes_company_id_companies_id_fk", - "feedback_votes_issue_id_issues_id_fk", - ]); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0048 safely when routines.variables already exists", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const flashyMarrowHash = await migrationHash("0048_flashy_marrow.sql"); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${flashyMarrowHash}'`, - ); - - const columns = await sql.unsafe<{ column_name: string }[]>( - ` - SELECT column_name - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'routines' - AND column_name = 'variables' - `, - ); - expect(columns).toHaveLength(1); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0048_flashy_marrow.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const columns = await verifySql.unsafe<{ column_name: string; is_nullable: string; data_type: string }[]>( - ` - SELECT column_name, is_nullable, data_type - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'routines' - AND column_name = 'variables' - `, - ); - expect(columns).toEqual([ - expect.objectContaining({ - column_name: "variables", - is_nullable: "NO", - data_type: "jsonb", - }), - ]); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0050 safely when projects.env already exists", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const stiffLuckmanHash = await migrationHash("0050_stiff_luckman.sql"); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${stiffLuckmanHash}'`, - ); - - const columns = await sql.unsafe<{ column_name: string }[]>( - ` - SELECT column_name - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'projects' - AND column_name = 'env' - `, - ); - expect(columns).toHaveLength(1); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0050_stiff_luckman.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const columns = await verifySql.unsafe<{ column_name: string; is_nullable: string; data_type: string }[]>( - ` - SELECT column_name, is_nullable, data_type - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'projects' - AND column_name = 'env' - `, - ); - expect(columns).toEqual([ - expect.objectContaining({ - column_name: "env", - is_nullable: "YES", - data_type: "jsonb", - }), - ]); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0059 safely when plugin_database_namespaces already exists", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const pluginNamespacesHash = await migrationHash( - "0059_plugin_database_namespaces.sql", - ); - - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${pluginNamespacesHash}'`, - ); - - const tables = await sql.unsafe<{ table_name: string }[]>( - ` - SELECT table_name - FROM information_schema.tables - WHERE table_schema = 'public' - AND table_name IN ('plugin_database_namespaces', 'plugin_migrations') - ORDER BY table_name - `, - ); - expect(tables.map((row) => row.table_name)).toEqual([ - "plugin_database_namespaces", - "plugin_migrations", - ]); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0059_plugin_database_namespaces.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const indexes = await verifySql.unsafe<{ indexname: string }[]>( - ` - SELECT indexname - FROM pg_indexes - WHERE schemaname = 'public' - AND tablename IN ('plugin_database_namespaces', 'plugin_migrations') - ORDER BY indexname - `, - ); - expect(indexes.map((row) => row.indexname)).toEqual( - expect.arrayContaining([ - "plugin_database_namespaces_namespace_idx", - "plugin_database_namespaces_plugin_idx", - "plugin_database_namespaces_status_idx", - "plugin_migrations_plugin_idx", - "plugin_migrations_plugin_key_idx", - "plugin_migrations_status_idx", - ]), - ); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays the built-in managed resources migration after the legacy 0136 journal entry", - async () => { - const connectionString = await createTempDatabase(); - - - const builtInResourcesHash = await migrationHash( - "0140_built_in_managed_resources.sql", - ); - const legacyBuiltInResourcesHash = createHash("sha256") - .update("legacy 0136_built_in_managed_resources.sql") - .digest("hex"); - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${builtInResourcesHash}'`, - ); - await sql.unsafe( - ` - INSERT INTO "drizzle"."__drizzle_migrations" ("hash", "created_at") - VALUES ('${legacyBuiltInResourcesHash}', 1783555200000) - `, - ); - await sql.unsafe(` - ALTER TABLE "built_in_managed_resources" - DROP CONSTRAINT IF EXISTS "built_in_managed_resources_company_id_companies_id_fk" - `); - await sql.unsafe(`DROP INDEX IF EXISTS "built_in_managed_resources_company_idx"`); - await sql.unsafe(`DROP INDEX IF EXISTS "built_in_managed_resources_resource_idx"`); - await sql.unsafe(`DROP INDEX IF EXISTS "built_in_managed_resources_company_bundle_resource_uq"`); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0140_built_in_managed_resources.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const rows = await verifySql.unsafe<{ - foreign_key_exists: boolean; - company_index_exists: boolean; - resource_index_exists: boolean; - unique_index_exists: boolean; - }[]>(` - SELECT - EXISTS ( - SELECT 1 - FROM "pg_constraint" c - JOIN "pg_class" t ON t.oid = c.conrelid - JOIN "pg_namespace" n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' - AND t.relname = 'built_in_managed_resources' - AND c.conname = 'built_in_managed_resources_company_id_companies_id_fk' - ) AS "foreign_key_exists", - EXISTS ( - SELECT 1 - FROM "pg_class" c - JOIN "pg_namespace" n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' - AND c.relkind = 'i' - AND c.relname = 'built_in_managed_resources_company_idx' - ) AS "company_index_exists", - EXISTS ( - SELECT 1 - FROM "pg_class" c - JOIN "pg_namespace" n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' - AND c.relkind = 'i' - AND c.relname = 'built_in_managed_resources_resource_idx' - ) AS "resource_index_exists", - EXISTS ( - SELECT 1 - FROM "pg_class" c - JOIN "pg_namespace" n ON n.oid = c.relnamespace - WHERE n.nspname = 'public' - AND c.relkind = 'i' - AND c.relname = 'built_in_managed_resources_company_bundle_resource_uq' - ) AS "unique_index_exists" - `); - expect(rows[0]).toEqual({ - foreign_key_exists: true, - company_index_exists: true, - resource_index_exists: true, - unique_index_exists: true, - }); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0134 without bumping issue updated_at for inbox archives", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const runResponsibleUserHash = await migrationHash( - "0134_run_responsible_user_invariant.sql", - ); - - await sql.unsafe(` - INSERT INTO "companies" ("id", "name", "issue_prefix", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000120', - 'Migration Inbox Co', - 'TST120', - '2026-03-26T09:00:00.000Z', - '2026-03-26T09:00:00.000Z' - ) - `); - await sql.unsafe(` - INSERT INTO "company_memberships" ( - "id", - "company_id", - "principal_type", - "principal_id", - "status", - "membership_role", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000121', - '00000000-0000-0000-0000-000000000120', - 'user', - 'owner-user', - 'active', - 'owner', - '2026-03-26T09:00:00.000Z', - '2026-03-26T09:00:00.000Z' - ) - `); - await sql.unsafe(` - INSERT INTO "issues" ( - "id", - "company_id", - "title", - "status", - "responsible_user_id", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000122', - '00000000-0000-0000-0000-000000000120', - 'Archived issue needing responsible user backfill', - 'todo', - NULL, - '2026-03-26T10:00:00.000Z', - '2026-03-26T10:00:00.000Z' - ) - `); - await sql.unsafe(` - INSERT INTO "issue_inbox_archives" ( - "id", - "company_id", - "issue_id", - "user_id", - "archived_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000123', - '00000000-0000-0000-0000-000000000120', - '00000000-0000-0000-0000-000000000122', - 'owner-user', - '2026-03-26T12:00:00.000Z', - '2026-03-26T12:00:00.000Z', - '2026-03-26T12:00:00.000Z' - ) - `); - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${runResponsibleUserHash}'`, - ); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0134_run_responsible_user_invariant.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const rows = await verifySql.unsafe<{ - responsible_user_id: string | null; - updated_at: Date; - inbox_archive_still_current: boolean; - }[]>(` - SELECT - i."responsible_user_id", - i."updated_at", - EXISTS ( - SELECT 1 - FROM "issue_inbox_archives" AS archive - WHERE archive."company_id" = i."company_id" - AND archive."issue_id" = i."id" - AND archive."user_id" = 'owner-user' - AND archive."archived_at" >= i."updated_at" - ) AS "inbox_archive_still_current" - FROM "issues" AS i - WHERE i."id" = '00000000-0000-0000-0000-000000000122' - `); - expect(rows).toHaveLength(1); - expect(rows[0]?.responsible_user_id).toBe("owner-user"); - expect(rows[0]?.updated_at.toISOString()).toBe("2026-03-26T10:00:00.000Z"); - expect(rows[0]?.inbox_archive_still_current).toBe(true); - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "replays migration 0135 to repair updated_at sweeps and no-op when clean", - async () => { - const connectionString = await createTempDatabase(); - - - const repairSweepHash = await migrationHash( - "0135_repair_run_responsible_user_updated_at_sweep.sql", - ); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await sql.unsafe(` - INSERT INTO "companies" ("id", "name", "issue_prefix", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000240', - 'Clean Migration Co', - 'CLN134', - '2026-04-01T09:00:00.000Z', - '2026-04-02T09:00:00.000Z' - ) - `); - await sql.unsafe(` - INSERT INTO "issues" ("id", "company_id", "title", "status", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000241', - '00000000-0000-0000-0000-000000000240', - 'Clean issue should not be touched', - 'todo', - '2026-04-01T10:00:00.000Z', - '2026-04-02T10:00:00.000Z' - ) - `); - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${repairSweepHash}'`, - ); - } finally { - await sql.end(); - } - - await applyPendingMigrations(connectionString); - - const afterCleanReplay = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const cleanRows = await afterCleanReplay.unsafe<{ updated_at: Date }[]>(` - SELECT "updated_at" - FROM "issues" - WHERE "id" = '00000000-0000-0000-0000-000000000241' - `); - expect(cleanRows[0]?.updated_at.toISOString()).toBe("2026-04-02T10:00:00.000Z"); - - await afterCleanReplay.unsafe(` - INSERT INTO "companies" ("id", "name", "issue_prefix", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000250', - 'Sweep Migration Co', - 'SWP134', - '2026-01-01T00:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000251', - '00000000-0000-0000-0000-000000000250', - 'Sweep Agent', - 'general', - 'process', - '2026-01-02T00:00:00.000Z', - '2026-01-02T00:00:00.000Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "issues" ("id", "company_id", "title", "status", "created_at", "updated_at") - SELECT - ('10000000-0000-0000-0000-' || lpad(gs::text, 12, '0'))::uuid, - '00000000-0000-0000-0000-000000000250', - 'Swept issue ' || gs::text, - 'todo', - '2026-02-01T00:00:00.000Z'::timestamptz + (gs::text || ' minutes')::interval, - '2026-04-03T12:00:00.123456Z' - FROM generate_series(1, 101) AS gs - `); - await afterCleanReplay.unsafe(` - UPDATE "issues" - SET - "status" = 'done', - "completed_at" = '2026-04-03T12:00:00.123456Z' - WHERE "id" = '10000000-0000-0000-0000-000000000003' - `); - await afterCleanReplay.unsafe(` - INSERT INTO "issue_comments" ("id", "company_id", "issue_id", "body", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000252', - '00000000-0000-0000-0000-000000000250', - '10000000-0000-0000-0000-000000000001', - 'Latest pre-sweep activity', - '2026-03-01T15:30:00.000Z', - '2026-03-02T16:45:00.000Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "heartbeat_runs" ( - "id", - "company_id", - "agent_id", - "status", - "started_at", - "finished_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000253', - '00000000-0000-0000-0000-000000000250', - '00000000-0000-0000-0000-000000000251', - 'completed', - '2026-02-10T10:00:00.000Z', - '2026-02-10T10:30:00.000Z', - '2026-02-10T09:55:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "heartbeat_runs" ( - "id", - "company_id", - "agent_id", - "status", - "started_at", - "last_output_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000256', - '00000000-0000-0000-0000-000000000250', - '00000000-0000-0000-0000-000000000251', - 'running', - '2026-02-10T11:00:00.000Z', - '2026-04-03T12:00:00.123456Z', - '2026-02-10T10:55:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "routines" ( - "id", - "company_id", - "title", - "last_triggered_at", - "last_enqueued_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000254', - '00000000-0000-0000-0000-000000000250', - 'Swept routine', - '2026-03-20T10:00:00.000Z', - '2026-03-21T11:00:00.000Z', - '2026-02-11T00:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "routines" ( - "id", - "company_id", - "title", - "last_triggered_at", - "last_enqueued_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000257', - '00000000-0000-0000-0000-000000000250', - 'Same-timestamp active routine', - '2026-03-20T10:00:00.000Z', - '2026-04-03T12:00:00.123456Z', - '2026-02-11T00:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "routine_runs" ( - "id", - "company_id", - "routine_id", - "source", - "status", - "completed_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000255', - '00000000-0000-0000-0000-000000000250', - '00000000-0000-0000-0000-000000000254', - 'schedule', - 'completed', - '2026-02-12T12:00:00.000Z', - '2026-02-12T11:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "routine_runs" ( - "id", - "company_id", - "routine_id", - "source", - "status", - "triggered_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000258', - '00000000-0000-0000-0000-000000000250', - '00000000-0000-0000-0000-000000000257', - 'schedule', - 'running', - '2026-04-03T12:00:00.123456Z', - '2026-02-12T13:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "companies" ("id", "name", "issue_prefix", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000260', - 'Coincident Timestamp Co', - 'CTS134', - '2026-01-05T00:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000261', - '00000000-0000-0000-0000-000000000260', - 'Coincident Agent', - 'general', - 'process', - '2026-01-05T00:10:00.000Z', - '2026-01-05T00:10:00.000Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "issues" ("id", "company_id", "title", "status", "created_at", "updated_at") - VALUES ( - '20000000-0000-0000-0000-000000000001', - '00000000-0000-0000-0000-000000000260', - 'Coincident timestamp issue should not be touched', - 'todo', - '2026-02-05T00:00:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe(` - INSERT INTO "heartbeat_runs" ( - "id", - "company_id", - "agent_id", - "status", - "started_at", - "finished_at", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000262', - '00000000-0000-0000-0000-000000000260', - '00000000-0000-0000-0000-000000000261', - 'completed', - '2026-02-05T10:00:00.000Z', - '2026-02-05T10:30:00.000Z', - '2026-02-05T09:55:00.000Z', - '2026-04-03T12:00:00.123456Z' - ) - `); - await afterCleanReplay.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${repairSweepHash}'`, - ); - } finally { - await afterCleanReplay.end(); - } - - await applyPendingMigrations(connectionString); - - const afterRepair = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const repairedRows = await afterRepair.unsafe<{ - subject: string; - updated_at: Date; - }[]>(` - SELECT 'company' AS subject, "updated_at" - FROM "companies" - WHERE "id" = '00000000-0000-0000-0000-000000000250' - UNION ALL - SELECT 'issue_with_comment' AS subject, "updated_at" - FROM "issues" - WHERE "id" = '10000000-0000-0000-0000-000000000001' - UNION ALL - SELECT 'issue_without_comment' AS subject, "updated_at" - FROM "issues" - WHERE "id" = '10000000-0000-0000-0000-000000000002' - UNION ALL - SELECT 'issue_with_state_activity' AS subject, "updated_at" - FROM "issues" - WHERE "id" = '10000000-0000-0000-0000-000000000003' - UNION ALL - SELECT 'heartbeat_run' AS subject, "updated_at" - FROM "heartbeat_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000253' - UNION ALL - SELECT 'heartbeat_run_with_output' AS subject, "updated_at" - FROM "heartbeat_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000256' - UNION ALL - SELECT 'other_company' AS subject, "updated_at" - FROM "companies" - WHERE "id" = '00000000-0000-0000-0000-000000000260' - UNION ALL - SELECT 'other_heartbeat_run' AS subject, "updated_at" - FROM "heartbeat_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000262' - UNION ALL - SELECT 'other_issue' AS subject, "updated_at" - FROM "issues" - WHERE "id" = '20000000-0000-0000-0000-000000000001' - UNION ALL - SELECT 'routine' AS subject, "updated_at" - FROM "routines" - WHERE "id" = '00000000-0000-0000-0000-000000000254' - UNION ALL - SELECT 'routine_with_activity' AS subject, "updated_at" - FROM "routines" - WHERE "id" = '00000000-0000-0000-0000-000000000257' - UNION ALL - SELECT 'routine_run' AS subject, "updated_at" - FROM "routine_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000255' - UNION ALL - SELECT 'routine_run_with_trigger' AS subject, "updated_at" - FROM "routine_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000258' - ORDER BY subject - `); - const repaired = Object.fromEntries( - repairedRows.map((row) => [row.subject, row.updated_at.toISOString()]), - ); - expect(repaired).toEqual({ - company: "2026-01-01T00:00:00.000Z", - heartbeat_run: "2026-02-10T10:30:00.000Z", - heartbeat_run_with_output: "2026-04-03T12:00:00.123Z", - issue_with_comment: "2026-03-02T16:45:00.000Z", - issue_with_state_activity: "2026-04-03T12:00:00.123Z", - issue_without_comment: "2026-02-01T00:02:00.000Z", - other_company: "2026-04-03T12:00:00.123Z", - other_heartbeat_run: "2026-04-03T12:00:00.123Z", - other_issue: "2026-04-03T12:00:00.123Z", - routine: "2026-03-21T11:00:00.000Z", - routine_run_with_trigger: "2026-04-03T12:00:00.123Z", - routine_with_activity: "2026-04-03T12:00:00.123Z", - routine_run: "2026-02-12T12:00:00.000Z", - }); - - await afterRepair.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${repairSweepHash}'`, - ); - } finally { - await afterRepair.end(); - } - - await applyPendingMigrations(connectionString); - - const afterSecondRun = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const secondRunRows = await afterSecondRun.unsafe<{ updated_at: Date }[]>(` - SELECT "updated_at" - FROM "issues" - WHERE "id" = '10000000-0000-0000-0000-000000000001' - `); - expect(secondRunRows[0]?.updated_at.toISOString()).toBe("2026-03-02T16:45:00.000Z"); - } finally { - await afterSecondRun.end(); - } - }, - 20_000, - ); - - it( - "replays the run responsible user repair migration when heartbeat run issue refs are identifiers", - async () => { - const connectionString = await createTempDatabase(); - - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const runResponsibleUserRepairHash = await migrationHash( - "0131_repair_run_responsible_user_context_refs.sql", - ); - - await sql.unsafe(` - INSERT INTO "companies" ("id", "name", "issue_prefix", "created_at", "updated_at") - VALUES ('00000000-0000-0000-0000-000000000130', 'Migration Test Co', 'TST130', now(), now()) - `); - await sql.unsafe(` - INSERT INTO "company_memberships" ( - "id", - "company_id", - "principal_type", - "principal_id", - "status", - "membership_role", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000131', - '00000000-0000-0000-0000-000000000130', - 'user', - 'owner-user', - 'active', - 'owner', - now(), - now() - ) - `); - await sql.unsafe(` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "created_at", "updated_at") - VALUES ( - '00000000-0000-0000-0000-000000000132', - '00000000-0000-0000-0000-000000000130', - 'Migration Agent', - 'general', - 'process', - now(), - now() - ) - `); - await sql.unsafe(` - INSERT INTO "issues" ( - "id", - "company_id", - "title", - "status", - "responsible_user_id", - "identifier", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000133', - '00000000-0000-0000-0000-000000000130', - 'Identifier referenced issue', - 'todo', - 'issue-user', - 'TST130-1', - now(), - now() - ) - `); - await sql.unsafe(` - INSERT INTO "heartbeat_runs" ( - "id", - "company_id", - "agent_id", - "status", - "responsible_user_id", - "context_snapshot", - "created_at", - "updated_at" - ) - VALUES ( - '00000000-0000-0000-0000-000000000134', - '00000000-0000-0000-0000-000000000130', - '00000000-0000-0000-0000-000000000132', - 'completed', - NULL, - '{"issueId":"TST130-1"}'::jsonb, - now(), - now() - ) - `); - await sql.unsafe( - `DELETE FROM "drizzle"."__drizzle_migrations" WHERE hash = '${runResponsibleUserRepairHash}'`, - ); - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: ["0131_repair_run_responsible_user_context_refs.sql"], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const runs = await verifySql.unsafe<{ responsible_user_id: string | null }[]>(` - SELECT "responsible_user_id" - FROM "heartbeat_runs" - WHERE "id" = '00000000-0000-0000-0000-000000000134' - `); - expect(runs).toEqual([{ responsible_user_id: "issue-user" }]); - - } finally { - await verifySql.end(); - } - }, - 20_000, - ); - - it( - "preserves legacy runs while adding native persistence and replay-safe status versioning", - async () => { - const clusterUrl = await createTempDatabase(); - await ensurePostgresDatabase(clusterUrl, "native_legacy"); - const legacyUrl = new URL(clusterUrl); - legacyUrl.pathname = "/native_legacy"; - const connectionString = legacyUrl.href; - cleanups.push(() => closeRegisteredClients(connectionString)); - const directory = await fs.promises.mkdtemp(join(tmpdir(), "paperclip-native-prior-migrations-")); - cleanups.push(() => fs.promises.rm(directory, { recursive: true, force: true })); - const migrationsRoot = new URL("./migrations/", import.meta.url); - const journal = JSON.parse(await fs.promises.readFile(new URL("meta/_journal.json", migrationsRoot), "utf8")); - const priorEntries = journal.entries.filter((entry: { idx: number }) => entry.idx < 227); - await fs.promises.mkdir(join(directory, "meta")); - for (const entry of priorEntries) { - await fs.promises.copyFile(new URL(`${entry.tag}.sql`, migrationsRoot), join(directory, `${entry.tag}.sql`)); - } - await fs.promises.writeFile(join(directory, "meta/_journal.json"), JSON.stringify({ ...journal, entries: priorEntries })); - - const nativePersistenceHash = await migrationHash("0227_modern_pandemic.sql"); - const eventSequenceUniquenessHash = await migrationHash( - "0235_heartbeat_run_event_sequence_uniqueness.sql", - ); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - const companyId = "10000000-0000-4000-8000-000000000227"; - const agentId = "20000000-0000-4000-8000-000000000227"; - const runId = "30000000-0000-4000-8000-000000000227"; - const issueId = "40000000-0000-4000-8000-000000000227"; - const contractId = "50000000-0000-4000-8000-000000000227"; - const resultId = "60000000-0000-4000-8000-000000000227"; - const assessmentId = "70000000-0000-4000-8000-000000000227"; - const decisionId = "80000000-0000-4000-8000-000000000227"; - const otherCompanyId = "11000000-0000-4000-8000-000000000227"; - const otherAgentId = "21000000-0000-4000-8000-000000000227"; - const otherRunId = "31000000-0000-4000-8000-000000000227"; - const otherIssueId = "41000000-0000-4000-8000-000000000227"; - const otherContractId = "51000000-0000-4000-8000-000000000227"; - const otherResultId = "61000000-0000-4000-8000-000000000227"; - const otherAssessmentId = "71000000-0000-4000-8000-000000000227"; - const otherDecisionId = "81000000-0000-4000-8000-000000000227"; - - try { - // Build the real pre-native schema. Downgrading the latest schema by - // dropping its unique index is invalid once later tenant FKs use it. - await migrate(drizzle(sql), { migrationsFolder: directory }); - expect(await sql`SELECT to_regclass('public.native_run_results') AS native_results`).toEqual([{ native_results: null }]); - await sql` - INSERT INTO companies (id, name, issue_prefix) - VALUES (${companyId}, 'Native persistence fixture', 'NPF') - `; - await sql` - INSERT INTO agents (id, company_id, name) - VALUES (${agentId}, ${companyId}, 'Legacy migration agent') - `; - await sql` - INSERT INTO heartbeat_runs (id, company_id, agent_id, status) - VALUES (${runId}, ${companyId}, ${agentId}, 'succeeded') - `; - await sql` - INSERT INTO issues (id, company_id, title, status) - VALUES (${issueId}, ${companyId}, 'Legacy migration issue', 'in_progress') - `; - await sql.unsafe(` - INSERT INTO heartbeat_run_events - (company_id, run_id, agent_id, seq, event_type, stream, level, message, payload, created_at) - VALUES - ('${companyId}', '${runId}', '${agentId}', 1, 'legacy.start', 'system', 'info', 'one', '{"bytes":"alpha-1"}'::jsonb, '2026-08-01T00:00:01.000Z'), - ('${companyId}', '${runId}', '${agentId}', 5, 'legacy.log', 'stdout', 'info', 'first-five', '{"bytes":"beta-5a"}'::jsonb, '2026-08-01T00:00:02.000Z'), - ('${companyId}', '${runId}', '${agentId}', 5, 'legacy.log', 'stderr', 'warn', 'duplicate-five', '{"bytes":"gamma-5b"}'::jsonb, '2026-08-01T00:00:03.000Z'), - ('${companyId}', '${runId}', '${agentId}', 9, 'legacy.end', 'system', 'info', 'nine', '{"bytes":"delta-9"}'::jsonb, '2026-08-01T00:00:04.000Z') - `); - } finally { - await sql.end(); - } - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const events = await verifySql.unsafe<{ - seq: string; - event_type: string; - stream: string; - level: string; - message: string; - payload: { bytes: string }; - created_at: Date; - }[]>(` - SELECT seq, event_type, stream, level, message, payload, created_at - FROM heartbeat_run_events - WHERE run_id = '${runId}' - ORDER BY id - `); - // 0235 preserves every legacy event while moving only duplicate - // sequence values above the old run maximum before installing the - // durable (run_id, seq) uniqueness invariant. - expect(events.map((event) => Number(event.seq))).toEqual([1, 5, 10, 9]); - expect(events.map(({ seq: _seq, ...event }) => ({ - ...event, - created_at: event.created_at.toISOString(), - }))).toEqual([ - { - event_type: "legacy.start", - stream: "system", - level: "info", - message: "one", - payload: { bytes: "alpha-1" }, - created_at: "2026-08-01T00:00:01.000Z", - }, - { - event_type: "legacy.log", - stream: "stdout", - level: "info", - message: "first-five", - payload: { bytes: "beta-5a" }, - created_at: "2026-08-01T00:00:02.000Z", - }, - { - event_type: "legacy.log", - stream: "stderr", - level: "warn", - message: "duplicate-five", - payload: { bytes: "gamma-5b" }, - created_at: "2026-08-01T00:00:03.000Z", - }, - { - event_type: "legacy.end", - stream: "system", - level: "info", - message: "nine", - payload: { bytes: "delta-9" }, - created_at: "2026-08-01T00:00:04.000Z", - }, - ]); - - const runs = await verifySql.unsafe<{ runtime_mode: string; next_event_seq: string }[]>(` - SELECT runtime_mode, next_event_seq - FROM heartbeat_runs - WHERE id = '${runId}' - `); - expect(runs.map((run) => ({ - runtimeMode: run.runtime_mode, - nextEventSeq: Number(run.next_event_seq), - }))).toEqual([{ runtimeMode: "legacy", nextEventSeq: 11 }]); - - const nativeRowsBefore = await verifySql.unsafe<{ table_name: string; row_count: number }[]>(` - SELECT 'completion_contracts' AS table_name, count(*)::int AS row_count FROM completion_contracts - UNION ALL SELECT 'native_run_results', count(*)::int FROM native_run_results - UNION ALL SELECT 'native_run_finalizations', count(*)::int FROM native_run_finalizations - UNION ALL SELECT 'work_assessments', count(*)::int FROM work_assessments - UNION ALL SELECT 'status_decisions', count(*)::int FROM status_decisions - UNION ALL SELECT 'status_decision_effects', count(*)::int FROM status_decision_effects - ORDER BY table_name - `); - expect(nativeRowsBefore.every((row) => row.row_count === 0)).toBe(true); - - await verifySql` - INSERT INTO companies (id, name, issue_prefix) - VALUES (${otherCompanyId}, 'Other native persistence fixture', 'ONP') - `; - await verifySql` - INSERT INTO agents (id, company_id, name) - VALUES (${otherAgentId}, ${otherCompanyId}, 'Other native migration agent') - `; - await verifySql` - INSERT INTO heartbeat_runs ( - id, company_id, agent_id, status, native_issue_id, completion_contract_id - ) VALUES ( - ${otherRunId}, ${otherCompanyId}, ${otherAgentId}, 'succeeded', - ${otherIssueId}, ${otherContractId} - ) - `; - await verifySql` - INSERT INTO issues (id, company_id, title, status) - VALUES (${otherIssueId}, ${otherCompanyId}, 'Other native issue', 'in_progress') - `; - await verifySql` - UPDATE heartbeat_runs - SET native_issue_id = ${issueId}, completion_contract_id = ${contractId} - WHERE id = ${runId} - `; - - await expect(verifySql` - INSERT INTO completion_contracts ( - company_id, issue_id, revision, schema_version, policy_version, - risk, completion_authority, incomplete_criteria_policy, contract_json, - canonical_sha256, created_by_actor_type, created_by_actor_id - ) VALUES ( - ${companyId}, ${otherIssueId}, 1, 'paperclip.completion-contract.v1', - 'policy-v1', 'low', 'server', 'review', ${JSON.stringify({ criteria: [] })}::jsonb, - 'cross-company-contract-sha', 'system', 'migration-test' - ) - `).rejects.toThrow(/completion_contracts_issue_company_fk/); - - await verifySql` - INSERT INTO completion_contracts ( - id, company_id, issue_id, revision, schema_version, policy_version, - risk, completion_authority, incomplete_criteria_policy, contract_json, - canonical_sha256, created_by_actor_type, created_by_actor_id - ) VALUES ( - ${contractId}, ${companyId}, ${issueId}, 1, 'paperclip.completion-contract.v1', - 'policy-v1', 'low', 'server', 'review', ${JSON.stringify({ criteria: [] })}::jsonb, - 'contract-sha', 'system', 'migration-test' - ) - `; - await verifySql` - INSERT INTO completion_contracts ( - id, company_id, issue_id, revision, schema_version, policy_version, - risk, completion_authority, incomplete_criteria_policy, contract_json, - canonical_sha256, created_by_actor_type, created_by_actor_id - ) VALUES ( - ${otherContractId}, ${otherCompanyId}, ${otherIssueId}, 1, - 'paperclip.completion-contract.v1', 'policy-v1', 'low', 'server', 'review', - ${JSON.stringify({ criteria: [] })}::jsonb, 'other-contract-sha', - 'system', 'migration-test' - ) - `; - - await expect(verifySql` - INSERT INTO native_run_results ( - company_id, issue_id, run_id, completion_contract_id, - server_fingerprint, schema_status, result_json, canonical_sha256 - ) VALUES ( - ${companyId}, ${issueId}, ${otherRunId}, ${contractId}, - 'cross-company-run', 'valid', ${JSON.stringify({ summary: "invalid" })}::jsonb, - 'cross-company-run-sha' - ) - `).rejects.toThrow(/native_run_results_run_contract_owner_fk/); - - await expect(verifySql` - INSERT INTO native_run_results ( - company_id, issue_id, run_id, completion_contract_id, - server_fingerprint, schema_status, result_json, canonical_sha256 - ) VALUES ( - ${companyId}, ${issueId}, ${runId}, ${otherContractId}, - 'cross-company-contract', 'valid', ${JSON.stringify({ summary: "invalid" })}::jsonb, - 'cross-company-contract-sha' - ) - `).rejects.toThrow(/native_run_results_run_contract_owner_fk/); - - await verifySql` - INSERT INTO native_run_results ( - id, company_id, issue_id, run_id, completion_contract_id, - server_fingerprint, schema_status, result_json, canonical_sha256 - ) VALUES ( - ${resultId}, ${companyId}, ${issueId}, ${runId}, ${contractId}, - 'result-fingerprint', 'valid', ${JSON.stringify({ summary: "done" })}::jsonb, 'result-sha' - ) - `; - await verifySql` - INSERT INTO native_run_results ( - id, company_id, issue_id, run_id, completion_contract_id, - server_fingerprint, schema_status, result_json, canonical_sha256 - ) VALUES ( - ${otherResultId}, ${otherCompanyId}, ${otherIssueId}, ${otherRunId}, - ${otherContractId}, 'other-result-fingerprint', 'valid', - ${JSON.stringify({ summary: "other" })}::jsonb, 'other-result-sha' - ) - `; - - await expect(verifySql` - INSERT INTO work_assessments ( - company_id, issue_id, run_id, contract_id, result_id, - trigger_kind, trigger_actor_company_id, prior_issue_status, - prior_status_version, policy_version, assessment_json, input_digest - ) VALUES ( - ${companyId}, ${issueId}, ${runId}, ${contractId}, ${otherResultId}, - 'run_terminal', ${companyId}, 'in_progress', 0, 'policy-v1', - ${JSON.stringify({ disposition: "invalid" })}::jsonb, - 'cross-company-assessment-input-sha' - ) - `).rejects.toThrow(/work_assessments_result_owner_fk/); - - await expect(verifySql` - INSERT INTO work_assessments ( - company_id, issue_id, run_id, contract_id, result_id, - trigger_kind, trigger_actor_company_id, prior_issue_status, - prior_status_version, policy_version, assessment_json, input_digest - ) VALUES ( - ${companyId}, ${issueId}, ${runId}, ${contractId}, ${resultId}, - 'run_terminal', ${otherCompanyId}, 'in_progress', 0, 'policy-v1', - ${JSON.stringify({ disposition: "invalid" })}::jsonb, - 'cross-company-trigger-input-sha' - ) - `).rejects.toThrow(/work_assessments_trigger_actor_company_check/); - - await verifySql` - INSERT INTO work_assessments ( - id, company_id, issue_id, run_id, contract_id, result_id, - trigger_kind, trigger_actor_company_id, prior_issue_status, - prior_status_version, policy_version, assessment_json, input_digest - ) VALUES ( - ${assessmentId}, ${companyId}, ${issueId}, ${runId}, ${contractId}, ${resultId}, - 'run_terminal', ${companyId}, 'in_progress', 0, 'policy-v1', - ${JSON.stringify({ disposition: "done" })}::jsonb, 'assessment-input-sha' - ) - `; - await verifySql` - INSERT INTO work_assessments ( - id, company_id, issue_id, run_id, contract_id, result_id, - trigger_kind, trigger_actor_company_id, prior_issue_status, - prior_status_version, policy_version, assessment_json, input_digest - ) VALUES ( - ${otherAssessmentId}, ${otherCompanyId}, ${otherIssueId}, ${otherRunId}, - ${otherContractId}, ${otherResultId}, 'run_terminal', ${otherCompanyId}, - 'in_progress', 0, 'policy-v1', - ${JSON.stringify({ disposition: "done" })}::jsonb, 'other-assessment-input-sha' - ) - `; - - await expect(verifySql` - INSERT INTO status_decisions ( - company_id, issue_id, run_id, assessment_id, decision_version, - policy_version, from_status, to_status, reason_code, - decision_json, decision_digest - ) VALUES ( - ${companyId}, ${issueId}, ${runId}, ${otherAssessmentId}, 1, - 'policy-v1', 'in_progress', 'done', 'native_result_accepted', - ${JSON.stringify({ toStatus: "done" })}::jsonb, 'cross-company-decision-sha' - ) - `).rejects.toThrow(/status_decisions_assessment_owner_fk/); - - await verifySql` - INSERT INTO status_decisions ( - id, company_id, issue_id, run_id, assessment_id, decision_version, - policy_version, from_status, to_status, reason_code, - decision_json, decision_digest - ) VALUES ( - ${decisionId}, ${companyId}, ${issueId}, ${runId}, ${assessmentId}, 1, - 'policy-v1', 'in_progress', 'done', 'native_result_accepted', - ${JSON.stringify({ toStatus: "done" })}::jsonb, 'decision-sha' - ) - `; - await verifySql` - INSERT INTO status_decisions ( - id, company_id, issue_id, run_id, assessment_id, decision_version, - policy_version, from_status, to_status, reason_code, - decision_json, decision_digest - ) VALUES ( - ${otherDecisionId}, ${otherCompanyId}, ${otherIssueId}, ${otherRunId}, - ${otherAssessmentId}, 1, 'policy-v1', 'in_progress', 'done', - 'native_result_accepted', ${JSON.stringify({ toStatus: "done" })}::jsonb, - 'other-decision-sha' - ) - `; - - await expect(verifySql` - INSERT INTO status_decision_effects ( - company_id, issue_id, decision_id, ordinal, effect_kind, - target_type, idempotency_key, payload - ) VALUES ( - ${companyId}, ${issueId}, ${otherDecisionId}, 0, 'update_issue_status', - 'issue', 'cross-company-decision-effect', ${JSON.stringify({ status: "done" })}::jsonb - ) - `).rejects.toThrow(/status_decision_effects_decision_owner_fk/); - - await verifySql` - INSERT INTO status_decision_effects ( - company_id, issue_id, decision_id, ordinal, effect_kind, - target_type, idempotency_key, payload - ) VALUES ( - ${companyId}, ${issueId}, ${decisionId}, 0, 'update_issue_status', - 'issue', 'decision-effect-1', ${JSON.stringify({ status: "done" })}::jsonb - ) - `; - - await expect(verifySql` - INSERT INTO native_run_finalizations ( - run_id, company_id, issue_id, phase, result_id, assessment_id, decision_id - ) VALUES ( - ${runId}, ${companyId}, ${issueId}, 'committed', ${resultId}, - ${assessmentId}, ${otherDecisionId} - ) - `).rejects.toThrow(/native_run_finalizations_decision_owner_fk/); - - await verifySql` - INSERT INTO native_run_finalizations ( - run_id, company_id, issue_id, phase, result_id, assessment_id, decision_id - ) VALUES ( - ${runId}, ${companyId}, ${issueId}, 'committed', ${resultId}, ${assessmentId}, ${decisionId} - ) - `; - - await verifySql`UPDATE issues SET title = 'Renamed legacy issue' WHERE id = ${issueId}`; - await verifySql`UPDATE issues SET status = 'done' WHERE id = ${issueId}`; - const issues = await verifySql.unsafe<{ status: string; status_version: string }[]>(` - SELECT status, status_version - FROM issues - WHERE id = '${issueId}' - `); - expect(issues.map((issue) => ({ - status: issue.status, - statusVersion: Number(issue.status_version), - }))).toEqual([{ status: "done", statusVersion: 1 }]); - - await verifySql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${nativePersistenceHash}`; - await verifySql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${eventSequenceUniquenessHash}`; - } finally { - await verifySql.end(); - } - - await expect(applyPendingMigrations(connectionString)).resolves.toBeUndefined(); - await expect(inspectMigrations(connectionString)).resolves.toMatchObject({ - status: "upToDate", - }); - - const replaySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const replayed = await replaySql.unsafe<{ - status_version: string; - next_event_seq: string; - trigger_count: number; - finalization_count: number; - }[]>(` - SELECT - issue.status_version, - run.next_event_seq, - ( - SELECT count(*)::int - FROM pg_trigger - WHERE tgname = 'paperclip_issue_status_version_trigger' - AND NOT tgisinternal - ) AS trigger_count, - ( - SELECT count(*)::int - FROM native_run_finalizations - WHERE run_id = '${runId}' - ) AS finalization_count - FROM issues issue - CROSS JOIN heartbeat_runs run - WHERE issue.id = '${issueId}' AND run.id = '${runId}' - `); - expect(replayed.map((row) => ({ - statusVersion: Number(row.status_version), - nextEventSeq: Number(row.next_event_seq), - triggerCount: row.trigger_count, - finalizationCount: row.finalization_count, - }))).toEqual([{ - statusVersion: 1, - nextEventSeq: 11, - triggerCount: 1, - finalizationCount: 1, - }]); - await replaySql`UPDATE issues SET assignee_agent_id = ${agentId} WHERE id = ${issueId}`; - expect(await replaySql`SELECT status_version::int FROM issues WHERE id = ${issueId}`) - .toEqual([{ status_version: 2 }]); - await replaySql`UPDATE issues SET status = 'backlog', assignee_agent_id = null, - assignee_user_id = 'handoff-owner' WHERE id = ${issueId}`; - expect(await replaySql`SELECT status_version::int FROM issues WHERE id = ${issueId}`) - .toEqual([{ status_version: 3 }]); - const assignmentVersionHash = await migrationHash("0358_issue_assignment_status_version.sql"); - await replaySql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${assignmentVersionHash}`; - await applyPendingMigrations(connectionString); - expect(await replaySql`SELECT status_version::int FROM issues WHERE id = ${issueId}`) - .toEqual([{ status_version: 3 }]); - expect(await replaySql`SELECT count(*)::int AS count FROM pg_trigger - WHERE tgname = 'paperclip_issue_assignment_version_trigger' AND NOT tgisinternal`) - .toEqual([{ count: 1 }]); - await replaySql`UPDATE issues SET assignee_user_id = null WHERE id = ${issueId}`; - expect(await replaySql`SELECT status_version::int FROM issues WHERE id = ${issueId}`) - .toEqual([{ status_version: 4 }]); - } finally { - await replaySql.end(); - } - }, - 60_000, - ); - - it( - "replays the idempotent provider trace migration", - async () => { - const connectionString = await createTempDatabase(); - const hash = await migrationHash( - "0234_provider_trace_records.sql", - ); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await sql` - DELETE FROM "drizzle"."__drizzle_migrations" - WHERE "hash" = ${hash} - `; - } finally { - await sql.end(); - } - - await expect( - applyPendingMigrations(connectionString), - ).resolves.toBeUndefined(); - await expect(inspectMigrations(connectionString)).resolves.toMatchObject({ - status: "upToDate", - }); - }, - 30_000, - ); - - it( - "removes retired model profiles from live records and configuration revisions", - async () => { - const connectionString = await createTempDatabase(); - const hash = await migrationHash("0236_remove_cheap_model_profiles.sql"); - const companyId = "10000000-0000-4000-8000-000000000236"; - const agentId = "20000000-0000-4000-8000-000000000236"; - const issueId = "30000000-0000-4000-8000-000000000236"; - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - - try { - await sql` - INSERT INTO companies (id, name, issue_prefix) - VALUES (${companyId}, 'Model profile migration fixture', 'MPF') - `; - await sql` - INSERT INTO agents (id, company_id, name, runtime_config) - VALUES ( - ${agentId}, - ${companyId}, - 'Legacy model profile agent', - '{"heartbeat":{"enabled":true},"modelProfiles":{"cheap":{"model":"legacy"}}}'::jsonb - ) - `; - await sql` - INSERT INTO issues (id, company_id, title, assignee_adapter_overrides) - VALUES ( - ${issueId}, - ${companyId}, - 'Legacy model profile issue', - '{"modelProfile":"cheap","workingDirectory":"/workspace"}'::jsonb - ) - `; - await sql` - INSERT INTO agent_config_revisions ( - company_id, - agent_id, - changed_keys, - before_config, - after_config - ) - VALUES ( - ${companyId}, - ${agentId}, - '["runtimeConfig"]'::jsonb, - '{"name":"Legacy model profile agent","runtimeConfig":{"modelProfiles":{"cheap":{"model":"legacy-before"}},"heartbeat":{"enabled":true}}}'::jsonb, - '{"name":"Legacy model profile agent","runtimeConfig":{"modelProfiles":{"cheap":{"model":"legacy-after"}},"heartbeat":{"enabled":false}}}'::jsonb - ) - `; - await sql` - DELETE FROM "drizzle"."__drizzle_migrations" - WHERE "hash" = ${hash} - `; - } finally { - await sql.end(); - } - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const [result] = await verifySql.unsafe<{ - runtime_config: Record; - assignee_adapter_overrides: Record | null; - before_config: Record; - after_config: Record; - }[]>(` - SELECT - agent.runtime_config, - issue.assignee_adapter_overrides, - revision.before_config, - revision.after_config - FROM agents agent - JOIN issues issue ON issue.company_id = agent.company_id - JOIN agent_config_revisions revision ON revision.agent_id = agent.id - WHERE agent.id = '${agentId}' AND issue.id = '${issueId}' - `); - - expect(result.runtime_config).toEqual({ heartbeat: { enabled: true } }); - expect(result.assignee_adapter_overrides).toEqual({ workingDirectory: "/workspace" }); - expect(result.before_config).toEqual({ - name: "Legacy model profile agent", - runtimeConfig: { heartbeat: { enabled: true } }, - }); - expect(result.after_config).toEqual({ - name: "Legacy model profile agent", - runtimeConfig: { heartbeat: { enabled: false } }, - }); - } finally { - await verifySql.end(); - } - }, - 30_000, - ); }); diff --git a/packages/db/src/client.ts b/packages/db/src/client.ts index 33d7ce4c72a..17ab8ba4a45 100644 --- a/packages/db/src/client.ts +++ b/packages/db/src/client.ts @@ -435,7 +435,11 @@ function trackClientEnd(client: Db, onEnd: (timeoutSeconds: number | undefined) const sql = client.$client; const end = sql.end; sql.end = async (options?: { timeout?: number }) => { - await Promise.all([onEnd(options?.timeout), end(options)]); + const resolvedOptions = + options?.timeout === undefined && process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim() + ? { ...options, timeout: 5 } + : options; + await Promise.all([onEnd(resolvedOptions?.timeout), end(resolvedOptions)]); }; } diff --git a/packages/db/src/company-secret-proposals-migration.test.ts b/packages/db/src/company-secret-proposals-migration.test.ts deleted file mode 100644 index 40e4ed629a0..00000000000 --- a/packages/db/src/company-secret-proposals-migration.test.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { createHash } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0207_moaning_amazoness.sql"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash(): Promise { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -if (!embeddedPostgresSupport.supported) { - console.warn( - `Skipping embedded Postgres company secret proposals migration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, - ); -} - -describeEmbeddedPostgres("company secret proposals migration", () => { - afterEach(async () => Promise.all(cleanups.splice(0).map((cleanup) => cleanup()))); - - // Starting an embedded Postgres and replaying a migration against it does not - // fit vitest's 5s default: the neighbouring replay suites measure 7-12s on - // CI. Every other embedded-Postgres migration test in this package carries an - // explicit timeout for that reason; this one did not, so it failed on any - // runner that was not unusually fast. - it("can be reapplied after its migration journal entry is removed", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-secret-proposals-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - - await expect(applyPendingMigrations(database.connectionString)).resolves.toBeUndefined(); - - const [result] = await sql<{ constraints: number; indexes: number }[]>` - SELECT - (SELECT count(*)::int FROM pg_constraint WHERE conrelid = 'company_secret_proposals'::regclass AND contype <> 'n') AS constraints, - (SELECT count(*)::int FROM pg_indexes WHERE tablename = 'company_secret_proposals') AS indexes - `; - expect(result).toEqual({ constraints: 14, indexes: 6 }); - }, 30_000); -}); diff --git a/packages/db/src/connection-grants-phase2-migration.test.ts b/packages/db/src/connection-grants-phase2-migration.test.ts deleted file mode 100644 index fb380437154..00000000000 --- a/packages/db/src/connection-grants-phase2-migration.test.ts +++ /dev/null @@ -1,34 +0,0 @@ -import fs from "node:fs"; -import path from "node:path"; -import { describe, expect, it } from "vitest"; - -const sql = fs.readFileSync(path.join(import.meta.dirname, "migrations/0232_fixed_hannibal_king.sql"), "utf8"); - -describe("connection grants phase 2 migration", () => { - it("renames workspace grants before restoring organization-only constraints", () => { - const rename = sql.indexOf(`UPDATE "connection_grants" SET "kind" = 'organization' WHERE "kind" = 'workspace'`); - const constraint = sql.indexOf(`"connection_grants"."kind" in ('organization', 'user')`); - expect(rename).toBeGreaterThan(-1); - expect(constraint).toBeGreaterThan(rename); - expect(sql).not.toContain(`CHECK ("connection_grants"."kind" in ('workspace', 'user'))`); - }); - - it("backfills a default organization grant only when a connection is missing one", () => { - expect(sql).toContain(`c."id", 'organization', c."credential_secret_refs", 'active', true`); - expect(sql).toContain(`WHERE NOT EXISTS`); - expect(sql).toContain(`g."connection_id" = c."id" AND g."is_default" = true`); - }); - - it("adds credential policy and the grant audience table", () => { - expect(sql).toContain(`CREATE TABLE IF NOT EXISTS "connection_grant_members"`); - expect(sql).toContain(`ADD COLUMN IF NOT EXISTS "credential_policy" text DEFAULT 'shared' NOT NULL`); - expect(sql).toContain(`'shared', 'per_user', 'per_user_with_fallback'`); - }); - - it("is safe to replay when schema state is ahead of the migration journal", () => { - expect(sql).toContain(`DROP CONSTRAINT IF EXISTS "connection_grant_members_company_grant_fk"`); - expect(sql).toContain(`DROP CONSTRAINT IF EXISTS "tool_connections_credential_policy_check"`); - expect(sql).toContain(`CREATE UNIQUE INDEX IF NOT EXISTS "connection_grants_default_uq"`); - expect(sql).toContain(`IF NOT EXISTS (\n\t\tSELECT 1\n\t\tFROM pg_constraint`); - }); -}); diff --git a/packages/db/src/connection-grants-phase4-migration.test.ts b/packages/db/src/connection-grants-phase4-migration.test.ts deleted file mode 100644 index 1fb47371f1f..00000000000 --- a/packages/db/src/connection-grants-phase4-migration.test.ts +++ /dev/null @@ -1,343 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import path from "node:path"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0232_fixed_hannibal_king.sql"; -const migrationSql = fs.readFileSync( - path.join(import.meta.dirname, "migrations", MIGRATION_FILE), - "utf8", -); -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -function migrationHash() { - return createHash("sha256").update(migrationSql).digest("hex"); -} - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -describe("connection grants phase 4 migration", () => { - it("adds replay-safe named-agent standing delegations", () => { - expect(migrationSql).toContain(`CREATE TABLE IF NOT EXISTS "connection_grant_delegations"`); - expect(migrationSql).toContain(`"connection_grant_delegations_grant_agent_uq"`); - expect(migrationSql).toContain(`FOREIGN KEY ("company_id","grant_id")`); - expect(migrationSql).toContain(`DROP CONSTRAINT IF EXISTS "connection_grant_delegations_company_grant_fk"`); - expect(migrationSql).toContain(`CREATE INDEX IF NOT EXISTS "connection_grant_delegations_company_agent_idx"`); - expect(migrationSql).toContain(`ON CONFLICT DO NOTHING`); - }); - - it("remediates ambiguous personal-secret ownership without assigning an arbitrary owner", () => { - expect(migrationSql).toContain(`phase4_ambiguous_personal_secrets`); - expect(migrationSql).toContain(`count(DISTINCT g."subject_user_id") AS "owner_count"`); - expect(migrationSql).toContain(`organization_grant."kind" <> 'user'`); - expect(migrationSql).toContain(`FROM "company_secret_bindings" binding`); - expect(migrationSql).toContain(`FROM "routine_triggers" routine_trigger`); - expect(migrationSql).toContain(`grant_row."kind" = 'user'`); - expect(migrationSql).not.toContain(`UPDATE "tool_connections" connection_row`); - expect(migrationSql).toContain(`"status" = 'needs_reauthorization'`); - }); -}); - -describeEmbeddedPostgres("connection grants phase 4 executable migration", () => { - it("converts one owner and rejects two-owner or mixed legacy references", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-connection-phase4-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - - async function rewindMigration() { - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${migrationHash()}`; - expect(await inspectMigrations(database.connectionString)).toMatchObject({ - status: "needsMigrations", - pendingMigrations: [MIGRATION_FILE], - }); - } - - async function seedLegacyCredential(input: { - ownerUserIds: string[]; - includeOrganizationGrant?: boolean; - includeConnectionReference?: boolean; - includeCompanyBinding?: boolean; - includeRoutineTrigger?: boolean; - credentialPolicy?: "shared" | "per_user" | "per_user_with_fallback"; - }) { - const companyId = randomUUID(); - const applicationId = randomUUID(); - const connectionId = randomUUID(); - const secretId = randomUUID(); - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, ${`Phase 4 ${companyId}`}, ${`P${companyId.slice(0, 5)}`}) - `; - await sql` - INSERT INTO "tool_applications" ("id", "company_id", "name", "type") - VALUES (${applicationId}, ${companyId}, ${`App ${applicationId}`}, 'mcp_http') - `; - await sql` - INSERT INTO "tool_connections" ( - "id", "company_id", "application_id", "name", "uid", "transport", - "status", "enabled", "health_status", "credential_policy", "credential_secret_refs" - ) VALUES ( - ${connectionId}, ${companyId}, ${applicationId}, ${`Connection ${connectionId}`}, - ${`connection-${connectionId}`}, 'mcp_remote', 'active', true, 'healthy', - ${input.credentialPolicy ?? "shared"}, - ${sql.json(input.includeConnectionReference ? [{ secretId, version: "latest" }] : [])} - ) - `; - await sql` - INSERT INTO "company_secrets" ("id", "company_id", "key", "name", "scope") - VALUES (${secretId}, ${companyId}, ${`secret-${secretId}`}, ${`Secret ${secretId}`}, 'company') - `; - for (const ownerUserId of input.ownerUserIds) { - await sql` - INSERT INTO "connection_grants" ( - "company_id", "connection_id", "kind", "subject_user_id", "credential_secret_refs" - ) VALUES ( - ${companyId}, ${connectionId}, 'user', ${ownerUserId}, - ${sql.json([{ secretId, version: "latest" }])} - ) - `; - } - if (input.includeOrganizationGrant) { - await sql` - INSERT INTO "connection_grants" ( - "company_id", "connection_id", "kind", "credential_secret_refs" - ) VALUES ( - ${companyId}, ${connectionId}, 'organization', - ${sql.json([{ secretId, version: "latest" }])} - ) - `; - } - if (input.includeCompanyBinding) { - await sql` - INSERT INTO "company_secret_bindings" ( - "company_id", "secret_id", "target_type", "target_id", "config_path" - ) VALUES ( - ${companyId}, ${secretId}, 'environment', ${randomUUID()}, 'env.SHARED_TOKEN' - ) - `; - } - if (input.includeRoutineTrigger) { - const routineId = randomUUID(); - await sql` - INSERT INTO "routines" ("id", "company_id", "title") - VALUES (${routineId}, ${companyId}, ${`Routine ${routineId}`}) - `; - await sql` - INSERT INTO "routine_triggers" ("company_id", "routine_id", "kind", "secret_id") - VALUES (${companyId}, ${routineId}, 'webhook', ${secretId}) - `; - } - return { companyId, connectionId, secretId, ownerUserId: input.ownerUserIds[0]! }; - } - - try { - const valid = await seedLegacyCredential({ ownerUserIds: ["alice"] }); - await rewindMigration(); - await applyPendingMigrations(database.connectionString); - const converted = await sql<{ - scope: string; - owner_user_id: string | null; - user_secret_definition_id: string | null; - }[]>` - SELECT "scope", "owner_user_id", "user_secret_definition_id" - FROM "company_secrets" - WHERE "id" = ${valid.secretId} - `; - expect(converted).toEqual([{ - scope: "user", - owner_user_id: valid.ownerUserId, - user_secret_definition_id: expect.any(String), - }]); - - const bound = await seedLegacyCredential({ - ownerUserIds: ["binding-owner"], - includeConnectionReference: true, - includeCompanyBinding: true, - credentialPolicy: "per_user", - }); - await rewindMigration(); - await applyPendingMigrations(database.connectionString); - expect(await sql<{ scope: string; owner_user_id: string | null }[]>` - SELECT "scope", "owner_user_id" - FROM "company_secrets" - WHERE "id" = ${bound.secretId} - `).toEqual([{ scope: "company", owner_user_id: null }]); - expect(await sql<{ status: string; enabled: boolean; credential_secret_refs: unknown[] }[]>` - SELECT "status", "enabled", "credential_secret_refs" - FROM "tool_connections" - WHERE "id" = ${bound.connectionId} - `).toEqual([{ - status: "active", - enabled: true, - credential_secret_refs: [{ secretId: bound.secretId, version: "latest" }], - }]); - - const routine = await seedLegacyCredential({ - ownerUserIds: ["routine-owner"], - includeConnectionReference: true, - includeRoutineTrigger: true, - credentialPolicy: "per_user", - }); - await rewindMigration(); - await applyPendingMigrations(database.connectionString); - expect(await sql<{ scope: string; owner_user_id: string | null }[]>` - SELECT "scope", "owner_user_id" - FROM "company_secrets" - WHERE "id" = ${routine.secretId} - `).toEqual([{ scope: "company", owner_user_id: null }]); - expect(await sql<{ status: string; enabled: boolean; credential_secret_refs: unknown[] }[]>` - SELECT "status", "enabled", "credential_secret_refs" - FROM "tool_connections" - WHERE "id" = ${routine.connectionId} - `).toEqual([{ - status: "active", - enabled: true, - credential_secret_refs: [{ secretId: routine.secretId, version: "latest" }], - }]); - expect(await sql<{ status: string; credential_secret_refs: unknown[] }[]>` - SELECT "status", "credential_secret_refs" - FROM "connection_grants" - WHERE "company_id" = ${routine.companyId} AND "kind" = 'user' - `).toEqual([{ status: "needs_reauthorization", credential_secret_refs: [] }]); - expect(await sql<{ secret_id: string }[]>` - SELECT "secret_id" - FROM "routine_triggers" - WHERE "company_id" = ${routine.companyId} - `).toEqual([{ secret_id: routine.secretId }]); - expect(await sql<{ status: string; enabled: boolean; credential_secret_refs: unknown[] }[]>` - SELECT "status", "enabled", "credential_secret_refs" - FROM "tool_connections" - WHERE "id" = ${routine.connectionId} - `).toEqual([{ - status: "active", - enabled: true, - credential_secret_refs: [{ secretId: routine.secretId, version: "latest" }], - }]); - - // Replaying also preserves the direct routine-trigger reference. - await rewindMigration(); - await applyPendingMigrations(database.connectionString); - expect(await sql<{ scope: string; owner_user_id: string | null }[]>` - SELECT "scope", "owner_user_id" - FROM "company_secrets" - WHERE "id" = ${routine.secretId} - `).toEqual([{ scope: "company", owner_user_id: null }]); - expect(await sql<{ status: string; credential_secret_refs: unknown[] }[]>` - SELECT "status", "credential_secret_refs" - FROM "connection_grants" - WHERE "company_id" = ${bound.companyId} AND "kind" = 'user' - `).toEqual([{ status: "needs_reauthorization", credential_secret_refs: [] }]); - expect(await sql<{ secret_id: string }[]>` - SELECT "secret_id" - FROM "company_secret_bindings" - WHERE "company_id" = ${bound.companyId} - `).toEqual([{ secret_id: bound.secretId }]); - - // Replaying the migration preserves the same company-scoped binding. - await rewindMigration(); - await applyPendingMigrations(database.connectionString); - expect(await sql<{ scope: string; owner_user_id: string | null }[]>` - SELECT "scope", "owner_user_id" - FROM "company_secrets" - WHERE "id" = ${bound.secretId} - `).toEqual([{ scope: "company", owner_user_id: null }]); - expect(await sql<{ status: string; enabled: boolean; credential_secret_refs: unknown[] }[]>` - SELECT "status", "enabled", "credential_secret_refs" - FROM "tool_connections" - WHERE "id" = ${bound.connectionId} - `).toEqual([{ - status: "active", - enabled: true, - credential_secret_refs: [{ secretId: bound.secretId, version: "latest" }], - }]); - - const ambiguous = await seedLegacyCredential({ ownerUserIds: ["alice", "bob"] }); - await rewindMigration(); - await expect(applyPendingMigrations(database.connectionString)).resolves.toBeUndefined(); - expect(await sql<{ - status: string; - is_default: boolean; - credential_secret_refs: unknown[]; - }[]>` - SELECT "status", "is_default", "credential_secret_refs" - FROM "connection_grants" - WHERE "company_id" = ${ambiguous.companyId} - ORDER BY "is_default" DESC, "id" - `).toEqual([ - { status: "active", is_default: true, credential_secret_refs: [] }, - { status: "needs_reauthorization", is_default: false, credential_secret_refs: [] }, - { status: "needs_reauthorization", is_default: false, credential_secret_refs: [] }, - ]); - expect(await sql<{ scope: string; owner_user_id: string | null }[]>` - SELECT "scope", "owner_user_id" - FROM "company_secrets" - WHERE "id" = ${ambiguous.secretId} - `).toEqual([{ scope: "company", owner_user_id: null }]); - - const mixed = await seedLegacyCredential({ - ownerUserIds: ["carol"], - includeOrganizationGrant: true, - includeConnectionReference: true, - }); - await rewindMigration(); - await expect(applyPendingMigrations(database.connectionString)).resolves.toBeUndefined(); - expect(await sql<{ - status: string; - enabled: boolean; - health_status: string; - credential_secret_refs: unknown[]; - }[]>` - SELECT "status", "enabled", "health_status", "credential_secret_refs" - FROM "tool_connections" - WHERE "id" = ${mixed.connectionId} - `).toEqual([{ - status: "active", - enabled: true, - health_status: "healthy", - credential_secret_refs: [{ secretId: mixed.secretId, version: "latest" }], - }]); - expect(await sql<{ - kind: string; - status: string; - is_default: boolean; - credential_secret_refs: unknown[]; - }[]>` - SELECT "kind", "status", "is_default", "credential_secret_refs" - FROM "connection_grants" - WHERE "company_id" = ${mixed.companyId} - ORDER BY "kind", "is_default" DESC, "id" - `).toEqual([ - { - kind: "organization", - status: "active", - is_default: true, - credential_secret_refs: [{ secretId: mixed.secretId, version: "latest" }], - }, - { - kind: "organization", - status: "active", - is_default: false, - credential_secret_refs: [{ secretId: mixed.secretId, version: "latest" }], - }, - { - kind: "user", - status: "needs_reauthorization", - is_default: false, - credential_secret_refs: [], - }, - ]); - } finally { - await sql.end(); - } - }, 45_000); -}); diff --git a/packages/db/src/connections-v3-schema-core-migration.test.ts b/packages/db/src/connections-v3-schema-core-migration.test.ts deleted file mode 100644 index 557ee301acb..00000000000 --- a/packages/db/src/connections-v3-schema-core-migration.test.ts +++ /dev/null @@ -1,140 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0182_connections_v3_schema_core.sql"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash() { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -describeEmbeddedPostgres("connections v3 schema core migration", () => { - afterEach(async () => Promise.all(cleanups.splice(0).map((cleanup) => cleanup()))); - - it("backfills a workspace grant and rolls back without losing the connection", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-connections-v3-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - // The fixture starts at the latest schema. Rewind the later chat FK before - // exercising migration 0182's composite connection key; never CASCADE away - // unknown dependencies or change the production constraint for this test. - const [chatForeignKey] = await sql<{ definition: string }[]>` - SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint - WHERE conrelid = 'chat_endpoints'::regclass - AND conname = 'chat_endpoints_company_connection_fk' - `; - expect(chatForeignKey?.definition).toBeTruthy(); - await sql`ALTER TABLE "chat_endpoints" DROP CONSTRAINT "chat_endpoints_company_connection_fk"`; - // Project consent is another later grant consumer; rewind only its known FK. - const [projectForeignKey] = await sql<{ definition: string }[]>` - SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint - WHERE conrelid = 'projects'::regclass - AND conname = 'projects_git_authorization_grant_id_connection_grants_id_fk' - `; - expect(projectForeignKey?.definition).toBeTruthy(); - await sql`ALTER TABLE "projects" DROP CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk"`; - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - // AI defaults arrive in 0273/0277 and depend on the composite grant key - // from 0232. Rewind those tables before recreating the 0182 grant schema. - // Router pins/cursors depend on pools, whose composite connection FK also - // arrives after 0182. Rewind these empty fixture tables in dependency order. - await sql`DROP TABLE IF EXISTS "ai_connection_task_pins"`; - await sql`DROP TABLE IF EXISTS "ai_connection_router_cursors"`; - await sql`DROP TABLE IF EXISTS "ai_connection_pools"`; - await sql`DROP TABLE IF EXISTS "ai_provider_defaults"`; - await sql`DROP TABLE IF EXISTS "ai_connection_defaults"`; - await sql`DROP TABLE IF EXISTS "connection_grant_delegations"`; - await sql`DROP TABLE IF EXISTS "connection_grant_members"`; - // Browser Use is a later grant consumer; rewind its empty fixture tables too. - await sql`DROP TABLE IF EXISTS "browser_use_browsers"`; - await sql`DROP TABLE IF EXISTS "browser_use_runs"`; - await sql`DROP TABLE IF EXISTS "browser_use_sessions"`; - await sql`DROP TABLE IF EXISTS "browser_use_settings"`; - // Managed-account observations are later consumers of the same connection key. - await sql`DROP TABLE IF EXISTS "tool_connection_app_syncs"`; - await sql`DROP TABLE IF EXISTS "tool_connection_app_snapshots"`; - // Subscription reporting adds a later grant binding; rewind the empty - // fixture table before recreating grants, preserving production FK checks. - await sql`DROP TABLE IF EXISTS "ai_subscription_connections"`; - await sql`DROP TABLE IF EXISTS "connection_grants"`; - await sql`DROP INDEX IF EXISTS "tool_connections_company_uid_uq"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT IF EXISTS "tool_connections_company_id_uq"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT IF EXISTS "tool_connections_ownership_check"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT IF EXISTS "tool_connections_transport_check"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT IF EXISTS "tool_connections_auth_kind_check"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN IF EXISTS "uid"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN IF EXISTS "ownership"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN IF EXISTS "auth_kind"`; - - const companyId = randomUUID(); - const applicationId = randomUUID(); - const connectionId = randomUUID(); - const secretId = randomUUID(); - await sql`INSERT INTO "companies" ("id", "name", "issue_prefix") VALUES (${companyId}, 'Paperclip', 'PAP')`; - await sql`INSERT INTO "tool_applications" ("id", "company_id", "application_key", "name", "type") VALUES (${applicationId}, ${companyId}, 'linear', 'Linear', 'mcp_http')`; - await sql` - INSERT INTO "tool_connections" ("id", "company_id", "application_id", "name", "connection_kind", "transport", "config", "credential_secret_refs") - VALUES (${connectionId}, ${companyId}, ${applicationId}, 'Production', 'managed', 'remote_http', '{"oauth":{"provider":"linear"}}'::jsonb, ${sql.json([{ secretId, configPath: "oauth.refresh_token" }])}) - `; - - await applyPendingMigrations(database.connectionString); - await sql.unsafe( - `ALTER TABLE "chat_endpoints" ADD CONSTRAINT "chat_endpoints_company_connection_fk" ${chatForeignKey!.definition}`, - ); - await sql.unsafe( - `ALTER TABLE "projects" ADD CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk" ${projectForeignKey!.definition}`, - ); - - const [connection] = await sql<{ uid: string; ownership: string; transport: string; auth_kind: string }[]>` - SELECT "uid", "ownership", "transport", "auth_kind" FROM "tool_connections" WHERE "id" = ${connectionId} - `; - expect(connection).toMatchObject({ ownership: "customer", transport: "mcp_remote", auth_kind: "oauth" }); - expect(connection?.uid).toMatch(/^linear\/production-[0-9a-f]{8}$/); - - const [grant] = await sql<{ kind: string; is_default: boolean; credential_secret_refs: unknown[] }[]>` - SELECT "kind", "is_default", "credential_secret_refs" FROM "connection_grants" WHERE "connection_id" = ${connectionId} - `; - expect(grant).toMatchObject({ kind: "workspace", is_default: true }); - expect(grant?.credential_secret_refs).toEqual([{ secretId, configPath: "oauth.refresh_token" }]); - - const otherCompanyId = randomUUID(); - await sql`INSERT INTO "companies" ("id", "name", "issue_prefix") VALUES (${otherCompanyId}, 'Other', 'OTH')`; - await expect(sql` - INSERT INTO "connection_grants" ("company_id", "connection_id", "kind") - VALUES (${otherCompanyId}, ${connectionId}, 'workspace') - `).rejects.toMatchObject({ code: "23503" }); - await expect(sql` - INSERT INTO "connection_grants" ("company_id", "connection_id", "kind", "subject_user_id", "is_default") - VALUES (${companyId}, ${connectionId}, 'user', 'user-1', true) - `).rejects.toMatchObject({ code: "23514" }); - - await sql`ALTER TABLE "chat_endpoints" DROP CONSTRAINT "chat_endpoints_company_connection_fk"`; - await sql`ALTER TABLE "projects" DROP CONSTRAINT "projects_git_authorization_grant_id_connection_grants_id_fk"`; - await sql`DROP TABLE IF EXISTS "connection_grant_members"`; - await sql`DROP TABLE "connection_grants"`; - await sql`DROP INDEX "tool_connections_company_uid_uq"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT "tool_connections_company_id_uq"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT "tool_connections_ownership_check"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT "tool_connections_transport_check"`; - await sql`ALTER TABLE "tool_connections" DROP CONSTRAINT "tool_connections_auth_kind_check"`; - await sql`UPDATE "tool_connections" SET "transport" = 'remote_http' WHERE "transport" = 'mcp_remote'`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN "uid"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN "ownership"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN "auth_kind"`; - - const [rolledBack] = await sql<{ id: string; transport: string }[]>` - SELECT "id", "transport" FROM "tool_connections" WHERE "id" = ${connectionId} - `; - expect(rolledBack).toEqual({ id: connectionId, transport: "remote_http" }); - }, 30_000); -}); diff --git a/packages/db/src/connector-policy-encoding-migration.test.ts b/packages/db/src/connector-policy-encoding-migration.test.ts deleted file mode 100644 index 66b1b2068db..00000000000 --- a/packages/db/src/connector-policy-encoding-migration.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, - type EmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; -const migration = "0355_agent_tool_definition_hooks.sql"; -const company = "00000000-0000-4000-8000-000000000001"; -const agent = "00000000-0000-4000-8000-000000000002"; -const whitespace = "\t\n\v\f\r \u00a0\u1680\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\ufeff"; - -describePostgres("connector policy migration database encodings", () => { - let database: EmbeddedPostgresTestDatabase | undefined; - let utf8: ReturnType | undefined; - let ascii: ReturnType | undefined; - let asciiUrl: string; - - beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("paperclip-connector-encoding-"); - utf8 = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - await utf8.unsafe("CREATE DATABASE legacy_ascii TEMPLATE template0 ENCODING 'SQL_ASCII' LC_COLLATE 'C' LC_CTYPE 'C'"); - const url = new URL(database.connectionString); - url.pathname = "/legacy_ascii"; - asciiUrl = url.toString(); - ascii = postgres(asciiUrl, { max: 1, onnotice: () => {} }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - afterAll(async () => { - try { - await Promise.all([utf8?.end(), ascii?.end()]); - } finally { - await database?.cleanup(); - } - }); - - it.each(["UTF8", "SQL_ASCII"])("migrates %s and matches JavaScript selector trimming", async (encoding) => { - const sql = encoding === "UTF8" ? utf8! : ascii!; - if (encoding === "SQL_ASCII") await applyPendingMigrations(asciiUrl); - expect((await sql`SHOW server_encoding`)[0]?.server_encoding).toBe(encoding); - for (const input of [...whitespace, whitespace, `${whitespace}${agent}${whitespace}`, "\u200b", "é", "中"]) { - const actual = await sql`SELECT * FROM paperclip_connector_policy_targets(${company}::uuid, ${sql.json({ agentIds: input })})`; - expect(Array.from(actual), JSON.stringify(input)).toEqual(input.trim() - ? [{ target_type: "agent", target_id: input.trim() }] - : [{ target_type: "company", target_id: company }]); - } - const arrays = await sql`SELECT * FROM paperclip_connector_policy_targets(${company}::uuid, - ${sql.json({ agentIds: [whitespace, agent, ` ${agent} `, null, 12] })})`; - expect(Array.from(arrays)).toEqual([ - { target_type: "agent", target_id: agent }, - { target_type: "agent", target_id: ` ${agent} ` }, - ]); - const intersection = await sql`SELECT * FROM paperclip_connector_policy_targets(${company}::uuid, - ${sql.json({ agentId: company, agentIds: [agent] })})`; - expect(Array.from(intersection)).toEqual([]); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("recognizes the shipped receipt without replaying older connector triggers", async () => { - const sql = utf8!; - const content = await readFile(new URL(`./migrations/${migration}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - const originalHash = "7ac76adac0220da522c78e51da20490aeb0f90512b4370a05af9f8dd0f75eda6"; - const before = await sql`SELECT pg_get_functiondef('paperclip_connector_runtime_changed()'::regprocedure) AS definition`; - const count = await sql`SELECT count(*)::int AS count FROM drizzle.__drizzle_migrations`; - await sql`UPDATE drizzle.__drizzle_migrations SET hash = ${originalHash} WHERE hash = ${hash}`; - await applyPendingMigrations(database!.connectionString); - expect((await inspectMigrations(database!.connectionString)).status).toBe("upToDate"); - expect(await sql`SELECT pg_get_functiondef('paperclip_connector_runtime_changed()'::regprocedure) AS definition`).toEqual(before); - expect(await sql`SELECT count(*)::int AS count FROM drizzle.__drizzle_migrations`).toEqual(count); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/decision-queue-migrations.test.ts b/packages/db/src/decision-queue-migrations.test.ts deleted file mode 100644 index 6ff23e85f26..00000000000 --- a/packages/db/src/decision-queue-migrations.test.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const DECISION_QUEUE_MIGRATIONS = [ - "0198_decision_queues_and_triage.sql", - "0199_decision_queue_composite_key.sql", - "0200_yellow_maria_hill.sql", -] as const; - -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function readMigration(fileName: string): Promise { - return fs.promises.readFile(new URL(`./migrations/${fileName}`, import.meta.url), "utf8"); -} - -async function reapplyDecisionQueueMigrations(sql: ReturnType): Promise { - for (const fileName of DECISION_QUEUE_MIGRATIONS) { - await sql.unsafe(await readMigration(fileName)); - } -} - -afterEach(async () => { - while (cleanups.length > 0) { - await cleanups.pop()?.(); - } -}); - -if (!embeddedPostgresSupport.supported) { - console.warn( - `Skipping decision queue migration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, - ); -} - -describeEmbeddedPostgres("decision queue migrations", () => { - it( - "can be reapplied without changing schema or existing data", - async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-decision-queue-migrations-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - const companyId = randomUUID(); - const queueId = randomUUID(); - const itemId = randomUUID(); - - try { - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Migration Test', 'DQM') - `; - await sql` - INSERT INTO "decision_queues" ( - "id", "company_id", "key", "title", "created_by_type", "created_by_user_id" - ) VALUES (${queueId}, ${companyId}, 'migration-test', 'Migration Test', 'user', 'test-user') - `; - await sql` - INSERT INTO "decision_queue_items" ( - "id", "company_id", "queue_id", "source_kind", "source_id", "added_by_type", "added_by_user_id" - ) VALUES (${itemId}, ${companyId}, ${queueId}, 'issue', 'DQM-1', 'user', 'test-user') - `; - - await reapplyDecisionQueueMigrations(sql); - await reapplyDecisionQueueMigrations(sql); - - const rows = await sql<{ id: string }[]>` - SELECT "id" FROM "decision_queue_items" WHERE "id" = ${itemId} - `; - expect(rows).toEqual([{ id: itemId }]); - - const constraints = await sql<{ conname: string }[]>` - SELECT "conname" - FROM "pg_constraint" - WHERE "conname" IN ( - 'decision_queues_id_company_uq', - 'decision_queue_items_queue_company_fk' - ) - ORDER BY "conname" - `; - expect(constraints).toEqual([ - { conname: "decision_queue_items_queue_company_fk" }, - { conname: "decision_queues_id_company_uq" }, - ]); - } finally { - await sql.end(); - } - }, - 30_000, - ); -}); diff --git a/packages/db/src/execution-admission-migration.test.ts b/packages/db/src/execution-admission-migration.test.ts deleted file mode 100644 index 82de5325181..00000000000 --- a/packages/db/src/execution-admission-migration.test.ts +++ /dev/null @@ -1,101 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const hashMigration = async (name: string) => createHash("sha256") - .update(await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8")).digest("hex"); -const migrationName = "0426_absent_guardian.sql"; -const migrationHash = await hashMigration(migrationName); -const retainedSetMigration = "0428_retained_admitted_project_sets.sql"; -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -describePostgres("execution admission migration", () => { - it("adds empty admission storage without changing existing projects or runs", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-execution-admission-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - await sql`DROP TABLE execution_admission_project_charges, execution_admissions, project_task_execution_policies`; - await sql`DROP FUNCTION paperclip_execution_admission_project_set_immutable`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash IN (${migrationHash}, ${await hashMigration(retainedSetMigration)})`; - const companyId = randomUUID(), agentId = randomUUID(), projectId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Upgrade', 'UPG')`; - await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Agent', 'process')`; - await sql`INSERT INTO projects (id, company_id, name, execution_workspace_policy, archived_at) VALUES - (${projectId}, ${companyId}, 'Legacy', '{"enabled":true,"sharedWorkspaceConcurrency":"serialize"}', now())`; - await sql`INSERT INTO heartbeat_runs (company_id, agent_id, status, context_snapshot) VALUES - (${companyId}, ${agentId}, 'running', ${sql.json({ projectId })})`; - const contents = async () => ({ - projects: await sql`SELECT * FROM projects ORDER BY id`, - runs: await sql`SELECT * FROM heartbeat_runs ORDER BY id`, - }); - const before = await contents(); - expect(await inspectMigrations(database.connectionString)) - .toMatchObject({ status: "needsMigrations", pendingMigrations: [migrationName, retainedSetMigration] }); - - await applyPendingMigrations(database.connectionString); - - expect(await contents()).toEqual(before); - for (const table of ["project_task_execution_policies", "execution_admissions", "execution_admission_project_charges"]) { - expect(await sql.unsafe(`SELECT count(*)::int AS count FROM "${table}"`)).toEqual([{ count: 0 }]); - } - expect((await sql`SELECT conname FROM pg_constraint WHERE conrelid = 'execution_admission_project_charges'::regclass - AND contype = 'f' ORDER BY conname`).map(row => row.conname)).toEqual([ - "execution_admission_project_charges_company_admission_fk", - "execution_admission_project_charges_company_project_fk", - ]); - expect(await inspectMigrations(database.connectionString)).toMatchObject({ status: "upToDate" }); - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("keeps the admitted sets of shipped 0426 rows that still have charges and marks settled ones unknown", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-execution-admission-sets-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - await sql`DROP TRIGGER paperclip_execution_admission_project_set_immutable ON execution_admissions`; - await sql`DROP FUNCTION paperclip_execution_admission_project_set_immutable`; - await sql`ALTER TABLE execution_admissions DROP CONSTRAINT execution_admissions_project_set_check, DROP COLUMN admitted_project_ids`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${await hashMigration(retainedSetMigration)}`; - const companyId = randomUUID(), agentId = randomUUID(); - const [a, b] = [randomUUID(), randomUUID()].sort(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Upgrade', 'UPS')`; - await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Agent', 'process')`; - await sql`INSERT INTO projects (id, company_id, name) VALUES (${b}, ${companyId}, 'B'), (${a}, ${companyId}, 'A')`; - const [live, empty, settled] = [randomUUID(), randomUUID(), randomUUID()]; - for (const id of [live, empty, settled]) { - const [run] = await sql`INSERT INTO heartbeat_runs (company_id, agent_id) VALUES (${companyId}, ${agentId}) RETURNING id`; - await sql`INSERT INTO execution_admissions (id, company_id, run_id, attempt, primary_project_id, context_revision, - settlement_id, settled_at) VALUES (${id}, ${companyId}, ${run.id}, 1, ${a}, 'issue:1', - ${id === settled ? randomUUID() : null}, ${id === settled ? sql`now()` : null})`; - } - await sql`INSERT INTO execution_admission_project_charges (admission_id, company_id, project_id) - VALUES (${live}, ${companyId}, ${b}), (${live}, ${companyId}, ${a})`; - - const sets = () => sql`SELECT id, admitted_project_ids FROM execution_admissions ORDER BY id`; - await applyPendingMigrations(database.connectionString); - - const upgraded = await sets(); - expect(upgraded).toEqual(expect.arrayContaining([ - { id: live, admitted_project_ids: [a, b] }, - { id: empty, admitted_project_ids: [] }, - { id: settled, admitted_project_ids: null }, - ])); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${await hashMigration(retainedSetMigration)}`; - await applyPendingMigrations(database.connectionString); - expect(await sets()).toEqual(upgraded); - expect(await sql`SELECT count(*)::int AS count FROM execution_admission_project_charges`).toEqual([{ count: 2 }]); - await expect(sql`UPDATE execution_admissions SET admitted_project_ids = '{}' WHERE id = ${settled}`) - .rejects.toMatchObject({ message: "execution admission project set is immutable" }); - expect(await inspectMigrations(database.connectionString)).toMatchObject({ status: "upToDate" }); - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/heartbeat-context-snapshot-index-migration.test.ts b/packages/db/src/heartbeat-context-snapshot-index-migration.test.ts deleted file mode 100644 index d1dafde28b0..00000000000 --- a/packages/db/src/heartbeat-context-snapshot-index-migration.test.ts +++ /dev/null @@ -1,98 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it, afterEach } from "vitest"; -import postgres from "postgres"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const d = support.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -d("heartbeat context_snapshot expression index migration", () => { - it("applies full migration chain and uses the new indexes", async () => { - const dbh = await startEmbeddedPostgresTestDatabase("pap16575-idx-"); - cleanups.push(() => dbh.cleanup()); - const sql = postgres(dbh.connectionString, { max: 1 }); - cleanups.push(async () => { await sql.end(); }); - - const idx = await sql`SELECT indexname FROM pg_indexes WHERE tablename IN ('heartbeat_runs','agent_wakeup_requests')`; - const names = idx.map((r) => r.indexname as string); - expect(names).toContain("heartbeat_runs_company_ctx_issue_created_idx"); - expect(names).toContain("heartbeat_runs_company_ctx_task_created_idx"); - expect(names).toContain("heartbeat_runs_company_ctx_taskkey_created_idx"); - expect(names).toContain("heartbeat_runs_company_ctx_paperclip_issue_created_idx"); - expect(names).toContain("heartbeat_runs_company_origin_issue_idx"); - expect(names).toContain("agent_wakeup_requests_company_payload_issue_idx"); - - await sql.unsafe("SET enable_seqscan = off"); - const plan = await sql.unsafe( - "EXPLAIN SELECT id FROM heartbeat_runs WHERE company_id = '00000000-0000-0000-0000-000000000001' AND context_snapshot ->> 'issueId' = 'x' ORDER BY created_at DESC, id DESC LIMIT 1", - ); - const planText = plan.map((r) => Object.values(r)[0]).join("\n"); - expect(planText).toContain("heartbeat_runs_company_ctx_issue_created_idx"); - - const taskPlan = await sql.unsafe( - "EXPLAIN SELECT id FROM heartbeat_runs WHERE company_id = '00000000-0000-0000-0000-000000000001' AND context_snapshot ->> 'taskId' = 'x' ORDER BY created_at DESC, id DESC LIMIT 1", - ); - const taskText = taskPlan.map((r) => Object.values(r)[0]).join("\n"); - expect(taskText).toContain("heartbeat_runs_company_ctx_task_created_idx"); - - // The productivity-review run scope ORs issueId/taskId/taskKey; all three - // expression indexes must exist so the planner can BitmapOr at real row - // counts instead of detoasting every run snapshot for the agent. An empty - // table plans a single index scan, so assert the taskKey index directly. - const taskKeyPlan = await sql.unsafe( - "EXPLAIN SELECT id FROM heartbeat_runs WHERE company_id = '00000000-0000-0000-0000-000000000001' AND context_snapshot ->> 'taskKey' = 'x' ORDER BY created_at DESC, id DESC LIMIT 1", - ); - const taskKeyText = taskKeyPlan.map((r) => Object.values(r)[0]).join("\n"); - expect(taskKeyText).toContain("heartbeat_runs_company_ctx_taskkey_created_idx"); - - // An empty table can use any company-prefix index for the OR. Check the - // new branch directly here; the populated benchmark proves BitmapOr use. - const redactionPlan = await sql.unsafe( - "EXPLAIN SELECT id FROM heartbeat_runs WHERE company_id = '00000000-0000-0000-0000-000000000001' AND context_snapshot -> 'paperclipIssue' ->> 'id' = 'x'", - ); - const redactionText = redactionPlan.map((r) => Object.values(r)[0]).join("\n"); - expect(redactionText).toContain("heartbeat_runs_company_ctx_paperclip_issue_created_idx"); - - const originPlan = await sql.unsafe( - "EXPLAIN SELECT id FROM heartbeat_runs WHERE company_id = '00000000-0000-0000-0000-000000000001' AND coalesce(native_issue_id::text, nullif(context_snapshot->>'issueId', ''), nullif(context_snapshot->>'taskId', ''), nullif(context_snapshot->>'taskKey', '')) IN ('x', 'SRC-1')", - ); - expect(originPlan.map((r) => Object.values(r)[0]).join("\n")) - .toContain("heartbeat_runs_company_origin_issue_idx"); - - const wakePlan = await sql.unsafe( - "EXPLAIN SELECT id FROM agent_wakeup_requests WHERE company_id = '00000000-0000-0000-0000-000000000001' AND status = 'deferred_issue_execution' AND payload ->> 'issueId' = 'x' LIMIT 1", - ); - const wakeText = wakePlan.map((r) => Object.values(r)[0]).join("\n"); - expect(wakeText).toContain("agent_wakeup_requests_company_payload_issue_idx"); - - // Idempotency: re-running the migration statements against an already - // migrated database must be a no-op, not an error. - for (const migration of [ - "./migrations/0209_heartbeat_context_snapshot_indexes.sql", - "./migrations/0210_heartbeat_context_taskkey_index.sql", - "./migrations/0345_luxuriant_carmella_unuscione.sql", - ]) { - const migrationSql = await readFile( - fileURLToPath(new URL(migration, import.meta.url)), - "utf8", - ); - const statements = migrationSql - .split("--> statement-breakpoint") - .map((s) => s.trim()) - .filter((s) => s.length > 0); - expect(statements.length).toBeGreaterThan(0); - for (const statement of statements) { - await sql.unsafe(statement); - } - } - }, 240_000); -}); diff --git a/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts b/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts deleted file mode 100644 index 6883c0c799f..00000000000 --- a/packages/db/src/heartbeat-run-issue-privacy-migration.test.ts +++ /dev/null @@ -1,286 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0313_private_task_access.sql"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -if (!embeddedPostgresSupport.supported) console.warn(`Private-task migration checks unavailable: ${embeddedPostgresSupport.reason}`); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash() { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -describeEmbeddedPostgres("heartbeat run issue privacy migration", () => { - it("backfills every valid context issue binding and preserves maintenance runs", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-run-issue-privacy-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => sql.end()); - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - - await sql`DROP TRIGGER IF EXISTS heartbeat_runs_set_scope_kind ON heartbeat_runs`; - const companyId = randomUUID(); - const agentId = randomUUID(); - const firstIssueId = randomUUID(); - const secondIssueId = randomUUID(); - const firstRunId = randomUUID(); - const secondRunId = randomUUID(); - const maintenanceRunId = randomUUID(); - - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Run Privacy', 'RPR') - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${agentId}, ${companyId}, 'Runner', 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES - (${firstIssueId}, ${companyId}, 'First private task', 'RPR-1'), - (${secondIssueId}, ${companyId}, 'Second private task', 'RPR-2') - `; - await sql` - INSERT INTO "heartbeat_runs" ( - "id", "company_id", "agent_id", "status", "issue_id", "context_snapshot" - ) - VALUES - (${firstRunId}, ${companyId}, ${agentId}, 'succeeded', NULL, ${sql.json({ issueId: firstIssueId })}), - (${secondRunId}, ${companyId}, ${agentId}, 'failed', NULL, ${sql.json({ taskId: secondIssueId })}), - (${maintenanceRunId}, ${companyId}, ${agentId}, 'succeeded', NULL, ${sql.json({ wakeReason: "heartbeat_timer" })}) - `; - - const legacyProjectId = randomUUID(); - await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES (${legacyProjectId}, ${companyId}, 'Legacy private project', 'private')`; - await sql`INSERT INTO activity_log (company_id, actor_type, actor_id, action, entity_type, entity_id) - VALUES (${companyId}, 'user', 'original-owner', 'project.created', 'project', ${legacyProjectId})`; - await sql`INSERT INTO project_access_members (company_id, project_id, subject_type, subject_id) - VALUES (${companyId}, ${legacyProjectId}, 'user', 'ordinary-reader')`; - - const agentProjectId = randomUUID(), runProjectId = randomUUID(), preferredProjectId = randomUUID(); - await sql`UPDATE heartbeat_runs SET responsible_user_id = 'run-owner' WHERE id = ${secondRunId}`; - await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES - (${agentProjectId}, ${companyId}, 'Agent API project', 'private'), - (${runProjectId}, ${companyId}, 'Run-backed project', 'private'), - (${preferredProjectId}, ${companyId}, 'Recorded owner project', 'private')`; - await sql`INSERT INTO activity_log (company_id, actor_type, actor_id, responsible_user_id, run_id, action, entity_type, entity_id) VALUES - (${companyId}, 'agent', ${agentId}, 'activity-owner', NULL, 'project.created', 'project', ${agentProjectId}), - (${companyId}, 'agent', ${agentId}, NULL, ${secondRunId}, 'project.created', 'project', ${runProjectId}), - (${companyId}, 'agent', ${agentId}, 'activity-owner', ${secondRunId}, 'project.created', 'project', ${preferredProjectId})`; - - await applyPendingMigrations(database.connectionString); - for (const [projectId, owner] of [[agentProjectId, 'activity-owner'], [runProjectId, 'run-owner'], [preferredProjectId, 'activity-owner']]) { - expect(await sql`SELECT privacy_owner_user_id FROM projects WHERE id = ${projectId}`).toEqual([{ privacy_owner_user_id: owner }]); - expect(await sql`SELECT subject_id FROM project_access_members WHERE project_id = ${projectId}`).toEqual([{ subject_id: owner }]); - } - const [legacyProject] = await sql`SELECT privacy_owner_user_id FROM projects WHERE id = ${legacyProjectId}`; - expect(legacyProject.privacy_owner_user_id).toBe('original-owner'); - expect(await sql`SELECT subject_id FROM project_access_members WHERE project_id = ${legacyProjectId} ORDER BY subject_id`) - .toEqual([{ subject_id: 'ordinary-reader' }, { subject_id: 'original-owner' }]); - - - const rows = await sql<{ id: string; issue_id: string | null; scope_kind: string }[]>` - SELECT "id", "issue_id", "scope_kind" - FROM "heartbeat_runs" - WHERE "id" IN (${firstRunId}, ${secondRunId}, ${maintenanceRunId}) - ORDER BY "id" - `; - const issueByRun = new Map(rows.map((row) => [row.id, row.issue_id])); - expect(issueByRun.get(firstRunId)).toBe(firstIssueId); - expect(issueByRun.get(secondRunId)).toBe(secondIssueId); - expect(issueByRun.get(maintenanceRunId)).toBeNull(); - expect(rows.find((row) => row.id === firstRunId)?.scope_kind).toBe("issue"); - expect(rows.find((row) => row.id === secondRunId)?.scope_kind).toBe("issue"); - expect(rows.find((row) => row.id === maintenanceRunId)?.scope_kind).toBe("company"); - - const [parity] = await sql<{ expected_count: number; populated_count: number }[]>` - SELECT - count(*) FILTER (WHERE "context_snapshot" ? 'issueId' OR "context_snapshot" ? 'taskId')::int AS "expected_count", - count(*) FILTER (WHERE ("context_snapshot" ? 'issueId' OR "context_snapshot" ? 'taskId') AND "issue_id" IS NOT NULL)::int AS "populated_count" - FROM "heartbeat_runs" - WHERE "id" IN (${firstRunId}, ${secondRunId}, ${maintenanceRunId}) - `; - expect(parity).toEqual({ expected_count: 2, populated_count: 2 }); - - const [newRun] = await sql<{ id: string; issue_id: string | null; scope_kind: string }[]>` - INSERT INTO heartbeat_runs (company_id, agent_id, status, context_snapshot) - VALUES (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: secondIssueId })}) - RETURNING id, issue_id, scope_kind`; - expect(newRun).toMatchObject({ issue_id: secondIssueId, scope_kind: "issue" }); - await sql`UPDATE heartbeat_runs SET context_snapshot = '{}'::jsonb, scope_kind = 'company' WHERE id = ${newRun.id}`; - expect(await sql`SELECT issue_id, scope_kind FROM heartbeat_runs WHERE id = ${newRun.id}`) - .toEqual([{ issue_id: secondIssueId, scope_kind: "issue" }]); - - const indexes = await sql<{ indexname: string }[]>` - SELECT "indexname" - FROM "pg_indexes" - WHERE "schemaname" = 'public' - AND "indexname" = 'heartbeat_runs_company_issue_created_idx' - `; - expect(indexes).toHaveLength(1); - }, 30_000); - - it("fails closed when a legacy issue claim cannot be resolved", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-run-issue-privacy-invalid-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => sql.end()); - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - - await sql`DROP TRIGGER IF EXISTS heartbeat_runs_set_scope_kind ON heartbeat_runs`; - const companyId = randomUUID(); - const otherCompanyId = randomUUID(); - const agentId = randomUUID(); - const foreignIssueId = randomUUID(); - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES - (${companyId}, 'Run Privacy', 'RPI'), - (${otherCompanyId}, 'Other Company', 'RPO') - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${agentId}, ${companyId}, 'Runner', 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${foreignIssueId}, ${otherCompanyId}, 'Foreign task', 'RPO-1') - `; - await sql` - INSERT INTO "heartbeat_runs" ("company_id", "agent_id", "status", "context_snapshot") - VALUES - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: "not-a-uuid" })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: randomUUID() })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ issueId: foreignIssueId })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: "not-a-uuid" })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: randomUUID() })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: foreignIssueId })}), - (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: null })}) - `; - - await applyPendingMigrations(database.connectionString); - const rows = await sql<{ issue_id: string | null; scope_kind: string }[]>` - SELECT issue_id, scope_kind FROM heartbeat_runs WHERE company_id = ${companyId}`; - expect(rows).toHaveLength(7); - expect(rows.every(row => row.scope_kind === "issue" && row.issue_id === null)).toBe(true); - // Re-running the migration preserves fail-closed tombstones and constraints. - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - await applyPendingMigrations(database.connectionString); - }, 30_000); - - it("releases schema and completed-batch row locks and resumes after interruption", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-privacy-batch-commits-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => sql.end()); - const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); - const runId = (n: number) => `00000000-0000-0000-0000-${String(n).padStart(12, "0")}`; - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Batch commits', 'BCH')`; - await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Runner', 'process')`; - await sql`INSERT INTO issues (id, company_id, title, visibility) VALUES (${issueId}, ${companyId}, 'Private task', 'private')`; - await sql`DROP TRIGGER heartbeat_runs_set_scope_kind ON heartbeat_runs`; - await sql`INSERT INTO heartbeat_runs (id, company_id, agent_id, status, context_snapshot) - SELECT ('00000000-0000-0000-0000-' || lpad(n::text, 12, '0'))::uuid, - ${companyId}::uuid, ${agentId}::uuid, 'succeeded', ${sql.json({ taskId: issueId })}::jsonb - FROM generate_series(1, 1001) n`; - // A failed concurrent build must be repaired rather than skipped by - // CREATE INDEX IF NOT EXISTS when the migration is retried. - await sql`DROP INDEX heartbeat_runs_company_issue_created_idx`; - await expect(sql.unsafe("CREATE UNIQUE INDEX CONCURRENTLY heartbeat_runs_company_issue_created_idx ON heartbeat_runs (company_id)")) - .rejects.toThrow(); - await sql.unsafe(`CREATE FUNCTION interrupt_privacy_batch_fixture() RETURNS trigger LANGUAGE plpgsql AS $$ - BEGIN - PERFORM pg_advisory_xact_lock(736319937); - RAISE EXCEPTION 'fixture interrupted second batch'; - END $$`); - await sql.unsafe(`CREATE TRIGGER zzz_interrupt_privacy_batch_fixture BEFORE UPDATE ON heartbeat_runs - FOR EACH ROW WHEN (OLD.scope_kind = 'company' AND NEW.id = '${runId(1001)}'::uuid) - EXECUTE FUNCTION interrupt_privacy_batch_fixture()`); - const hash = await migrationHash(); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await sql`SELECT pg_advisory_lock(736319937)`; - const migration = applyPendingMigrations(database.connectionString).then(() => null, error => error); - let contender: Promise | undefined; - try { - // The second batch is blocked while another session can see the first - // committed batch and write a row whose lock has already been released. - await expect.poll(async () => { - const [row] = await sql`SELECT count(*)::int AS n FROM heartbeat_runs - WHERE company_id = ${companyId} AND scope_kind = 'issue'`; - return row.n; - }, { timeout: 10_000 }).toBe(1000); - // The session lock survives batch commits and blocks another migrator. - contender = applyPendingMigrations(database.connectionString).then(() => null, error => error); - await expect.poll(async () => { - const [row] = await sql`SELECT count(*)::int AS n FROM pg_stat_activity - WHERE datname = current_database() AND query LIKE '%SELECT pg_try_advisory_lock%' - AND query NOT LIKE '%FROM pg_stat_activity%' - AND strpos(query, 'paperclip:migrations') > 0`; - return row.n; - }, { timeout: 10_000 }).toBe(1); - expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(0); - await sql`SET lock_timeout = '500ms'`; - await sql`UPDATE heartbeat_runs SET context_snapshot = context_snapshot || '{"probe":"visible"}'::jsonb - WHERE id = ${runId(1)}`; - expect(await sql`SELECT context_snapshot->>'probe' AS probe FROM heartbeat_runs WHERE id = ${runId(1)}`) - .toEqual([{ probe: "visible" }]); - } finally { - await sql`SELECT pg_advisory_unlock(736319937)`; - await sql`RESET lock_timeout`; - await migration; - await contender; - } - expect(await migration).toMatchObject({ message: "fixture interrupted second batch" }); - expect(await contender).toMatchObject({ message: "fixture interrupted second batch" }); - expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(0); - await sql`DROP TRIGGER zzz_interrupt_privacy_batch_fixture ON heartbeat_runs`; - await sql`DROP FUNCTION interrupt_privacy_batch_fixture()`; - await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]); - const [finished] = await sql`SELECT count(*)::int AS n FROM heartbeat_runs - WHERE company_id = ${companyId} AND scope_kind = 'issue' AND issue_id = ${issueId}`; - expect(finished.n).toBe(1001); - expect(await sql`SELECT indisvalid FROM pg_index WHERE indexrelid = 'heartbeat_runs_company_issue_created_idx'::regclass`) - .toEqual([{ indisvalid: true }]); - expect(await sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`).toHaveLength(1); - }, 30_000); - - it("keeps all privacy triggers installed when replacement is interrupted", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-privacy-trigger-atomic-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => sql.end()); - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - const replacements = content.split("--> statement-breakpoint").filter(statement => /DROP TRIGGER IF EXISTS/.test(statement)); - expect(replacements).toHaveLength(4); - for (const statement of replacements) { - const name = statement.match(/DROP TRIGGER IF EXISTS ([A-Za-z_]+)/)![1]; - const interrupted = statement.replace("CREATE TRIGGER", "RAISE EXCEPTION 'fixture interrupted trigger replacement';\n CREATE TRIGGER"); - await expect(sql.unsafe(interrupted)).rejects.toThrow("fixture interrupted trigger replacement"); - expect(await sql`SELECT tgname FROM pg_trigger WHERE tgname = ${name} AND NOT tgisinternal`).toEqual([{ tgname: name }]); - } - const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Atomic triggers', 'ATR')`; - await sql`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${companyId}, 'Runner', 'process')`; - await sql`INSERT INTO issues (id, company_id, title, visibility) VALUES (${issueId}, ${companyId}, 'Private', 'private')`; - expect(await sql`INSERT INTO heartbeat_runs (company_id, agent_id, status, context_snapshot) - VALUES (${companyId}, ${agentId}, 'succeeded', ${sql.json({ taskId: issueId })}) RETURNING issue_id, scope_kind`) - .toEqual([{ issue_id: issueId, scope_kind: "issue" }]); - }, 30_000); - -}); diff --git a/packages/db/src/inbox-archive-agent-policies-migration.test.ts b/packages/db/src/inbox-archive-agent-policies-migration.test.ts deleted file mode 100644 index dafec04ad39..00000000000 --- a/packages/db/src/inbox-archive-agent-policies-migration.test.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const INBOX_ARCHIVE_AGENT_POLICIES_MIGRATION = "0172_inbox_archive_agent_policies.sql"; - -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function createTempDatabase(): Promise { - const db = await startEmbeddedPostgresTestDatabase("paperclip-inbox-archive-policies-"); - cleanups.push(db.cleanup); - return db.connectionString; -} - -async function migrationHash(): Promise { - const content = await fs.promises.readFile( - new URL(`./migrations/${INBOX_ARCHIVE_AGENT_POLICIES_MIGRATION}`, import.meta.url), - "utf8", - ); - return createHash("sha256").update(content).digest("hex"); -} - -afterEach(async () => { - while (cleanups.length > 0) { - const cleanup = cleanups.pop(); - await cleanup?.(); - } -}); - -if (!embeddedPostgresSupport.supported) { - console.warn( - `Skipping embedded Postgres inbox archive policy migration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, - ); -} - -describeEmbeddedPostgres("inbox archive agent policy migration", () => { - it( - "upgrades legacy archives and round-trips attribution and unique policies", - async () => { - const connectionString = await createTempDatabase(); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - const companyId = randomUUID(); - const agentId = randomUUID(); - const deletedAgentId = randomUUID(); - const issueId = randomUUID(); - const runId = randomUUID(); - const legacyArchiveId = randomUUID(); - const agentArchiveId = randomUUID(); - - try { - const hash = await migrationHash(); - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${hash}`; - await sql`DROP TABLE IF EXISTS "user_inbox_agent_policies"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP CONSTRAINT IF EXISTS "issue_inbox_archives_archived_by_agent_id_agents_id_fk"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP CONSTRAINT IF EXISTS "issue_inbox_archives_archived_by_run_id_heartbeat_runs_id_fk"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP CONSTRAINT IF EXISTS "issue_inbox_archives_archived_by_actor_type_check"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP COLUMN IF EXISTS "archived_by_agent_id"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP COLUMN IF EXISTS "archived_by_run_id"`; - await sql`ALTER TABLE "issue_inbox_archives" DROP COLUMN IF EXISTS "archived_by_actor_type"`; - - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Inbox migration company', 'IAM') - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${agentId}, ${companyId}, 'Inbox agent', 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${deletedAgentId}, ${companyId}, 'Deleted inbox agent', 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${issueId}, ${companyId}, 'Legacy inbox issue', 'IAM-1') - `; - await sql` - INSERT INTO "heartbeat_runs" ("id", "company_id", "agent_id", "status") - VALUES (${runId}, ${companyId}, ${agentId}, 'succeeded') - `; - await sql` - INSERT INTO "issue_inbox_archives" ("id", "company_id", "issue_id", "user_id") - VALUES (${legacyArchiveId}, ${companyId}, ${issueId}, 'legacy-user') - `; - } finally { - await sql.end(); - } - - expect(await inspectMigrations(connectionString)).toMatchObject({ - status: "needsMigrations", - pendingMigrations: [INBOX_ARCHIVE_AGENT_POLICIES_MIGRATION], - }); - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const legacyRows = await verifySql<{ - archived_by_actor_type: string; - archived_by_agent_id: string | null; - archived_by_run_id: string | null; - }[]>` - SELECT "archived_by_actor_type", "archived_by_agent_id", "archived_by_run_id" - FROM "issue_inbox_archives" - WHERE "id" = ${legacyArchiveId} - `; - expect(legacyRows).toEqual([{ - archived_by_actor_type: "user", - archived_by_agent_id: null, - archived_by_run_id: null, - }]); - - await verifySql` - INSERT INTO "issue_inbox_archives" ( - "id", - "company_id", - "issue_id", - "user_id", - "archived_by_actor_type", - "archived_by_agent_id", - "archived_by_run_id" - ) - VALUES (${agentArchiveId}, ${companyId}, ${issueId}, 'agent-managed-user', 'agent', ${agentId}, ${runId}) - `; - const agentRows = await verifySql<{ - archived_by_actor_type: string; - archived_by_agent_id: string; - archived_by_run_id: string; - }[]>` - SELECT "archived_by_actor_type", "archived_by_agent_id", "archived_by_run_id" - FROM "issue_inbox_archives" - WHERE "id" = ${agentArchiveId} - `; - expect(agentRows).toEqual([{ - archived_by_actor_type: "agent", - archived_by_agent_id: agentId, - archived_by_run_id: runId, - }]); - - await verifySql` - INSERT INTO "user_inbox_agent_policies" ( - "company_id", - "user_id", - "mode", - "allowed_agent_ids" - ) - VALUES (${companyId}, 'agent-managed-user', 'allowlist', ${verifySql.json([agentId, deletedAgentId])}) - `; - const policies = await verifySql<{ - mode: string; - allowed_agent_ids: string[]; - }[]>` - SELECT "mode", "allowed_agent_ids" - FROM "user_inbox_agent_policies" - WHERE "company_id" = ${companyId} - AND "user_id" = 'agent-managed-user' - `; - expect(policies).toEqual([{ - mode: "allowlist", - allowed_agent_ids: [agentId, deletedAgentId], - }]); - - await verifySql`DELETE FROM "agents" WHERE "id" = ${deletedAgentId}`; - const policiesAfterAgentDeletion = await verifySql<{ - allowed_agent_ids: string[]; - }[]>` - SELECT "allowed_agent_ids" - FROM "user_inbox_agent_policies" - WHERE "company_id" = ${companyId} - AND "user_id" = 'agent-managed-user' - `; - expect(policiesAfterAgentDeletion).toEqual([{ allowed_agent_ids: [agentId] }]); - - await expect(verifySql` - INSERT INTO "user_inbox_agent_policies" ("company_id", "user_id", "mode") - VALUES (${companyId}, 'agent-managed-user', 'disabled') - `).rejects.toMatchObject({ code: "23505" }); - } finally { - await verifySql.end(); - } - - expect((await inspectMigrations(connectionString)).status).toBe("upToDate"); - }, - 30_000, - ); -}); diff --git a/packages/db/src/issue-comment-derived-attribution-migration.test.ts b/packages/db/src/issue-comment-derived-attribution-migration.test.ts deleted file mode 100644 index f208dced2f0..00000000000 --- a/packages/db/src/issue-comment-derived-attribution-migration.test.ts +++ /dev/null @@ -1,345 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { - applyPendingMigrations, - inspectMigrations, -} from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const DERIVED_ATTRIBUTION_MIGRATION = "0132_issue_comment_derived_attribution_fast.sql"; - -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function createTempDatabase(): Promise { - const db = await startEmbeddedPostgresTestDatabase("paperclip-derived-attribution-"); - cleanups.push(db.cleanup); - return db.connectionString; -} - -async function migrationHash(migrationFile: string): Promise { - const content = await fs.promises.readFile( - new URL(`./migrations/${migrationFile}`, import.meta.url), - "utf8", - ); - return createHash("sha256").update(content).digest("hex"); -} - -async function makeDerivedAttributionMigrationPending( - sql: ReturnType, -): Promise { - const hash = await migrationHash(DERIVED_ATTRIBUTION_MIGRATION); - await sql` - DELETE FROM "drizzle"."__drizzle_migrations" - WHERE "hash" = ${hash} - `; -} - -async function dropDerivedAttributionSchema(sql: ReturnType): Promise { - await sql`ALTER TABLE "issue_comments" DROP CONSTRAINT IF EXISTS "issue_comments_derived_author_agent_id_agents_id_fk"`; - await sql`ALTER TABLE "issue_comments" DROP CONSTRAINT IF EXISTS "issue_comments_derived_created_by_run_id_heartbeat_runs_id_fk"`; - await sql`ALTER TABLE "issue_comments" DROP COLUMN IF EXISTS "derived_author_agent_id"`; - await sql`ALTER TABLE "issue_comments" DROP COLUMN IF EXISTS "derived_created_by_run_id"`; - await sql`ALTER TABLE "issue_comments" DROP COLUMN IF EXISTS "derived_author_source"`; -} - -async function createSeedGraph(sql: ReturnType, label: string) { - const companyId = randomUUID(); - const agentId = randomUUID(); - const issueId = randomUUID(); - const runId = randomUUID(); - - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, ${`Company ${label}`}, ${`T${label}`}) - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${agentId}, ${companyId}, ${`Agent ${label}`}, 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${issueId}, ${companyId}, ${`Issue ${label}`}, ${`T${label}-1`}) - `; - await sql` - INSERT INTO "heartbeat_runs" ("id", "company_id", "agent_id", "status") - VALUES (${runId}, ${companyId}, ${agentId}, 'succeeded') - `; - - return { companyId, agentId, issueId, runId }; -} - -async function expectDerivedAttributionSchema(sql: ReturnType): Promise { - const columns = await sql<{ column_name: string; data_type: string; is_nullable: string }[]>` - SELECT "column_name", "data_type", "is_nullable" - FROM "information_schema"."columns" - WHERE "table_schema" = 'public' - AND "table_name" = 'issue_comments' - AND "column_name" IN ( - 'derived_author_agent_id', - 'derived_created_by_run_id', - 'derived_author_source' - ) - ORDER BY "column_name" - `; - expect(columns).toEqual([ - { column_name: "derived_author_agent_id", data_type: "uuid", is_nullable: "YES" }, - { column_name: "derived_author_source", data_type: "text", is_nullable: "YES" }, - { column_name: "derived_created_by_run_id", data_type: "uuid", is_nullable: "YES" }, - ]); - - const constraints = await sql<{ conname: string; delete_rule: string }[]>` - SELECT tc."constraint_name" AS "conname", rc."delete_rule" - FROM "information_schema"."table_constraints" tc - JOIN "information_schema"."referential_constraints" rc - ON rc."constraint_schema" = tc."constraint_schema" - AND rc."constraint_name" = tc."constraint_name" - WHERE tc."table_schema" = 'public' - AND tc."table_name" = 'issue_comments' - AND tc."constraint_name" IN ( - 'issue_comments_derived_author_agent_id_agents_id_fk', - 'issue_comments_derived_created_by_run_id_heartbeat_runs_id_fk' - ) - ORDER BY tc."constraint_name" - `; - expect(constraints).toEqual([ - { - conname: "issue_comments_derived_author_agent_id_agents_id_fk", - delete_rule: "SET NULL", - }, - { - conname: "issue_comments_derived_created_by_run_id_heartbeat_runs_id_fk", - delete_rule: "SET NULL", - }, - ]); -} - -afterEach(async () => { - while (cleanups.length > 0) { - const cleanup = cleanups.pop(); - await cleanup?.(); - } -}); - -if (!embeddedPostgresSupport.supported) { - console.warn( - `Skipping embedded Postgres derived attribution migration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`, - ); -} - -describeEmbeddedPostgres("issue comment derived attribution migration", () => { - it( - "fresh installs include the relocated schema and no deleted 0126 migration", - async () => { - const connectionString = await createTempDatabase(); - const state = await inspectMigrations(connectionString); - - expect(state.status).toBe("upToDate"); - expect(state.availableMigrations).not.toContain("0126_issue_comment_derived_attribution.sql"); - expect(state.availableMigrations).toContain(DERIVED_ATTRIBUTION_MIGRATION); - - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await expectDerivedAttributionSchema(sql); - const supportIndexes = await sql<{ indexname: string }[]>` - SELECT "indexname" - FROM "pg_indexes" - WHERE "schemaname" = 'public' - AND "indexname" = 'issue_comments_derived_attribution_backfill_idx' - `; - expect(supportIndexes).toEqual([]); - } finally { - await sql.end(); - } - }, - 20_000, - ); - - it( - "is idempotent for a database that already has 0126 schema and data", - async () => { - const connectionString = await createTempDatabase(); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - const alreadyBackfilledCommentId = randomUUID(); - const timingTierCommentId = randomUUID(); - const realUserCommentId = randomUUID(); - - try { - await makeDerivedAttributionMigrationPending(sql); - const { companyId, agentId, issueId, runId } = await createSeedGraph(sql, "OLD126"); - await sql` - INSERT INTO "user" ("id", "name", "email", "email_verified", "created_at", "updated_at") - VALUES ('real-user', 'Real User', 'real-user@example.test', true, now(), now()) - ON CONFLICT ("id") DO NOTHING - `; - await sql` - INSERT INTO "issue_comments" ( - "id", - "company_id", - "issue_id", - "author_user_id", - "created_by_run_id", - "derived_author_agent_id", - "derived_created_by_run_id", - "derived_author_source", - "body" - ) - VALUES - (${alreadyBackfilledCommentId}, ${companyId}, ${issueId}, 'local-board', ${runId}, ${agentId}, ${runId}, 'run_id', 'already attributed'), - (${timingTierCommentId}, ${companyId}, ${issueId}, 'local-board', NULL, ${agentId}, ${runId}, 'run_window_unique', 'timing tier'), - (${realUserCommentId}, ${companyId}, ${issueId}, 'real-user', ${runId}, NULL, NULL, NULL, 'human comment') - `; - } finally { - await sql.end(); - } - - const pendingState = await inspectMigrations(connectionString); - expect(pendingState).toMatchObject({ - status: "needsMigrations", - pendingMigrations: [DERIVED_ATTRIBUTION_MIGRATION], - reason: "pending-migrations", - }); - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - const rows = await verifySql<{ - id: string; - derived_author_agent_id: string | null; - derived_created_by_run_id: string | null; - derived_author_source: string | null; - }[]>` - SELECT - "id", - "derived_author_agent_id", - "derived_created_by_run_id", - "derived_author_source" - FROM "issue_comments" - WHERE "id" IN (${alreadyBackfilledCommentId}, ${timingTierCommentId}, ${realUserCommentId}) - ORDER BY "body" - `; - - expect(rows).toEqual([ - expect.objectContaining({ - id: alreadyBackfilledCommentId, - derived_author_source: "run_id", - }), - { - id: realUserCommentId, - derived_author_agent_id: null, - derived_created_by_run_id: null, - derived_author_source: null, - }, - { - id: timingTierCommentId, - derived_author_agent_id: null, - derived_created_by_run_id: null, - derived_author_source: null, - }, - ]); - } finally { - await verifySql.end(); - } - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - }, - 20_000, - ); - - it( - "completes a partially backfilled pre-0131 database", - async () => { - const connectionString = await createTempDatabase(); - const sql = postgres(connectionString, { max: 1, onnotice: () => {} }); - const eligibleCommentId = randomUUID(); - const deletedUserCommentId = randomUUID(); - const agentAuthoredCommentId = randomUUID(); - - try { - await dropDerivedAttributionSchema(sql); - await makeDerivedAttributionMigrationPending(sql); - const { companyId, agentId, issueId, runId } = await createSeedGraph(sql, "PARTIAL"); - await sql` - INSERT INTO "issue_comments" ( - "id", - "company_id", - "issue_id", - "author_user_id", - "created_by_run_id", - "body" - ) - VALUES - (${eligibleCommentId}, ${companyId}, ${issueId}, 'local-board', ${runId}, 'eligible local-board'), - (${deletedUserCommentId}, ${companyId}, ${issueId}, 'deleted-user', ${runId}, 'eligible deleted user') - `; - await sql` - INSERT INTO "issue_comments" ( - "id", - "company_id", - "issue_id", - "author_agent_id", - "author_user_id", - "created_by_run_id", - "body" - ) - VALUES (${agentAuthoredCommentId}, ${companyId}, ${issueId}, ${agentId}, 'local-board', ${runId}, 'already agent-authored') - `; - } finally { - await sql.end(); - } - - await applyPendingMigrations(connectionString); - - const verifySql = postgres(connectionString, { max: 1, onnotice: () => {} }); - try { - await expectDerivedAttributionSchema(verifySql); - const rows = await verifySql<{ - id: string; - derived_author_agent_id: string | null; - derived_created_by_run_id: string | null; - derived_author_source: string | null; - }[]>` - SELECT - "id", - "derived_author_agent_id", - "derived_created_by_run_id", - "derived_author_source" - FROM "issue_comments" - WHERE "id" IN (${eligibleCommentId}, ${deletedUserCommentId}, ${agentAuthoredCommentId}) - ORDER BY "body" - `; - - expect(rows).toEqual([ - { - id: agentAuthoredCommentId, - derived_author_agent_id: null, - derived_created_by_run_id: null, - derived_author_source: null, - }, - expect.objectContaining({ - id: deletedUserCommentId, - derived_author_source: "run_id", - }), - expect.objectContaining({ - id: eligibleCommentId, - derived_author_source: "run_id", - }), - ]); - } finally { - await verifySql.end(); - } - - const finalState = await inspectMigrations(connectionString); - expect(finalState.status).toBe("upToDate"); - }, - 20_000, - ); -}); diff --git a/packages/db/src/issue-comment-on-behalf-migration.test.ts b/packages/db/src/issue-comment-on-behalf-migration.test.ts deleted file mode 100644 index 34fde0e20d6..00000000000 --- a/packages/db/src/issue-comment-on-behalf-migration.test.ts +++ /dev/null @@ -1,156 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0205_narrow_shiva.sql"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash() { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -describeEmbeddedPostgres("issue comment on-behalf attribution migration", () => { - it("reapplies the migration and round-trips the nullable user attribution FK", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-comment-on-behalf-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - const historicalCompanyId = randomUUID(); - const historicalAgentId = randomUUID(); - const historicalIssueId = randomUUID(); - const historicalRunId = randomUUID(); - const historicalCommentId = randomUUID(); - const historicalUserId = `historical-comment-user-${randomUUID()}`; - - try { - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - await sql`ALTER TABLE "issue_comments" DROP CONSTRAINT IF EXISTS "issue_comments_on_behalf_of_user_id_user_id_fk"`; - await sql`ALTER TABLE "issue_comments" DROP COLUMN IF EXISTS "on_behalf_of_user_id"`; - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${historicalCompanyId}, 'Historical attribution company', 'HAC') - `; - await sql` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${historicalAgentId}, ${historicalCompanyId}, 'Historical comment agent', 'engineer', 'process', '{}'::jsonb) - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${historicalIssueId}, ${historicalCompanyId}, 'Historical comment issue', 'HAC-1') - `; - await sql` - INSERT INTO "user" ("id", "name", "email", "email_verified", "created_at", "updated_at") - VALUES (${historicalUserId}, 'Historical Comment User', 'historical-comment-user@example.test', true, now(), now()) - `; - await sql` - INSERT INTO "heartbeat_runs" ("id", "company_id", "agent_id", "status", "responsible_user_id") - VALUES (${historicalRunId}, ${historicalCompanyId}, ${historicalAgentId}, 'succeeded', ${historicalUserId}) - `; - await sql` - INSERT INTO "issue_comments" ( - "id", "company_id", "issue_id", "author_agent_id", "created_by_run_id", "body" - ) VALUES ( - ${historicalCommentId}, ${historicalCompanyId}, ${historicalIssueId}, ${historicalAgentId}, - ${historicalRunId}, 'Historical attributed comment' - ) - `; - } finally { - await sql.end(); - } - - expect(await inspectMigrations(database.connectionString)).toMatchObject({ - status: "needsMigrations", - pendingMigrations: [MIGRATION_FILE], - }); - await applyPendingMigrations(database.connectionString); - - const verify = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const columns = await verify<{ column_name: string; data_type: string; is_nullable: string }[]>` - SELECT "column_name", "data_type", "is_nullable" - FROM "information_schema"."columns" - WHERE "table_schema" = 'public' - AND "table_name" = 'issue_comments' - AND "column_name" = 'on_behalf_of_user_id' - `; - expect(columns).toEqual([{ - column_name: "on_behalf_of_user_id", - data_type: "text", - is_nullable: "YES", - }]); - - const constraints = await verify<{ constraint_name: string; delete_rule: string }[]>` - SELECT tc."constraint_name", rc."delete_rule" - FROM "information_schema"."table_constraints" tc - JOIN "information_schema"."referential_constraints" rc - ON rc."constraint_schema" = tc."constraint_schema" - AND rc."constraint_name" = tc."constraint_name" - WHERE tc."table_schema" = 'public' - AND tc."table_name" = 'issue_comments' - AND tc."constraint_name" = 'issue_comments_on_behalf_of_user_id_user_id_fk' - `; - expect(constraints).toEqual([{ - constraint_name: "issue_comments_on_behalf_of_user_id_user_id_fk", - delete_rule: "SET NULL", - }]); - - const historical = await verify<{ on_behalf_of_user_id: string | null }[]>` - SELECT "on_behalf_of_user_id" - FROM "issue_comments" - WHERE "id" = ${historicalCommentId} - `; - expect(historical).toEqual([{ on_behalf_of_user_id: historicalUserId }]); - - const companyId = randomUUID(); - const agentId = randomUUID(); - const issueId = randomUUID(); - const commentId = randomUUID(); - const userId = `comment-user-${randomUUID()}`; - await verify` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Comment attribution company', 'CAC') - `; - await verify` - INSERT INTO "agents" ("id", "company_id", "name", "role", "adapter_type", "adapter_config") - VALUES (${agentId}, ${companyId}, 'Comment agent', 'engineer', 'process', '{}'::jsonb) - `; - await verify` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${issueId}, ${companyId}, 'Comment issue', 'CAC-1') - `; - await verify` - INSERT INTO "user" ("id", "name", "email", "email_verified", "created_at", "updated_at") - VALUES (${userId}, 'Comment User', 'comment-user@example.test', true, now(), now()) - `; - await verify` - INSERT INTO "issue_comments" ( - "id", "company_id", "issue_id", "author_agent_id", "on_behalf_of_user_id", "body" - ) VALUES (${commentId}, ${companyId}, ${issueId}, ${agentId}, ${userId}, 'Attributed comment') - `; - const inserted = await verify<{ on_behalf_of_user_id: string | null }[]>` - SELECT "on_behalf_of_user_id" FROM "issue_comments" WHERE "id" = ${commentId} - `; - expect(inserted).toEqual([{ on_behalf_of_user_id: userId }]); - - await verify`DELETE FROM "user" WHERE "id" = ${userId}`; - const afterDelete = await verify<{ on_behalf_of_user_id: string | null }[]>` - SELECT "on_behalf_of_user_id" FROM "issue_comments" WHERE "id" = ${commentId} - `; - expect(afterDelete).toEqual([{ on_behalf_of_user_id: null }]); - } finally { - await verify.end(); - } - }, 30_000); -}); diff --git a/packages/db/src/issue-thread-interaction-resolver-policy-migration.test.ts b/packages/db/src/issue-thread-interaction-resolver-policy-migration.test.ts deleted file mode 100644 index ddebb0835fd..00000000000 --- a/packages/db/src/issue-thread-interaction-resolver-policy-migration.test.ts +++ /dev/null @@ -1,172 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import { fileURLToPath } from "node:url"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const d = support.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -async function resolverPolicyMigrationStatements(): Promise { - const migrationSql = await readFile( - fileURLToPath(new URL("./migrations/0218_mushy_jack_murdock.sql", import.meta.url)), - "utf8", - ); - return migrationSql - .split("--> statement-breakpoint") - .map((statement) => statement.trim()) - .filter((statement) => statement.length > 0); -} - -d("issue interaction resolver policy migration", () => { - it("replays safely and completes a partial prior run", async () => { - const dbh = await startEmbeddedPostgresTestDatabase("resolver-policy-migration-"); - cleanups.push(() => dbh.cleanup()); - const sql = postgres(dbh.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => { - await sql.end(); - }); - - const companyId = randomUUID(); - const issueId = randomUUID(); - const legacyInteractionId = randomUUID(); - const partialInteractionId = randomUUID(); - - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Resolver migration test', 'RMT') - `; - await sql` - INSERT INTO "issues" ("id", "company_id", "title", "identifier") - VALUES (${issueId}, ${companyId}, 'Test migration replay', 'RMT-1') - `; - await sql.unsafe( - 'ALTER TABLE "issue_thread_interactions" ALTER COLUMN "resolver_policy_provenance" DROP NOT NULL', - ); - await sql.unsafe( - 'ALTER TABLE "issue_thread_interactions" ALTER COLUMN "effective_resolver_policy_source" DROP NOT NULL', - ); - await sql` - INSERT INTO "issue_thread_interactions" ( - "id", - "company_id", - "issue_id", - "kind", - "requested_resolver_policy", - "effective_resolver_policy", - "resolver_policy_provenance", - "effective_resolver_policy_source", - "payload" - ) - VALUES - ( - ${legacyInteractionId}, - ${companyId}, - ${issueId}, - 'request_confirmation', - 'board_or_agents', - 'board_only', - NULL, - NULL, - '{}'::jsonb - ), - ( - ${partialInteractionId}, - ${companyId}, - ${issueId}, - 'request_confirmation', - 'human_only', - 'human_only', - 'explicit', - NULL, - '{}'::jsonb - ) - `; - - const statements = await resolverPolicyMigrationStatements(); - expect(statements.length).toBeGreaterThan(0); - for (const statement of statements) await sql.unsafe(statement); - - const rowsAfterFirstRun = await sql<{ - id: string; - requested_resolver_policy: string; - effective_resolver_policy: string; - resolver_policy_provenance: string; - effective_resolver_policy_source: string; - }[]>` - SELECT - "id", - "requested_resolver_policy", - "effective_resolver_policy", - "resolver_policy_provenance", - "effective_resolver_policy_source" - FROM "issue_thread_interactions" - WHERE "id" IN (${legacyInteractionId}, ${partialInteractionId}) - ORDER BY "id" - `; - expect(rowsAfterFirstRun).toEqual( - [ - { - id: legacyInteractionId, - requested_resolver_policy: "not_creator", - effective_resolver_policy: "human_only", - resolver_policy_provenance: "legacy_inherited_restriction", - effective_resolver_policy_source: "company_cap", - }, - { - id: partialInteractionId, - requested_resolver_policy: "human_only", - effective_resolver_policy: "human_only", - resolver_policy_provenance: "explicit", - effective_resolver_policy_source: "requested", - }, - ].sort((left, right) => left.id.localeCompare(right.id)), - ); - - for (const statement of statements) await sql.unsafe(statement); - const rowsAfterReplay = await sql` - SELECT - "id", - "requested_resolver_policy", - "effective_resolver_policy", - "resolver_policy_provenance", - "effective_resolver_policy_source" - FROM "issue_thread_interactions" - WHERE "id" IN (${legacyInteractionId}, ${partialInteractionId}) - ORDER BY "id" - `; - expect(rowsAfterReplay).toEqual(rowsAfterFirstRun); - - const columns = await sql< - { column_name: string; is_nullable: string; column_default: string }[] - >` - SELECT "column_name", "is_nullable", "column_default" - FROM "information_schema"."columns" - WHERE "table_schema" = 'public' - AND "table_name" = 'issue_thread_interactions' - AND "column_name" IN ('resolver_policy_provenance', 'effective_resolver_policy_source') - ORDER BY "column_name" - `; - expect(columns).toEqual([ - { - column_name: "effective_resolver_policy_source", - is_nullable: "NO", - column_default: "'requested'::text", - }, - { - column_name: "resolver_policy_provenance", - is_nullable: "NO", - column_default: "'inherited'::text", - }, - ]); - }, 240_000); -}); diff --git a/packages/db/src/muse-migration-idempotence.test.ts b/packages/db/src/muse-migration-idempotence.test.ts deleted file mode 100644 index 746ff79cd24..00000000000 --- a/packages/db/src/muse-migration-idempotence.test.ts +++ /dev/null @@ -1,187 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const museMigrations = [ - { file: "0349_oval_dragon_lord.sql", preview: "0344_perpetual_eternity.sql", hash: "5c422698d40da1d6cdc587134553e371f7c807ce9617e07d7ff77eb05810ae49" }, - { file: "0350_friendly_rhodey.sql", preview: "0345_lumpy_celestials.sql", hash: "a9373b52e02fa985bf10c15da91f6681c49d8726d94d5d68fd77e5802fd47a68" }, - { file: "0351_hard_albert_cleary.sql", preview: "0346_powerful_epoch.sql", hash: "65f4f08c6a8fed7396db491e0691e693636f48c4ca4fa63cd2057af38039861a" }, - { file: "0352_special_warbound.sql", preview: "0347_big_meggan.sql", hash: "1d2d5834fd499b60a43778d6d14b2520e3e2980258b8c0997d80cb95465f4abf" }, - { file: "0353_skinny_gamma_corps.sql", preview: "0348_foamy_lightspeed.sql", hash: "1a379bc03d80c34815546bb9f50bf1408ccf156f4a1df2d86edb0a01acdc55c0" }, -] as const; -const museTables = [ - "external_agent_holds", "muse_agent_bindings", "muse_credentials", "muse_idle_receipts", - "muse_input_deliveries", "muse_mailbox_items", "muse_receiver_contact_buckets", - "muse_runner_assignments", "muse_runner_operations", -] as const; -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; -afterEach(async () => { while (cleanups.length) await cleanups.pop()?.(); }); - -async function database() { - const db = await startEmbeddedPostgresTestDatabase("paperclip-muse-migration-replay-"); - cleanups.push(db.cleanup); - const sql = postgres(db.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => { await sql.end(); }); - return { sql, url: db.connectionString }; -} -async function content(file: string) { - return readFile(new URL(`./migrations/${file}`, import.meta.url), "utf8"); -} -function statements(sql: string) { return sql.split("--> statement-breakpoint").map(s => s.trim()).filter(Boolean); } -async function rawReplay(sql: ReturnType) { - for (const migration of museMigrations) for (const statement of statements(await content(migration.file))) await sql.unsafe(statement); -} -async function history(sql: ReturnType) { - return Array.from(await sql`SELECT id, hash, created_at::text AS created_at FROM drizzle.__drizzle_migrations ORDER BY id`); -} -async function shape(sql: ReturnType) { - return { - columns: Array.from(await sql`SELECT table_name, column_name, data_type, udt_name, is_nullable, column_default - FROM information_schema.columns WHERE table_schema = 'public' ORDER BY table_name, column_name`), - constraints: Array.from(await sql`SELECT t.relname, c.conname, c.convalidated, pg_get_constraintdef(c.oid, true) AS definition - FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' ORDER BY t.relname, c.conname`), - indexes: Array.from(await sql`SELECT t.relname, i.indisvalid, i.indisready, pg_get_indexdef(i.indexrelid) AS definition - FROM pg_index i JOIN pg_class t ON t.oid = i.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' ORDER BY t.relname, definition`), - }; -} -async function removeMuseSchemaAndReceipts(sql: ReturnType) { - // A disposable, fully migrated DB supplies the canonical prefix. Remove only - // this feature's tables/receipts to model interrupted unjournaled DDL. - await sql.unsafe(`DROP TABLE ${museTables.map(table => `"${table}"`).join(", ")} CASCADE`); - for (const migration of museMigrations) { - const hash = createHash("sha256").update(await content(migration.file)).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - } -} -async function seedRows(sql: ReturnType, complete: boolean) { - const [company] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Migration replay', 'RPL') RETURNING id`; - const [agent] = await sql`INSERT INTO agents (company_id, name, adapter_type) VALUES (${company.id}, 'Retained agent', 'paperclip_runner') RETURNING id`; - const [task] = await sql`INSERT INTO issues (company_id, title, assignee_agent_id) VALUES (${company.id}, 'Retained task', ${agent.id}) RETURNING id`; - const [run] = await sql`INSERT INTO heartbeat_runs (company_id, agent_id, invocation_source, trigger_detail, status) - VALUES (${company.id}, ${agent.id}, 'assignment', 'system', 'failed') RETURNING id`; - const [binding] = await sql`INSERT INTO muse_agent_bindings (company_id, agent_id, operator_id, generation, revision, status, worker_cursor, detector_removed_at, revoked_at) - VALUES (${company.id}, ${agent.id}, 'synthetic-operator', 3, 9, 'revoked', 13, '2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z') RETURNING id`; - const [assignment] = await sql`INSERT INTO muse_runner_assignments (company_id, binding_id, binding_generation, run_id, agent_id, - normalized_session_id, turn_id, controller_generation, catalog_digest, status, projection, accept_by, expires_at) - VALUES (${company.id}, ${binding.id}, 3, ${run.id}, ${agent.id}, 'retained-session', 'retained-turn', 4, 'retained-digest', 'fenced', - '{"retained":true}'::jsonb, '2026-01-01T00:00:00Z', '2026-01-02T00:00:00Z') RETURNING id`; - await sql`INSERT INTO external_agent_holds (company_id, agent_id, provider, assignment_id, binding_id, binding_generation, run_id, worker_unknown, native_effects_unknown, stop_boundary) - VALUES (${company.id}, ${agent.id}, 'muse', ${assignment.id}, ${binding.id}, 3, ${run.id}, true, true, '{"retained":true}'::jsonb)`; - await sql`INSERT INTO muse_credentials (company_id, binding_id, binding_generation, kind, family_id, token_hash, expires_at, revoked_at) - VALUES (${company.id}, ${binding.id}, 3, 'cleanup', ${randomUUID()}, ${randomUUID()}, '2026-01-02T00:00:00Z', '2026-01-01T00:00:00Z')`; - await sql`INSERT INTO muse_idle_receipts (company_id, binding_id, binding_generation, request_id, digest, outcome) - VALUES (${company.id}, ${binding.id}, 3, ${randomUUID()}, 'retained-idle', '{"retained":true}'::jsonb)`; - await sql`INSERT INTO muse_input_deliveries (company_id, assignment_id, request_id, turn_id, input_digest, response, source_event_id, consumed_at, continuation_receipt_id) - VALUES (${company.id}, ${assignment.id}, 'retained-input', 'retained-turn', 'retained-digest', '{"retained":true}'::jsonb, 'retained-input-event', '2026-01-01T00:00:00Z', ${randomUUID()})`; - await sql`INSERT INTO muse_mailbox_items (company_id, binding_id, binding_generation, assignment_id, kind, source_event_id, "references") - VALUES (${company.id}, ${binding.id}, 3, ${assignment.id}, 'assignment', 'retained-mailbox', '{"retained":true}'::jsonb)`; - await sql`INSERT INTO muse_receiver_contact_buckets (company_id, binding_id, binding_generation, replica_id, bucket_at, first_at, last_at, contacts, gaps_at_most_seven_seconds, max_gap_ms) - VALUES (${company.id}, ${binding.id}, 3, ${randomUUID()}, '2026-01-01T00:00:00Z', '2026-01-01T00:00:01Z', '2026-01-01T00:00:03Z', 2, 1, 2000)`; - await sql`INSERT INTO muse_runner_operations (company_id, assignment_id, request_id, digest, command, status, outcome) - VALUES (${company.id}, ${assignment.id}, ${randomUUID()}, 'retained-operation', '{"retained":true}'::jsonb, 'unknown', '{"retained":true}'::jsonb)`; - const userId = randomUUID(), clientId = `replay-client-${randomUUID()}`; - await sql`INSERT INTO "user" (id, name, email, created_at, updated_at) VALUES (${userId}, 'Synthetic operator', ${`${userId}@example.test`}, now(), now())`; - await sql`INSERT INTO mcp_oauth_clients (id, name, redirect_uris) VALUES (${clientId}, 'Synthetic client', '["https://example.test/callback"]'::jsonb)`; - const [grant] = await sql`INSERT INTO mcp_oauth_grants (company_id, user_id, client_id, resource, purpose, agent_id, scopes) - VALUES (${company.id}, ${userId}, ${clientId}, 'https://example.test/api/muse/v1', 'agent', ${agent.id}, '["paperclip:agent","offline_access"]'::jsonb) RETURNING id`; - await sql`UPDATE muse_agent_bindings SET grant_id = ${grant.id} WHERE id = ${binding.id}`; - if (complete) { - await sql`UPDATE muse_agent_bindings SET qualification_started_at = '2026-01-01T00:00:00Z', deadline_enforced_at = '2026-01-02T00:00:00Z', - cadence_evidence_incomplete_at = '2026-01-03T00:00:00Z', detector_removal_requested_at = '2026-01-04T00:00:00Z' WHERE id = ${binding.id}`; - await sql`UPDATE muse_receiver_contact_buckets SET timestamps = '["2026-01-01T00:00:01Z"]'::jsonb, incomplete = true WHERE binding_id = ${binding.id}`; - await sql`UPDATE muse_mailbox_items SET signal_attempt = 9, signal_notified_at = '2026-01-05T00:00:00Z' WHERE binding_id = ${binding.id}`; - await sql`UPDATE muse_runner_operations SET continuation_receipt_id = ${randomUUID()} WHERE assignment_id = ${assignment.id}`; - } - return async () => { - const rows: Record = {}; - for (const table of [...museTables, "companies", "issues", "heartbeat_runs", "mcp_oauth_grants"] as const) { - rows[table] = Array.from(await sql.unsafe(`SELECT to_jsonb(t) AS row FROM "${table}" t WHERE ${table === "companies" ? "id" : "company_id"} = $1 ORDER BY id`, [company.id])).map(row => row.row); - } - return rows; - }; -} - -describePostgres("Muse migration SQL idempotence", () => { - it("replays every raw SQL file twice without changing schema, receipts or runtime evidence", async () => { - const { sql, url } = await database(); - const rows = await seedRows(sql, true); - const before = { shape: await shape(sql), history: await history(sql), rows: await rows() }; - await rawReplay(sql); - await rawReplay(sql); - expect(await shape(sql)).toEqual(before.shape); - expect(await history(sql)).toEqual(before.history); - expect(await rows()).toEqual(before.rows); - await applyPendingMigrations(url); - expect((await inspectMigrations(url)).status).toBe("upToDate"); - expect(await history(sql)).toEqual(before.history); - expect(await rows()).toEqual(before.rows); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("completes mixed partial unjournaled DDL and preserves existing rows and journal identities", async () => { - const { sql, url } = await database(); - const expectedShape = await shape(sql); - await removeMuseSchemaAndReceipts(sql); - const prefixHistory = await history(sql); - const baseStatements = statements(await content(museMigrations[0].file)); - for (const statement of baseStatements.slice(0, 10)) await sql.unsafe(statement); - await sql.unsafe(baseStatements.find(statement => /^CREATE (?:UNIQUE )?INDEX/.test(statement))!); - for (const migration of museMigrations.slice(1)) await sql.unsafe(statements(await content(migration.file))[0]); - // A same-named FK elsewhere must not hide the missing public-table FK. - await sql`CREATE SCHEMA migration_decoy`; - await sql`CREATE TABLE migration_decoy.constraint_owner (binding_id uuid, - CONSTRAINT muse_credentials_binding_id_muse_agent_bindings_id_fk FOREIGN KEY (binding_id) REFERENCES public.companies(id))`; - const rows = await seedRows(sql, false); - const beforeRows = await rows(); - await applyPendingMigrations(url); - expect((await inspectMigrations(url)).status).toBe("upToDate"); - expect(await shape(sql)).toEqual(expectedShape); - expect(await rows()).toMatchObject(beforeRows); - const afterHistory = await history(sql); - expect(afterHistory.slice(0, prefixHistory.length)).toEqual(prefixHistory); - expect(afterHistory).toHaveLength(prefixHistory.length + museMigrations.length); - expect(await sql`SELECT timestamps, incomplete FROM muse_receiver_contact_buckets`).toMatchObject([{ timestamps: [], incomplete: false }]); - expect(await sql`SELECT signal_attempt, signal_notified_at FROM muse_mailbox_items`).toMatchObject([{ signal_attempt: 0, signal_notified_at: null }]); - const finalRows = await rows(); - await rawReplay(sql); - await applyPendingMigrations(url); - expect(await history(sql)).toEqual(afterHistory); - expect(await shape(sql)).toEqual(expectedShape); - expect(await rows()).toEqual(finalRows); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("retains exact preview SQL hashes and receipts while journaling guarded successors", async () => { - const { sql, url } = await database(); - const expectedShape = await shape(sql); - await removeMuseSchemaAndReceipts(sql); - for (const [index, migration] of museMigrations.entries()) { - const preview = await readFile(new URL(`./__fixtures__/muse-preview-migrations/${migration.preview}`, import.meta.url), "utf8"); - expect(createHash("sha256").update(preview).digest("hex")).toBe(migration.hash); - expect(createHash("sha256").update(await content(migration.file)).digest("hex")).not.toBe(migration.hash); - for (const statement of statements(preview)) await sql.unsafe(statement); - await sql`INSERT INTO drizzle.__drizzle_migrations (hash, created_at) VALUES (${migration.hash}, ${1791904391794 + index})`; - } - const rows = await seedRows(sql, true), beforeRows = await rows(), beforeHistory = await history(sql); - await applyPendingMigrations(url); - expect((await inspectMigrations(url)).status).toBe("upToDate"); - expect(await shape(sql)).toEqual(expectedShape); - expect(await rows()).toEqual(beforeRows); - const afterHistory = await history(sql); - expect(afterHistory.slice(0, beforeHistory.length)).toEqual(beforeHistory); - expect(afterHistory).toHaveLength(beforeHistory.length + museMigrations.length); - for (const migration of museMigrations) expect(afterHistory.filter(row => row.hash === migration.hash)).toHaveLength(1); - await applyPendingMigrations(url); - expect(await history(sql)).toEqual(afterHistory); - expect(await rows()).toEqual(beforeRows); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/native-runner-recovery-migration.test.ts b/packages/db/src/native-runner-recovery-migration.test.ts deleted file mode 100644 index 39973565b87..00000000000 --- a/packages/db/src/native-runner-recovery-migration.test.ts +++ /dev/null @@ -1,155 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = support.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -describeEmbeddedPostgres("native runner recovery migration", () => { - it( - "repairs a partial application and can be replayed without changing the schema", - async () => { - const database = await startEmbeddedPostgresTestDatabase( - "paperclip-native-recovery-migration-", - ); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - cleanups.push(async () => sql.end()); - - const migration = await readFile( - new URL( - "./migrations/0238_graceful_infant_terrible.sql", - import.meta.url, - ), - "utf8", - ); - const statements = migration - .split("--> statement-breakpoint") - .map((statement) => statement.trim()) - .filter((statement) => statement.length > 0); - - // Model an interrupted migration: earlier statements committed, but one of - // the later columns did not. Reapplying must skip completed work and repair - // only the missing portion. - await sql`ALTER TABLE "native_run_finalizations" DROP COLUMN "recovery_request_id"`; - for (const statement of statements) await sql.unsafe(statement); - - const columnsAfterRepair = await sql< - { - columnName: string; - dataType: string; - isNullable: "YES" | "NO"; - columnDefault: string | null; - }[] - >` - SELECT - column_name AS "columnName", - udt_name AS "dataType", - is_nullable AS "isNullable", - column_default AS "columnDefault" - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'native_run_finalizations' - AND column_name IN ( - 'controller_boot_id', - 'controller_pid', - 'controller_process_started_at', - 'controller_generation', - 'recovery_state', - 'recovery_request_id', - 'recovery_history' - ) - ORDER BY column_name - `; - - for (const statement of statements) await sql.unsafe(statement); - const columnsAfterReplay = await sql< - { - columnName: string; - dataType: string; - isNullable: "YES" | "NO"; - columnDefault: string | null; - }[] - >` - SELECT - column_name AS "columnName", - udt_name AS "dataType", - is_nullable AS "isNullable", - column_default AS "columnDefault" - FROM information_schema.columns - WHERE table_schema = 'public' - AND table_name = 'native_run_finalizations' - AND column_name IN ( - 'controller_boot_id', - 'controller_pid', - 'controller_process_started_at', - 'controller_generation', - 'recovery_state', - 'recovery_request_id', - 'recovery_history' - ) - ORDER BY column_name - `; - - expect(columnsAfterReplay).toEqual(columnsAfterRepair); - expect(columnsAfterReplay).toEqual([ - { - columnName: "controller_boot_id", - dataType: "text", - isNullable: "YES", - columnDefault: null, - }, - { - columnName: "controller_generation", - dataType: "int4", - isNullable: "NO", - columnDefault: "0", - }, - { - columnName: "controller_pid", - dataType: "int4", - isNullable: "YES", - columnDefault: null, - }, - { - columnName: "controller_process_started_at", - dataType: "timestamptz", - isNullable: "YES", - columnDefault: null, - }, - { - columnName: "recovery_history", - dataType: "jsonb", - isNullable: "NO", - columnDefault: "'[]'::jsonb", - }, - { - columnName: "recovery_request_id", - dataType: "text", - isNullable: "YES", - columnDefault: null, - }, - { - columnName: "recovery_state", - dataType: "text", - isNullable: "YES", - columnDefault: null, - }, - ]); - }, - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - ); -}); diff --git a/packages/db/src/native-warm-follow-up-default-migration.test.ts b/packages/db/src/native-warm-follow-up-default-migration.test.ts deleted file mode 100644 index 8a5d2e6644d..00000000000 --- a/packages/db/src/native-warm-follow-up-default-migration.test.ts +++ /dev/null @@ -1,80 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const migrationFile = "0443_native_warm_follow_up_default.sql"; -const actor = "migration:native-warm-follow-up-default"; - -(support.supported ? describe : describe.skip)("native warm follow-up default migration", () => { - it("clears only the old per_turn default and records an auditable entry per agent", async () => { - const database = await startEmbeddedPostgresTestDatabase("native-warm-follow-up-default-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const [company] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Warm default', 'WD1') RETURNING id`; - const candidates: Array<{ name: string; adapterType?: string; config: Record; explicit?: boolean; migrates: boolean }> = [ - { name: "Codex default", config: { provider: "codex", model: "m", lifecycleMode: "per_turn", codexPermissionMode: "never" }, migrates: true }, - { name: "OpenCode default", config: { provider: "opencode", model: "m", lifecycleMode: "per_turn" }, migrates: true }, - { name: "Claude default", config: { provider: "acpx", acpxAgent: "claude", model: "m", lifecycleMode: "per_turn" }, migrates: true }, - // A user who switched to Turn by turn keeps it. - { name: "Codex explicit", config: { provider: "codex", model: "m", lifecycleMode: "per_turn" }, explicit: true, migrates: false }, - { name: "Codex warm", config: { provider: "codex", model: "m", lifecycleMode: "warm", idleTimeoutMs: 900_000 }, migrates: false }, - { name: "Codex unset", config: { provider: "codex", model: "m" }, migrates: false }, - // Unmeasured harnesses keep their stored lifecycle. - { name: "Grok", config: { provider: "acpx", acpxAgent: "grok", lifecycleMode: "per_turn" }, migrates: false }, - { name: "Pi", config: { provider: "acpx", acpxAgent: "pi", lifecycleMode: "per_turn" }, migrates: false }, - { name: "Cursor", config: { provider: "cursor_cloud", lifecycleMode: "per_turn" }, migrates: false }, - { name: "Legacy Codex", adapterType: "codex_local", config: { lifecycleMode: "per_turn" }, migrates: false }, - ]; - const ids = new Map(); - for (const candidate of candidates) { - const id = randomUUID(); - ids.set(candidate.name, id); - await sql`INSERT INTO agents (id, company_id, name, adapter_type, adapter_config) - VALUES (${id}, ${company!.id}, ${candidate.name}, ${candidate.adapterType ?? "paperclip_runner"}, ${sql.json(candidate.config)})`; - if (candidate.explicit) { - await sql`INSERT INTO agent_config_revisions (company_id, agent_id, changed_keys, before_config, after_config) - VALUES (${company!.id}, ${id}, ${sql.json(["adapterConfig"])}, - ${sql.json({ adapterConfig: { ...candidate.config, lifecycleMode: "warm" } })}, - ${sql.json({ adapterConfig: candidate.config })})`; - } - } - // A later unrelated edit that kept per_turn is not an explicit choice of it. - await sql`INSERT INTO agent_config_revisions (company_id, agent_id, changed_keys, before_config, after_config) - VALUES (${company!.id}, ${ids.get("Codex default")!}, ${sql.json(["adapterConfig"])}, - ${sql.json({ adapterConfig: { provider: "codex", model: "old", lifecycleMode: "per_turn" } })}, - ${sql.json({ adapterConfig: { provider: "codex", model: "m", lifecycleMode: "per_turn" } })})`; - - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await applyPendingMigrations(database.connectionString); - - const rows = await sql`SELECT id, adapter_config FROM agents WHERE company_id = ${company!.id}`; - const configOf = (name: string) => rows.find(row => row.id === ids.get(name))!.adapter_config as Record; - for (const candidate of candidates) { - if (candidate.migrates) { - const { lifecycleMode: _cleared, ...rest } = candidate.config; - expect(configOf(candidate.name)).toEqual(rest); - } else { - expect(configOf(candidate.name)).toEqual(candidate.config); - } - } - const audit = await sql`SELECT entity_id, action, details FROM activity_log WHERE actor_id = ${actor} ORDER BY entity_id`; - const migrated = candidates.filter(candidate => candidate.migrates).map(candidate => ids.get(candidate.name)!).sort(); - expect(audit.map(row => row.entity_id)).toEqual(migrated); - expect(audit.every(row => row.action === "agent.updated" && row.details.source === "migration" - && row.details.before.lifecycleMode === "per_turn" && row.details.after.lifecycleMode === null)).toBe(true); - - // Re-running finds nothing left to migrate and writes no duplicate audit rows. - await sql.unsafe(content); - expect(await sql`SELECT id FROM activity_log WHERE actor_id = ${actor}`).toHaveLength(migrated.length); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 120_000); -}); diff --git a/packages/db/src/nested-skill-folders-migration.test.ts b/packages/db/src/nested-skill-folders-migration.test.ts deleted file mode 100644 index 64ba1cd9040..00000000000 --- a/packages/db/src/nested-skill-folders-migration.test.ts +++ /dev/null @@ -1,123 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { applyPendingMigrations } from "./client.js"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0175_nested_skill_folders.sql"; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -async function migrationHash() { - const content = await fs.promises.readFile(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); - return createHash("sha256").update(content).digest("hex"); -} - -describeEmbeddedPostgres("nested skill folders migration", () => { - afterEach(async () => { - await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); - }); - - it("backfills existing folders, bundled skills, and project scan skills", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-nested-folders-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${await migrationHash()}`; - await sql`DROP INDEX IF EXISTS "folders_company_kind_parent_position_idx"`; - await sql`DROP INDEX IF EXISTS "folders_company_kind_system_key_uq"`; - await sql`DROP INDEX IF EXISTS "folders_company_kind_root_slug_uq"`; - await sql`DROP INDEX IF EXISTS "folders_company_kind_parent_slug_uq"`; - await sql`ALTER TABLE "folders" DROP CONSTRAINT IF EXISTS "folders_company_kind_parent_slug_uq"`; - await sql`ALTER TABLE "folders" DROP CONSTRAINT IF EXISTS "folders_parent_id_folders_id_fk"`; - await sql`ALTER TABLE "folders" DROP COLUMN IF EXISTS "system_key"`; - await sql`ALTER TABLE "folders" DROP COLUMN IF EXISTS "slug"`; - await sql`ALTER TABLE "folders" DROP COLUMN IF EXISTS "parent_id"`; - await sql`CREATE UNIQUE INDEX IF NOT EXISTS "folders_company_kind_name_uq" ON "folders" ("company_id", "kind", "name")`; - - const companyId = randomUUID(); - const projectId = randomUUID(); - const existingFolderId = randomUUID(); - const squattedBundledId = randomUUID(); - const squattedProjectsId = randomUUID(); - const bundledSkillId = randomUUID(); - const projectSkillId = randomUUID(); - const unfiledSkillId = randomUUID(); - await sql` - INSERT INTO "companies" ("id", "name", "issue_prefix") - VALUES (${companyId}, 'Paperclip', 'PAP') - `; - await sql` - INSERT INTO "projects" ("id", "company_id", "name") - VALUES (${projectId}, ${companyId}, 'Agent Platform') - `; - await sql` - INSERT INTO "folders" ("id", "company_id", "kind", "name", "position") - VALUES - (${existingFolderId}, ${companyId}, 'skill', 'Team Notes', 0), - (${squattedBundledId}, ${companyId}, 'skill', 'Bundled', 1), - (${squattedProjectsId}, ${companyId}, 'skill', 'Projects', 2) - `; - await sql` - INSERT INTO "company_skills" ("id", "company_id", "key", "slug", "name", "markdown", "metadata") - VALUES - (${bundledSkillId}, ${companyId}, 'paperclipai/bundled/software-development/review', 'review', 'Review', '# Review', '{"sourceKind":"paperclip_bundled"}'::jsonb), - (${projectSkillId}, ${companyId}, 'company/project-skill', 'project-skill', 'Project Skill', '# Project', ${sql.json({ sourceKind: "project_scan", projectId, projectName: "Agent Platform" })}), - (${unfiledSkillId}, ${companyId}, 'company/unfiled', 'unfiled', 'Unfiled', '# Unfiled', '{}'::jsonb) - `; - - await applyPendingMigrations(database.connectionString); - - const folderRows = await sql<{ - id: string; - parent_id: string | null; - slug: string; - system_key: string | null; - }[]>` - SELECT "id", "parent_id", "slug", "system_key" - FROM "folders" - WHERE "company_id" = ${companyId} - ORDER BY "slug" - `; - expect(folderRows).toEqual(expect.arrayContaining([ - expect.objectContaining({ id: existingFolderId, slug: "team-notes", parent_id: null }), - expect.objectContaining({ id: squattedBundledId, slug: `bundled-${squattedBundledId.replace(/-/g, "").slice(0, 8)}`, system_key: null }), - expect.objectContaining({ id: squattedProjectsId, slug: `projects-${squattedProjectsId.replace(/-/g, "").slice(0, 8)}`, system_key: null }), - expect.objectContaining({ slug: "bundled", system_key: "bundled", parent_id: null }), - expect.objectContaining({ slug: "software-development", system_key: "bundled:software-development" }), - expect.objectContaining({ slug: "projects", system_key: "projects", parent_id: null }), - expect.objectContaining({ slug: "agent-platform", system_key: `project:${projectId}` }), - ])); - - const skills = await sql<{ id: string; folder_id: string | null; folder_slug: string | null }[]>` - SELECT skill."id", skill."folder_id", folder."slug" AS folder_slug - FROM "company_skills" AS skill - LEFT JOIN "folders" AS folder ON folder."id" = skill."folder_id" - WHERE skill."company_id" = ${companyId} - ORDER BY skill."id" - `; - expect(skills.find((skill) => skill.id === bundledSkillId)).toMatchObject({ folder_slug: "software-development" }); - expect(skills.find((skill) => skill.id === projectSkillId)).toMatchObject({ folder_slug: "agent-platform" }); - expect(skills.find((skill) => skill.id === unfiledSkillId)).toMatchObject({ folder_id: null, folder_slug: null }); - - const indexes = await sql<{ indexname: string; indexdef: string }[]>` - SELECT "indexname", "indexdef" - FROM "pg_indexes" - WHERE "tablename" = 'folders' - AND "indexname" IN ('folders_company_kind_root_slug_uq', 'folders_company_kind_parent_slug_uq') - ORDER BY "indexname" - `; - expect(indexes).toHaveLength(2); - expect(indexes.map((index) => index.indexdef).join("\n")).not.toContain("NULLS NOT DISTINCT"); - expect(indexes.find((index) => index.indexname === "folders_company_kind_root_slug_uq")?.indexdef) - .toContain("WHERE (parent_id IS NULL)"); - expect(indexes.find((index) => index.indexname === "folders_company_kind_parent_slug_uq")?.indexdef) - .toContain("WHERE (parent_id IS NOT NULL)"); - }, 30_000); -}); diff --git a/packages/db/src/private-task-draft-assets-migration.test.ts b/packages/db/src/private-task-draft-assets-migration.test.ts deleted file mode 100644 index 54007d4c788..00000000000 --- a/packages/db/src/private-task-draft-assets-migration.test.ts +++ /dev/null @@ -1,35 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs/promises"; -import postgres from "postgres"; -import { expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const itEmbeddedPostgres = embeddedPostgresSupport.supported ? it : it.skip; - -itEmbeddedPostgres("backfills owned draft images without attaching another uploader's images", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-draft-privacy-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const migration = await fs.readFile(new URL("./migrations/0314_private_task_draft_assets.sql", import.meta.url), "utf8"); - const hash = createHash("sha256").update(migration).digest("hex"); - const company = randomUUID(), task = randomUUID(), owned = randomUUID(), foreign = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${company}, 'Draft privacy', 'DRAFT')`; - for (const [id, owner] of [[owned, 'owner'], [foreign, 'someone-else']]) { - await sql`INSERT INTO assets (id, company_id, provider, object_key, content_type, byte_size, sha256, created_by_user_id) - VALUES (${id}, ${company}, 'local_disk', ${`${company}/assets/issues/drafts/${id}`}, 'image/png', 1, 'test', ${owner})`; - } - await sql`INSERT INTO issues (id, company_id, title, description, visibility, created_by_user_id) - VALUES (${task}, ${company}, 'Private task', ${`![owned](/api/assets/${owned}/content) ![foreign](/api/assets/${foreign}/content)`}, 'private', 'owner')`; - for (let run = 0; run < 2; run += 1) { - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await applyPendingMigrations(database.connectionString); - expect(await sql`SELECT issue_id, asset_id FROM issue_attachments WHERE company_id = ${company}`) - .toEqual([{ issue_id: task, asset_id: owned }]); - } - } finally { - await sql.end(); - await database.cleanup(); - } -}, 60_000); diff --git a/packages/db/src/project-environment-overlap-migration.test.ts b/packages/db/src/project-environment-overlap-migration.test.ts deleted file mode 100644 index 1ffad040217..00000000000 --- a/packages/db/src/project-environment-overlap-migration.test.ts +++ /dev/null @@ -1,130 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; -const migrations = ["0466_drop_project_environment.sql", "0467_fair_human_torch.sql"]; -const hashes = await Promise.all(migrations.map(async (file) => createHash("sha256") - .update(await readFile(new URL(`./migrations/${file}`, import.meta.url))).digest("hex"))); - -describePostgres("project environment rolling migration", () => { - let database: Awaited>; - let sql: ReturnType; - - beforeAll(async () => { - database = await startEmbeddedPostgresTestDatabase("paperclip-project-environment-overlap-"); - sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - afterAll(async () => { - await sql?.end(); - await database?.cleanup(); - }); - - async function prepare() { - await sql`DELETE FROM projects`; - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash IN ${sql(hashes)}`; - const environmentIds = [randomUUID(), randomUUID()]; - await sql`INSERT INTO environments (id, name, driver) VALUES - (${environmentIds[0]}, ${randomUUID()}, 'ssh'), (${environmentIds[1]}, ${randomUUID()}, 'ssh')`; - const projectIds = [randomUUID(), randomUUID(), randomUUID()]; - for (let index = 0; index < projectIds.length; index++) { - const companyId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Legacy company', ${`P${index}${companyId.slice(0, 6)}`})`; - await sql`INSERT INTO projects (id, company_id, name, environment_id) VALUES - (${projectIds[index]}, ${companyId}, 'Legacy project', ${environmentIds[index] ?? null})`; - } - return { environmentIds, projectIds }; - } - - const rows = () => sql`SELECT id, environment_id FROM projects ORDER BY id`; - const receipts = () => sql`SELECT hash FROM drizzle.__drizzle_migrations WHERE hash IN ${sql(hashes)} ORDER BY hash`; - - it("preserves committed old-writer values and gives concurrent old readers an unbroken column", async () => { - const { environmentIds, projectIds } = await prepare(); - const writer = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - const readerUrl = new URL(database.connectionString); - readerUrl.searchParams.set("application_name", "project-column-overlap-reader"); - const reader = postgres(readerUrl.toString(), { max: 1, onnotice: () => {} }); - const migrationUrl = new URL(database.connectionString); - migrationUrl.searchParams.set("application_name", "project-column-overlap-migrator"); - let migration: Promise | undefined; - let read: Promise | undefined; - try { - await writer`BEGIN`; - await writer`UPDATE projects SET environment_id = ${environmentIds[1]} WHERE id = ${projectIds[0]}`; - migration = applyPendingMigrations(migrationUrl.toString()); - await expect.poll(async () => (await sql`SELECT EXISTS ( - SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid - WHERE l.relation = 'projects'::regclass AND l.mode = 'AccessExclusiveLock' AND NOT l.granted - AND a.application_name = 'project-column-overlap-migrator') AS waiting`)[0]?.waiting, - { timeout: 10_000 }).toBe(true); - read = reader`SELECT id, environment_id FROM projects ORDER BY id`.then((result) => Array.from(result)); - await expect.poll(async () => (await sql`SELECT EXISTS ( - SELECT 1 FROM pg_locks l JOIN pg_stat_activity a ON a.pid = l.pid - WHERE l.relation = 'projects'::regclass AND l.mode = 'AccessShareLock' AND NOT l.granted - AND a.application_name = 'project-column-overlap-reader') AS waiting`)[0]?.waiting, - { timeout: 10_000 }).toBe(true); - const before = Array.from(await writer`SELECT id, environment_id FROM projects ORDER BY id`); - await writer`COMMIT`; - await migration; - expect(await read).toEqual(before); - expect(Array.from(await rows())).toEqual(before); - expect(Array.from(await receipts())).toEqual(hashes.toSorted().map((hash) => ({ hash }))); - const state = await inspectMigrations(database.connectionString); - expect(state.status).toBe("upToDate"); - await applyPendingMigrations(database.connectionString); - expect(Array.from(await rows())).toEqual(before); - expect(await receipts()).toHaveLength(2); - await writer`UPDATE projects SET environment_id = ${environmentIds[0]} WHERE id = ${projectIds[0]}`; - await sql`DELETE FROM environments WHERE id = ${environmentIds[0]}`; - expect((await sql`SELECT environment_id FROM projects WHERE id = ${projectIds[0]}`)[0]?.environment_id).toBeNull(); - } finally { - await writer`ROLLBACK`; - await Promise.allSettled([migration, read]); - await Promise.all([writer.end(), reader.end()]); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("rolls back both DDL and genuine receipts if restoring the legacy values fails", async () => { - await prepare(); - const before = Array.from(await rows()); - await sql.unsafe(`CREATE FUNCTION reject_project_environment_restore() RETURNS trigger LANGUAGE plpgsql AS $$ - BEGIN RAISE EXCEPTION 'project_environment_restore_fixture'; END $$`); - await sql.unsafe(`CREATE TRIGGER reject_project_environment_restore BEFORE UPDATE ON projects - FOR EACH ROW EXECUTE FUNCTION reject_project_environment_restore()`); - try { - await expect(applyPendingMigrations(database.connectionString)).rejects.toThrow("project_environment_restore_fixture"); - expect(Array.from(await rows())).toEqual(before); - expect(await receipts()).toHaveLength(0); - } finally { - await sql.unsafe("DROP TRIGGER reject_project_environment_restore ON projects"); - await sql.unsafe("DROP FUNCTION reject_project_environment_restore()"); - } - await applyPendingMigrations(database.connectionString); - expect(Array.from(await rows())).toEqual(before); - expect(await receipts()).toHaveLength(2); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("applies only the additive repair when the published drop was already committed", async () => { - await sql`DELETE FROM projects`; - await sql.unsafe('ALTER TABLE projects DROP COLUMN environment_id'); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hashes[1]}`; - await applyPendingMigrations(database.connectionString); - expect((await sql`SELECT data_type, is_nullable FROM information_schema.columns - WHERE table_schema = 'public' AND table_name = 'projects' AND column_name = 'environment_id'`)[0]) - .toEqual({ data_type: "uuid", is_nullable: "YES" }); - expect((await sql`SELECT confdeltype FROM pg_constraint WHERE conrelid = 'projects'::regclass - AND conname = 'projects_environment_id_environments_id_fk'`)[0]?.confdeltype).toBe("n"); - expect(await receipts()).toHaveLength(2); - expect((await inspectMigrations(database.connectionString)).status).toBe("upToDate"); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/project-skill-sources-migration.test.ts b/packages/db/src/project-skill-sources-migration.test.ts deleted file mode 100644 index dbb2e240d44..00000000000 --- a/packages/db/src/project-skill-sources-migration.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -describePostgres("project skill source migration replay", () => { - it("keeps imported content, private provenance and scheduling when renumbered SQL runs again", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-project-skill-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companyId = randomUUID(), projectId = randomUUID(), workspaceId = randomUUID(); - const sourceId = randomUUID(), skillId = randomUUID(), bindingId = randomUUID(), agentId = randomUUID(); - const connectionId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Migration company', 'PSM')`; - await sql`INSERT INTO projects (id, company_id, name, visibility) VALUES (${projectId}, ${companyId}, 'Private project', 'private')`; - await sql`INSERT INTO project_workspaces (id, company_id, project_id, name, repo_url) VALUES (${workspaceId}, ${companyId}, ${projectId}, 'Repository', 'https://github.com/acme/skills')`; - await sql`INSERT INTO agents (id, company_id, name) VALUES (${agentId}, ${companyId}, 'Setup agent')`; - await sql`INSERT INTO company_skill_sources (id, company_id, repository_url, full_name, tracking_ref, access_scope, automatic_updates, import_new_skills, refresh_user_id, refresh_agent_id, connection_id, excluded_folders, revision, failure_count, next_sync_at) - VALUES (${sourceId}, ${companyId}, 'https://github.com/acme/skills', 'acme/skills', 'HEAD', 'projects', false, true, 'setup-person', ${agentId}, ${connectionId}, '["excluded"]', 7, 3, '2030-01-01')`; - await sql`INSERT INTO company_skills (id, company_id, key, slug, name, markdown, access_source_id) VALUES (${skillId}, ${companyId}, 'repo/review', 'review', 'Review', 'Keep installed content', ${sourceId})`; - await sql`INSERT INTO project_skill_sources (id, company_id, project_id, workspace_id, source_id, repository_url, tracking_ref, active, status, refresh_user_id, refresh_agent_id, connection_id) - VALUES (${bindingId}, ${companyId}, ${projectId}, ${workspaceId}, ${sourceId}, 'https://github.com/acme/skills', 'HEAD', false, 'ready', 'setup-person', ${agentId}, ${connectionId})`; - // Preview builds used an agent FK that would erase the authorizing identity. - await sql.unsafe('ALTER TABLE project_skill_sources ADD CONSTRAINT project_skill_sources_refresh_agent_id_agents_id_fk FOREIGN KEY (refresh_agent_id) REFERENCES agents(id) ON DELETE SET NULL'); - const source = () => sql`SELECT * FROM company_skill_sources WHERE id = ${sourceId}`; - const binding = () => sql`SELECT * FROM project_skill_sources WHERE id = ${bindingId}`; - const skill = () => sql`SELECT * FROM company_skills WHERE id = ${skillId}`; - const relations = () => sql`SELECT oid::text, relname FROM pg_class WHERE relname IN ('company_skill_sources', 'project_skill_sources', 'company_skills') ORDER BY relname`; - const before = { source: await source(), binding: await binding(), skill: await skill(), relations: await relations() }; - const migration = await readFile(new URL("./migrations/0341_abnormal_bucky.sql", import.meta.url), "utf8"); - for (let attempt = 0; attempt < 2; attempt++) { - for (const statement of migration.split("--> statement-breakpoint")) { - if (statement.trim()) await sql.unsafe(statement); - } - expect(await source()).toEqual(before.source); - expect(await binding()).toEqual(before.binding); - expect(await skill()).toEqual(before.skill); - expect(await relations()).toEqual(before.relations); - } - await sql`DELETE FROM agents WHERE id = ${agentId}`; - expect((await source())[0]?.refresh_agent_id).toBe(agentId); - expect((await binding())[0]?.refresh_agent_id).toBe(agentId); - expect((await binding())[0]?.connection_id).toBe(connectionId); - expect((await skill())[0]?.access_source_id).toBe(sourceId); - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/prompt-injection-prevention-migration.test.ts b/packages/db/src/prompt-injection-prevention-migration.test.ts deleted file mode 100644 index 6429fcac8fd..00000000000 --- a/packages/db/src/prompt-injection-prevention-migration.test.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readdir, readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const migration = await readFile(new URL("./migrations/0362_large_roughhouse.sql", import.meta.url), "utf8"); -const migrationHash = createHash("sha256").update(migration).digest("hex"); -// SQL published by this PR before its replay guards were added (14a1d73991). -const originalMigrationHash = "bf087cbc9551b3c07aabffac45c87239ba53d1a095f03807d4ff98718028ea25"; -const statements = migration.split("--> statement-breakpoint").map(statement => statement.trim()).filter(Boolean); -// Later migrations that redefine a CHECK constraint 0362 also defines. An -// upgrade that runs 0362 runs these after it, in journal order, so the -// recovery cases below leave them pending too and let the migrator run them. -const SHARED_CONSTRAINTS = ["budget_reservations_source_check", "cost_events_usage_kind_check"]; -const laterRedefining = (await Promise.all((await readdir(new URL("./migrations/", import.meta.url))) - .filter(name => /^\d{4}_.*\.sql$/.test(name) && Number(name.slice(0, 4)) > 362) - .sort() - .map(name => readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8")))) - .filter(text => SHARED_CONSTRAINTS.some(name => text.includes(`"${name}"`))) - .map(text => ({ - hash: createHash("sha256").update(text).digest("hex"), - statements: text.split("--> statement-breakpoint").map(statement => statement.trim()).filter(Boolean), - })); -async function replayLaterMigrations(sql: ReturnType) { - for (const later of laterRedefining) for (const statement of later.statements) await sql.unsafe(statement); -} -async function forgetLaterMigrations(sql: ReturnType) { - for (const later of laterRedefining) await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${later.hash}`; -} -const cleanups: Array<() => Promise> = []; -afterEach(async () => { while (cleanups.length) await cleanups.pop()?.(); }); - -async function database() { - const database = await startEmbeddedPostgresTestDatabase("paperclip-injection-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => { await sql.end(); }); - return { sql, url: database.connectionString }; -} -async function replay(sql: ReturnType) { - for (const statement of statements) await sql.unsafe(statement); -} -async function history(sql: ReturnType) { - return Array.from(await sql`SELECT id, hash, created_at::text AS created_at FROM drizzle.__drizzle_migrations ORDER BY id`); -} -async function shape(sql: ReturnType) { - return { - columns: Array.from(await sql`SELECT table_name, column_name, udt_name, is_nullable, column_default - FROM information_schema.columns WHERE table_schema = 'public' - AND table_name IN ('company_prompt_injection_prevention', 'prompt_injection_invocations', 'budget_reservations', 'cost_events') - ORDER BY table_name, column_name`), - constraints: Array.from(await sql`SELECT t.relname, c.conname, c.convalidated, pg_get_constraintdef(c.oid, true) AS definition - FROM pg_constraint c JOIN pg_class t ON t.oid = c.conrelid JOIN pg_namespace n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' - AND t.relname IN ('company_prompt_injection_prevention', 'prompt_injection_invocations', 'budget_reservations', 'cost_events') - ORDER BY t.relname, c.conname`), - indexes: Array.from(await sql`SELECT t.relname, i.indisvalid, i.indisready, pg_get_indexdef(i.indexrelid) AS definition - FROM pg_index i JOIN pg_class t ON t.oid = i.indrelid JOIN pg_namespace n ON n.oid = t.relnamespace - WHERE n.nspname = 'public' - AND t.relname IN ('company_prompt_injection_prevention', 'prompt_injection_invocations', 'budget_reservations', 'cost_events') - ORDER BY t.relname, definition`), - }; -} -async function seed(sql: ReturnType) { - const [company] = await sql`INSERT INTO companies (name, issue_prefix) VALUES ('Migration replay', 'PIM') RETURNING id`; - const connectionId = randomUUID(), grantId = randomUUID(); - await sql`INSERT INTO company_prompt_injection_prevention (company_id, connection_id, grant_id, enabled, model) - VALUES (${company.id}, ${connectionId}, ${grantId}, true, 'openai/gpt-oss-safeguard-20b')`; - const [charge] = await sql`INSERT INTO cost_events - (company_id, usage_kind, provider, biller, billing_type, cost_status, model, cost_cents, occurred_at) - VALUES (${company.id}, 'prompt_injection', 'openai', 'openrouter', 'metered_api', 'unpriced', 'openai/gpt-oss-safeguard-20b', 0, now()) RETURNING id`; - const [invocation] = await sql`INSERT INTO prompt_injection_invocations - (company_id, source, actor_type, actor_id, connection_id, grant_id, policy_version, model, status, error_code, cost_event_id) - VALUES (${company.id}, 'gateway', 'system', 'retained-actor', ${connectionId}, ${grantId}, 'tool-result-v1', - 'openai/gpt-oss-safeguard-20b', 'unknown', 'timeout', ${charge.id}) RETURNING id`; - await sql`INSERT INTO budget_reservations (company_id, prompt_injection_invocation_id, amount_cents, state) - VALUES (${company.id}, ${invocation.id}, 10, 'held')`; - return { companyId: company.id, invocationId: invocation.id, chargeId: charge.id }; -} -async function rows(sql: ReturnType) { - return { - settings: Array.from(await sql`SELECT to_jsonb(t) AS row FROM company_prompt_injection_prevention t ORDER BY company_id`), - invocations: Array.from(await sql`SELECT to_jsonb(t) AS row FROM prompt_injection_invocations t ORDER BY id`), - charges: Array.from(await sql`SELECT to_jsonb(t) AS row FROM cost_events t ORDER BY id`), - reservations: Array.from(await sql`SELECT to_jsonb(t) AS row FROM budget_reservations t ORDER BY id`), - }; -} - -describe("prompt injection migration replay", () => { - it("replays raw SQL twice without changing settings, accounting, schema, or migration receipts", async () => { - const { sql } = await database(); - const fixture = await seed(sql); - const before = { shape: await shape(sql), rows: await rows(sql), history: await history(sql) }; - await replay(sql); - await replay(sql); - await replayLaterMigrations(sql); - expect(await shape(sql)).toEqual(before.shape); - expect(await rows(sql)).toEqual(before.rows); - expect(await history(sql)).toEqual(before.history); - await expect(sql`UPDATE company_prompt_injection_prevention SET grant_id = NULL WHERE company_id = ${fixture.companyId}`) - .rejects.toMatchObject({ code: "23514" }); - await expect(sql`UPDATE prompt_injection_invocations SET status = 'invalid' WHERE id = ${fixture.invocationId}`) - .rejects.toMatchObject({ code: "23514" }); - await expect(sql`UPDATE cost_events SET usage_kind = 'invalid' WHERE id = ${fixture.chargeId}`) - .rejects.toMatchObject({ code: "23514" }); - await expect(sql`UPDATE budget_reservations SET prompt_injection_invocation_id = NULL WHERE company_id = ${fixture.companyId}`) - .rejects.toMatchObject({ code: "23514" }); - await expect(sql`INSERT INTO budget_reservations (company_id, prompt_injection_invocation_id, amount_cents) - VALUES (${fixture.companyId}, ${fixture.invocationId}, 10)`).rejects.toMatchObject({ code: "23505" }); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("finishes partial unjournaled DDL without losing existing configuration or unresolved charges", async () => { - const { sql, url } = await database(); - const expectedShape = await shape(sql); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${migrationHash}`; - await forgetLaterMigrations(sql); - await sql`DROP TABLE prompt_injection_invocations`; - await sql`DROP TABLE company_prompt_injection_prevention`; - await sql`ALTER TABLE budget_reservations DROP CONSTRAINT budget_reservations_source_check`; - await sql`ALTER TABLE budget_reservations DROP COLUMN prompt_injection_invocation_id`; - await sql`ALTER TABLE cost_events DROP CONSTRAINT cost_events_usage_kind_check`; - // Keep mixed completed work, including a table, column, index and FK. The - // missing journal receipt must not cause any of those objects to collide. - for (const statement of statements.slice(0, 2)) await sql.unsafe(statement); - await sql.unsafe(statements.find(statement => statement.includes('ADD COLUMN') && statement.includes('prompt_injection_invocation_id'))!); - await sql.unsafe(statements.find(statement => statement.includes('CREATE INDEX') && statement.includes('prompt_injection_invocations_company_started_idx'))!); - await sql.unsafe(statements.find(statement => statement.includes('ADD CONSTRAINT "company_prompt_injection_prevention_company_id_companies_id_fk"'))!); - await seed(sql); - const beforeRows = await rows(sql), beforeHistory = await history(sql); - await applyPendingMigrations(url); - expect((await inspectMigrations(url)).status).toBe("upToDate"); - expect(await shape(sql)).toEqual(expectedShape); - expect(await rows(sql)).toEqual(beforeRows); - const afterHistory = await history(sql); - expect(afterHistory.slice(0, beforeHistory.length)).toEqual(beforeHistory); - expect(afterHistory).toHaveLength(beforeHistory.length + 1 + laterRedefining.length); - await replay(sql); - await applyPendingMigrations(url); - expect(await history(sql)).toEqual(afterHistory); - expect(await rows(sql)).toEqual(beforeRows); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); - - it("preserves the original SQL receipt when upgrading a company that already applied this PR", async () => { - const { sql, url } = await database(); - await seed(sql); - await sql`UPDATE drizzle.__drizzle_migrations SET hash = ${originalMigrationHash} WHERE hash = ${migrationHash}`; - await forgetLaterMigrations(sql); - const before = { shape: await shape(sql), rows: await rows(sql), history: await history(sql) }; - await applyPendingMigrations(url); - expect((await inspectMigrations(url)).status).toBe("upToDate"); - expect(await shape(sql)).toEqual(before.shape); - expect(await rows(sql)).toEqual(before.rows); - const after = await history(sql); - expect(after.slice(0, before.history.length)).toEqual(before.history); - expect(after.some(row => row.hash === originalMigrationHash)).toBe(true); - expect(after.filter(row => row.hash === migrationHash)).toHaveLength(1); - await applyPendingMigrations(url); - expect(await history(sql)).toEqual(after); - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/question-response-delivery-migration.test.ts b/packages/db/src/question-response-delivery-migration.test.ts deleted file mode 100644 index 434502ae868..00000000000 --- a/packages/db/src/question-response-delivery-migration.test.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { fileURLToPath } from "node:url"; -import { afterEach, describe, expect, it } from "vitest"; -import postgres from "postgres"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const cleanups: Array<() => Promise> = []; -const support = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = support.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -async function migrationStatements(): Promise { - const migrationSql = await readFile( - fileURLToPath( - new URL("./migrations/0228_nasty_grim_reaper.sql", import.meta.url), - ), - "utf8", - ); - return migrationSql - .split("--> statement-breakpoint") - .map((statement) => statement.trim()) - .filter((statement) => statement.length > 0); -} - -describeEmbeddedPostgres("question response delivery migration", () => { - it("can be replayed against an already migrated database", async () => { - const database = await startEmbeddedPostgresTestDatabase( - "question-response-migration-", - ); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { - max: 1, - onnotice: () => {}, - }); - cleanups.push(async () => sql.end()); - - const statements = await migrationStatements(); - expect(statements.length).toBeGreaterThan(0); - - for (const statement of statements) await sql.unsafe(statement); - for (const statement of statements) await sql.unsafe(statement); - - const [table] = await sql<{ table_name: string }[]>` - SELECT table_name - FROM information_schema.tables - WHERE table_schema = 'public' - AND table_name = 'issue_question_response_deliveries' - `; - expect(table?.table_name).toBe("issue_question_response_deliveries"); - - const indexes = await sql<{ indexname: string }[]>` - SELECT indexname - FROM pg_indexes - WHERE indexname IN ( - 'issue_question_response_deliveries_interaction_uq', - 'issue_question_response_deliveries_correlation_uq', - 'issue_question_response_deliveries_pending_idx', - 'issue_question_response_deliveries_company_issue_idx', - 'agent_wakeup_requests_question_response_delivery_idempotency_uq' - ) - `; - expect(indexes.map((row) => row.indexname).sort()).toEqual( - [ - "agent_wakeup_requests_question_response_delivery_idempotency_uq", - "issue_question_response_deliveries_company_issue_idx", - "issue_question_response_deliveries_correlation_uq", - "issue_question_response_deliveries_interaction_uq", - "issue_question_response_deliveries_pending_idx", - ].sort(), - ); - }, 240_000); -}); diff --git a/packages/db/src/question-response-history-migration.test.ts b/packages/db/src/question-response-history-migration.test.ts deleted file mode 100644 index f09fbe03ac4..00000000000 --- a/packages/db/src/question-response-history-migration.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const indexName = "agent_wakeup_requests_question_response_history_idx"; -const migrationFile = "0332_little_night_nurse.sql"; - -(support.supported ? describe : describe.skip)("question-response history migration", () => { - it("repairs an interrupted concurrent index build and serializes replay without deleting wakes", async () => { - const database = await startEmbeddedPostgresTestDatabase("question-history-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companyId = randomUUID(); - const agentId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Migration fixture', 'QHM')`; - await sql`INSERT INTO agents (id, company_id, name, role, adapter_type) - VALUES (${agentId}, ${companyId}, 'Fixture', 'engineer', 'process')`; - await sql`INSERT INTO agent_wakeup_requests (company_id, agent_id, source, idempotency_key, status) - SELECT ${companyId}::uuid, ${agentId}::uuid, 'automation', 'question-response:' || n::text, 'failed' - FROM generate_series(1, 3) n`; - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await sql.unsafe(`DROP INDEX ${indexName}`); - // A failed concurrent UNIQUE build leaves the same invalid-index state - // as an interrupted nonunique build, without relying on timing a cancel. - await expect(sql.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON agent_wakeup_requests (company_id)`)) - .rejects.toThrow(); - const [invalid] = await sql`SELECT i.indisvalid FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid - WHERE c.relname = ${indexName}`; - expect(invalid?.indisvalid).toBe(false); - await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]); - const [rebuilt] = await sql`SELECT i.indisvalid, i.indisunique, pg_get_indexdef(i.indexrelid) AS definition - FROM pg_index i JOIN pg_class c ON c.oid = i.indexrelid WHERE c.relname = ${indexName}`; - expect(rebuilt?.indisvalid).toBe(true); - expect(rebuilt?.indisunique).toBe(false); - expect(rebuilt?.definition).toContain("company_id, idempotency_key"); - expect(rebuilt?.definition).toContain("question-response:%"); - const [wakes] = await sql`SELECT count(*)::int AS n FROM agent_wakeup_requests WHERE company_id = ${companyId}`; - expect(wakes?.n).toBe(3); - const [history] = await sql`SELECT count(*)::int AS n FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - expect(history?.n).toBe(1); - await applyPendingMigrations(database.connectionString); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 60_000); -}); diff --git a/packages/db/src/run-identity-migration.test.ts b/packages/db/src/run-identity-migration.test.ts deleted file mode 100644 index 18c7643563a..00000000000 --- a/packages/db/src/run-identity-migration.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFileSync } from "node:fs"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const migrations = [ - "0240_pink_fantastic_four.sql", "0241_conscious_adam_destine.sql", - "0242_wide_lightspeed.sql", "0243_sleepy_metal_master.sql", "0244_organic_meltdown.sql", "0245_misty_nightshade.sql", -].map((name) => readFileSync(new URL(`./migrations/${name}`, import.meta.url), "utf8")); - -(support.supported ? describe : describe.skip)("execution identity migration", () => { - it("can replay without inventing historical authorship or losing accepted contexts", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-identity-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companyId = randomUUID(), agentId = randomUUID(), historicalRunId = randomUUID(), runId = randomUUID(), contextId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Identity migration', 'MIG')`; - await sql`INSERT INTO agents (id, company_id, name, role, adapter_type) VALUES (${agentId}, ${companyId}, 'Shared', 'engineer', 'codex_local')`; - await sql`INSERT INTO heartbeat_runs (id, company_id, agent_id, status) VALUES - (${historicalRunId}, ${companyId}, ${agentId}, 'succeeded'), (${runId}, ${companyId}, ${agentId}, 'running')`; - await sql`INSERT INTO run_identity_contexts (id, company_id, run_id, revision, responsible_user_id, cause, correlation_id, accepted_at) - VALUES (${contextId}, ${companyId}, ${runId}, 1, 'person-a', 'instruction', 'dispatch', now())`; - await sql`UPDATE heartbeat_runs SET active_identity_context_id = ${contextId}, responsible_user_id = 'person-a' WHERE id = ${runId}`; - for (let pass = 0; pass < 2; pass++) { - for (const migration of migrations) { - for (const statement of migration.split('--> statement-breakpoint')) { - if (statement.trim()) await sql.unsafe(statement); - } - } - } - const [historical] = await sql`SELECT active_identity_context_id, responsible_user_id FROM heartbeat_runs WHERE id = ${historicalRunId}`; - expect(historical).toEqual({ active_identity_context_id: null, responsible_user_id: null }); - const contexts = await sql`SELECT id, responsible_user_id FROM run_identity_contexts WHERE company_id = ${companyId}`; - expect(contexts).toEqual([{ id: contextId, responsible_user_id: 'person-a' }]); - const [active] = await sql`SELECT active_identity_context_id FROM heartbeat_runs WHERE id = ${runId}`; - expect(active.active_identity_context_id).toBe(contextId); - // Agent removal deletes its run rows, but surviving task continuations - // must retain attribution. Even replaying the migration set must be safe. - await sql`DELETE FROM heartbeat_runs WHERE id = ${runId}`; - for (const migration of migrations) { - for (const statement of migration.split('--> statement-breakpoint')) { - if (statement.trim()) await sql.unsafe(statement); - } - } - const [retained] = await sql`SELECT run_id, responsible_user_id FROM run_identity_contexts WHERE id = ${contextId}`; - expect(retained).toEqual({ run_id: runId, responsible_user_id: 'person-a' }); - await sql`DELETE FROM heartbeat_runs WHERE company_id = ${companyId}`; - await sql`DELETE FROM agents WHERE company_id = ${companyId}`; - await sql`DELETE FROM companies WHERE id = ${companyId}`; - expect(await sql`SELECT id FROM run_identity_contexts WHERE id = ${contextId}`).toHaveLength(0); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 30_000); -}); diff --git a/packages/db/src/session-goal-migration.test.ts b/packages/db/src/session-goal-migration.test.ts deleted file mode 100644 index eb5f5830383..00000000000 --- a/packages/db/src/session-goal-migration.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFileSync } from "node:fs"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const migration = readFileSync(new URL("./migrations/0248_small_manta.sql", import.meta.url), "utf8"); - -(support.supported ? describe : describe.skip)("session goal migration", () => { - it("preserves preview goals, tombstone revisions, and pending actions on replay", async () => { - const database = await startEmbeddedPostgresTestDatabase("goal-migration-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companyId = randomUUID(), agentId = randomUUID(), sessionId = randomUUID(), clearedId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Goal migration', 'GMG')`; - await sql`INSERT INTO agents (id, company_id, name, role, adapter_type) VALUES (${agentId}, ${companyId}, 'Goal agent', 'engineer', 'paperclip_runner')`; - const goal = { objective: "Keep the preview objective", status: "paused" }; - await sql`INSERT INTO agent_task_sessions (id, company_id, agent_id, adapter_type, task_key, goal_json, goal_status, goal_revision) - VALUES (${sessionId}, ${companyId}, ${agentId}, 'paperclip_runner', 'active', ${sql.json(goal)}, 'paused', 7), - (${clearedId}, ${companyId}, ${agentId}, 'paperclip_runner', 'cleared', NULL, NULL, 9)`; - await sql`INSERT INTO agent_session_goal_actions (company_id, session_id, request_id, action, payload_json) - VALUES (${companyId}, ${sessionId}, 'resume-once', 'resume', '{}')`; - for (let pass = 0; pass < 2; pass++) { - for (const statement of migration.split("--> statement-breakpoint")) { - if (statement.trim()) await sql.unsafe(statement); - } - } - const sessions = await sql`SELECT task_key, goal_json, goal_status, goal_revision FROM agent_task_sessions - WHERE company_id = ${companyId} ORDER BY task_key`; - expect([...sessions]).toEqual([ - { task_key: "active", goal_json: goal, goal_status: "paused", goal_revision: 7 }, - { task_key: "cleared", goal_json: null, goal_status: null, goal_revision: 9 }, - ]); - const actions = await sql`SELECT request_id, action, status FROM agent_session_goal_actions WHERE company_id = ${companyId}`; - expect([...actions]).toEqual([{ request_id: "resume-once", action: "resume", status: "pending" }]); - await expect(sql`INSERT INTO agent_session_goal_actions (company_id, session_id, request_id, action, payload_json) - VALUES (${companyId}, ${sessionId}, 'resume-once', 'resume', '{}')`).rejects.toMatchObject({ code: "23505" }); - await sql`DELETE FROM agent_task_sessions WHERE company_id = ${companyId}`; - expect(await sql`SELECT id FROM agent_session_goal_actions WHERE company_id = ${companyId}`).toHaveLength(0); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 30_000); -}); diff --git a/packages/db/src/speko-voice-migration.test.ts b/packages/db/src/speko-voice-migration.test.ts deleted file mode 100644 index 155e8b0e362..00000000000 --- a/packages/db/src/speko-voice-migration.test.ts +++ /dev/null @@ -1,87 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -(support.supported ? describe : describe.skip)("Speko additive voice migration", () => { - it("upgrades existing Slack data and constrains voice transport to channel connections", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-speko-upgrade-"); - const sql = postgres(database.connectionString, { max: 1 }); - try { - expect(await sql`SELECT to_regclass('chat_voice_sessions') AS name`).toEqual([{ name: "chat_voice_sessions" }]); - // Reconstruct exactly the pre-Speko schema in this disposable database. - await sql`DROP TABLE chat_voice_inbound_calls`; - await sql`DROP TABLE chat_voice_phone_lines`; - await sql`DROP TABLE chat_voice_reports`; - await sql`DROP TABLE chat_voice_callbacks`; - await sql`DROP TABLE chat_voice_replies`; - await sql`DROP TABLE chat_voice_tool_calls`; - await sql`DROP TABLE chat_voice_sessions`; - const constraints = [ - ["chat_endpoints", "chat_endpoints_provider_check", "provider in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"], - ["chat_external_principals", "chat_external_principals_provider_check", "provider in ('slack', 'github', 'discord', 'microsoft-teams', 'telegram', 'agentmail', 'imessage-photon')"], - ["tool_connections", "tool_connections_transport_check", "transport in ('mcp_remote', 'rest_api', 'local_stdio', 'chat_sdk', 'runtime_auth')"], - ["tool_connections", "tool_connections_channel_transport_check", "(connection_purpose = 'tool' and transport not in ('chat_sdk', 'runtime_auth')) or (connection_purpose = 'channel' and (transport = 'chat_sdk' or (transport = 'rest_api' and config->>'provider' = 'agentmail'))) or (connection_purpose = 'ai' and transport = 'runtime_auth')"], - ]; - for (const [table, name, definition] of constraints) { - await sql.unsafe(`ALTER TABLE ${table} DROP CONSTRAINT ${name}`); - await sql.unsafe(`ALTER TABLE ${table} ADD CONSTRAINT ${name} CHECK (${definition})`); - } - for (const name of ["0324_long_franklin_storm.sql", "0325_aberrant_machine_man.sql", "0326_blushing_screwball.sql", "0327_sad_proteus.sql", "0328_chunky_mentallo.sql", "0329_free_wolf_cub.sql", "0330_spooky_white_tiger.sql"]) { - const migration = await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(migration).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - } - const company = randomUUID(), agent = randomUUID(), application = randomUUID(), connection = randomUUID(), endpoint = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${company}, 'Existing company', 'OLD')`; - await sql`INSERT INTO agents (id, company_id, name, role, status, adapter_type) VALUES (${agent}, ${company}, 'Existing agent', 'general', 'idle', 'process')`; - await sql`INSERT INTO tool_applications (id, company_id, application_key, name, type, status) VALUES (${application}, ${company}, 'slack', 'Slack', 'chat', 'active')`; - await sql`INSERT INTO tool_connections (id, company_id, application_id, name, uid, connection_purpose, transport, status, enabled) VALUES (${connection}, ${company}, ${application}, 'Existing Slack', 'slack/existing', 'channel', 'chat_sdk', 'active', true)`; - await sql`INSERT INTO chat_endpoints (id, company_id, connection_id, provider, public_id, assigned_agent_id, status) VALUES (${endpoint}, ${company}, ${connection}, 'slack', ${randomUUID()}, ${agent}, 'active')`; - const aiConnection = randomUUID(), mailConnection = randomUUID(); - await sql`INSERT INTO tool_connections (id, company_id, application_id, name, uid, connection_purpose, transport, status, enabled) VALUES (${aiConnection}, ${company}, ${application}, 'Existing AI', 'ai/existing', 'ai', 'runtime_auth', 'active', true)`; - await sql`INSERT INTO tool_connections (id, company_id, application_id, name, uid, connection_purpose, transport, status, enabled, config) VALUES (${mailConnection}, ${company}, ${application}, 'Existing email', 'email/existing', 'channel', 'rest_api', 'active', true, '{"provider":"agentmail"}'::jsonb)`; - await applyPendingMigrations(database.connectionString); - expect(await sql`SELECT transport FROM tool_connections WHERE id = ${aiConnection}`).toEqual([{ transport: "runtime_auth" }]); - expect(await sql`SELECT transport FROM tool_connections WHERE id = ${mailConnection}`).toEqual([{ transport: "rest_api" }]); - // Upstream AI/email transports and newly added chat providers remain valid. - await sql`UPDATE tool_connections SET connection_purpose = 'ai', transport = 'runtime_auth' WHERE id = ${aiConnection}`; - await sql`UPDATE tool_connections SET config = '{"provider":"agentmail"}'::jsonb WHERE id = ${mailConnection}`; - await sql`UPDATE chat_endpoints SET provider = 'imessage-photon' WHERE id = ${endpoint}`; - await sql`UPDATE chat_endpoints SET provider = 'agentmail', publication_mode = 'explicit', external_execution_policy = 'agent' WHERE id = ${endpoint}`; - await sql`UPDATE chat_endpoints SET provider = 'slack' WHERE id = ${endpoint}`; - expect(await sql`SELECT provider, assigned_agent_id FROM chat_endpoints WHERE id = ${endpoint}`).toEqual([{ provider: "slack", assigned_agent_id: agent }]); - expect(await sql`SELECT name, transport FROM tool_connections WHERE id = ${connection}`).toEqual([{ name: "Existing Slack", transport: "chat_sdk" }]); - await sql`UPDATE tool_connections SET transport = 'voice' WHERE id = ${connection}`; - await expect(sql`UPDATE tool_connections SET connection_purpose = 'tool' WHERE id = ${connection}`).rejects.toMatchObject({ code: "23514" }); - await sql`UPDATE chat_endpoints SET provider = 'speko' WHERE id = ${endpoint}`; - expect(await sql`SELECT to_regclass('chat_voice_tool_calls') AS name`).toEqual([{ name: "chat_voice_tool_calls" }]); - expect(await sql`SELECT to_regclass('chat_voice_reports') AS name`).toEqual([{ name: "chat_voice_reports" }]); - const [toolConstraint] = await sql`SELECT pg_get_constraintdef(oid) AS definition FROM pg_constraint WHERE conname = 'chat_voice_tool_calls_tool_check'`; - expect(toolConstraint.definition).toContain("answer_question"); - expect(await sql`SELECT to_regclass('chat_voice_callbacks') AS name`).toEqual([{ name: "chat_voice_callbacks" }]); - await sql`INSERT INTO chat_voice_callbacks (company_id, endpoint_id, user_id, phone_number) VALUES (${company}, ${endpoint}, 'member', '+12015551234')`; - expect(await sql`SELECT enabled FROM chat_voice_callbacks WHERE endpoint_id = ${endpoint}`).toEqual([{ enabled: false }]); - await expect(sql`INSERT INTO chat_voice_callbacks (company_id, endpoint_id, user_id, phone_number) VALUES (${company}, ${endpoint}, 'invalid', '555')`).rejects.toMatchObject({ code: "23514" }); - await expect(sql`INSERT INTO chat_voice_callbacks (company_id, endpoint_id, user_id, phone_number) VALUES (${randomUUID()}, ${endpoint}, 'foreign', '+12015551234')`).rejects.toMatchObject({ code: "23503" }); - await expect(sql`INSERT INTO chat_voice_callbacks (company_id, endpoint_id, user_id, phone_number) VALUES (${company}, ${endpoint}, 'member', '+12015559999')`).rejects.toMatchObject({ code: "23505" }); - await applyPendingMigrations(database.connectionString); - // Existing installations have older migration hashes after renumbering. - // Force each stage to execute again while preserving the actual saved rows. - for (const name of ["0324_long_franklin_storm.sql", "0325_aberrant_machine_man.sql", "0326_blushing_screwball.sql", "0327_sad_proteus.sql", "0328_chunky_mentallo.sql", "0329_free_wolf_cub.sql", "0330_spooky_white_tiger.sql"]) { - const migration = await readFile(new URL(`./migrations/${name}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(migration).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - } - await applyPendingMigrations(database.connectionString); - expect(await sql`SELECT count(*)::int AS count FROM chat_endpoints WHERE id = ${endpoint}`).toEqual([{ count: 1 }]); - expect(await sql`SELECT phone_number, enabled FROM chat_voice_callbacks WHERE endpoint_id = ${endpoint} AND user_id = 'member'`).toEqual([{phone_number: "+12015551234", enabled: false}]); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 60_000); -}); diff --git a/packages/db/src/status-card-migrations.test.ts b/packages/db/src/status-card-migrations.test.ts deleted file mode 100644 index 6e049d2a707..00000000000 --- a/packages/db/src/status-card-migrations.test.ts +++ /dev/null @@ -1,43 +0,0 @@ -import fs from "node:fs"; -import { afterEach, describe, it } from "vitest"; -import postgres from "postgres"; -import { - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const MIGRATION_FILES = [ - "0185_status_cards.sql", - "0186_status_card_compile_provenance.sql", - "0187_status_card_pending_change_hash.sql", - "0188_status_card_generation_issue_index.sql", - "0189_status_card_agent.sql", -] as const; -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -describeEmbeddedPostgres("status card migrations", () => { - afterEach(async () => { - await Promise.all(cleanups.splice(0).map((cleanup) => cleanup())); - }); - - // Same reason as every other embedded-Postgres migration test here: starting - // the server and replaying migrations against it does not fit vitest's 5s - // default. This suite has not tripped yet only because it replays fewer - // statements than its neighbours — it is the same latent failure. - it("can be reapplied after the schema already exists", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-status-card-migrations-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1 }); - cleanups.push(async () => sql.end()); - - for (const migrationFile of MIGRATION_FILES) { - const migrationSql = await fs.promises.readFile( - new URL(`./migrations/${migrationFile}`, import.meta.url), - "utf8", - ); - await sql.unsafe(migrationSql); - } - }, 30_000); -}); diff --git a/packages/db/src/status-card-reason-upgrade.test.ts b/packages/db/src/status-card-reason-upgrade.test.ts deleted file mode 100644 index 8a772a2003f..00000000000 --- a/packages/db/src/status-card-reason-upgrade.test.ts +++ /dev/null @@ -1,111 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations, inspectMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const adminUrl = process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL; -const support = adminUrl ? { supported: true } : await getEmbeddedPostgresTestSupport(); -const journal = JSON.parse(await readFile(new URL("./migrations/meta/_journal.json", import.meta.url), "utf8")) as { - entries: Array<{ idx: number; tag: string }>; -}; -const master = journal.entries.find(entry => entry.tag === "0419_slippery_impossible_man")!; -const status = journal.entries.find(entry => entry.tag === "0420_broad_johnny_storm")!; -const statusSql = await readFile(new URL(`./migrations/${status.tag}.sql`, import.meta.url), "utf8"); -const hash = async (tag: string) => createHash("sha256") - .update(await readFile(new URL(`./migrations/${tag}.sql`, import.meta.url), "utf8")).digest("hex"); - -async function database() { - if (!adminUrl) return startEmbeddedPostgresTestDatabase("status-reason-upgrade-"); - const name = `status_reason_${randomUUID().replaceAll("-", "")}_test`; - const admin = postgres(adminUrl, { max: 1, onnotice: () => {} }); - try { await admin.unsafe(`create database "${name}"`); } - finally { await admin.end(); } - const url = new URL(adminUrl); url.pathname = `/${name}`; - const cleanup = async () => { - const admin = postgres(adminUrl, { max: 1, onnotice: () => {} }); - try { await admin.unsafe(`drop database "${name}"`); } - finally { await admin.end(); } - }; - try { await applyPendingMigrations(url.toString()); } - catch (error) { await cleanup(); throw error; } - return { connectionString: url.toString(), cleanup }; -} - -async function seed(sql: postgres.Sql) { - const companyId = randomUUID(), agentId = randomUUID(), issueId = randomUUID(), userId = randomUUID(); - const lastMessage = new Date("2026-10-20T12:00:00.000Z"); - await sql`insert into companies (id, name, issue_prefix) values (${companyId}, 'Migration proof', ${`M${companyId.slice(0, 10)}`})`; - await sql`insert into agents (id, company_id, name, adapter_type) values (${agentId}, ${companyId}, 'Agent', 'process')`; - await sql`insert into "user" (id, name, email, email_verified, created_at, updated_at) - values (${userId}, 'Reader', ${`${userId}@example.test`}, true, now(), now())`; - await sql`insert into issues (id, company_id, title, status, assignee_agent_id, - conversation_agent_id, conversation_user_id, conversation_state) - values (${issueId}, ${companyId}, 'Conversation', 'in_review', ${agentId}, ${agentId}, ${userId}, 'waiting')`; - await sql`insert into issue_comments (company_id, issue_id, author_agent_id, author_type, body, origin, client_request_id, created_at) - values (${companyId}, ${issueId}, ${agentId}, 'agent', 'Preserved reply', 'comment', 'retry-key', ${lastMessage})`; - await sql`insert into issue_comments (company_id, issue_id, author_agent_id, author_type, body, origin, created_at) - values (${companyId}, ${issueId}, ${agentId}, 'system', 'Excluded system notice', 'comment', ${new Date(lastMessage.getTime() + 1000)})`; - const cardId = randomUUID(), savedDeadline = new Date("2026-10-21T12:00:00.000Z"); - await sql`insert into status_cards (id, company_id, interest_prompt, refresh_policy, next_eval_at, pending_change_hash) - values (${cardId}, ${companyId}, 'Watch preserved work', '{"mode":"manual"}'::jsonb, ${savedDeadline}, 'preserved-change')`; - return { companyId, agentId, issueId, userId, lastMessage, cardId, savedDeadline }; -} - -async function assertFinal(sql: postgres.Sql, row: Awaited>, expectedRead: Date) { - const [column] = await sql`select data_type, is_nullable from information_schema.columns - where table_schema = 'public' and table_name = 'status_cards' and column_name = 'next_eval_reason'`; - expect(column).toMatchObject({ data_type: "text", is_nullable: "YES" }); - const [constraint] = await sql`select i.indisvalid, i.indisunique from pg_constraint c - join pg_index i on i.indexrelid = c.conindid - where c.conrelid = 'issue_comments'::regclass and c.conname = 'issue_comments_agent_client_request_uq'`; - expect(constraint).toMatchObject({ indisvalid: true, indisunique: true }); - const [read] = await sql`select last_read_at from issue_read_states - where company_id = ${row.companyId} and issue_id = ${row.issueId} and user_id = ${row.userId}`; - expect(read.last_read_at).toEqual(expectedRead); - const [card] = await sql`select next_eval_at, next_eval_reason, pending_change_hash from status_cards where id = ${row.cardId}`; - expect(card).toMatchObject({ next_eval_at: row.savedDeadline, next_eval_reason: null, pending_change_hash: "preserved-change" }); - await sql`update status_cards set next_eval_reason = 'retry' where id = ${row.cardId}`; - expect((await sql`select next_eval_at, next_eval_reason from status_cards where id = ${row.cardId}`)[0]) - .toMatchObject({ next_eval_at: row.savedDeadline, next_eval_reason: "retry" }); - await expect(sql`insert into issue_comments (company_id, issue_id, author_agent_id, body, client_request_id) - values (${row.companyId}, ${row.issueId}, ${row.agentId}, 'Duplicate', 'retry-key')`) - .rejects.toMatchObject({ code: "23505", constraint_name: "issue_comments_agent_client_request_uq" }); -} - -describe.skipIf(!support.supported)("status-card reason migration after the published comment migration", () => { - it.each(["0418", "master0419"] as const)("upgrades from %s without dropping comment uniqueness or read history", async previous => { - expect(master.idx).toBe(419); - expect(status.idx).toBeGreaterThan(master.idx); - expect(statusSql.trim()).toBe('ALTER TABLE "status_cards" ADD COLUMN "next_eval_reason" text;'); - const db = await database(); - const sql = postgres(db.connectionString, { max: 1, onnotice: () => {} }); - try { - // Reconstruct exactly the two migrations' preimages; all older schema and - // receipts stay intact, as in the repository's other replay regressions. - await sql`alter table status_cards drop column next_eval_reason`; - await sql`delete from drizzle.__drizzle_migrations where hash = ${await hash(status.tag)}`; - if (previous === "0418") { - await sql`alter table issue_comments drop constraint issue_comments_agent_client_request_uq`; - await sql`delete from drizzle.__drizzle_migrations where hash = ${await hash(master.tag)}`; - } - const row = await seed(sql); - const preservedRead = new Date("2026-10-19T12:00:00.000Z"); - if (previous === "master0419") await sql`insert into issue_read_states (company_id, issue_id, user_id, last_read_at) - values (${row.companyId}, ${row.issueId}, ${row.userId}, ${preservedRead})`; - expect(await inspectMigrations(db.connectionString)).toMatchObject({ - status: "needsMigrations", - pendingMigrations: previous === "0418" ? [`${master.tag}.sql`, `${status.tag}.sql`] : [`${status.tag}.sql`], - }); - await applyPendingMigrations(db.connectionString); - expect(await inspectMigrations(db.connectionString)).toMatchObject({ status: "upToDate" }); - await assertFinal(sql, row, previous === "0418" ? row.lastMessage : preservedRead); - const receipts = await sql`select hash from drizzle.__drizzle_migrations order by id`; - const hashes = receipts.map(receipt => receipt.hash); - expect(hashes.indexOf(await hash(master.tag))).toBeLessThan(hashes.indexOf(await hash(status.tag))); - await applyPendingMigrations(db.connectionString); - expect(await sql`select hash from drizzle.__drizzle_migrations order by id`).toEqual(receipts); - } finally { await sql.end(); await db.cleanup(); } - }, 90_000); -}); diff --git a/packages/db/src/task-list-activity-index-migration.test.ts b/packages/db/src/task-list-activity-index-migration.test.ts deleted file mode 100644 index 004a690fb0a..00000000000 --- a/packages/db/src/task-list-activity-index-migration.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const indexName = "activity_log_company_entity_created_idx"; -const migrationFile = "0414_closed_edwin_jarvis.sql"; - -(support.supported ? describe : describe.skip)("task-list activity index migration", () => { - it("repairs an unjournaled invalid index and records one receipt after concurrent replay", async () => { - const database = await startEmbeddedPostgresTestDatabase("task-activity-index-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companies = await sql`INSERT INTO companies (name,issue_prefix) VALUES ('First','TAI1'),('Second','TAI2') RETURNING id`; - await sql`INSERT INTO activity_log(company_id,actor_id,action,entity_type,entity_id) - VALUES (${companies[0]!.id},'reader','issue.updated','issue','canonical-task')`; - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await sql`DELETE FROM drizzle.__drizzle_migrations WHERE hash=${hash}`; - await sql.unsafe(`DROP INDEX ${indexName}`); - await expect(sql.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON companies ((true))`)).rejects.toThrow(); - const [invalid] = await sql`SELECT indisvalid FROM pg_index WHERE indexrelid=${indexName}::regclass`; - expect(invalid!.indisvalid).toBe(false); - await Promise.all([applyPendingMigrations(database.connectionString), applyPendingMigrations(database.connectionString)]); - const [rebuilt] = await sql`SELECT indisvalid,indisunique,pg_get_indexdef(indexrelid) definition - FROM pg_index WHERE indexrelid=${indexName}::regclass`; - expect(rebuilt!.indisvalid).toBe(true); - expect(rebuilt!.indisunique).toBe(false); - expect(rebuilt!.definition).toContain("activity_log"); - expect(rebuilt!.definition).toContain("company_id, entity_type, entity_id, created_at"); - expect(await sql`SELECT entity_id FROM activity_log WHERE company_id=${companies[0]!.id}`).toEqual([{ entity_id: "canonical-task" }]); - const [history] = await sql`SELECT count(*)::int count FROM drizzle.__drizzle_migrations WHERE hash=${hash}`; - expect(history!.count).toBe(1); - await applyPendingMigrations(database.connectionString); - const [unchanged] = await sql`SELECT count(*)::int count FROM drizzle.__drizzle_migrations WHERE hash=${hash}`; - expect(unchanged!.count).toBe(1); - } finally { - await sql.end(); - await database.cleanup(); - } - }, 120_000); -}); diff --git a/packages/db/src/test-postgres-admin.ts b/packages/db/src/test-postgres-admin.ts index 95e91a447ab..e5fa8d85039 100644 --- a/packages/db/src/test-postgres-admin.ts +++ b/packages/db/src/test-postgres-admin.ts @@ -31,20 +31,32 @@ export async function startTestPostgresDatabase(adminUrl: string): Promise<{ if (template && !/^paperclip_test_template_[a-f0-9]+$/.test(template)) { throw new Error("Invalid disposable test template name"); } - const admin = postgres(adminUrl, { max: 1, connect_timeout: 5, onnotice() {} }); const url = new URL(adminUrl); url.pathname = `/${name}`; const connectionString = url.toString(); let cleaning: Promise | null = null; const cleanup = () => cleaning ??= (async () => { + const dropAdmin = postgres(adminUrl, { max: 1, connect_timeout: 5, onnotice() {} }); try { await closeRegisteredClients(connectionString, { scope: "database" }); - await admin.unsafe(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`); - } finally { await admin.end({ timeout: 1 }); } + await dropAdmin.unsafe(`DROP DATABASE IF EXISTS "${name}" WITH (FORCE)`); + } finally { + await dropAdmin.end({ timeout: 1 }); + } })(); + const setupAdmin = postgres(adminUrl, { max: 1, connect_timeout: 5, onnotice() {} }); + let created = false; + try { + await setupAdmin.unsafe(`CREATE DATABASE "${name}"${template ? ` TEMPLATE "${template}"` : ""}`); + created = true; + await setupAdmin.unsafe(QUIET_TEST_DATABASE_SQL(name)); + } catch (error) { + await setupAdmin.end({ timeout: 1 }).catch(() => {}); + if (created) await cleanup(); + throw error; + } + await setupAdmin.end({ timeout: 1 }); try { - await admin.unsafe(`CREATE DATABASE "${name}"${template ? ` TEMPLATE "${template}"` : ""}`); - await admin.unsafe(QUIET_TEST_DATABASE_SQL(name)); await applyPendingMigrations(connectionString); return { connectionString, cleanup }; } catch (error) { diff --git a/packages/db/src/test-postgres-command.ts b/packages/db/src/test-postgres-command.ts index 5edb86f2d5a..dcedaac7254 100644 --- a/packages/db/src/test-postgres-command.ts +++ b/packages/db/src/test-postgres-command.ts @@ -20,12 +20,21 @@ try { const url = new URL(server.connectionString); url.pathname = "/postgres"; adminUrl = url.toString(); - if (env.PAPERCLIP_TEST_POSTGRES_TEMPLATE !== "0") { - const template = `paperclip_test_template_${computeEmbeddedPostgresTemplateKey()}`; - const admin = createDb(adminUrl, { maxConnections: 1 }); - try { await admin.$client.unsafe(`CREATE DATABASE "${template}" TEMPLATE "paperclip"`); } - finally { await admin.$client.end({ timeout: 1 }); } - env.PAPERCLIP_TEST_POSTGRES_TEMPLATE = template; + const admin = createDb(adminUrl, { maxConnections: 1 }); + try { + // Disposable test server destroyed on exit: disable durability flushes so + // template copies, migrations, and per-test transactions run at memory speed. + await admin.$client.unsafe("ALTER SYSTEM SET fsync = off"); + await admin.$client.unsafe("ALTER SYSTEM SET synchronous_commit = off"); + await admin.$client.unsafe("ALTER SYSTEM SET full_page_writes = off"); + await admin.$client.unsafe("SELECT pg_reload_conf()"); + if (env.PAPERCLIP_TEST_POSTGRES_TEMPLATE !== "0") { + const template = `paperclip_test_template_${computeEmbeddedPostgresTemplateKey()}`; + await admin.$client.unsafe(`CREATE DATABASE "${template}" TEMPLATE "paperclip"`); + env.PAPERCLIP_TEST_POSTGRES_TEMPLATE = template; + } + } finally { + await admin.$client.end({ timeout: 1 }); } } env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL = adminUrl; diff --git a/packages/db/src/user-workspace-preferences-migration.test.ts b/packages/db/src/user-workspace-preferences-migration.test.ts deleted file mode 100644 index 908bd2a1f4a..00000000000 --- a/packages/db/src/user-workspace-preferences-migration.test.ts +++ /dev/null @@ -1,48 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFile, readdir } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { - EMBEDDED_POSTGRES_TEST_TIMEOUT_MS, - getEmbeddedPostgresTestSupport, - startEmbeddedPostgresTestDatabase, -} from "./test-embedded-postgres.js"; - -const support = await getEmbeddedPostgresTestSupport(); -const describePostgres = support.supported ? describe : describe.skip; - -describePostgres("workspace preferences migration", () => { - it("defaults Classic off and preserves existing preferences when the table migration replays", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-workspace-preferences-replay-"); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const userId = randomUUID(); - const [original] = await sql` - INSERT INTO user_workspace_preferences (user_id) VALUES (${userId}) RETURNING * - `; - expect(original.coordinator_workspace_enabled).toBe(true); - expect(original.classic_workspace_enabled).toBe(false); - await sql`UPDATE user_workspace_preferences SET coordinator_workspace_enabled = false, classic_workspace_enabled = true WHERE user_id = ${userId}`; - const [before] = await sql`SELECT * FROM user_workspace_preferences WHERE user_id = ${userId}`; - - // An isolated build may already have applied this table under an older - // migration number before master claimed that number for another table. - const migrations = new URL("./migrations/", import.meta.url); - const files = (await readdir(migrations)).filter(file => file.endsWith(".sql")); - const statements = await Promise.all(files.map(file => readFile(new URL(file, migrations), "utf8"))); - const migration = statements.find(source => /CREATE TABLE(?: IF NOT EXISTS)? "user_workspace_preferences"/.test(source)); - expect(migration, "workspace preferences table migration is present").toBeDefined(); - for (const statement of migration!.split("--> statement-breakpoint").map(value => value.trim()).filter(Boolean)) { - await sql.unsafe(statement); - } - - const [after] = await sql`SELECT * FROM user_workspace_preferences WHERE user_id = ${userId}`; - expect(after).toEqual(before); - await expect(sql`INSERT INTO user_workspace_preferences (user_id) VALUES (${userId})`) - .rejects.toMatchObject({ code: "23505", constraint_name: "user_workspace_preferences_user_uq" }); - } finally { - await sql.end(); - await database.cleanup(); - } - }, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS); -}); diff --git a/packages/db/src/vercel-connect-credential-source-migration.test.ts b/packages/db/src/vercel-connect-credential-source-migration.test.ts deleted file mode 100644 index 05c689f639f..00000000000 --- a/packages/db/src/vercel-connect-credential-source-migration.test.ts +++ /dev/null @@ -1,79 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import fs from "node:fs"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const MIGRATION_FILE = "0233_living_dreaming_celestial.sql"; -const migrationSql = fs.readFileSync(new URL(`./migrations/${MIGRATION_FILE}`, import.meta.url), "utf8"); -const migrationHash = createHash("sha256").update(migrationSql).digest("hex"); -const cleanups: Array<() => Promise> = []; -const embeddedPostgresSupport = await getEmbeddedPostgresTestSupport(); -const describeEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip; - -afterEach(async () => { - while (cleanups.length > 0) await cleanups.pop()?.(); -}); - -describeEmbeddedPostgres("Vercel Connect credential-source migration", () => { - it("defaults legacy rows to the vault and rejects mixed credential custody", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-vercel-connect-migration-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - cleanups.push(async () => sql.end()); - - await sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${migrationHash}`; - await sql`ALTER TABLE "connection_grants" DROP COLUMN "external_credential"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN "external_credential"`; - await sql`ALTER TABLE "tool_connections" DROP COLUMN "credential_source"`; - - const companyId = randomUUID(); - const applicationId = randomUUID(); - const connectionId = randomUUID(); - await sql`INSERT INTO "companies" ("id", "name", "issue_prefix") VALUES (${companyId}, 'Vercel migration', 'VCM')`; - await sql`INSERT INTO "tool_applications" ("id", "company_id", "name", "type") VALUES (${applicationId}, ${companyId}, 'PostHog', 'mcp_http')`; - await sql` - INSERT INTO "tool_connections" ("id", "company_id", "application_id", "name", "uid", "transport") - VALUES (${connectionId}, ${companyId}, ${applicationId}, 'PostHog', ${`posthog/${connectionId}`}, 'mcp_remote') - `; - - await applyPendingMigrations(database.connectionString); - - const [legacy] = await sql<{ credential_source: string; external_credential: unknown }[]>` - SELECT "credential_source", "external_credential" FROM "tool_connections" WHERE "id" = ${connectionId} - `; - expect(legacy).toEqual({ credential_source: "paperclip_vault", external_credential: null }); - - await expect(sql` - UPDATE "tool_connections" SET "credential_source" = 'vercel_connect' WHERE "id" = ${connectionId} - `).rejects.toMatchObject({ code: "23514" }); - - await sql` - UPDATE "tool_connections" SET - "credential_source" = 'vercel_connect', - "external_credential" = ${sql.json({ provider: "vercel_connect", connectorUid: "posthog-paperclip" })}, - "credential_refs" = '[]'::jsonb, - "credential_secret_refs" = '[]'::jsonb - WHERE "id" = ${connectionId} - `; - await expect(sql` - UPDATE "tool_connections" SET "credential_secret_refs" = ${sql.json([{ secretId: randomUUID() }])} - WHERE "id" = ${connectionId} - `).rejects.toMatchObject({ code: "23514" }); - - const grantId = randomUUID(); - await sql` - INSERT INTO "connection_grants" ( - "id", "company_id", "connection_id", "kind", "is_default", "external_credential" - ) VALUES ( - ${grantId}, ${companyId}, ${connectionId}, 'organization', true, - ${sql.json({ provider: "vercel_connect", subjectType: "app" })} - ) - `; - await expect(sql` - UPDATE "connection_grants" SET "credential_secret_refs" = ${sql.json([{ secretId: randomUUID() }])} - WHERE "id" = ${grantId} - `).rejects.toMatchObject({ code: "23514" }); - }, 30_000); -}); diff --git a/packages/db/src/voice-inbound-cleanup-migration.test.ts b/packages/db/src/voice-inbound-cleanup-migration.test.ts deleted file mode 100644 index d406e813f13..00000000000 --- a/packages/db/src/voice-inbound-cleanup-migration.test.ts +++ /dev/null @@ -1,120 +0,0 @@ -import { createHash, randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { describe, expect, it } from "vitest"; -import { applyPendingMigrations } from "./client.js"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const external = process.env.PAPERCLIP_MIGRATION_TEST_DATABASE_URL; -if (external && !new URL(external).pathname.endsWith("_test")) throw new Error("Migration test URL must name a test database"); -const support = external ? { supported: true } : await getEmbeddedPostgresTestSupport(); -const migrationFile = "0396_tan_paladin.sql"; -const indexName = "chat_voice_inbound_cleanup_idx"; - -(support.supported ? describe : describe.skip)("inbound voice cleanup migration", () => { - it("boots through the application migrator and repairs an interrupted index on concurrent replay", async () => { - let temporary: Awaited> | undefined; - let admin: ReturnType | undefined; - let databaseName: string | undefined; - let connectionString: string; - let client: ReturnType | undefined; - try { - if (external) { - admin = postgres(external, { max: 1, onnotice: () => {} }); - databaseName = `voice_migration_${randomUUID().replaceAll("-", "")}_test`; - await admin.unsafe(`CREATE DATABASE "${databaseName}"`); - const url = new URL(external); url.pathname = `/${databaseName}`; - connectionString = url.toString(); - await applyPendingMigrations(connectionString); - } else { - temporary = await startEmbeddedPostgresTestDatabase("voice-inbound-migration-"); - connectionString = temporary.connectionString; - } - client = postgres(connectionString, { max: 1, onnotice: () => {} }); - const columns = await client`SELECT column_name FROM information_schema.columns - WHERE table_name = 'chat_voice_inbound_calls'`; - expect(columns.map(row => row.column_name)).toEqual(expect.arrayContaining([ - "cleanup_confirmed_at", "cleanup_next_attempt_at", "provider_account_id", - ])); - const content = await readFile(new URL(`./migrations/${migrationFile}`, import.meta.url), "utf8"); - const hash = createHash("sha256").update(content).digest("hex"); - await client`DELETE FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - await client.unsafe(`DROP INDEX ${indexName}`); - const [company, otherCompany] = await client`INSERT INTO companies (name, issue_prefix) - VALUES ('First', 'VM1'), ('Second', 'VM2') RETURNING id`; - const agentId = randomUUID(), applicationId = randomUUID(), connectionId = randomUUID(), endpointId = randomUUID(); - await client`INSERT INTO agents (id, company_id, name, adapter_type) VALUES (${agentId}, ${company.id}, 'Migration voice', 'paperclip_runner')`; - await client`INSERT INTO tool_applications (id, company_id, name, type) VALUES (${applicationId}, ${company.id}, 'Voice', 'chat')`; - await client`INSERT INTO tool_connections (id, company_id, application_id, name, uid, transport, connection_purpose) - VALUES (${connectionId}, ${company.id}, ${applicationId}, 'Voice', ${connectionId}, 'voice', 'channel')`; - await client`INSERT INTO chat_endpoints (id, company_id, connection_id, assigned_agent_id, provider, public_id, status) - VALUES (${endpointId}, ${company.id}, ${connectionId}, ${agentId}, 'speko', ${endpointId}, 'active')`; - await client`WITH candidates AS (SELECT gen_random_uuid() AS id FROM generate_series(1, 1005)) - INSERT INTO chat_voice_inbound_calls (id, company_id, endpoint_id, provider_session_id, state, - approval_code, generation, credential_fingerprint, tool_token_hash, request_fingerprint, expires_at) - SELECT id, ${company.id}, ${endpointId}, 'migration:' || id::text, 'ended', '123456', 1, - 'migration', repeat('a', 64), id::text, now() FROM candidates`; - const nilId = '00000000-0000-0000-0000-000000000000', signed = randomUUID(); - const denied = randomUUID(), wrongCompany = randomUUID(), wrongAction = randomUUID(); - const pending = randomUUID(), expired = randomUUID(), confirmed = randomUUID(); - const confirmedAt = new Date('2020-01-01T00:00:00Z'); - const rows = [ - { id: nilId, state: 'ended', actor: null }, { id: signed, state: 'ended', actor: 'approver' }, - { id: denied, state: 'ended', actor: 'denier' }, { id: wrongCompany, state: 'ended', actor: 'approver' }, - { id: wrongAction, state: 'ended', actor: 'approver' }, { id: pending, state: 'awaiting_approval', actor: null }, - { id: expired, state: 'expired', actor: null }, { id: confirmed, state: 'ended', actor: null }, - ].map(row => ({ id: row.id, company_id: company.id, endpoint_id: endpointId, - provider_session_id: `migration:${row.id}`, state: row.state, approved_by_user_id: row.actor, - approval_code: '123456', generation: 1, credential_fingerprint: 'migration', tool_token_hash: 'a'.repeat(64), - request_fingerprint: row.id, expires_at: new Date(), cleanup_confirmed_at: row.id === confirmed ? confirmedAt : null })); - await client`INSERT INTO chat_voice_inbound_calls ${client(rows, 'id', 'company_id', 'endpoint_id', - 'provider_session_id', 'state', 'approved_by_user_id', 'approval_code', 'generation', - 'credential_fingerprint', 'tool_token_hash', 'request_fingerprint', 'expires_at', 'cleanup_confirmed_at')}`; - await client`INSERT INTO activity_log (company_id, actor_id, action, entity_type, entity_id) - VALUES (${company.id}, 'migration', 'voice.call.ended', 'voice_inbound_call', ${signed}), - (${otherCompany.id}, 'migration', 'voice.call.ended', 'voice_inbound_call', ${wrongCompany}), - (${company.id}, 'migration', 'voice.call.requested', 'voice_inbound_call', ${wrongAction})`; - await client.unsafe(`CREATE TABLE voice_cleanup_backfill_probe (call_id uuid NOT NULL, transaction_id bigint NOT NULL); - CREATE FUNCTION record_voice_cleanup_backfill() RETURNS trigger LANGUAGE plpgsql AS $$ - BEGIN INSERT INTO voice_cleanup_backfill_probe VALUES (NEW.id, txid_current()); RETURN NEW; END $$; - CREATE TRIGGER record_voice_cleanup_backfill AFTER UPDATE ON chat_voice_inbound_calls - FOR EACH ROW WHEN (OLD.cleanup_confirmed_at IS NULL AND NEW.cleanup_confirmed_at IS NOT NULL) - EXECUTE FUNCTION record_voice_cleanup_backfill()`); - - // A failed unique build deterministically leaves an invalid index under - // the migration's name, as cancellation does, without timing a cancel. - await expect(client.unsafe(`CREATE UNIQUE INDEX CONCURRENTLY ${indexName} ON companies ((true))`)).rejects.toThrow(); - const [invalid] = await client`SELECT indisvalid FROM pg_index WHERE indexrelid = ${indexName}::regclass`; - expect(invalid.indisvalid).toBe(false); - await Promise.all([applyPendingMigrations(connectionString), applyPendingMigrations(connectionString)]); - const [rebuilt] = await client`SELECT indisvalid, pg_get_indexdef(indexrelid) AS definition - FROM pg_index WHERE indexrelid = ${indexName}::regclass`; - expect(rebuilt.indisvalid).toBe(true); - expect(rebuilt.definition).toContain("chat_voice_inbound_calls"); - expect(rebuilt.definition).toContain("cleanup_confirmed_at IS NULL"); - const [history] = await client`SELECT count(*)::int AS count FROM drizzle.__drizzle_migrations WHERE hash = ${hash}`; - expect(history.count).toBe(1); - const [backfill] = await client`SELECT count(*)::int AS count, count(DISTINCT transaction_id)::int AS transactions - FROM voice_cleanup_backfill_probe`; - expect(backfill.count).toBe(1007); expect(backfill.transactions).toBeGreaterThanOrEqual(2); - const [batch] = await client`SELECT max(size)::int AS size FROM ( - SELECT count(*) AS size FROM voice_cleanup_backfill_probe GROUP BY transaction_id - ) groups`; - expect(batch.size).toBeLessThanOrEqual(1000); - const proof = await client`SELECT id, cleanup_confirmed_at FROM chat_voice_inbound_calls - WHERE id = ANY(${[nilId, signed, denied, wrongCompany, wrongAction, pending, expired, confirmed]})`; - for (const id of [nilId, signed]) expect(proof.find(row => row.id === id)?.cleanup_confirmed_at).toBeInstanceOf(Date); - for (const id of [denied, wrongCompany, wrongAction, pending, expired]) - expect(proof.find(row => row.id === id)?.cleanup_confirmed_at).toBeNull(); - expect(proof.find(row => row.id === confirmed)?.cleanup_confirmed_at.getTime()).toBe(confirmedAt.getTime()); - await applyPendingMigrations(connectionString); - const [unchanged] = await client`SELECT count(*)::int AS count FROM voice_cleanup_backfill_probe`; - expect(unchanged.count).toBe(1007); - } finally { - await client?.end(); - if (admin && databaseName) await admin.unsafe(`DROP DATABASE "${databaseName}" WITH (FORCE)`); - await admin?.end(); - await temporary?.cleanup(); - } - }, 120_000); -}); diff --git a/packages/db/src/workspace-defaults-migration.test.ts b/packages/db/src/workspace-defaults-migration.test.ts deleted file mode 100644 index a9d585ceac5..00000000000 --- a/packages/db/src/workspace-defaults-migration.test.ts +++ /dev/null @@ -1,77 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import postgres from "postgres"; -import { afterEach, describe, expect, it } from "vitest"; -import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./test-embedded-postgres.js"; - -const migration = await readFile(new URL("./migrations/0433_workspace_defaults.sql", import.meta.url), "utf8"); -const support = await getEmbeddedPostgresTestSupport(); -const cleanups: Array<() => Promise> = []; -afterEach(async () => { while (cleanups.length) await cleanups.pop()?.(); }); - -(support.supported ? describe : describe.skip)("standard workspace defaults", () => { - it("defaults new people to Coordinator", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-workspace-defaults-fresh-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - expect(await sql`SELECT user_id FROM user_workspace_preferences`).toHaveLength(0); - const [row] = await sql`INSERT INTO user_workspace_preferences (user_id) VALUES ('new-person') RETURNING coordinator_workspace_enabled`; - expect(row.coordinator_workspace_enabled).toBe(true); - } finally { await sql.end(); } - }, 30_000); - - it.each([null, true, false])("preserves legacy preferences and unrelated instance storage (%s) on upgrade and replay", async chat => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-workspace-defaults-upgrade-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - const companyId = randomUUID(); - await sql`INSERT INTO companies (id, name, issue_prefix) VALUES (${companyId}, 'Existing company', 'OLD')`; - for (const id of ['unchanged-classic', 'saved-coordinator', 'saved-classic']) { - await sql`INSERT INTO "user" (id, name, email, created_at, updated_at) VALUES (${id}, ${id}, ${id + '@example.test'}, now(), now())`; - } - await sql`INSERT INTO company_memberships (company_id, principal_type, principal_id) VALUES (${companyId}, 'user', 'existing-member')`; - await sql`INSERT INTO user_workspace_preferences (user_id, coordinator_workspace_enabled) VALUES ('saved-coordinator', true), ('saved-classic', false)`; - const settings = { enableStatusCards: true, ...(chat === null ? {} : { enableAgentChat: chat }) }; - await sql`INSERT INTO instance_settings (singleton_key, experimental) VALUES ('default', ${sql.json(settings)}) ON CONFLICT (singleton_key) DO UPDATE SET experimental = EXCLUDED.experimental`; - for (let replay = 0; replay < 2; replay++) { - for (const statement of migration.split('--> statement-breakpoint')) { - if (statement.trim()) await sql.unsafe(statement); - } - } - const rows = await sql`SELECT user_id, coordinator_workspace_enabled FROM user_workspace_preferences`; - expect(Object.fromEntries(rows.map(row => [row.user_id, row.coordinator_workspace_enabled]))).toEqual({ - 'saved-coordinator': true, 'saved-classic': false, - }); - const [instance] = await sql`SELECT experimental FROM instance_settings WHERE singleton_key = 'default'`; - expect(instance.experimental).toEqual(settings); - const [newPerson] = await sql`INSERT INTO user_workspace_preferences (user_id) VALUES ('new-person') RETURNING coordinator_workspace_enabled`; - expect(newPerson.coordinator_workspace_enabled).toBe(true); - } finally { await sql.end(); } - }, 30_000); - - it("starts Classic off for legacy preferences and preserves a later explicit opt-in on replay", async () => { - const database = await startEmbeddedPostgresTestDatabase("paperclip-classic-workspace-upgrade-"); - cleanups.push(database.cleanup); - const sql = postgres(database.connectionString, { max: 1, onnotice: () => {} }); - try { - await sql`ALTER TABLE user_workspace_preferences DROP COLUMN classic_workspace_enabled`; - await sql`INSERT INTO user_workspace_preferences (user_id, coordinator_workspace_enabled) VALUES ('old-off', false), ('old-on', true)`; - for (const statement of migration.split('--> statement-breakpoint')) { - if (statement.trim()) await sql.unsafe(statement); - } - const upgraded = await sql`SELECT user_id, classic_workspace_enabled FROM user_workspace_preferences ORDER BY user_id`; - expect(upgraded.map(row => row.classic_workspace_enabled)).toEqual([false, false]); - await sql`UPDATE user_workspace_preferences SET classic_workspace_enabled = true WHERE user_id = 'old-off'`; - for (const statement of migration.split('--> statement-breakpoint')) { - if (statement.trim()) await sql.unsafe(statement); - } - const [saved] = await sql`SELECT classic_workspace_enabled FROM user_workspace_preferences WHERE user_id = 'old-off'`; - expect(saved.classic_workspace_enabled).toBe(true); - const [fresh] = await sql`INSERT INTO user_workspace_preferences (user_id) VALUES ('new-classic-choice') RETURNING classic_workspace_enabled`; - expect(fresh.classic_workspace_enabled).toBe(false); - } finally { await sql.end(); } - }, 30_000); - -}); diff --git a/scripts/__tests__/ci-typecheck-lane.test.mjs b/scripts/__tests__/ci-typecheck-lane.test.mjs index 0385c614866..04c745a0de6 100644 --- a/scripts/__tests__/ci-typecheck-lane.test.mjs +++ b/scripts/__tests__/ci-typecheck-lane.test.mjs @@ -2,8 +2,17 @@ import assert from "node:assert/strict"; import { readFileSync } from "node:fs"; import { getPriority } from "node:os"; import test from "node:test"; -import { BACKGROUND_PRIORITY, createReporter, planLane, runLane, SERIAL_BUILD_GAPS } from "../ci-typecheck-lane.mjs"; -import { PROJECTS } from "../typecheck-test-projects.mjs"; +import { + BACKGROUND_PRIORITY, + createReporter, + planLane, + resolveScope, + runLane, + selectBuildGapPackages, + SERIAL_BUILD_GAPS, + shouldRunReleaseRegistryTests, +} from "../ci-typecheck-lane.mjs"; +import { PROJECTS, selectTestProjects } from "../typecheck-test-projects.mjs"; const plan = () => planLane({ @@ -38,18 +47,25 @@ test("the shared outputs are written before the parallel checks start", () => { test("every check of the sequential job is planned, and only declaration readers wait", () => { const { tasks } = plan(); const byName = new Map(tasks.map((task) => [task.name, task])); - assert.deepEqual(byName.get("server declarations").args, ["server/scripts/typecheck-layers.mjs", "--declarations-only"]); + assert.deepEqual(byName.get("server declarations").args, [ + "server/scripts/typecheck-layers.mjs", + "--declarations-only", + "--checkers", + "2", + ]); for (const layer of ["tests", "test-tree-0"]) { const task = byName.get(`server layer ${layer}`); - assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer]); + assert.deepEqual(task.args, ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"]); assert.deepEqual(task.needs, ["server declarations"]); } for (const project of PROJECTS) { const task = byName.get(`test project ${project}`); assert.deepEqual(task.args.slice(-2), ["--reuse-declarations", project]); + assert.ok(task.args.includes("--checkers")); assert.deepEqual(task.needs, ["server declarations"]); } for (const name of ["paperclipai", "@paperclipai/ui"]) assert.ok(byName.has(`typecheck ${name}`), name); + assert.deepEqual(byName.get("typecheck @paperclipai/ui").env, { GOMAXPROCS: "2" }); assert.deepEqual(byName.get("release registry tests").args, ["run", "test:release-registry"]); assert.ok(!byName.has("CLI guidance safety")); const waiting = tasks.filter((task) => task.needs); @@ -60,6 +76,163 @@ test("every check of the sequential job is planned, and only declaration readers ); }); +test("resolveScope uses CI_PLAN in PR mode, honors PAPERCLIP_CI_FULL, and fails closed", () => { + const validPlan = JSON.stringify({ version: 1, mode: "enabled", forceReason: null, changed: ["server/src/a.ts"] }); + assert.deepEqual(resolveScope({ root: "/repo", env: { CI_PLAN: validPlan } }), { + mode: "pr", + changedFiles: ["server/src/a.ts"], + reason: "CI_PLAN", + }); + assert.equal( + resolveScope({ root: "/repo", env: { CI_PLAN: validPlan, PAPERCLIP_CI_FULL: "1" } }).mode, + "full", + ); + assert.equal( + resolveScope({ + root: "/repo", + env: { CI_PLAN: JSON.stringify({ mode: "full", forceReason: "Full CI requested", changed: ["server/src/a.ts"] }) }, + }).mode, + "full", + ); + assert.equal( + resolveScope({ + root: "/repo", + env: { CI_PLAN: JSON.stringify({ mode: "enabled", forceReason: "Diff unavailable: shallow", changed: [] }) }, + }).mode, + "full", + ); + assert.equal(resolveScope({ root: "/repo", env: { CI_PLAN: "{bad json" } }).mode, "full"); + assert.equal(resolveScope({ root: "/repo", env: {} }).mode, "full"); + + // Git merge-parent fallback when CI_PLAN is unset + const gitCalls = []; + const merged = resolveScope({ + root: "/repo", + env: { PAPERCLIP_CI_BASE_SHA: "abc123" }, + execGit: (args) => { + gitCalls.push(args); + if (args[0] === "rev-parse") return "head2sha\n"; + return "server/src/x.ts\0ui/src/y.tsx\0"; + }, + }); + assert.deepEqual(merged, { + mode: "pr", + changedFiles: ["server/src/x.ts", "ui/src/y.tsx"], + reason: "git diff HEAD^1 HEAD", + }); + assert.equal(gitCalls[1].includes("HEAD^1"), true); +}); + +test("PR mode for a server-only change skips release registry, UI, runner, sandbox providers, and untouched test projects", () => { + const { prepare, tasks } = planLane({ + buildGapPackages: [ + "paperclipai", + "@paperclipai/paperclip-runner", + "@paperclipai/ui", + "@paperclipai/plugin-llm-wiki", + "@paperclipai/plugin-authoring-smoke-example", + ], + testLayers: ["tests", "test-tree-0"], + changedFiles: ["server/src/services/isolated-unreferenced-feature.ts", "server/src/__tests__/isolated-unreferenced-feature.test.ts"], + }); + const prepareNames = prepare.map((task) => task.name); + const taskNames = tasks.map((task) => task.name); + + assert.ok(prepareNames.includes("build server without type checks")); + assert.ok(prepareNames.includes("CLI guidance safety")); + assert.ok(!prepareNames.includes("install test program dependencies")); + assert.ok(!prepareNames.includes("typecheck @paperclipai/paperclip-runner")); + + assert.ok(taskNames.includes("server declarations")); + assert.ok(taskNames.includes("server layer tests")); + assert.ok(taskNames.includes("typecheck paperclipai")); + assert.ok(!taskNames.includes("release registry tests")); + assert.ok(!taskNames.includes("typecheck test programs")); + assert.ok(!taskNames.includes("typecheck @paperclipai/ui")); + assert.ok(!taskNames.includes("typecheck @paperclipai/plugin-llm-wiki")); + assert.ok(!taskNames.includes("typecheck @paperclipai/plugin-authoring-smoke-example")); + for (const skipped of PROJECTS) { + assert.ok(!taskNames.includes(`test project ${skipped}`), skipped); + } +}); + +test("selectTestProjects follows the import graph so imported UI and server helpers trigger their callers", () => { + for (const helper of [ + "ui/src/lib/company-routes.ts", + "ui/src/lib/issue-reference.ts", + "ui/src/lib/markdown-reply-content.ts", + ]) { + assert.deepEqual(selectTestProjects([helper]), ["tests/runner-e2e"], helper); + } + assert.deepEqual(selectTestProjects(["ui/src/components/Sidebar.tsx"]), []); + assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("tests/runner-e2e")); + assert.ok(selectTestProjects(["server/src/services/issues.ts"]).includes("server/src/__tests__/helpers/maintenance")); + assert.ok(selectTestProjects(["tests/unknown-new-project/a.ts"], [...PROJECTS, "tests/unknown-new-project"]).includes("tests/unknown-new-project")); + + const uiHelperPlan = planLane({ + buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"], + testLayers: ["tests"], + changedFiles: ["ui/src/lib/company-routes.ts"], + }); + assert.ok(uiHelperPlan.tasks.some((t) => t.name === "server declarations")); + assert.ok(uiHelperPlan.tasks.some((t) => t.name === "test project tests/runner-e2e")); + assert.ok(uiHelperPlan.tasks.some((t) => t.name === "typecheck @paperclipai/ui")); +}); + +test("PR mode for a pure UI component change skips server build/declarations, release registry, and sandbox providers", () => { + const { prepare, tasks } = planLane({ + buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"], + testLayers: ["tests", "test-tree-0"], + changedFiles: ["ui/src/components/Sidebar.tsx", "ui/src/components/Sidebar.test.tsx"], + }); + const prepareNames = prepare.map((task) => task.name); + const taskNames = tasks.map((task) => task.name); + + assert.ok(prepareNames.includes("CLI guidance safety")); + assert.ok(!prepareNames.includes("build server without type checks")); + assert.ok(!prepareNames.includes("install test program dependencies")); + assert.ok(!taskNames.includes("server declarations")); + assert.ok(!taskNames.includes("release registry tests")); + assert.ok(!taskNames.includes("typecheck paperclipai")); + assert.ok(taskNames.includes("typecheck @paperclipai/ui")); + + const programs = tasks.find((task) => task.name === "typecheck test programs"); + assert.ok(programs.args.includes("--no-providers")); + assert.ok(programs.args.includes("--check-file")); + assert.ok(programs.args.includes("ui/src/components/Sidebar.test.tsx")); + assert.ok(programs.args.includes("tests/tsconfig.playwright.json")); +}); + +test("PR mode runs release registry tests for scripts, workflows, manifests, and release files", () => { + assert.equal(shouldRunReleaseRegistryTests(["server/src/index.ts"]), false); + assert.equal(shouldRunReleaseRegistryTests(["ui/src/pages/Issues.tsx"]), false); + for (const trigger of [ + "scripts/release.sh", + ".github/workflows/pr-trusted.yml", + "package.json", + "server/package.json", + "releases/v2026.11.0.md", + "Dockerfile", + ]) { + assert.equal(shouldRunReleaseRegistryTests([trigger]), true, trigger); + } +}); + +test("PR mode fails closed for unknown build-gap packages and global typecheck inputs", () => { + assert.deepEqual(selectBuildGapPackages(["@paperclipai/ui", "@paperclipai/new-pkg"], ["server/src/a.ts"]), [ + "@paperclipai/new-pkg", + ]); + const globalPlan = planLane({ + buildGapPackages: ["paperclipai", "@paperclipai/paperclip-runner", "@paperclipai/ui"], + testLayers: ["tests"], + changedFiles: ["tsconfig.base.json"], + }); + assert.ok(globalPlan.prepare.some((t) => t.name === "install test program dependencies")); + assert.ok(globalPlan.prepare.some((t) => t.name === "typecheck @paperclipai/paperclip-runner")); + assert.ok(globalPlan.tasks.some((t) => t.name === "typecheck @paperclipai/ui")); + assert.ok(globalPlan.tasks.some((t) => t.name === "test project tests/runner-e2e")); +}); + test("checks run at most the given number at a time, in priority order", async () => { let running = 0; let peak = 0; diff --git a/scripts/__tests__/e2e-shard.test.mjs b/scripts/__tests__/e2e-shard.test.mjs index e1474715184..d19d0eba92a 100644 --- a/scripts/__tests__/e2e-shard.test.mjs +++ b/scripts/__tests__/e2e-shard.test.mjs @@ -7,7 +7,15 @@ import { fileURLToPath } from "node:url"; import test from "node:test"; import { defaultSuiteWeight, loadShardDurations } from "../general-server-shard.mjs"; -import { IGNORED_SPECS, listE2eSpecs, selectE2eShard } from "../e2e-shard.mjs"; +import { + DEFAULT_PARALLEL_WORKERS, + IGNORED_SPECS, + SERIAL_SPECS, + isSerialE2eSpec, + listE2eSpecs, + partitionE2eShards, + selectE2eShard, +} from "../e2e-shard.mjs"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const script = path.join(repoRoot, "scripts", "e2e-shard.mjs"); @@ -124,6 +132,32 @@ test("the ignored spec list matches playwright.config.ts testIgnore", () => { assert.deepEqual([...configured].sort(), [...IGNORED_SPECS].sort()); }); +test("the serial spec list matches playwright.config.ts SERIAL_SPECS and never mixes with parallel specs", () => { + const config = readFileSync(playwrightConfig, "utf8"); + const match = config.match(/export const SERIAL_SPECS = \[([\s\S]*?)\];/); + assert.ok(match, "expected a SERIAL_SPECS array in playwright.config.ts"); + const configured = [...match[1].matchAll(/"([^"]+)"/g)].map((entry) => entry[1]); + assert.deepEqual([...configured].sort(), [...SERIAL_SPECS].sort()); + + const specs = listE2eSpecs(); + const durations = loadShardDurations(durationsManifest); + const shards = partitionE2eShards(specs, SHARD_COUNT, durations); + assert.equal(shards.length, SHARD_COUNT); + for (const shard of shards) { + const serialCount = shard.files.filter(isSerialE2eSpec).length; + assert.ok( + serialCount === 0 || serialCount === shard.files.length, + `shard must not mix serial and parallel specs: ${shard.files.join(", ")}`, + ); + } +}); + +test("playwright.config.ts supports skipping the UI build when PAPERCLIP_E2E_SKIP_UI_BUILD=1", () => { + const config = readFileSync(playwrightConfig, "utf8"); + assert.match(config, /PAPERCLIP_E2E_SKIP_UI_BUILD/); + assert.match(config, /ui-dist.*index\.html/); +}); + test("the duration manifest only names specs that still exist", () => { const durations = loadShardDurations(durationsManifest); assert.ok(Object.keys(durations).length > 0, "expected a populated duration manifest"); @@ -136,25 +170,25 @@ test("the duration manifest only names specs that still exist", () => { test("the weighted partition keeps the shards close to balanced", () => { const durations = loadShardDurations(durationsManifest); const specs = listE2eSpecs(); - // New specs use the scheduler's median estimate until measured durations exist. const fallbackWeight = defaultSuiteWeight(durations); - const weights = Array.from({ length: SHARD_COUNT }, (_, index) => - selectE2eShard(specs, index, SHARD_COUNT, durations).reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0), - ); + const shards = partitionE2eShards(specs, SHARD_COUNT, durations, { + parallelWorkers: DEFAULT_PARALLEL_WORKERS, + }); + const wallWeights = shards.map((shard) => { + const serialSum = shard.files.reduce((sum, file) => sum + (durations[file] ?? fallbackWeight), 0); + return shard.mode === "parallel" ? serialSum / DEFAULT_PARALLEL_WORKERS : serialSum; + }); - const heaviest = Math.max(...weights); - const total = weights.reduce((sum, weight) => sum + weight, 0); - // Round-robin/count-based sharding would strand the ~168s smoke-lab spec on - // one runner alongside other specs. Assert the weighted split stays within - // 15% of an even cut so a future spec-time regression surfaces here instead - // of on the PR critical path. A single indivisible spec (smoke-lab) can - // legitimately exceed the even cut on its own, so the bound is floored at - // the largest per-spec weight — the best any file-level partition can do. - const largestSpec = Math.max(...specs.map((file) => durations[file] ?? fallbackWeight)); - const bound = Math.max((total / SHARD_COUNT) * 1.15, largestSpec); + const heaviest = Math.max(...wallWeights); + const totalWall = wallWeights.reduce((sum, weight) => sum + weight, 0); + const largestSerialSpec = Math.max( + 0, + ...specs.filter(isSerialE2eSpec).map((file) => durations[file] ?? fallbackWeight), + ); + const bound = Math.max((totalWall / SHARD_COUNT) * 1.15, largestSerialSpec); assert.ok( heaviest <= bound, - `heaviest shard ${heaviest}ms exceeds the balance bound (${bound}ms)`, + `heaviest shard ${Math.round(heaviest)}ms exceeds the balance bound (${Math.round(bound)}ms)`, ); }); diff --git a/scripts/__tests__/public-install-closure.test.mjs b/scripts/__tests__/public-install-closure.test.mjs index 9dd9ac2ddf5..f23b7c0d9db 100644 --- a/scripts/__tests__/public-install-closure.test.mjs +++ b/scripts/__tests__/public-install-closure.test.mjs @@ -48,15 +48,15 @@ test('the warm-up refuses to run without the cache the verifier will read', () = assert.match(result.stderr, /PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE/); }); -test('the Build lane warms the cache before pnpm build and hands the same directory to the verifier', () => { - const workflow = readFileSync(new URL('../../.github/workflows/pr-trusted.yml', import.meta.url), 'utf8'); - const build = workflow.slice(workflow.indexOf('\n build:\n'), workflow.indexOf('\n verify_serialized_server:\n')); - const position = fragment => { const index = build.indexOf(fragment); assert.notEqual(index, -1, `Build job must contain ${fragment}`); return index; }; - const warm = position('PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache" node scripts/warm-public-install-npm-cache.mjs'); - assert.ok(position('- name: Install dependencies') < warm && warm < position('- name: Build\n'), 'the warm-up overlaps the Rust restore and pnpm build'); - assert.ok(build.includes('set +e\n'), 'a failed warm-up still records its status, so the verifier never waits it out'); - const verify = position('export PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE="$RUNNER_TEMP/public-install-npm-cache"'); - assert.ok(verify < position('node scripts/verify-grok-npm-install.mjs')); +test('public npm install verification stays in release/docker checks rather than PR Build', () => { + const prWorkflow = readFileSync(new URL('../../.github/workflows/pr-trusted.yml', import.meta.url), 'utf8'); + const build = prWorkflow.slice(prWorkflow.indexOf('\n build:\n'), prWorkflow.indexOf('\n verify_serialized_server:\n')); + assert.ok(!build.includes('node scripts/verify-grok-npm-install.mjs'), 'PR Build skips the 4-min public npm install verifier'); + assert.ok(!build.includes('warm-public-install-npm-cache.mjs'), 'PR Build does not warm the unused public npm install cache'); + const releaseSmoke = readFileSync(new URL('../../.github/workflows/release-smoke.yml', import.meta.url), 'utf8'); + assert.ok(releaseSmoke.includes('node scripts/verify-grok-npm-install.mjs'), 'release-smoke.yml covers verify-grok-npm-install.mjs'); + const dockerRunner = readFileSync(new URL('../../.github/workflows/docker-runner-check.yml', import.meta.url), 'utf8'); + assert.ok(dockerRunner.includes('node scripts/verify-grok-npm-install.mjs'), 'docker-runner-check.yml covers verify-grok-npm-install.mjs'); const verifier = readFileSync(new URL('../verify-grok-npm-install.mjs', import.meta.url), 'utf8'); assert.ok(verifier.includes("const cache = process.env.PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE ? resolve(process.env.PAPERCLIP_PUBLIC_INSTALL_NPM_CACHE) : join(root, 'cache');")); }); diff --git a/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs new file mode 100644 index 00000000000..0e53b26f544 --- /dev/null +++ b/scripts/__tests__/run-vitest-stable-pr-mode.test.mjs @@ -0,0 +1,235 @@ +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import test from "node:test"; +import { selectionHash } from "../ci/test-selection-manifest.mjs"; + +const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); +const script = path.join(repoRoot, "scripts", "run-vitest-stable.mjs"); +const nativeRunnerSuitePath = "server/src/services/native-runtime/plugin-runner-probe.test.ts"; + +function workflowEnv(envOverrides = {}) { + const env = { ...process.env, ...envOverrides }; + for (const key of [ + "GITHUB_WORKFLOW", + "PAPERCLIP_CI_FULL", + "PAPERCLIP_CI_EXCLUDE_NIGHTLY", + "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", + "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", + "PAPERCLIP_CI_TEST_SELECTION", + "PAPERCLIP_CI_SELECTION_HASH", + ]) { + if (!(key in envOverrides)) { + delete env[key]; + } + } + return env; +} + +function dryRunJson(args, envOverrides = {}) { + const result = spawnSync(process.execPath, [script, ...args, "--dry-run"], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv(envOverrides), + }); + assert.equal(result.status, 0, `expected success for ${args.join(" ")}: ${result.stderr}`); + return JSON.parse(result.stdout); +} + +test("general-workspaces-b and general-workspaces-a batch all projects into one vitest invocation", { skip: process.platform === "win32" }, () => { + const directory = mkdtempSync(path.join(os.tmpdir(), "batch-workspaces-")); + const receipt = path.join(directory, "calls.ndjson"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`); + chmodSync(fakePnpm, 0o755); + try { + const run = (args) => { + rmSync(receipt, { force: true }); + const result = spawnSync(process.execPath, [script, ...args], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + return readFileSync(receipt, "utf8").trim().split("\n").map((line) => JSON.parse(line)); + }; + + const workspacesBProjects = dryRunJson(["--mode", "general", "--group", "general-workspaces-b"]).workspaceProjects; + const bCalls = run(["--mode", "general", "--group", "general-workspaces-b"]); + assert.equal(bCalls.length, 1, "general-workspaces-b must invoke vitest once for all projects"); + const bProjectsArg = bCalls[0].flatMap((arg, index) => (arg === "--project" ? [bCalls[0][index + 1]] : [])); + assert.deepEqual(bProjectsArg, workspacesBProjects); + + const workspacesAProjects = dryRunJson(["--mode", "general", "--group", "general-workspaces-a"]).workspaceProjects; + const aCalls = run(["--mode", "general", "--group", "general-workspaces-a", "--shard-index", "1", "--shard-count", "2"]); + assert.equal(aCalls.length, 1, "general-workspaces-a must invoke vitest once for all projects in the shard"); + const aProjectsArg = aCalls[0].flatMap((arg, index) => (arg === "--project" ? [aCalls[0][index + 1]] : [])); + assert.deepEqual(aProjectsArg, workspacesAProjects); + assert.ok(aCalls[0].includes("--shard=2/2")); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("nightly-only suites manifest excludes listed suites only in PR mode and respects PAPERCLIP_CI_FULL=1", { skip: process.platform === "win32" }, () => { + const directory = mkdtempSync(path.join(os.tmpdir(), "nightly-manifest-")); + const manifestFile = path.join(directory, "nightly-only-suites.json"); + const fullGeneral = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], { GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_FULL: "1" }); + const sampleGeneralSuite = fullGeneral.selectedGeneralServerSuites[0]; + const sampleKeptGeneralSuite = fullGeneral.selectedGeneralServerSuites[1]; + const fullSerialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"]); + const sampleSerializedSuite = fullSerialized.selectedSerializedSuites[0]; + const sampleNativeSuite = nativeRunnerSuitePath; + const sampleDbSuite = "packages/db/src/client.test.ts"; + + writeFileSync(manifestFile, JSON.stringify({ + $comment: "fixture manifest", + suites: [ + { path: sampleGeneralSuite, category: "soak", reason: "fixture", measuredMs: 120000 }, + sampleSerializedSuite, + { path: sampleNativeSuite, category: "restart-lease-soak", reason: "fixture", measuredMs: 200000 }, + { path: sampleDbSuite, category: "db-soak", reason: "fixture", measuredMs: 90000 }, + ], + }, null, 2)); + + try { + const prEnv = { GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile }; + const prGeneral = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], prEnv); + assert.equal(prGeneral.nightlyExclusionActive, true); + assert.ok(!prGeneral.selectedGeneralServerSuites.includes(sampleGeneralSuite)); + assert.deepEqual(prGeneral.excludedNightlySuites, [sampleGeneralSuite]); + + const prSerialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"], prEnv); + assert.ok(!prSerialized.selectedSerializedSuites.includes(sampleSerializedSuite)); + assert.equal(prSerialized.serializedSuiteCount, fullSerialized.serializedSuiteCount - 1); + assert.deepEqual(prSerialized.excludedNightlySuites, [sampleSerializedSuite]); + + const prNative = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], prEnv); + assert.ok(!prNative.selectedGeneralServerSuites.includes(sampleNativeSuite)); + assert.deepEqual(prNative.excludedNightlySuites, [sampleNativeSuite]); + + // PAPERCLIP_CI_FULL=1, Release, Cloud readiness, and local runs retain all suites. + for (const fullEnv of [ + { ...prEnv, PAPERCLIP_CI_FULL: "1" }, + { GITHUB_WORKFLOW: "Release", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile }, + { GITHUB_WORKFLOW: "Cloud readiness", PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile }, + { PAPERCLIP_CI_NIGHTLY_SUITES_FILE: manifestFile }, + ]) { + const general = dryRunJson(["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], fullEnv); + assert.equal(general.nightlyExclusionActive, false); + assert.deepEqual(general.excludedNightlySuites, []); + assert.ok(general.selectedGeneralServerSuites.includes(sampleGeneralSuite)); + const serialized = dryRunJson(["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"], fullEnv); + assert.ok(serialized.selectedSerializedSuites.includes(sampleSerializedSuite)); + const native = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], fullEnv); + assert.ok(native.selectedGeneralServerSuites.includes(sampleNativeSuite)); + } + + // Empty-list guard: when every native-runner suite is excluded in PR mode, vitest must NOT run unfiltered. + const allNative = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"]).selectedGeneralServerSuites; + const allNativeManifest = path.join(directory, "all-native-nightly.json"); + writeFileSync(allNativeManifest, JSON.stringify({ suites: allNative })); + const receipt = path.join(directory, "empty-guard-calls.ndjson"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync(fakePnpm, `#!/usr/bin/env node\nrequire('node:fs').appendFileSync(${JSON.stringify(receipt)}, JSON.stringify(process.argv.slice(2)) + '\\n');\n`); + chmodSync(fakePnpm, 0o755); + const emptyResult = spawnSync(process.execPath, [script, "--mode", "general", "--group", "general-server-native-runner"], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + GITHUB_WORKFLOW: "PR", + PAPERCLIP_CI_NIGHTLY_SUITES_FILE: allNativeManifest, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + }), + }); + assert.equal(emptyResult.status, 0, emptyResult.stdout + emptyResult.stderr); + assert.equal(existsSync(receipt), false, "an empty filtered suite set must skip vitest instead of running unfiltered"); + + // Selected runs in PR mode also filter nightly-only suites unless PAPERCLIP_CI_FULL=1. + const selectionFile = path.join(directory, "selection-manifest.json"); + const head = spawnSync("git", ["rev-parse", "HEAD"], { cwd: repoRoot, encoding: "utf8" }).stdout.trim(); + const selManifest = { + version: 1, + head, + lanes: { + "general-server-without-chat": { + shards: [{ "@paperclipai/server": [sampleGeneralSuite, sampleKeptGeneralSuite] }], + }, + }, + }; + writeFileSync(selectionFile, JSON.stringify(selManifest)); + const selHash = selectionHash(selManifest); + const prSelected = dryRunJson( + ["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], + { ...prEnv, PAPERCLIP_CI_TEST_SELECTION: selectionFile, PAPERCLIP_CI_SELECTION_HASH: selHash }, + ); + assert.deepEqual(prSelected.selection["@paperclipai/server"], [sampleKeptGeneralSuite], "selected PR run must drop nightly-only suite"); + + const fullSelected = dryRunJson( + ["--mode", "general", "--group", "general-server-without-chat", "--shard-index", "0", "--shard-count", "1"], + { ...prEnv, PAPERCLIP_CI_FULL: "1", PAPERCLIP_CI_TEST_SELECTION: selectionFile, PAPERCLIP_CI_SELECTION_HASH: selHash }, + ); + assert.deepEqual( + fullSelected.selection["@paperclipai/server"], + [sampleGeneralSuite, sampleKeptGeneralSuite], + "PAPERCLIP_CI_FULL=1 selected run must keep nightly-only suite", + ); + + // general-workspaces-c forwards packages/db nightly excludes to vitest --exclude. + rmSync(receipt, { force: true }); + const dbResult = spawnSync(process.execPath, [script, "--mode", "general", "--group", "general-workspaces-c"], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + ...prEnv, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + }), + }); + assert.equal(dbResult.status, 0, dbResult.stdout + dbResult.stderr); + const dbCall = JSON.parse(readFileSync(receipt, "utf8").trim()); + assert.ok(dbCall.includes("--exclude") && dbCall.includes("src/client.test.ts"), `expected db nightly exclude in ${dbCall.join(" ")}`); + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); + +test("shared Postgres wrapper skips non-Postgres workspace groups even when opted in", { skip: process.platform === "win32" }, () => { + const directory = mkdtempSync(path.join(os.tmpdir(), "shared-pg-skip-")); + const receipt = path.join(directory, "env.json"); + const fakePnpm = path.join(directory, "pnpm"); + writeFileSync( + fakePnpm, + `#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(receipt)}, JSON.stringify({ admin: process.env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL ?? null, template: process.env.PAPERCLIP_TEST_POSTGRES_TEMPLATE ?? null }));\n`, + ); + chmodSync(fakePnpm, 0o755); + try { + for (const group of ["general-workspaces-a", "general-workspaces-b"]) { + rmSync(receipt, { force: true }); + const result = spawnSync(process.execPath, [script, "--mode", "general", "--group", group], { + cwd: repoRoot, + encoding: "utf8", + env: workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "1", + }), + }); + assert.equal(result.status, 0, result.stdout + result.stderr); + assert.deepEqual(JSON.parse(readFileSync(receipt, "utf8")), { admin: null, template: null }, `${group} must not boot shared Postgres`); + } + } finally { + rmSync(directory, { recursive: true, force: true }); + } +}); diff --git a/scripts/__tests__/run-vitest-stable-shard.test.mjs b/scripts/__tests__/run-vitest-stable-shard.test.mjs index dbfef487ba4..8868e8301c5 100644 --- a/scripts/__tests__/run-vitest-stable-shard.test.mjs +++ b/scripts/__tests__/run-vitest-stable-shard.test.mjs @@ -31,8 +31,17 @@ const serializedDurationsManifest = path.join( // themselves run inside a workflow on CI. function workflowEnv(envOverrides = {}) { const env = { ...process.env, ...envOverrides }; - if (!("GITHUB_WORKFLOW" in envOverrides)) { - delete env.GITHUB_WORKFLOW; + for (const key of [ + "GITHUB_WORKFLOW", + "PAPERCLIP_CI_FULL", + "PAPERCLIP_CI_EXCLUDE_NIGHTLY", + "PAPERCLIP_CI_NIGHTLY_SUITES_FILE", + "PAPERCLIP_VITEST_MAX_WORKERS", + "PAPERCLIP_TEST_POSTGRES_ADMIN_URL", + ]) { + if (!(key in envOverrides)) { + delete env[key]; + } } return env; } @@ -383,7 +392,11 @@ test("12 PR without-chat shards plus the dedicated chat and native-runner lanes assert.ok(!files.includes(pluginWarmOwnerSuitePath)); assert.ok(!files.includes(pluginReleaseResumeSuitePath)); assert.ok(!files.includes(pluginEvictionSuitePath)); - assert.deepEqual([...files, chatSuitePath, nativeRunnerSuitePath, ingressRetrySuitePath, dotRunnerSuitePath, restartRecoverySuitePath, ...restartWaitSuites, cutTurnStartRetrySuitePath, usageDeliverySuitePath, warmCheckpointOwnershipSuitePath, warmSuccessorRunnerReleaseSuitePath, pluginWarmOwnerSuitePath, pluginReleaseResumeSuitePath, pluginEvictionSuitePath, "server/src/services/native-runtime/plugin-runner-probe.test.ts"].sort(), full.selectedGeneralServerSuites.sort()); + const excludedNightly = shards[0].excludedNightlySuites ?? []; + for (const shard of shards) { + assert.deepEqual(shard.excludedNightlySuites ?? [], excludedNightly, "nightly exclusions must agree across shards"); + } + assert.deepEqual([...files, ...excludedNightly, chatSuitePath, nativeRunnerSuitePath, ingressRetrySuitePath, dotRunnerSuitePath, restartRecoverySuitePath, ...restartWaitSuites, cutTurnStartRetrySuitePath, usageDeliverySuitePath, warmCheckpointOwnershipSuitePath, warmSuccessorRunnerReleaseSuitePath, pluginWarmOwnerSuitePath, pluginReleaseResumeSuitePath, pluginEvictionSuitePath, "server/src/services/native-runtime/plugin-runner-probe.test.ts"].sort(), full.selectedGeneralServerSuites.sort()); assert.equal(new Set(files).size, files.length); const defaultRun = dryRunJson([], prEnv); assert.ok(defaultRun.generalServerSuiteCount === full.generalServerSuiteCount); @@ -468,7 +481,11 @@ test("the PR workflow wiring for the native-runner lane holds", () => { const vitestLanes = matrix.verify_paperclip_runner.filter((entry) => entry.command.startsWith("test:typescript:vitest")); for (const entry of vitestLanes) { assert.match(entry.command, /^test:typescript:vitest (--package-lane=\d+\/\d+|--native-server)$/, entry.lane_label); - assert.equal(entry.task, "ci:runner-vitest", entry.lane_label); + assert.equal( + entry.task, + entry.command.endsWith("--native-server") ? "ci:runner-vitest" : "ci:runner-package", + entry.lane_label, + ); } const lanes = vitestLanes .map((entry) => /--package-lane=(\d+)\/(\d+)$/.exec(entry.command)) @@ -769,7 +786,8 @@ function defaultLauncher({ shared = false, failureIndex = null } = {}) { const result = spawnSync(process.execPath, [script, "--mode", "general"], { cwd: repoRoot, encoding: "utf8", timeout: 30_000, env: workflowEnv({ GITHUB_WORKFLOW: "PR", PATH: `${directory}${path.delimiter}${process.env.PATH}`, - PAPERCLIP_TEST_DATABASE_URL: shared ? "postgresql://shared/test" : "", PAPERCLIP_CI_PROFILE: "false" }), + PAPERCLIP_TEST_DATABASE_URL: shared ? "postgresql://shared/test" : "", PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0" }), }); const events = existsSync(receipt) ? readFileSync(receipt, "utf8").trim().split("\n").map(line => JSON.parse(line)) : []; return { result, events, lines }; @@ -857,7 +875,7 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro "--shard-index", "0", "--shard-count", "3"], { cwd: repoRoot, encoding: "utf8", timeout: 30_000, env: { ...process.env, PATH: `${directory}${path.delimiter}${process.env.PATH}`, - PAPERCLIP_TEST_DATABASE_URL: "", PAPERCLIP_CI_PROFILE: "false" }, + PAPERCLIP_TEST_DATABASE_URL: "", PAPERCLIP_CI_PROFILE: "false", PAPERCLIP_TEST_POSTGRES_SHARED: "0" }, }); assert.equal(result.status, 1, result.stdout + result.stderr); assert.match(result.stderr, /failed \(7\)/); @@ -867,10 +885,11 @@ test("a failed chat child fails the job after its sibling finishes", { skip: pro } }); -for (const [group, parallelWorkers, shardArgs] of [ - ["general-server-native-runner", 4, []], - ["general-server-without-chat-or-native-runner", 3, ["--shard-index", "0", "--shard-count", "12"]], -]) test(`${group} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => { +for (const [label, modeArgs, parallelWorkers] of [ + ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], 4], + ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], 4], + ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], 3], +]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => { const directory = mkdtempSync(path.join(os.tmpdir(), "native-file-workers-")); const receipt = path.join(directory, "args.json"); const fakePnpm = path.join(directory, "pnpm"); @@ -882,19 +901,24 @@ for (const [group, parallelWorkers, shardArgs] of [ [{ PAPERCLIP_TEST_DATABASE_URL: "postgresql://shared/test" }, 1], [{ PAPERCLIP_ISSUE_RECOVERY_TEST_DATABASE_URL: "postgresql://shared/recovery_test" }, 1], [{ PAPERCLIP_TEST_POSTGRES_ADMIN_URL: "postgresql://owned/postgres" }, parallelWorkers], + [{ PAPERCLIP_VITEST_MAX_WORKERS: "2" }, 2], ]) { - const env = workflowEnv({ PATH: `${directory}${path.delimiter}${process.env.PATH}`, PAPERCLIP_CI_PROFILE: "false" }); + const env = workflowEnv({ + PATH: `${directory}${path.delimiter}${process.env.PATH}`, + PAPERCLIP_CI_PROFILE: "false", + PAPERCLIP_TEST_POSTGRES_SHARED: "0", + }); for (const key of Object.keys(env)) if (key.endsWith("_TEST_DATABASE_URL")) delete env[key]; Object.assign(env, databaseEnv); - const result = spawnSync(process.execPath, [script, "--mode", "general", "--group", group, ...shardArgs], { + const result = spawnSync(process.execPath, [script, ...modeArgs], { cwd: repoRoot, encoding: "utf8", env, }); assert.equal(result.status, 0, result.stdout + result.stderr); const args = JSON.parse(readFileSync(receipt, "utf8")); - assert.ok(args.includes(`--maxWorkers=${workers}`)); + assert.ok(args.includes(`--maxWorkers=${workers}`), `expected --maxWorkers=${workers} in ${args.join(" ")}`); assert.ok(args.includes(workers > 1 ? "--fileParallelism" : "--no-file-parallelism")); if (workers > 1) assert.ok(args.includes("--pool=forks") && args.includes("--isolate")); - if (group === "general-server-native-runner") { + if (label === "general-server-native-runner") { for (const file of [restartRecoverySuitePath, ...restartWaitSuites]) assert.ok(args.includes(file)); } } diff --git a/scripts/__tests__/runner-release-crate-cache.test.mjs b/scripts/__tests__/runner-release-crate-cache.test.mjs index 72cabec8e16..a4019627eae 100644 --- a/scripts/__tests__/runner-release-crate-cache.test.mjs +++ b/scripts/__tests__/runner-release-crate-cache.test.mjs @@ -362,11 +362,14 @@ test("the Verify Paperclip Runner job restores the crate only in the lanes that const lanes = JSON.parse(readFileSync(path.join(repoRoot, ".github/ci-task-matrix.json"), "utf8")) .verify_paperclip_runner.map((entry) => [entry.lane_label, entry.release_crate === true]); assert.deepEqual(lanes, [ - ["static checks", false], + ["static checks", true], ["rust", true], - ["vitest package (1/3)", false], - ["vitest package (2/3)", false], - ["vitest package (3/3)", false], + ["vitest package (1/6)", false], + ["vitest package (2/6)", false], + ["vitest package (3/6)", false], + ["vitest package (4/6)", false], + ["vitest package (5/6)", false], + ["vitest package (6/6)", false], ["vitest native server", true], ]); for (const stepName of [KEY_STEP, RESTORE_STEP]) { @@ -419,7 +422,9 @@ test("only the master Rust lane writes the crate, after a lookup, with the reade // The dependency cache's own writer gate is the same expression. assert.match(body, new RegExp(`save-if: \\$\\{\\{ ${WRITER_GATE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")} \\}\\}`)); - assert.equal((releaseWorkflow.match(/actions\/cache\/save@/g) ?? []).length, 2, "release and debug workspace caches have separate guarded writers"); + assert.equal((body.match(/actions\/cache\/save@/g) ?? []).length, 2, "release and debug workspace caches have separate guarded writers"); + // The only other cache save in release-verify.yml is the master-guarded E2E UI dist writer in `build`. + assert.equal((releaseWorkflow.match(/actions\/cache\/save@/g) ?? []).length, 3, "release-verify.yml has guarded writers for release crate, debug crate, and E2E UI dist"); }); test("the scope names the platform, the compiler and the checkout root, and survives a missing rustc", () => { diff --git a/scripts/check-query-error-rendering.mjs b/scripts/check-query-error-rendering.mjs index dbdde137d23..674f99e912a 100644 --- a/scripts/check-query-error-rendering.mjs +++ b/scripts/check-query-error-rendering.mjs @@ -62,7 +62,6 @@ export const ALLOWLIST = new Set([ "ui/src/artifact-directions/main.tsx:retry-false", "ui/src/wizard-preview-main.tsx:retry-false", "ui/src/fixtures/TaskChatPerfHarness.tsx:retry-false", - "ui/src/pages/NewAgent.test-support.tsx:retry-false", "ui/src/components/TaskChatThread.tsx:is-error-render", "ui/src/components/transcript/RunTranscriptView.tsx:is-error-render", "ui/src/components/task-chat/transcript-adapter.ts:is-error-render", diff --git a/scripts/ci-typecheck-lane.mjs b/scripts/ci-typecheck-lane.mjs index dedf200319a..3595963956f 100644 --- a/scripts/ci-typecheck-lane.mjs +++ b/scripts/ci-typecheck-lane.mjs @@ -1,79 +1,344 @@ #!/usr/bin/env node -import { spawn, spawnSync } from "node:child_process"; +import { execFileSync, spawn, spawnSync } from "node:child_process"; import { availableParallelism, setPriority } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { listLayers } from "../server/scripts/typecheck-layers.mjs"; import { LOW_MEMORY_VARIABLE, EMIT_ONLY_VARIABLE } from "./run-tsc.mjs"; -import { PROJECTS } from "./typecheck-test-projects.mjs"; +import { selectTestPrograms } from "./typecheck-test-programs.mjs"; +import { PROJECTS, selectTestProjects } from "./typecheck-test-projects.mjs"; export const SERIAL_BUILD_GAPS = ["@paperclipai/paperclip-runner"]; export const BACKGROUND_PRIORITY = 10; +export const DEFAULT_MAX_CONCURRENCY = 3; +export const DEFAULT_TEST_PROGRAMS_CONCURRENCY = 2; const SERVER_DECLARATIONS = "server declarations"; export const CLI_GUIDANCE_SAFETY = "CLI guidance safety"; const lowMemory = { [LOW_MEMORY_VARIABLE]: "1" }; -export function planLane({ buildGapPackages, testLayers, projects = PROJECTS }) { +const GLOBAL_TYPECHECK_INPUTS = new Set([ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "tsconfig.base.json", + ".npmrc", + "scripts/run-tsc.mjs", + "scripts/ci-typecheck-lane.mjs", + "scripts/typecheck-test-programs.mjs", + "scripts/typecheck-test-projects.mjs", + "server/scripts/typecheck-layers.mjs", +]); + +const SERVER_UI_INPUTS = [ + "ui/src/lib/", + "ui/src/api/", + "ui/src/types/", + "ui/src/index.css", + "ui/src/bootstrapSetup.ts", + "ui/src/pages/CompanyExport.tsx", + "ui/src/components/MarkdownBody.tsx", +]; + +const hasPrefix = (files, prefixes) => + files.some((file) => prefixes.some((prefix) => file === prefix || file.startsWith(prefix))); + +export function isGlobalTypecheckInput(file) { + return GLOBAL_TYPECHECK_INPUTS.has(file) || file.startsWith("patches/"); +} + +export function shouldRunReleaseRegistryTests(changedFiles) { + if (!Array.isArray(changedFiles)) return true; + return changedFiles.some( + (file) => + file.startsWith("scripts/") || + file.startsWith(".github/") || + file === "package.json" || + file.endsWith("/package.json") || + file === "pnpm-lock.yaml" || + file === "pnpm-workspace.yaml" || + file.startsWith("releases/") || + file.startsWith("patches/") || + file.startsWith("Dockerfile") || + file.startsWith("docker/") || + file === "turbo.json" || + file.startsWith("vitest.config.") || + file === "packages/paperclip-runner/acpx-profiles.json" || + file === "packages/paperclip-runner/antigravity-distributions.json" || + file.startsWith("packages/paperclip-runner/cursor-") || + file.startsWith("packages/paperclip-runner/vitest.config.") || + file.startsWith("packages/paperclip-runner/scripts/"), + ); +} + +export function selectBuildGapPackages(buildGapPackages, changedFiles) { + if (!Array.isArray(changedFiles)) return [...buildGapPackages]; + if (changedFiles.some(isGlobalTypecheckInput)) return [...buildGapPackages]; + return buildGapPackages.filter((name) => { + if (name === "@paperclipai/paperclip-runner") { + return hasPrefix(changedFiles, [ + "packages/paperclip-runner/", + "packages/paperclip-eval-kernel/", + "packages/shared/", + "packages/adapter-utils/", + ]); + } + if (name === "@paperclipai/ui") { + return hasPrefix(changedFiles, [ + "ui/", + "packages/shared/", + "packages/adapter-utils/", + "packages/adapters/", + "packages/plugins/sdk/", + "maps/", + ]); + } + if (name === "paperclipai") { + return hasPrefix(changedFiles, [ + "cli/", + "server/", + "packages/db/", + "packages/shared/", + "packages/adapter-utils/", + "packages/adapters/", + ]); + } + if (name === "@paperclipai/plugin-llm-wiki") { + return hasPrefix(changedFiles, [ + "packages/plugins/plugin-llm-wiki/", + "packages/plugins/sdk/", + "packages/shared/", + ]); + } + if (name === "@paperclipai/plugin-authoring-smoke-example") { + return hasPrefix(changedFiles, [ + "packages/plugins/examples/plugin-authoring-smoke-example/", + "packages/plugins/sdk/", + "packages/shared/", + ]); + } + // Fail closed for any unknown build-gap workspace package. + return true; + }); +} + +export function shouldRunServerTypecheck(changedFiles, selectedProjects = []) { + if (!Array.isArray(changedFiles)) return true; + if (selectedProjects.length > 0) return true; + return changedFiles.some( + (file) => + isGlobalTypecheckInput(file) || + file.startsWith("server/") || + file.startsWith("packages/") || + file.startsWith("cli/") || + SERVER_UI_INPUTS.some((prefix) => file === prefix || file.startsWith(prefix)) || + /^ui\/[^/]+$/.test(file), + ); +} + +function readGitDiff(root, rangeArgs, execGit) { + const output = execGit(["diff", "--no-ext-diff", "--no-textconv", "--no-renames", "--name-only", "-z", ...rangeArgs, "--"], { + cwd: root, + encoding: "utf8", + maxBuffer: 16 * 1024 * 1024, + }); + return output.split("\0").filter(Boolean); +} + +export function resolveScope({ + root, + env = process.env, + base, + full = false, + execGit = (args, options) => execFileSync("git", args, options), +} = {}) { + if (full || env.PAPERCLIP_CI_FULL === "1" || env.PAPERCLIP_CI_FULL === "true") { + return { mode: "full", changedFiles: null, reason: "PAPERCLIP_CI_FULL" }; + } + + if (env.CI_PLAN) { + try { + const plan = JSON.parse(env.CI_PLAN); + if ( + plan?.mode === "full" || + plan?.forceReason === "Full CI requested" || + plan?.forceReason === "Missing or invalid diff" || + (typeof plan?.forceReason === "string" && plan.forceReason.startsWith("Diff unavailable:")) + ) { + return { mode: "full", changedFiles: null, reason: plan.forceReason || "CI_PLAN mode=full" }; + } + if (Array.isArray(plan?.changed) && plan.changed.length > 0) { + return { mode: "pr", changedFiles: plan.changed, reason: "CI_PLAN" }; + } + return { mode: "full", changedFiles: null, reason: "CI_PLAN had no changed files" }; + } catch { + return { mode: "full", changedFiles: null, reason: "invalid CI_PLAN" }; + } + } + + const baseSha = base || env.PAPERCLIP_CI_BASE_SHA; + if (!baseSha && env.GITHUB_EVENT_NAME !== "pull_request") { + return { mode: "full", changedFiles: null, reason: "full default" }; + } + + try { + if (base) { + const changedFiles = readGitDiff(root, [`${base}...HEAD`], execGit); + if (changedFiles.length > 0) return { mode: "pr", changedFiles, reason: `git diff ${base}...HEAD` }; + return { mode: "full", changedFiles: null, reason: "empty git diff" }; + } + let hasMergeSecondParent = false; + try { + execGit(["rev-parse", "--verify", "--quiet", "HEAD^2"], { cwd: root, encoding: "utf8" }); + hasMergeSecondParent = true; + } catch {} + const rangeArgs = hasMergeSecondParent ? ["HEAD^1", "HEAD"] : [`${baseSha}...HEAD`]; + const changedFiles = readGitDiff(root, rangeArgs, execGit); + if (changedFiles.length > 0) { + return { mode: "pr", changedFiles, reason: `git diff ${rangeArgs.join(" ")}` }; + } + return { mode: "full", changedFiles: null, reason: "empty git diff" }; + } catch { + return { mode: "full", changedFiles: null, reason: "git diff unavailable" }; + } +} + +export function planLane({ + buildGapPackages, + testLayers, + projects = PROJECTS, + changedFiles = null, + testProgramsConcurrency = DEFAULT_TEST_PROGRAMS_CONCURRENCY, +}) { + const isPrMode = Array.isArray(changedFiles); + const selectedBuildGaps = selectBuildGapPackages(buildGapPackages, changedFiles); + const selectedProjects = selectTestProjects(changedFiles, projects); + const runServer = shouldRunServerTypecheck(changedFiles, selectedProjects); + const runReleaseRegistry = shouldRunReleaseRegistryTests(changedFiles); + const programSelection = selectTestPrograms(changedFiles); + const typecheckPackage = (name, background) => ({ name: `typecheck ${name}`, command: "pnpm", args: ["--filter", name, "typecheck"], - env: lowMemory, + // UI typecheck runs ~7x faster without --singleThreaded while staying at ~4.4 GiB with GOMAXPROCS=2. + env: name === "@paperclipai/ui" ? { GOMAXPROCS: "2" } : lowMemory, background, }); - const prepare = [ - { name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }, - { name: "build plugin SDK", command: "pnpm", args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"] }, - { - name: "build server without type checks", + + const prepare = [{ name: "link workspace packages", command: "pnpm", args: ["run", "preflight:workspace-links"] }]; + + if (runServer || selectedBuildGaps.length > 0 || programSelection.programs.length > 0) { + prepare.push({ + name: "build plugin SDK", command: "pnpm", - args: ["--filter", "@paperclipai/server", "build"], - env: { [EMIT_ONLY_VARIABLE]: "1" }, - }, - { - name: "check server runtime assets", - command: "node", - args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], - }, - { name: "install test program dependencies", command: "node", args: ["scripts/typecheck-test-programs.mjs", "--prepare-only"] }, - ...buildGapPackages.filter((name) => SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, false)), + args: ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"], + }); + } + + if (runServer) { + prepare.push( + { + name: "build server without type checks", + command: "pnpm", + args: ["--filter", "@paperclipai/server", "build"], + env: { [EMIT_ONLY_VARIABLE]: "1" }, + }, + { + name: "check server runtime assets", + command: "node", + args: ["scripts/run-typecheck-build-gaps.mjs", "--runtime-assets-only"], + }, + ); + } + + if (programSelection.includeProviders || programSelection.includeRunnerEval) { + const prepareArgs = ["scripts/typecheck-test-programs.mjs", "--prepare-only"]; + if (isPrMode) { + prepareArgs.push("--skip-plugin-sdk"); + if (!programSelection.includeProviders) prepareArgs.push("--no-providers"); + if (!programSelection.includeRunnerEval) prepareArgs.push("--no-runner-eval"); + } + prepare.push({ name: "install test program dependencies", command: "node", args: prepareArgs }); + } + + prepare.push( + ...selectedBuildGaps.filter((name) => SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, false)), { name: CLI_GUIDANCE_SAFETY, command: "pnpm", args: ["exec", "vitest", "run", "--project", "@paperclipai/server", "server/src/__tests__/cli-invocation-safety.test.ts"], }, - ]; + ); + const needsDeclarations = [SERVER_DECLARATIONS]; - const tasks = [ - { + const tasks = []; + + if (runServer) { + tasks.push({ name: SERVER_DECLARATIONS, command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--declarations-only"], - env: lowMemory, - }, - { name: "release registry tests", command: "pnpm", args: ["run", "test:release-registry"] }, - { + args: ["server/scripts/typecheck-layers.mjs", "--declarations-only", "--checkers", "2"], + }); + } + + if (runReleaseRegistry) { + tasks.push({ name: "release registry tests", command: "pnpm", args: ["run", "test:release-registry"] }); + } + + if (programSelection.programs.length > 0 || programSelection.checkCoverage) { + const programArgs = [ + "scripts/typecheck-test-programs.mjs", + "--skip-prepare", + "--checkers", + "1", + "--concurrency", + String(testProgramsConcurrency), + ]; + if (isPrMode) { + if (!programSelection.includeProviders) programArgs.push("--no-providers"); + if (!programSelection.checkCoverage) { + programArgs.push("--no-coverage"); + } else if (programSelection.changedTestFiles) { + for (const file of programSelection.changedTestFiles) programArgs.push("--check-file", file); + } else { + programArgs.push("--force-coverage"); + } + if (programSelection.programs.length === 0) { + programArgs.push("--coverage-only"); + } else { + programArgs.push(...programSelection.programs); + } + } + tasks.push({ name: "typecheck test programs", command: "node", - args: ["scripts/typecheck-test-programs.mjs", "--low-memory", "--skip-prepare"], + args: programArgs, background: true, - }, - ...testLayers.map((layer) => ({ - name: `server layer ${layer}`, - command: "node", - args: ["server/scripts/typecheck-layers.mjs", "--layer", layer], - env: lowMemory, - needs: needsDeclarations, - })), - ...projects.map((project) => ({ - name: `test project ${project}`, - command: "node", - args: ["scripts/typecheck-test-projects.mjs", "--low-memory", "--reuse-declarations", project], - needs: needsDeclarations, - })), - ...buildGapPackages.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)), - ]; + }); + } + + if (runServer) { + tasks.push( + ...testLayers.map((layer) => ({ + name: `server layer ${layer}`, + command: "node", + args: ["server/scripts/typecheck-layers.mjs", "--layer", layer, "--checkers", "1"], + needs: needsDeclarations, + })), + ...selectedProjects.map((project) => ({ + name: `test project ${project}`, + command: "node", + args: ["scripts/typecheck-test-projects.mjs", "--checkers", "1", "--reuse-declarations", project], + needs: needsDeclarations, + })), + ); + } + + tasks.push( + ...selectedBuildGaps.filter((name) => !SERIAL_BUILD_GAPS.includes(name)).map((name) => typecheckPackage(name, true)), + ); + return { prepare, tasks }; } @@ -259,11 +524,26 @@ function listBuildGapPackages(root) { if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - const concurrencyIndex = args.indexOf("--concurrency"); - const concurrency = concurrencyIndex === -1 ? availableParallelism() : Number(args[concurrencyIndex + 1]); - const extra = args.filter((_, index) => concurrencyIndex === -1 || (index !== concurrencyIndex && index !== concurrencyIndex + 1)); - if (!Number.isInteger(concurrency) || concurrency < 1 || extra.length > 0) { - console.error("Usage: node scripts/ci-typecheck-lane.mjs [--concurrency ]"); + let concurrency = Math.max(1, Math.min(DEFAULT_MAX_CONCURRENCY, availableParallelism())); + let base; + let full = false; + let valid = true; + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (arg === "--concurrency") { + concurrency = Number(args[++i]); + if (!Number.isInteger(concurrency) || concurrency < 1) valid = false; + } else if (arg === "--base") { + base = args[++i]; + if (!base || base.startsWith("--")) valid = false; + } else if (arg === "--full") { + full = true; + } else { + valid = false; + } + } + if (!valid) { + console.error("Usage: node scripts/ci-typecheck-lane.mjs [--concurrency ] [--base ] [--full]"); process.exitCode = 2; } else { const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -274,8 +554,18 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me const testLayers = listLayers(path.join(root, "server")) .filter((layer) => !layer.emitsDeclarations) .map((layer) => layer.name); - console.log(`typecheck lane: ${concurrency} at a time; build gaps: ${buildGapPackages.join(", ")}`); - process.exitCode = await runLane({ ...planLane({ buildGapPackages, testLayers }), concurrency, cwd: root }); + const scope = resolveScope({ root, env: process.env, base, full }); + const scopeDetail = + scope.mode === "pr" + ? `PR (${scope.changedFiles.length} changed files via ${scope.reason})` + : `full (${scope.reason})`; + const lanePlan = planLane({ buildGapPackages, testLayers, changedFiles: scope.changedFiles }); + console.log( + `typecheck lane: ${concurrency} at a time; mode: ${scopeDetail}; ` + + `prepare: ${lanePlan.prepare.length}; tasks: ${lanePlan.tasks.length}; ` + + `build gaps: ${buildGapPackages.join(", ")}`, + ); + process.exitCode = await runLane({ ...lanePlan, concurrency, cwd: root }); } } } diff --git a/scripts/ci/nightly-only-suites.json b/scripts/ci/nightly-only-suites.json new file mode 100644 index 00000000000..768f344cd7e --- /dev/null +++ b/scripts/ci/nightly-only-suites.json @@ -0,0 +1,1955 @@ +{ + "$comment": "Real-clock soak, crash-recovery, lease-expiry, restart, workspace-recovery, and large-scale performance suites skipped in ordinary PR CI unless PAPERCLIP_CI_FULL=1. Always executed on master, release-verify, cloud-readiness, and local runs.", + "suites": [ + { + "path": "server/src/__tests__/heartbeat-process-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heavy serialized heartbeat process-crash recovery soak (285 cases, 344s); core heartbeat/recovery.test.ts stays on PRs", + "measuredMs": 344017 + }, + { + "path": "server/src/services/ssh-remote-workspace.integration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (332.0s in run 45238253588)", + "measuredMs": 332029 + }, + { + "path": "server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process plugin runner eviction/release-resume soak (312.5s in run 45238253588)", + "measuredMs": 312473 + }, + { + "path": "server/src/__tests__/deferred-execution-receipt-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Deferred execution receipt durable recovery soak (36 cases, 292s)", + "measuredMs": 292434 + }, + { + "path": "server/src/__tests__/maintenance-server-routes.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Assembled maintenance server real-clock soak with two 90s wall-clock sleeps (4 cases, 276s)", + "measuredMs": 276429 + }, + { + "path": "server/src/__tests__/issue-recovery-idle-backstop.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (270.3s in run 45238253588)", + "measuredMs": 270345 + }, + { + "path": "server/src/services/native-runtime/native-codex-runner.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process native Codex runner integration soak (1 case, 224s); covered by release-verify/cloud-readiness", + "measuredMs": 224015 + }, + { + "path": "server/src/__tests__/heartbeat-native-restart-suspension.test.ts", + "category": "restart-lease-soak", + "reason": "Real-clock native controller restart suspension & lease-lapse soak (75 cases, 223s)", + "measuredMs": 223420 + }, + { + "path": "server/src/__tests__/recovery-settled-records-census.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (221.4s in run 45238253588)", + "measuredMs": 221352 + }, + { + "path": "server/src/services/workspace-recovery-admission.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery admission & contention soak (65 cases, 220s)", + "measuredMs": 219865 + }, + { + "path": "server/src/services/workspace-recovery-warm-handoff.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery warm-handoff soak (20 cases, 215s)", + "measuredMs": 215408 + }, + { + "path": "server/src/__tests__/live-recovery-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Residual live-recovery production matrix soak (36 cases, 208s)", + "measuredMs": 207953 + }, + { + "path": "server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process plugin runner eviction/release-resume soak (205.8s in run 45238253588)", + "measuredMs": 205790 + }, + { + "path": "server/src/__tests__/git-workspace-expiration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Git workspace TTL expiration & cleanup sweep soak (81 cases, 198s)", + "measuredMs": 198261 + }, + { + "path": "server/src/services/native-runtime/native-runner-restart-checkpoint-cost.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process runner restart checkpoint-cost soak (2 cases, 187s)", + "measuredMs": 187000 + }, + { + "path": "server/src/services/native-runtime/external-chat-wait.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Long-running external chat wait & native restart soak (85 cases, 181s)", + "measuredMs": 181027 + }, + { + "path": "server/src/__tests__/issue-recovery-dependencies.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock issue dependency recovery timer soak (4 cases, 178s)", + "measuredMs": 178002 + }, + { + "path": "server/src/services/native-runtime/native-runner-restart-diskless.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process diskless runner restart soak (172s)", + "measuredMs": 172000 + }, + { + "path": "server/src/__tests__/heartbeat-project-repositories.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (159.0s in run 45238253588)", + "measuredMs": 158961 + }, + { + "path": "server/src/services/native-runtime/native-runner-restart-preparation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process runner restart preparation soak (3 cases, 155s)", + "measuredMs": 155000 + }, + { + "path": "server/src/__tests__/managed-skill-content.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (152.2s in run 45238253588)", + "measuredMs": 152199 + }, + { + "path": "server/src/__tests__/idle-sleep-safety.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Idle-sleep backup checkpoint & quietness soak (88 cases, 150s); fast unit idle-sleep-diagnostics.test.ts stays on PRs", + "measuredMs": 150013 + }, + { + "path": "server/src/__tests__/issue-recovery-deadlines.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue recovery deadline & 1000-issue scan bound soak (20 cases, 148s)", + "measuredMs": 148225 + }, + { + "path": "server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Stale heartbeat queue invalidation recovery soak (36 cases, 145s)", + "measuredMs": 145134 + }, + { + "path": "server/src/__tests__/issue-recovery-live-run-agent-census.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (144.1s in run 45238253588)", + "measuredMs": 144083 + }, + { + "path": "server/src/services/remote-workspaces.integration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace snapshot/restore integration soak (39 cases, 134s)", + "measuredMs": 134113 + }, + { + "path": "server/src/__tests__/issue-recovery-assignments.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue assignment recovery & drain/resume soak (7 cases, 134s)", + "measuredMs": 133886 + }, + { + "path": "server/src/services/workspace-recovery-retry-copyback.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery retry copyback soak (27 cases, 126s)", + "measuredMs": 126213 + }, + { + "path": "server/src/services/remote-workspace-migration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Offline/online remote workspace migration soak (86 cases, 125s)", + "measuredMs": 124839 + }, + { + "path": "server/src/__tests__/issue-recovery-company-reload-census.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (120.4s in run 45238253588)", + "measuredMs": 120352 + }, + { + "path": "server/src/services/native-runtime/native-runner-restart-lease-renewal.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-clock runner restart lease-renewal soak (1 case, 119s)", + "measuredMs": 119000 + }, + { + "path": "server/src/__tests__/issue-recovery-activity-hints.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (112.9s in run 45238253588)", + "measuredMs": 112944 + }, + { + "path": "server/src/__tests__/agent-directory-working-copies.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (111.0s in run 45238253588)", + "measuredMs": 110993 + }, + { + "path": "server/src/services/native-runtime/provider-pack-archive.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (109.7s in run 45238253588)", + "measuredMs": 109677 + }, + { + "path": "server/src/services/explicit-native-continuation.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (108.5s in run 45238253588)", + "measuredMs": 108543 + }, + { + "path": "server/src/__tests__/muse-control.test.ts", + "category": "channel-integration-soak", + "reason": "Heavy external channel/connector integration soak (107.5s in run 45238253588)", + "measuredMs": 107452 + }, + { + "path": "server/src/services/native-runtime/preserved-native-response-wait.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Preserved native response wait/restart integration soak (19 cases, 107s)", + "measuredMs": 106952 + }, + { + "path": "server/src/__tests__/idle-completed-history.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Idle completed-history 34-family retention soak (48 cases, 106s)", + "measuredMs": 105817 + }, + { + "path": "server/src/services/workspace-recovery-preparation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery preparation soak (11 cases, 103s)", + "measuredMs": 102797 + }, + { + "path": "server/src/__tests__/native-status-arbiter-corpus.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Executable 53-fixture x 70-row status-authority corpus (68 cases, 98s)", + "measuredMs": 98250 + }, + { + "path": "server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process harness filesystem independence & volume-loss soak (49 cases, 98s)", + "measuredMs": 98077 + }, + { + "path": "server/src/__tests__/isolated-repository-rehome.test.ts", + "category": "workspace-recovery-soak", + "reason": "Isolated git repository rehoming & clone soak (28 cases, 93s)", + "measuredMs": 93407 + }, + { + "path": "server/src/__tests__/sandbox-creation-operations.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (90.6s in run 45238253588)", + "measuredMs": 90610 + }, + { + "path": "server/src/services/fresh-continuation-fallback.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (89.9s in run 45238253588)", + "measuredMs": 89949 + }, + { + "path": "server/src/__tests__/heartbeat-workspace-busy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (85.1s in run 45238253588)", + "measuredMs": 85133 + }, + { + "path": "server/src/services/object-byte-journal.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (83.5s in run 45238253588)", + "measuredMs": 83546 + }, + { + "path": "server/src/__tests__/heartbeat-comment-wake-batching.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (81.4s in run 45238253588)", + "measuredMs": 81437 + }, + { + "path": "server/src/__tests__/heartbeat-repository-catalog-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Heartbeat repository catalog recovery soak (6 cases, 79s)", + "measuredMs": 79077 + }, + { + "path": "server/src/__tests__/voice-session-store.integration.test.ts", + "category": "channel-integration-soak", + "reason": "Heavy external channel/connector integration soak (78.9s in run 45238253588)", + "measuredMs": 78942 + }, + { + "path": "server/src/__tests__/nested-clone-migration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Nested git clone to worktree migration soak (19 cases, 78s)", + "measuredMs": 78158 + }, + { + "path": "server/src/__tests__/attention-retention-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Attention retention background sweep soak (77s)", + "measuredMs": 77085 + }, + { + "path": "server/src/__tests__/issue-recovery-agent-row-write-census.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (74.9s in run 45238253588)", + "measuredMs": 74922 + }, + { + "path": "server/src/__tests__/issue-recovery-conversations.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue recovery conversation drain/park soak (3 cases, 74s)", + "measuredMs": 74439 + }, + { + "path": "server/src/__tests__/ownership-reconciliation-report.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Report-only ownership reconciliation matrix soak (48 cases, 73s)", + "measuredMs": 73104 + }, + { + "path": "server/src/__tests__/plugin-scheduled-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Plugin scheduled-work real-clock deadline/quietness soak (70s)", + "measuredMs": 69649 + }, + { + "path": "server/src/__tests__/heartbeat-held-comment-wake.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (67.8s in run 45238253588)", + "measuredMs": 67821 + }, + { + "path": "server/src/__tests__/status-card-evaluation-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Status-card background evaluation debounce/quietness soak (68s)", + "measuredMs": 67793 + }, + { + "path": "server/src/services/remote-workspace-cohort-migration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace cohort migration soak (22 cases, 66s)", + "measuredMs": 65834 + }, + { + "path": "server/src/__tests__/issue-tree-pause-resume-run.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (65.7s in run 45238253588)", + "measuredMs": 65684 + }, + { + "path": "server/src/services/native-runtime/native-safe-replacement.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (61.7s in run 45238253588)", + "measuredMs": 61717 + }, + { + "path": "server/src/services/remote-workspace-online-source.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace online source capture soak (40 cases, 62s)", + "measuredMs": 61675 + }, + { + "path": "server/src/services/workspace-recovery-preparation-proof.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery preparation proof soak (3 cases, 61s)", + "measuredMs": 60597 + }, + { + "path": "server/src/services/workspace-recovery-preparation-dispatch.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery preparation dispatch soak (8 cases, 59s)", + "measuredMs": 59369 + }, + { + "path": "server/src/services/governed-wait-runner-loss.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (59.3s in run 45238253588)", + "measuredMs": 59275 + }, + { + "path": "server/src/__tests__/native-status-reassessment-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Native status reassessment background recovery soak (22 cases, 58s)", + "measuredMs": 57482 + }, + { + "path": "server/src/__tests__/agent-scaling-load-model.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (55.9s in run 45238253588)", + "measuredMs": 55895 + }, + { + "path": "server/src/services/workspace-recovery-preparation-gates.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery preparation gates soak (13 cases, 55s)", + "measuredMs": 55229 + }, + { + "path": "server/src/__tests__/chat-run-milestone-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (55.2s in run 45238253588)", + "measuredMs": 55190 + }, + { + "path": "server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Serialized heartbeat issue liveness escalation soak (29 cases, 55s)", + "measuredMs": 54768 + }, + { + "path": "server/src/__tests__/heartbeat-retry-scheduling.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (54.2s in run 45238253588)", + "measuredMs": 54171 + }, + { + "path": "server/src/__tests__/assigned-work-recheck-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (53.1s in run 45238253588)", + "measuredMs": 53061 + }, + { + "path": "server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Harness backup object-storage roundtrip soak (46 cases, 53s)", + "measuredMs": 52555 + }, + { + "path": "server/src/__tests__/tool-connection-health-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (52.4s in run 45238253588)", + "measuredMs": 52429 + }, + { + "path": "server/src/__tests__/recovery-wake-herd.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Recovery wake-herd thundering-herd soak (37 cases, 52s)", + "measuredMs": 51736 + }, + { + "path": "server/src/__tests__/heartbeat-run-dispatch-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (51.5s in run 45238253588)", + "measuredMs": 51459 + }, + { + "path": "server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Real-process runner restart recovery matrix (107 cases, 51s)", + "measuredMs": 51000 + }, + { + "path": "server/src/services/native-runtime/native-workspace-reconstruction.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (50.4s in run 45238253588)", + "measuredMs": 50395 + }, + { + "path": "server/src/__tests__/heartbeat-observed-workspace-preservation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (50.1s in run 45238253588)", + "measuredMs": 50141 + }, + { + "path": "server/src/services/remote-workspace-transport.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace transport archive soak (97 cases, 50s)", + "measuredMs": 49930 + }, + { + "path": "server/src/__tests__/agent-timer-deadlines.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock agent timer deadline soak (43 cases, 49s)", + "measuredMs": 49401 + }, + { + "path": "server/src/services/native-runtime/native-preserved-monitor-wait.test.ts", + "category": "restart-lease-soak", + "reason": "Real-clock preserved monitor wait soak (11 cases, 49s)", + "measuredMs": 49316 + }, + { + "path": "server/src/__tests__/git-restore-point-expiration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Git restore-point expiration sweep soak (35 cases, 49s)", + "measuredMs": 49208 + }, + { + "path": "server/src/__tests__/blocker-workspace-history-performance.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "55,000-row Postgres EXPLAIN ANALYZE query-plan benchmark (2 cases, 49s)", + "measuredMs": 48579 + }, + { + "path": "server/src/__tests__/tool-connection-content-deletion-canary.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (47.4s in run 45238253588)", + "measuredMs": 47442 + }, + { + "path": "server/src/__tests__/idle-native-finalization.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Idle native finalization drain/quietness soak (15 cases, 47s)", + "measuredMs": 47149 + }, + { + "path": "server/src/__tests__/issue-recovery-actions.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Issue recovery action export/timeout soak (76 cases, 47s)", + "measuredMs": 46806 + }, + { + "path": "server/src/__tests__/idle-issue-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Idle issue schedule quietness soak (13 cases, 45s)", + "measuredMs": 45057 + }, + { + "path": "server/src/__tests__/terminal-workspace-deadlines.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (42.8s in run 45238253588)", + "measuredMs": 42823 + }, + { + "path": "server/src/__tests__/issue-recovery-work-debug-attribution.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (41.3s in run 45238253588)", + "measuredMs": 41278 + }, + { + "path": "server/src/services/workspace-git-snapshot-streaming.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (40.7s in run 45238253588)", + "measuredMs": 40665 + }, + { + "path": "server/src/services/native-runtime/native-controller-migration.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Volume-free native controller migration integration soak (14 cases, 41s)", + "measuredMs": 40595 + }, + { + "path": "server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Online harness preservation integration soak (9 cases, 40s)", + "measuredMs": 40303 + }, + { + "path": "server/src/__tests__/email-channels.integration.test.ts", + "category": "channel-integration-soak", + "reason": "Heavy external channel/connector integration soak (40.3s in run 45238253588)", + "measuredMs": 40296 + }, + { + "path": "server/src/services/remote-workspace-original-bare-source.integration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace original bare-source integration soak (5 cases, 40s)", + "measuredMs": 40278 + }, + { + "path": "server/src/__tests__/browser-use-connection.test.ts", + "category": "channel-integration-soak", + "reason": "Heavy external channel/connector integration soak (40.1s in run 45238253588)", + "measuredMs": 40117 + }, + { + "path": "server/src/__tests__/idle-connection-history.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (39.5s in run 45238253588)", + "measuredMs": 39494 + }, + { + "path": "server/src/__tests__/idle-domain-deadlines-postgres.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (38.9s in run 45238253588)", + "measuredMs": 38880 + }, + { + "path": "server/src/services/remote-workspace-snapshot-reuse.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote workspace snapshot reuse soak (39s)", + "measuredMs": 38856 + }, + { + "path": "server/src/__tests__/native-workspace-sync-history.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (38.5s in run 45238253588)", + "measuredMs": 38523 + }, + { + "path": "server/src/__tests__/photon/channel.integration.test.ts", + "category": "channel-integration-soak", + "reason": "Heavy external channel/connector integration soak (38.4s in run 45238253588)", + "measuredMs": 38384 + }, + { + "path": "server/src/__tests__/closed-native-receipt-accounting.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (38.1s in run 45238253588)", + "measuredMs": 38079 + }, + { + "path": "server/src/__tests__/agent-instruction-working-copies.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (38.0s in run 45238253588)", + "measuredMs": 37991 + }, + { + "path": "server/src/services/heartbeat/dispatch-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (38.0s in run 45238253588)", + "measuredMs": 37986 + }, + { + "path": "server/src/__tests__/idle-response-waits.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (37.6s in run 45238253588)", + "measuredMs": 37561 + }, + { + "path": "server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (37.5s in run 45238253588)", + "measuredMs": 37524 + }, + { + "path": "server/src/__tests__/native-run-projection-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (36.5s in run 45238253588)", + "measuredMs": 36499 + }, + { + "path": "server/src/__tests__/isolated-task-directory-retention.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (36.3s in run 45238253588)", + "measuredMs": 36349 + }, + { + "path": "server/src/__tests__/environment-cleanup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (36.3s in run 45238253588)", + "measuredMs": 36256 + }, + { + "path": "server/src/services/remote-workspace-snapshot-archive.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (36.2s in run 45238253588)", + "measuredMs": 36211 + }, + { + "path": "server/src/__tests__/routine-execution-status-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (36.1s in run 45238253588)", + "measuredMs": 36142 + }, + { + "path": "server/src/__tests__/remote-workspace-file-resources.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (35.8s in run 45238253588)", + "measuredMs": 35772 + }, + { + "path": "server/src/__tests__/native-harness-backup-expiration.test.ts", + "category": "restart-lease-soak", + "reason": "Harness backup retention/expiration soak (35s)", + "measuredMs": 34702 + }, + { + "path": "server/src/__tests__/issue-monitor-scheduler.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (34.3s in run 45238253588)", + "measuredMs": 34340 + }, + { + "path": "server/src/services/legacy-controller-lease.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (34.3s in run 45238253588)", + "measuredMs": 34340 + }, + { + "path": "server/src/__tests__/failed-continuation-continues-again.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (34.1s in run 45238253588)", + "measuredMs": 34068 + }, + { + "path": "server/src/__tests__/heartbeat-native-predispatch-retry.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (34.0s in run 45238253588)", + "measuredMs": 34006 + }, + { + "path": "server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (33.3s in run 45238253588)", + "measuredMs": 33312 + }, + { + "path": "server/src/services/public-mcp/events-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (33.0s in run 45238253588)", + "measuredMs": 32996 + }, + { + "path": "server/src/__tests__/automatic-run-brake-recovery-passes.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (32.3s in run 45238253588)", + "measuredMs": 32314 + }, + { + "path": "server/src/__tests__/idle-incoming-wake.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (32.0s in run 45238253588)", + "measuredMs": 32015 + }, + { + "path": "server/src/__tests__/skill-version-retention.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (31.8s in run 45238253588)", + "measuredMs": 31824 + }, + { + "path": "server/src/__tests__/workspace-worktree-concurrency.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (30.4s in run 45238253588)", + "measuredMs": 30390 + }, + { + "path": "server/src/services/workspace-recovery-fallback.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery fallback soak (30s)", + "measuredMs": 29586 + }, + { + "path": "server/src/services/remote-workspace-unchanged-release.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (29.3s in run 45238253588)", + "measuredMs": 29322 + }, + { + "path": "server/src/__tests__/native-result-commit-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (29.0s in run 45238253588)", + "measuredMs": 28978 + }, + { + "path": "server/src/__tests__/slack-cloud-owner-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (27.5s in run 45238253588)", + "measuredMs": 27508 + }, + { + "path": "server/src/services/workspace-recovery-passive-fairness.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery passive fairness soak (26s)", + "measuredMs": 25923 + }, + { + "path": "server/src/__tests__/voice-recovery-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (25.4s in run 45238253588)", + "measuredMs": 25368 + }, + { + "path": "server/src/services/native-runtime/native-failed-workspace-recovery.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (24.8s in run 45238253588)", + "measuredMs": 24768 + }, + { + "path": "server/src/services/native-runtime/off-loop-file-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (24.8s in run 45238253588)", + "measuredMs": 24764 + }, + { + "path": "server/src/__tests__/decision-effect-recovery-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (24.4s in run 45238253588)", + "measuredMs": 24365 + }, + { + "path": "server/src/services/native-runtime/native-controller-recovery.integration.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (24.3s in run 45238253588)", + "measuredMs": 24304 + }, + { + "path": "server/src/services/workspace-recovery-disk-full.test.ts", + "category": "workspace-recovery-soak", + "reason": "Workspace recovery disk-full soak (23s)", + "measuredMs": 23363 + }, + { + "path": "server/src/services/native-runtime/agent-chat-response-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (22.3s in run 45238253588)", + "measuredMs": 22254 + }, + { + "path": "server/src/__tests__/routine-schedule-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.9s in run 45238253588)", + "measuredMs": 21858 + }, + { + "path": "server/src/__tests__/chat-receiver-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (21.3s in run 45238253588)", + "measuredMs": 21267 + }, + { + "path": "server/src/services/workspace-recovery-stop-proof.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", + "measuredMs": 20908 + }, + { + "path": "server/src/services/remote-workspace-snapshot-retention.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.9s in run 45238253588)", + "measuredMs": 20875 + }, + { + "path": "server/src/services/remote-workspace-save-concurrency.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.7s in run 45238253588)", + "measuredMs": 20703 + }, + { + "path": "server/src/services/workspace-recovery-scheduled-preparation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.6s in run 45238253588)", + "measuredMs": 20606 + }, + { + "path": "server/src/__tests__/heartbeat-remote-workspace-busy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (20.2s in run 45238253588)", + "measuredMs": 20229 + }, + { + "path": "server/src/__tests__/native-environment-settlement-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (19.9s in run 45238253588)", + "measuredMs": 19901 + }, + { + "path": "server/src/services/remote-workspace-nested-verification.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (19.9s in run 45238253588)", + "measuredMs": 19868 + }, + { + "path": "server/src/services/skill-source-sync-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (19.9s in run 45238253588)", + "measuredMs": 19860 + }, + { + "path": "server/src/services/native-runtime/plugin-task-source-recovery.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (18.7s in run 45238253588)", + "measuredMs": 18697 + }, + { + "path": "server/src/__tests__/issue-recovery-pass-reads.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (18.1s in run 45238253588)", + "measuredMs": 18095 + }, + { + "path": "server/src/__tests__/external-object-refresh-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (18.0s in run 45238253588)", + "measuredMs": 17969 + }, + { + "path": "server/src/__tests__/merged-pr-confirmation-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (17.6s in run 45238253588)", + "measuredMs": 17605 + }, + { + "path": "server/src/__tests__/github-connection-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (17.5s in run 45238253588)", + "measuredMs": 17548 + }, + { + "path": "server/src/__tests__/join-request-retention-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (17.4s in run 45238253588)", + "measuredMs": 17441 + }, + { + "path": "server/src/__tests__/git-workspace-expiration-eligibility.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (17.4s in run 45238253588)", + "measuredMs": 17358 + }, + { + "path": "server/src/services/online-remote-workspace-recovery-hold.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (16.8s in run 45238253588)", + "measuredMs": 16840 + }, + { + "path": "server/src/__tests__/recovery-durable-wait-projection.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.8s in run 45238253588)", + "measuredMs": 16751 + }, + { + "path": "server/src/__tests__/retained-native-session-cleanup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.4s in run 45238253588)", + "measuredMs": 16414 + }, + { + "path": "server/src/__tests__/execution-control-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", + "measuredMs": 16340 + }, + { + "path": "server/src/__tests__/task-creation-recovery.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.3s in run 45238253588)", + "measuredMs": 16295 + }, + { + "path": "server/src/__tests__/decision-expiry-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (16.0s in run 45238253588)", + "measuredMs": 16024 + }, + { + "path": "server/src/__tests__/native-recovery-notice-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (15.7s in run 45238253588)", + "measuredMs": 15693 + }, + { + "path": "server/src/__tests__/chat-native-progress-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (15.3s in run 45238253588)", + "measuredMs": 15340 + }, + { + "path": "server/src/services/remote-workspace-snapshot-storage.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (15.0s in run 45238253588)", + "measuredMs": 14951 + }, + { + "path": "server/src/__tests__/native-result-commit-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.8s in run 45238253588)", + "measuredMs": 14821 + }, + { + "path": "server/src/__tests__/native-retention-blocker-batch.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.6s in run 45238253588)", + "measuredMs": 14621 + }, + { + "path": "server/src/__tests__/decision-target-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (14.6s in run 45238253588)", + "measuredMs": 14584 + }, + { + "path": "server/src/services/saved-work-recovery-overdue.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.9s in run 45238253588)", + "measuredMs": 13858 + }, + { + "path": "server/src/__tests__/native-failed-run-owner-release-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.8s in run 45238253588)", + "measuredMs": 13796 + }, + { + "path": "server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.6s in run 45238253588)", + "measuredMs": 13612 + }, + { + "path": "server/src/__tests__/native-startup-cleanup-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.6s in run 45238253588)", + "measuredMs": 13606 + }, + { + "path": "server/src/__tests__/idle-sleep-diagnostics-postgres.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.6s in run 45238253588)", + "measuredMs": 13581 + }, + { + "path": "server/src/__tests__/eval-feedback-recovery.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.5s in run 45238253588)", + "measuredMs": 13456 + }, + { + "path": "server/src/__tests__/login-cleanup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.4s in run 45238253588)", + "measuredMs": 13356 + }, + { + "path": "server/src/services/workspace-recovery-capture-policy.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (13.3s in run 45238253588)", + "measuredMs": 13345 + }, + { + "path": "server/src/__tests__/grok-dispatch-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.3s in run 45238253588)", + "measuredMs": 13302 + }, + { + "path": "server/src/services/superseded-workspace-export-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (13.1s in run 45238253588)", + "measuredMs": 13089 + }, + { + "path": "server/src/__tests__/continuation-delivery-unwakeable-agent-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.9s in run 45238253588)", + "measuredMs": 12925 + }, + { + "path": "server/src/services/chat-channels/github/terminal-response-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.9s in run 45238253588)", + "measuredMs": 12889 + }, + { + "path": "server/src/services/native-runtime/native-idle-sleep-continuation.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.3s in run 45238253588)", + "measuredMs": 12300 + }, + { + "path": "server/src/__tests__/native-workspace-finalization-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.2s in run 45238253588)", + "measuredMs": 12186 + }, + { + "path": "server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (12.1s in run 45238253588)", + "measuredMs": 12088 + }, + { + "path": "server/src/services/workspace-recovery-dependency-finalize.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (12.0s in run 45238253588)", + "measuredMs": 11990 + }, + { + "path": "server/src/__tests__/decision-retention-service.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (11.7s in run 45238253588)", + "measuredMs": 11706 + }, + { + "path": "server/src/services/remote-workspace-recovery-receipt-fallback.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.6s in run 45238253588)", + "measuredMs": 11646 + }, + { + "path": "server/src/__tests__/issue-recovery-signal-fanout.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (11.4s in run 45238253588)", + "measuredMs": 11432 + }, + { + "path": "server/src/__tests__/issue-recovery-saved-deferrals.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (11.4s in run 45238253588)", + "measuredMs": 11424 + }, + { + "path": "server/src/__tests__/plugin-idle-manager.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (11.4s in run 45238253588)", + "measuredMs": 11378 + }, + { + "path": "server/src/services/finalized-workspace-recovery-migration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (11.4s in run 45238253588)", + "measuredMs": 11370 + }, + { + "path": "server/src/__tests__/chat-run-milestone-governed-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.8s in run 45238253588)", + "measuredMs": 10752 + }, + { + "path": "server/src/services/isolated-remote-workspace-source-lock.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.5s in run 45238253588)", + "measuredMs": 10495 + }, + { + "path": "server/src/services/workspace-recovery-source.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (10.4s in run 45238253588)", + "measuredMs": 10414 + }, + { + "path": "server/src/__tests__/plugin-environment-driver-ready-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.4s in run 45238253588)", + "measuredMs": 10383 + }, + { + "path": "server/src/__tests__/terminal-workspace-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.2s in run 45238253588)", + "measuredMs": 10197 + }, + { + "path": "server/src/__tests__/heartbeat-run-scratch-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (10.0s in run 45238253588)", + "measuredMs": 10008 + }, + { + "path": "server/src/services/skill-package-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.9s in run 45238253588)", + "measuredMs": 9936 + }, + { + "path": "server/src/__tests__/online-workspace-migration-compatibility.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (9.7s in run 45238253588)", + "measuredMs": 9742 + }, + { + "path": "server/src/__tests__/legacy-workspace-restore-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.6s in run 45238253588)", + "measuredMs": 9551 + }, + { + "path": "server/src/services/native-runtime/tool-receipt-recovery.integration.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.5s in run 45238253588)", + "measuredMs": 9465 + }, + { + "path": "server/src/services/legacy-explicit-continuation-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.4s in run 45238253588)", + "measuredMs": 9358 + }, + { + "path": "server/src/__tests__/chat-run-milestone-recovery-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (9.2s in run 45238253588)", + "measuredMs": 9193 + }, + { + "path": "server/src/__tests__/heartbeat-agent-status-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.9s in run 45238253588)", + "measuredMs": 8890 + }, + { + "path": "server/src/services/native-runtime/remote-warm-session-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.8s in run 45238253588)", + "measuredMs": 8796 + }, + { + "path": "server/src/__tests__/chat-run-milestone-identity-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", + "measuredMs": 8727 + }, + { + "path": "server/src/__tests__/issue-recovery-terminal-run-settling.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.7s in run 45238253588)", + "measuredMs": 8681 + }, + { + "path": "server/src/services/recovery/issue-state-read.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", + "measuredMs": 8448 + }, + { + "path": "server/src/__tests__/human-directed-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", + "measuredMs": 8399 + }, + { + "path": "server/src/__tests__/github-connection-enrollment-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.4s in run 45238253588)", + "measuredMs": 8390 + }, + { + "path": "server/src/services/native-runtime/native-controller-host-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.3s in run 45238253588)", + "measuredMs": 8314 + }, + { + "path": "server/src/services/recovery/provider-failure-classification.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.3s in run 45238253588)", + "measuredMs": 8303 + }, + { + "path": "server/src/services/remote-workspace-migration-concurrency.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (8.3s in run 45238253588)", + "measuredMs": 8274 + }, + { + "path": "server/src/__tests__/chat-run-milestone-resource-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.0s in run 45238253588)", + "measuredMs": 8027 + }, + { + "path": "server/src/__tests__/issue-recovery-review-wait-pass.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.0s in run 45238253588)", + "measuredMs": 8021 + }, + { + "path": "server/src/services/native-runtime/native-workspace-owner-restart-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (8.0s in run 45238253588)", + "measuredMs": 8020 + }, + { + "path": "server/src/__tests__/recovery-observability.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.8s in run 45238253588)", + "measuredMs": 7801 + }, + { + "path": "server/src/services/native-runtime/native-staged-attachment-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.8s in run 45238253588)", + "measuredMs": 7781 + }, + { + "path": "server/src/__tests__/native-finalization-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.8s in run 45238253588)", + "measuredMs": 7766 + }, + { + "path": "server/src/__tests__/cloud-configuration-migration-postgres.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (7.7s in run 45238253588)", + "measuredMs": 7737 + }, + { + "path": "server/src/__tests__/native-workspace-sync-retention.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.7s in run 45238253588)", + "measuredMs": 7658 + }, + { + "path": "server/src/services/native-runtime/runtime-asset-retention.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.7s in run 45238253588)", + "measuredMs": 7656 + }, + { + "path": "server/src/services/recovery/service.pause-durability.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.6s in run 45238253588)", + "measuredMs": 7577 + }, + { + "path": "server/src/__tests__/idle-accounting-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.5s in run 45238253588)", + "measuredMs": 7533 + }, + { + "path": "server/src/services/heartbeat/native-recovery-deadlines.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.5s in run 45238253588)", + "measuredMs": 7505 + }, + { + "path": "server/src/services/native-runtime/native-controller-recovery.test.ts", + "category": "restart-lease-soak", + "reason": "Native runner replacement, lease, or continuation recovery soak (7.5s in run 45238253588)", + "measuredMs": 7453 + }, + { + "path": "server/src/services/recovery/run-context-read.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", + "measuredMs": 7429 + }, + { + "path": "server/src/services/native-runtime/native-blocked-reply-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.4s in run 45238253588)", + "measuredMs": 7382 + }, + { + "path": "server/src/services/public-mcp/idle-sleep-proof.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.3s in run 45238253588)", + "measuredMs": 7346 + }, + { + "path": "server/src/services/idle-incoming-wake.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.3s in run 45238253588)", + "measuredMs": 7303 + }, + { + "path": "server/src/__tests__/workspace-runtime-control-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.3s in run 45238253588)", + "measuredMs": 7273 + }, + { + "path": "server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", + "measuredMs": 7215 + }, + { + "path": "server/src/services/recovery/native-runner-routing.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.2s in run 45238253588)", + "measuredMs": 7196 + }, + { + "path": "server/src/services/remote-workspace-reservation.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (7.0s in run 45238253588)", + "measuredMs": 7014 + }, + { + "path": "server/src/__tests__/native-recovery-dispatch-lease-reacquire.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", + "measuredMs": 6988 + }, + { + "path": "server/src/services/recovery/run-result-read.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", + "measuredMs": 6976 + }, + { + "path": "server/src/services/native-runtime/native-restart-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (7.0s in run 45238253588)", + "measuredMs": 6957 + }, + { + "path": "server/src/maintenance/online-workspace-migration.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (6.9s in run 45238253588)", + "measuredMs": 6949 + }, + { + "path": "server/src/services/heartbeat/idle-recovery-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.9s in run 45238253588)", + "measuredMs": 6940 + }, + { + "path": "server/src/services/execution-recovery-dead-controller.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.9s in run 45238253588)", + "measuredMs": 6855 + }, + { + "path": "server/src/services/recovery/reconciliation-run-read.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.8s in run 45238253588)", + "measuredMs": 6847 + }, + { + "path": "server/src/services/execution-projection-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.8s in run 45238253588)", + "measuredMs": 6830 + }, + { + "path": "server/src/services/heartbeat/remote-workspace-source.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (6.8s in run 45238253588)", + "measuredMs": 6797 + }, + { + "path": "server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.7s in run 45238253588)", + "measuredMs": 6716 + }, + { + "path": "server/src/__tests__/idle-sleep-preparation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.6s in run 45238253588)", + "measuredMs": 6643 + }, + { + "path": "server/src/__tests__/attention-retention-candidates.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.6s in run 45238253588)", + "measuredMs": 6627 + }, + { + "path": "server/src/services/recovery/legacy-disposition-read.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.6s in run 45238253588)", + "measuredMs": 6591 + }, + { + "path": "server/src/__tests__/recovery-classifiers.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.5s in run 45238253588)", + "measuredMs": 6462 + }, + { + "path": "server/src/__tests__/chat-action-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.4s in run 45238253588)", + "measuredMs": 6415 + }, + { + "path": "server/src/__tests__/recovery-deadline-bootstrap.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.4s in run 45238253588)", + "measuredMs": 6390 + }, + { + "path": "server/src/services/native-runtime/native-workspace-queued-wake-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.4s in run 45238253588)", + "measuredMs": 6366 + }, + { + "path": "server/src/__tests__/email-idle-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.3s in run 45238253588)", + "measuredMs": 6264 + }, + { + "path": "server/src/__tests__/github-health-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", + "measuredMs": 6236 + }, + { + "path": "server/src/__tests__/chat-delivery-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", + "measuredMs": 6220 + }, + { + "path": "server/src/services/execution-recovery-resolution.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", + "measuredMs": 6207 + }, + { + "path": "server/src/services/native-runtime/native-recovery-usage-delivery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.2s in run 45238253588)", + "measuredMs": 6172 + }, + { + "path": "server/src/services/native-runtime/native-finalization-recovery-state.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", + "measuredMs": 6133 + }, + { + "path": "server/src/__tests__/issue-recovery-work-lifecycle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", + "measuredMs": 6108 + }, + { + "path": "server/src/services/idle-deadline-proof.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", + "measuredMs": 6083 + }, + { + "path": "server/src/services/native-runtime/native-recovery-preparation-failure.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.1s in run 45238253588)", + "measuredMs": 6054 + }, + { + "path": "server/src/services/system-recovery-state.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (6.0s in run 45238253588)", + "measuredMs": 6030 + }, + { + "path": "server/src/services/online-legacy-workspace-recovery.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (6.0s in run 45238253588)", + "measuredMs": 6018 + }, + { + "path": "server/src/services/execution-recovery-attempt.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.9s in run 45238253588)", + "measuredMs": 5915 + }, + { + "path": "server/src/services/recovery/review-path-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.6s in run 45238253588)", + "measuredMs": 5566 + }, + { + "path": "server/src/services/recovery/assigned-work-invariant.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.5s in run 45238253588)", + "measuredMs": 5474 + }, + { + "path": "server/src/modules/wake-queue/adapters/retryable-before-provider-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.2s in run 45238253588)", + "measuredMs": 5229 + }, + { + "path": "server/src/services/remote-workspace-archive-worker.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.2s in run 45238253588)", + "measuredMs": 5150 + }, + { + "path": "server/src/services/isolated-remote-workspace-source.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (5.1s in run 45238253588)", + "measuredMs": 5129 + }, + { + "path": "server/src/__tests__/recovery-deadline-ordinary-bootstrap.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (5.0s in run 45238253588)", + "measuredMs": 4981 + }, + { + "path": "server/src/services/legacy-execution-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (4.9s in run 45238253588)", + "measuredMs": 4882 + }, + { + "path": "server/src/services/native-runtime/native-run-log-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (4.8s in run 45238253588)", + "measuredMs": 4775 + }, + { + "path": "server/src/__tests__/voice-inbound-retention.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (4.7s in run 45238253588)", + "measuredMs": 4727 + }, + { + "path": "server/src/__tests__/import-spool-cleanup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (3.4s in run 45238253588)", + "measuredMs": 3447 + }, + { + "path": "server/src/services/skill-package-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (3.3s in run 45238253588)", + "measuredMs": 3323 + }, + { + "path": "server/src/services/chat-channels/github/review-check-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (3.2s in run 45238253588)", + "measuredMs": 3215 + }, + { + "path": "server/src/__tests__/plugin-idle-rpc.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (3.1s in run 45238253588)", + "measuredMs": 3073 + }, + { + "path": "server/src/__tests__/scoped-deadline-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (3.0s in run 45238253588)", + "measuredMs": 2998 + }, + { + "path": "server/src/services/remote-workspace-transfer-timeout.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (2.9s in run 45238253588)", + "measuredMs": 2876 + }, + { + "path": "server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", + "measuredMs": 2696 + }, + { + "path": "server/src/services/native-runtime/antigravity-credential-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.7s in run 45238253588)", + "measuredMs": 2691 + }, + { + "path": "server/src/__tests__/scheduled-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.5s in run 45238253588)", + "measuredMs": 2510 + }, + { + "path": "server/src/__tests__/custom-image-cleanup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.5s in run 45238253588)", + "measuredMs": 2507 + }, + { + "path": "server/src/services/remote-workspace-snapshot-archive-environments.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (2.5s in run 45238253588)", + "measuredMs": 2478 + }, + { + "path": "server/src/__tests__/provider-trace-retention-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.3s in run 45238253588)", + "measuredMs": 2344 + }, + { + "path": "server/src/services/public-mcp/idle-client-mirror.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.3s in run 45238253588)", + "measuredMs": 2297 + }, + { + "path": "server/src/services/public-mcp/idle-subscription-proof.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.3s in run 45238253588)", + "measuredMs": 2275 + }, + { + "path": "server/src/services/public-mcp/idle-device-status.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.3s in run 45238253588)", + "measuredMs": 2262 + }, + { + "path": "server/src/services/native-runtime/remote-runner-recovery-diagnostics.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.2s in run 45238253588)", + "measuredMs": 2182 + }, + { + "path": "server/src/__tests__/status-card-idle-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.1s in run 45238253588)", + "measuredMs": 2123 + }, + { + "path": "server/src/services/chat-channels/slack/idle-incoming.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.1s in run 45238253588)", + "measuredMs": 2089 + }, + { + "path": "server/src/__tests__/sleep-idle-work-capture.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.1s in run 45238253588)", + "measuredMs": 2055 + }, + { + "path": "server/src/services/chat-channels/discord/command-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.0s in run 45238253588)", + "measuredMs": 2014 + }, + { + "path": "server/src/__tests__/git-restore-point-expiration-config.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (2.0s in run 45238253588)", + "measuredMs": 1957 + }, + { + "path": "server/src/services/recovery/stranded-notice.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1926 + }, + { + "path": "server/src/__tests__/browser-use-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1905 + }, + { + "path": "server/src/services/skill-source-idle-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1902 + }, + { + "path": "server/src/__tests__/deadline-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1862 + }, + { + "path": "server/src/services/public-mcp/idle-transfer-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1862 + }, + { + "path": "server/src/services/recovery/successful-run-handoff.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.9s in run 45238253588)", + "measuredMs": 1860 + }, + { + "path": "server/src/services/idle-incoming-wake-capability.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.8s in run 45238253588)", + "measuredMs": 1842 + }, + { + "path": "server/src/__tests__/terminal-workspace-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.8s in run 45238253588)", + "measuredMs": 1814 + }, + { + "path": "server/src/__tests__/run-evidence-migration-work.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (1.8s in run 45238253588)", + "measuredMs": 1802 + }, + { + "path": "server/src/__tests__/database-backup-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.8s in run 45238253588)", + "measuredMs": 1755 + }, + { + "path": "server/src/services/public-mcp/idle-wake-proof.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.7s in run 45238253588)", + "measuredMs": 1661 + }, + { + "path": "server/src/__tests__/isolated-task-directory-retention-config.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (1.6s in run 45238253588)", + "measuredMs": 1632 + }, + { + "path": "server/src/__tests__/native-harness-backup-expiration-config.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.6s in run 45238253588)", + "measuredMs": 1632 + }, + { + "path": "server/src/services/public-mcp/idle-event-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.6s in run 45238253588)", + "measuredMs": 1615 + }, + { + "path": "server/src/services/native-runtime/remote-runner-recovery-probe.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.6s in run 45238253588)", + "measuredMs": 1601 + }, + { + "path": "server/src/__tests__/skill-version-retention-work.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (1.6s in run 45238253588)", + "measuredMs": 1585 + }, + { + "path": "server/src/__tests__/skill-version-retention-config.test.ts", + "category": "storage-integration-soak", + "reason": "Heavy object-storage, archive, or retention integration soak (1.5s in run 45238253588)", + "measuredMs": 1526 + }, + { + "path": "server/src/services/chat-channels/slack/form-ack-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.5s in run 45238253588)", + "measuredMs": 1521 + }, + { + "path": "server/src/__tests__/native-workspace-sync-retention-config.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.5s in run 45238253588)", + "measuredMs": 1494 + }, + { + "path": "server/src/__tests__/idle-admission.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.4s in run 45238253588)", + "measuredMs": 1366 + }, + { + "path": "server/src/maintenance/ephemeral-migration-service.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (1.3s in run 45238253588)", + "measuredMs": 1291 + }, + { + "path": "server/src/__tests__/recovery-cutover.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.1s in run 45238253588)", + "measuredMs": 1141 + }, + { + "path": "server/src/__tests__/static-ui-idle.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.1s in run 45238253588)", + "measuredMs": 1062 + }, + { + "path": "server/src/services/remote-workspace-readonly-inventory.test.ts", + "category": "workspace-recovery-soak", + "reason": "Remote/git workspace recovery, migration, or heavy working-copy soak (1.0s in run 45238253588)", + "measuredMs": 1027 + }, + { + "path": "server/src/__tests__/idle-database-backup.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (1.0s in run 45238253588)", + "measuredMs": 999 + }, + { + "path": "server/src/__tests__/external-object-idle-schedule.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.9s in run 45238253588)", + "measuredMs": 941 + }, + { + "path": "server/src/__tests__/idle-database-backup-sync.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.9s in run 45238253588)", + "measuredMs": 890 + }, + { + "path": "server/src/services/idle-api-activity.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.9s in run 45238253588)", + "measuredMs": 861 + }, + { + "path": "server/src/services/idle-api-wake-admission.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.8s in run 45238253588)", + "measuredMs": 773 + }, + { + "path": "server/src/services/recovery/legacy-continuation.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.8s in run 45238253588)", + "measuredMs": 773 + }, + { + "path": "server/src/services/native-runtime/native-runner-recovery-contract.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.8s in run 45238253588)", + "measuredMs": 769 + }, + { + "path": "server/src/__tests__/runner-api-recovery.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.7s in run 45238253588)", + "measuredMs": 741 + }, + { + "path": "server/src/startup-recovery-timing.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.7s in run 45238253588)", + "measuredMs": 696 + }, + { + "path": "server/src/__tests__/idle-scheduled-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.7s in run 45238253588)", + "measuredMs": 669 + }, + { + "path": "server/src/__tests__/idle-local-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.6s in run 45238253588)", + "measuredMs": 607 + }, + { + "path": "server/src/__tests__/mcp-task-work.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.6s in run 45238253588)", + "measuredMs": 602 + }, + { + "path": "server/src/services/recovery/status-only-context.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.6s in run 45238253588)", + "measuredMs": 579 + }, + { + "path": "server/src/__tests__/recovery-postgres-mode.test.ts", + "category": "recovery-idle-maintenance-soak", + "reason": "Real-clock recovery, census, idle-quietness, retention, deadline, or background-work soak (0.5s in run 45238253588)", + "measuredMs": 539 + } + ] +} diff --git a/scripts/ci/nightly-only-suites.mjs b/scripts/ci/nightly-only-suites.mjs new file mode 100644 index 00000000000..1ce2b02a640 --- /dev/null +++ b/scripts/ci/nightly-only-suites.mjs @@ -0,0 +1,67 @@ +import { existsSync, readFileSync } from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const ciScriptsDir = path.dirname(fileURLToPath(import.meta.url)); +export const PR_WORKFLOW_NAME = "PR"; + +export function resolveNightlyOnlySuitesPath({ + repoRoot = process.cwd(), + env = process.env, +} = {}) { + const override = env.PAPERCLIP_CI_NIGHTLY_SUITES_FILE?.trim(); + if (override) { + return path.resolve(repoRoot, override); + } + return path.join(ciScriptsDir, "nightly-only-suites.json"); +} + +export function loadNightlyOnlySuites(manifestPath) { + if (!existsSync(manifestPath)) { + return new Set(); + } + let parsed; + try { + parsed = JSON.parse(readFileSync(manifestPath, "utf8")); + } catch (error) { + throw new Error(`Failed to parse nightly-only suites manifest ${manifestPath}: ${error.message}`); + } + const entries = Array.isArray(parsed) ? parsed : parsed?.suites; + if (!Array.isArray(entries)) { + throw new Error(`Nightly-only suites manifest ${manifestPath} must contain a "suites" array.`); + } + const suites = new Set(); + for (const entry of entries) { + const suitePath = typeof entry === "string" ? entry : entry?.path; + if (typeof suitePath !== "string" || suitePath.trim() === "") { + throw new Error(`Invalid entry in nightly-only suites manifest ${manifestPath}.`); + } + suites.add(suitePath.trim().split(path.sep).join("/")); + } + return suites; +} + +export function isNightlyExclusionEnabled(env = process.env) { + const fullOverride = env.PAPERCLIP_CI_FULL?.trim().toLowerCase(); + if (fullOverride === "1" || fullOverride === "true") { + return false; + } + const excludeOverride = env.PAPERCLIP_CI_EXCLUDE_NIGHTLY?.trim().toLowerCase(); + if (excludeOverride === "0" || excludeOverride === "false") { + return false; + } + if (excludeOverride === "1" || excludeOverride === "true") { + return true; + } + return env.GITHUB_WORKFLOW === PR_WORKFLOW_NAME; +} + +export function activeNightlySuitesForEnv({ + repoRoot = process.cwd(), + env = process.env, +} = {}) { + if (!isNightlyExclusionEnabled(env)) { + return new Set(); + } + return loadNightlyOnlySuites(resolveNightlyOnlySuitesPath({ repoRoot, env })); +} diff --git a/scripts/ci/select-tests.mjs b/scripts/ci/select-tests.mjs index ca488c547bc..f53929144c1 100644 --- a/scripts/ci/select-tests.mjs +++ b/scripts/ci/select-tests.mjs @@ -4,6 +4,7 @@ import { fileURLToPath } from "node:url"; import path from "node:path"; import assert from "node:assert/strict"; import { refineTestPlan, selectionDurations } from "./test-selection-plan.mjs"; +import { activeNightlySuitesForEnv } from "./nightly-only-suites.mjs"; import { productInputs } from "../../.github/scripts/ci-inputs.mjs"; import { mergeDiff } from "../../.github/scripts/ci-diff.mjs"; import { selectProjects } from "./select-projects.mjs"; @@ -30,7 +31,7 @@ function runnerInventory(group) { const args = group === "serialized" ? ["--mode", "serialized", "--shard-index", "0", "--shard-count", "1"] : ["--mode", "general", "--group", group, ...(group === "general-server-without-chat" ? ["--shard-index", "0", "--shard-count", "1"] : [])]; - const env = { ...process.env, GITHUB_WORKFLOW: "PR" }; + const env = { ...process.env, GITHUB_WORKFLOW: "PR", PAPERCLIP_CI_FULL: "1" }; delete env.PAPERCLIP_CI_TEST_SELECTION; return JSON.parse(execFileSync(process.execPath, ["scripts/run-vitest-stable.mjs", ...args, "--dry-run"], { env, encoding: "utf8", maxBuffer: 16 * 1024 * 1024 })); @@ -77,7 +78,8 @@ export async function createTestSelection(plan, head) { ...native.selectedGeneralServerSuites, "server/src/__tests__/chat-channels.integration.test.ts"].sort(), server.inventory, "Server inventory must be completely covered by existing lane ownership"); } - return { ...refineTestPlan({ plan, head, owners, graphs, durations: selectionDurations() }), graphs }; + const excludedSuites = activeNightlySuitesForEnv(); + return { ...refineTestPlan({ plan, head, owners, graphs, durations: selectionDurations(), excludedSuites }), graphs }; } async function main() { diff --git a/scripts/ci/test-selection-manifest.mjs b/scripts/ci/test-selection-manifest.mjs index 50b46995d78..18910ef96f3 100644 --- a/scripts/ci/test-selection-manifest.mjs +++ b/scripts/ci/test-selection-manifest.mjs @@ -18,7 +18,7 @@ export function validateSelection(manifest, { head, hash } = {}) { const seen = new Set(); for (const [group, lane] of Object.entries(manifest.lanes)) { assert.ok(selectableGroups.includes(group), `Unknown selection group: ${group}`); - assert.ok(Array.isArray(lane.shards) && lane.shards.length > 0 && lane.shards.length <= 12); + assert.ok(Array.isArray(lane.shards) && lane.shards.length > 0 && lane.shards.length <= 24); for (const shard of lane.shards) { assert.ok(shard && typeof shard === "object" && !Array.isArray(shard)); let count = 0; diff --git a/scripts/ci/test-selection-plan.mjs b/scripts/ci/test-selection-plan.mjs index 309299c41fd..a9665af07c0 100644 --- a/scripts/ci/test-selection-plan.mjs +++ b/scripts/ci/test-selection-plan.mjs @@ -12,7 +12,7 @@ export function partitionSelection(inventory, selected, maxShards, durations = { return selected.length ? partitionGeneralServerSuites(selected, count, durations).map((shard) => shard.files) : []; } -export function refineTestPlan({ plan, head, owners, graphs, durations = {} }) { +export function refineTestPlan({ plan, head, owners, graphs, durations = {}, excludedSuites = new Set() }) { const result = structuredClone(plan); const manifest = { version: 1, head, lanes: {} }; const stats = []; @@ -38,7 +38,7 @@ export function refineTestPlan({ plan, head, owners, graphs, durations = {} }) { assert.ok(inventory.has(file), `Runner/Vitest inventory disagreement: ${file}`); assert.ok(!projectByFile.has(file), `Ambiguous owner: ${file}`); projectByFile.set(file, project); - if (affected.has(file)) selected.push(file); + if (affected.has(file) && !excludedSuites.has(file)) selected.push(file); } } const partitions = partitionSelection([...projectByFile.keys()], selected, original.length, durations[group]); diff --git a/scripts/ci/test-selection-pr-timings.test.mjs b/scripts/ci/test-selection-pr-timings.test.mjs index 2ab1bf03109..5b54873b827 100644 --- a/scripts/ci/test-selection-pr-timings.test.mjs +++ b/scripts/ci/test-selection-pr-timings.test.mjs @@ -237,10 +237,10 @@ test("collection skips unmerged, absent, stale-head and incomplete runs, and sam }); test("general server weights come from complete full-width PR shard sets that cover the lane", async () => { - assert.equal(generalServerShardCount(), 12); - assert.deepEqual(generalServerJob("ci / General tests (server (3/12))", 12), { index: 3, count: 12 }); - for (const name of ["ci / General tests (server (1/3))", "ci / General tests (chat (1/3))", "ci / Serialized tests (1/9)"]) { - assert.equal(generalServerJob(name, 12), null); + assert.equal(generalServerShardCount(), 20); + assert.deepEqual(generalServerJob("ci / General tests (server (3/20))", 20), { index: 3, count: 20 }); + for (const name of ["ci / General tests (server (1/3))", "ci / General tests (chat (1/5))", "ci / Serialized tests (1/9)"]) { + assert.equal(generalServerJob(name, 20), null); } const api = "/repos/paperclipai/paperclip"; const timing = (file, ms) => `2026-11-13T00:00:00.0000000Z ${timingPrefix}${JSON.stringify({ version: 1, file, durationMs: ms })}`; diff --git a/scripts/ci/test-selection.integration.test.mjs b/scripts/ci/test-selection.integration.test.mjs index 64ce85b5814..c74716a4fae 100644 --- a/scripts/ci/test-selection.integration.test.mjs +++ b/scripts/ci/test-selection.integration.test.mjs @@ -232,3 +232,35 @@ test("mixed audited documentation stays graph eligible and large complete source assert.ok(selectionEligibility({ ...plan, changed: ["doc/DEVELOPING.md"] })); assert.ok(selectionEligibility({ ...plan, changed: [...plan.changed, "docs/api/issues.md"] })); }); + +test("refineTestPlan applies nightly exclusions before partitioning while keeping full inventory validation", () => { + const nightlySuite = "server/src/__tests__/heartbeat-process-recovery.test.ts"; + const fastSuite = "server/src/__tests__/issues-service.test.ts"; + const entries = [0, 1].map((shard_index) => ({ + group: "general-server-without-chat", + group_label: `server (${shard_index + 1}/2)`, + shard_index, + shard_count: 2, + task: "ci:server", + })); + const plan = { + version: 1, + mode: "enabled", + forceReason: null, + changed: ["server/src/services/heartbeat.ts"], + jobs: { + general_tests: { run: true, matrix: { include: entries }, selected: 2, total: 2 }, + verify_serialized_server: { run: false, matrix: { include: [{ task: "ci:serialized" }] } }, + }, + }; + const owners = { "general-server-without-chat": { "@paperclipai/server": [nightlySuite, fastSuite] } }; + const graphs = [{ project: "@paperclipai/server", inventory: [nightlySuite, fastSuite], selected: [nightlySuite, fastSuite] }]; + + const prRefined = refineTestPlan({ plan, head, owners, graphs, excludedSuites: new Set([nightlySuite]) }); + const prFiles = prRefined.manifest.lanes["general-server-without-chat"].shards.flatMap((s) => s["@paperclipai/server"]); + assert.deepEqual(prFiles, [fastSuite], "PR selection must exclude nightly-only suites before partitioning"); + + const fullRefined = refineTestPlan({ plan, head, owners, graphs }); + const fullFiles = fullRefined.manifest.lanes["general-server-without-chat"].shards.flatMap((s) => s["@paperclipai/server"]); + assert.deepEqual(fullFiles.sort(), [fastSuite, nightlySuite].sort(), "full selection must retain nightly-only suites"); +}); diff --git a/scripts/ci/vitest-shared-postgres.mjs b/scripts/ci/vitest-shared-postgres.mjs new file mode 100644 index 00000000000..79c85802a31 --- /dev/null +++ b/scripts/ci/vitest-shared-postgres.mjs @@ -0,0 +1,90 @@ +import { spawn } from "node:child_process"; +import { existsSync } from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { pathToFileURL } from "node:url"; + +export function resolveTsxLoaderPath(repoRoot) { + const candidates = [ + path.join(repoRoot, "packages", "db", "node_modules", "tsx", "dist", "loader.mjs"), + path.join(repoRoot, "node_modules", "tsx", "dist", "loader.mjs"), + path.join(repoRoot, "cli", "node_modules", "tsx", "dist", "loader.mjs"), + ]; + return candidates.find((candidate) => existsSync(candidate)) ?? null; +} + +export function shouldWrapWithSharedPostgres({ + repoRoot, + dryRun, + hasSharedTestDatabase, + usesPostgres, + hasScheduledSuites, + env = process.env, +}) { + if (dryRun) return false; + if (env.PAPERCLIP_TEST_POSTGRES_ADMIN_URL?.trim()) return false; + if (hasSharedTestDatabase) return false; + const sharedOverride = env.PAPERCLIP_TEST_POSTGRES_SHARED?.trim().toLowerCase(); + if (sharedOverride === "0" || sharedOverride === "false") return false; + // Mocked-pnpm node:test harnesses run under NODE_TEST_CONTEXT; don't boot a + // real Postgres cluster for unit tests unless explicitly opted in. + if (env.NODE_TEST_CONTEXT && sharedOverride !== "1" && sharedOverride !== "true") return false; + if (!usesPostgres) return false; + if (!hasScheduledSuites) return false; + const wrapperScript = path.join(repoRoot, "packages", "db", "src", "test-postgres-command.ts"); + if (!existsSync(wrapperScript)) return false; + return resolveTsxLoaderPath(repoRoot) !== null; +} + +export async function runUnderSharedPostgres({ + repoRoot, + runnerScriptPath, + argv = process.argv.slice(2), + env = process.env, +}) { + const tsxLoader = resolveTsxLoaderPath(repoRoot); + const wrapperScript = path.join(repoRoot, "packages", "db", "src", "test-postgres-command.ts"); + const child = spawn( + process.execPath, + [ + "--import", + pathToFileURL(tsxLoader).href, + wrapperScript, + "--", + process.execPath, + runnerScriptPath, + ...argv, + ], + { + cwd: repoRoot, + env, + stdio: "inherit", + }, + ); + const forwardSignal = (signal) => { + if (child.exitCode === null && child.signalCode === null) { + try { + child.kill(signal); + } catch { + // Ignore ESRCH if child already exited. + } + } + }; + process.on("SIGINT", forwardSignal); + process.on("SIGTERM", forwardSignal); + process.on("SIGHUP", forwardSignal); + try { + const status = await new Promise((resolve, reject) => { + child.once("error", reject); + child.once("exit", (code, signal) => { + if (signal) resolve(128 + (os.constants.signals[signal] ?? 1)); + else resolve(code ?? 1); + }); + }); + process.exitCode = status; + } finally { + process.removeListener("SIGINT", forwardSignal); + process.removeListener("SIGTERM", forwardSignal); + process.removeListener("SIGHUP", forwardSignal); + } +} diff --git a/scripts/e2e-shard-durations.json b/scripts/e2e-shard-durations.json index 7b91c42c0a7..befb5135e66 100644 --- a/scripts/e2e-shard-durations.json +++ b/scripts/e2e-shard-durations.json @@ -25,9 +25,9 @@ } ], "coverage": { - "measured": 56, - "withSetup": 56, - "inventory": 56 + "measured": 51, + "withSetup": 51, + "inventory": 51 }, "durations": { "tests/e2e/acp-stop-continuation.spec.ts": 67299, @@ -35,52 +35,47 @@ "tests/e2e/agent-chat-messages.spec.ts": 23569, "tests/e2e/agent-chat-projects.spec.ts": 206156, "tests/e2e/agent-chat-sessions.spec.ts": 117218, - "tests/e2e/agent-configuration.spec.ts": 105794, + "tests/e2e/agent-configuration.spec.ts": 109800, "tests/e2e/agentmail.spec.ts": 27227, "tests/e2e/ai-personal-connection-recovery.spec.ts": 12373, "tests/e2e/announcement-first-session.spec.ts": 9986, "tests/e2e/announcement-placement.spec.ts": 18485, "tests/e2e/app-not-connected.spec.ts": 10832, - "tests/e2e/application-delete-screenshot.spec.ts": 2970, - "tests/e2e/applications-crud.spec.ts": 23859, - "tests/e2e/apps-dark-mode-shots.spec.ts": 18910, + "tests/e2e/applications-crud.spec.ts": 15000, "tests/e2e/apps-prosumer-mcp-flow.spec.ts": 13276, "tests/e2e/archived-company-url.spec.ts": 6145, - "tests/e2e/artifact-tab-arrival.spec.ts": 20087, + "tests/e2e/artifact-tab-arrival.spec.ts": 19900, "tests/e2e/artifact-uploads.spec.ts": 28200, "tests/e2e/board-attachment-receipts.spec.ts": 112020, - "tests/e2e/cases-read-only.spec.ts": 9657, + "tests/e2e/cases-read-only.spec.ts": 12700, "tests/e2e/chat-adapters-ui-messaging.spec.ts": 181303, "tests/e2e/chat-adapters-ui-providers.spec.ts": 181541, "tests/e2e/chunk-load-recovery.spec.ts": 16330, - "tests/e2e/classic-workspace.spec.ts": 6483, + "tests/e2e/classic-workspace.spec.ts": 8000, "tests/e2e/cloud-auth.spec.ts": 33711, "tests/e2e/company-context-refresh.spec.ts": 4128, "tests/e2e/completed-task-paused-assignee.spec.ts": 25016, - "tests/e2e/composer-stop.spec.ts": 74978, + "tests/e2e/composer-stop.spec.ts": 55500, "tests/e2e/conference-room-typing-intro.spec.ts": 30042, - "tests/e2e/connection-intents.spec.ts": 23775, - "tests/e2e/connection-reviews.spec.ts": 134583, + "tests/e2e/connection-intents.spec.ts": 20100, + "tests/e2e/connection-reviews.spec.ts": 75000, "tests/e2e/coordinator-inbox-views.spec.ts": 18241, "tests/e2e/daytona-connector.spec.ts": 2603, - "tests/e2e/disconnect-resilience.spec.ts": 200278, + "tests/e2e/disconnect-resilience.spec.ts": 55000, "tests/e2e/disconnect-write-recovery.spec.ts": 51072, "tests/e2e/document-image-gallery.spec.ts": 46344, - "tests/e2e/legacy-failure-continuation.spec.ts": 89961, "tests/e2e/mcp-user-stories.spec.ts": 37417, "tests/e2e/new-task-picker-touch.spec.ts": 22514, - "tests/e2e/nux-phase4-screenshots.spec.ts": 11330, - "tests/e2e/onboarding.spec.ts": 62933, + "tests/e2e/onboarding.spec.ts": 68700, "tests/e2e/paused-composer.spec.ts": 38240, "tests/e2e/plan-task-fixture.spec.ts": 7828, - "tests/e2e/planning-mode-visual-verification.spec.ts": 26325, "tests/e2e/project-repositories.spec.ts": 13403, "tests/e2e/railway-catalog.spec.ts": 2813, "tests/e2e/runner-e2e-dashboard.spec.ts": 4985, "tests/e2e/runner-task-creation.spec.ts": 32437, "tests/e2e/sidebar-takeover.spec.ts": 9119, "tests/e2e/signoff-policy.spec.ts": 52229, - "tests/e2e/smoke-lab-p1-p4.spec.ts": 22390, + "tests/e2e/smoke-lab-p1-p4.spec.ts": 19700, "tests/e2e/smoke-lab-p5-p7.spec.ts": 16416, "tests/e2e/task-loading-frame.spec.ts": 31309, "tests/e2e/task-reload.spec.ts": 20988, diff --git a/scripts/e2e-shard.mjs b/scripts/e2e-shard.mjs index d206f58e505..d07610aec2e 100644 --- a/scripts/e2e-shard.mjs +++ b/scripts/e2e-shard.mjs @@ -14,6 +14,31 @@ const DURATIONS_MANIFEST = path.join(HERE, "e2e-shard-durations.json"); // test in scripts/__tests__/e2e-shard.test.mjs fails if the two ever drift. export const IGNORED_SPECS = ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"]; +// Specs that mutate instance-wide state on the shared throwaway server or +// assert strict real-time latency / focus restoration sensitive to concurrent +// Chromium contention, and therefore must run with `workers: 1`. Keep in sync +// with `SERIAL_SPECS` in tests/e2e/playwright.config.ts — +// `scripts/__tests__/e2e-shard.test.mjs` fails if the two ever drift. +export const SERIAL_SPECS = [ + "agent-configuration.spec.ts", + "cases-read-only.spec.ts", + "classic-workspace.spec.ts", + "composer-stop.spec.ts", + "connection-intents.spec.ts", + "document-image-gallery.spec.ts", + "onboarding.spec.ts", + "smoke-lab-p1-p4.spec.ts", + "smoke-lab-p5-p7.spec.ts", +]; + +// Matches the CI worker count in tests/e2e/playwright.config.ts for shards +// that contain only parallel-safe specs. +export const DEFAULT_PARALLEL_WORKERS = 2; + +export function isSerialE2eSpec(file) { + return SERIAL_SPECS.includes(path.posix.basename(file.split(path.sep).join("/"))); +} + // Enumerates the specs the default e2e lane actually runs, as repo-relative // paths so the output can be handed straight to `playwright test`. export function listE2eSpecs(e2eDir = E2E_DIR, repoRoot = REPO_ROOT) { @@ -23,12 +48,63 @@ export function listE2eSpecs(e2eDir = E2E_DIR, repoRoot = REPO_ROOT) { .sort((a, b) => a.localeCompare(b)); } -// Playwright's own --shard balances by test count, which is useless here: one -// spec (smoke-lab) is ~40% of the lane's wall clock. Reuse the deterministic -// longest-processing-time partition already proven on the general-server lane -// so every runner computes the identical, non-overlapping split. -export function selectE2eShard(files, shardIndex, shardCount, durations = {}) { - return partitionGeneralServerSuites(files, shardCount, durations)[shardIndex].files; +// Isolate instance-mutating specs onto dedicated serial shards so every other +// shard runs purely parallel-safe specs with `workers > 1` and `fullyParallel`. +// Choose the serial/parallel shard split that minimizes projected max wall-clock +// across all shards (serial shards run at 1x, parallel shards at 1/parallelWorkers). +export function partitionE2eShards( + files, + shardCount, + durations = {}, + { parallelWorkers = DEFAULT_PARALLEL_WORKERS } = {}, +) { + const serialFiles = files.filter(isSerialE2eSpec); + const parallelFiles = files.filter((file) => !isSerialE2eSpec(file)); + + if (shardCount <= 1 || serialFiles.length === 0 || parallelFiles.length === 0) { + const mode = serialFiles.length > 0 ? "serial" : "parallel"; + const effectiveWorkers = mode === "parallel" ? parallelWorkers : 1; + return partitionGeneralServerSuites(files, shardCount, durations).map((shard) => ({ + ...shard, + mode, + estimatedWallMs: shard.totalWeight / effectiveWorkers, + })); + } + + const maxSerialShards = Math.min(serialFiles.length, shardCount - 1); + let bestPlan = null; + + for (let serialShardCount = 1; serialShardCount <= maxSerialShards; serialShardCount += 1) { + const parallelShardCount = shardCount - serialShardCount; + if (parallelShardCount > parallelFiles.length) continue; + + const serialShards = partitionGeneralServerSuites(serialFiles, serialShardCount, durations).map((shard) => ({ + ...shard, + mode: "serial", + estimatedWallMs: shard.totalWeight, + })); + const parallelShards = partitionGeneralServerSuites(parallelFiles, parallelShardCount, durations).map((shard) => ({ + ...shard, + mode: "parallel", + estimatedWallMs: shard.totalWeight / parallelWorkers, + })); + const combined = [...serialShards, ...parallelShards]; + const maxWallMs = Math.max(...combined.map((shard) => shard.estimatedWallMs)); + + if (!bestPlan || maxWallMs < bestPlan.maxWallMs) { + bestPlan = { maxWallMs, shards: combined }; + } + } + + return bestPlan.shards; +} + +// Playwright's own --shard balances by test count, which is useless here: spec +// durations vary by 80x and a handful of specs mutate instance-wide settings. +// Partition into dedicated serial and parallel shards weighted by estimated +// wall-clock time so every runner finishes together. +export function selectE2eShard(files, shardIndex, shardCount, durations = {}, options = {}) { + return partitionE2eShards(files, shardCount, durations, options)[shardIndex].files; } function parseArgs(argv) { diff --git a/scripts/general-server-shard-durations.json b/scripts/general-server-shard-durations.json index bc915a450f3..0f158636879 100644 --- a/scripts/general-server-shard-durations.json +++ b/scripts/general-server-shard-durations.json @@ -3,1839 +3,2026 @@ "unit": "ms", "sources": [ { - "pull": 21385, - "run": 43439145752, + "pull": 22679, + "run": 45238253588, "attempt": 1, - "sha": "1ea680d1f0f767cb6e5249d7e98ea694f523f1c6", - "url": "https://github.com/paperclipai/paperclip/actions/runs/43439145752" - }, - { - "pull": 21384, - "run": 43439279537, - "attempt": 1, - "sha": "dfb265766578f2720723866683bf8e9bd4060e2e", - "url": "https://github.com/paperclipai/paperclip/actions/runs/43439279537" + "sha": "8d513d5b1ab8fbfa2905d41be44c165b03a8a320", + "url": "https://github.com/paperclipai/paperclip/actions/runs/45238253588" } ], "coverage": { - "measured": 1826, - "withSetup": 1826, - "inventory": 1882 + "measured": 2052, + "withSetup": 2052, + "inventory": 2033 }, "durations": { - "server/scripts/bundle-runtime.test.mjs": 1503, - "server/scripts/prepare-runner-vendor.test.mjs": 740, - "server/scripts/reporting-lock-policy.test.mjs": 114, - "server/scripts/sleep-otel-setup.test.mjs": 192, - "server/scripts/sleep-qualification.test.mjs": 277, - "server/scripts/typecheck-layers.test.mjs": 6115, - "server/scripts/verify-runner-vendor-dependencies.test.mjs": 133, - "server/src/__tests__/abandoned-workspace-files-hold.test.ts": 17494, - "server/src/__tests__/access-service.test.ts": 8064, - "server/src/__tests__/access-validators.test.ts": 855, - "server/src/__tests__/activity-credential-access.test.ts": 6036, - "server/src/__tests__/activity-log-responsible-user.test.ts": 6101, - "server/src/__tests__/activity-service.test.ts": 9535, - "server/src/__tests__/adapter-cost-failure-paths.test.ts": 7250, - "server/src/__tests__/adapter-models.test.ts": 4684, - "server/src/__tests__/adapter-registry.test.ts": 5305, - "server/src/__tests__/adapter-session-codecs.test.ts": 1167, - "server/src/__tests__/admission-independent-of-cleanup.test.ts": 13589, - "server/src/__tests__/agent-auth-identity-transfer.test.ts": 6042, - "server/src/__tests__/agent-auth-jwt.test.ts": 1009, - "server/src/__tests__/agent-auth-middleware.test.ts": 5196, - "server/src/__tests__/agent-avatars.test.ts": 9010, - "server/src/__tests__/agent-budget-configuration.test.ts": 4831, - "server/src/__tests__/agent-chat-messages.test.ts": 18694, - "server/src/__tests__/agent-commentary-daytona-smoke.test.ts": 1902, - "server/src/__tests__/agent-commentary-helper.test.ts": 11369, - "server/src/__tests__/agent-commentary-reader.test.ts": 6885, - "server/src/__tests__/agent-commentary-skills.test.ts": 1213, - "server/src/__tests__/agent-commentary.integration.test.ts": 19043, - "server/src/__tests__/agent-config-read-access.test.ts": 7540, - "server/src/__tests__/agent-configuration-revision.test.ts": 959, - "server/src/__tests__/agent-configuration-save.test.ts": 10679, - "server/src/__tests__/agent-conversation-delivery.test.ts": 7211, - "server/src/__tests__/agent-conversations.test.ts": 17475, - "server/src/__tests__/agent-default-configure-grants.test.ts": 4648, - "server/src/__tests__/agent-directory-lock-crash-point.test.ts": 4354, - "server/src/__tests__/agent-directory-probe.test.ts": 2234, - "server/src/__tests__/agent-directory-working-copies.test.ts": 75279, - "server/src/__tests__/agent-file-checkpoints.test.ts": 5451, - "server/src/__tests__/agent-file-durability.test.ts": 15683, - "server/src/__tests__/agent-harness-verification-preflight.test.ts": 7621, - "server/src/__tests__/agent-harness-verification-provider-api.test.ts": 15137, - "server/src/__tests__/agent-harness-verification-remote.test.ts": 4967, - "server/src/__tests__/agent-harness-verification.test.ts": 5179, - "server/src/__tests__/agent-hire-ai-connections.test.ts": 27904, - "server/src/__tests__/agent-identity-master-key.test.ts": 475, - "server/src/__tests__/agent-identity.test.ts": 27739, - "server/src/__tests__/agent-instance-secrets.test.ts": 8770, - "server/src/__tests__/agent-instruction-git-exclusion.test.ts": 452, - "server/src/__tests__/agent-instruction-revisions.test.ts": 6917, - "server/src/__tests__/agent-instruction-working-copies.test.ts": 26167, - "server/src/__tests__/agent-instructions-service.test.ts": 5765, - "server/src/__tests__/agent-interaction-acceptance.test.ts": 80358, - "server/src/__tests__/agent-interaction-mutations.test.ts": 7834, - "server/src/__tests__/agent-interaction-permissions.test.ts": 22629, - "server/src/__tests__/agent-interaction-policy.test.ts": 2894, - "server/src/__tests__/agent-invokability.test.ts": 1586, - "server/src/__tests__/agent-observability-status-guidance.test.ts": 2863, - "server/src/__tests__/agent-observability-test.test.ts": 1468, - "server/src/__tests__/agent-observability.test.ts": 7331, - "server/src/__tests__/agent-permission-grants.test.ts": 4866, - "server/src/__tests__/agent-permissions-service.test.ts": 934, - "server/src/__tests__/agent-persona-persistence.test.ts": 5778, - "server/src/__tests__/agent-profile-avatar.test.ts": 8470, - "server/src/__tests__/agent-project-access.test.ts": 8093, - "server/src/__tests__/agent-provider-rate-limits.test.ts": 7250, - "server/src/__tests__/agent-record-read-projections.test.ts": 6276, - "server/src/__tests__/agent-refusal-finality.test.ts": 5217, - "server/src/__tests__/agent-run-authentication.test.ts": 2835, - "server/src/__tests__/agent-runner-platform.test.ts": 4117, - "server/src/__tests__/agent-runtime-assignments.test.ts": 7635, - "server/src/__tests__/agent-runtime-connector-access.test.ts": 8675, - "server/src/__tests__/agent-runtime-hooks.test.ts": 20055, - "server/src/__tests__/agent-runtime-settings.test.ts": 756, - "server/src/__tests__/agent-runtime-skills.test.ts": 5583, - "server/src/__tests__/agent-runtime-tool-definitions.test.ts": 9834, - "server/src/__tests__/agent-setup-connection-intents.test.ts": 6618, - "server/src/__tests__/agent-shortname-collision.test.ts": 4943, - "server/src/__tests__/agent-skill-contract.test.ts": 172, - "server/src/__tests__/agent-task-hierarchy-depth.test.ts": 7231, - "server/src/__tests__/agent-task-run-telemetry.test.ts": 2731, + "server/scripts/bundle-runtime.test.mjs": 2860, + "server/scripts/prepare-runner-vendor.test.mjs": 1759, + "server/scripts/reporting-lock-policy.test.mjs": 798, + "server/scripts/sleep-otel-setup.test.mjs": 791, + "server/scripts/sleep-qualification.test.mjs": 908, + "server/scripts/typecheck-layers.test.mjs": 7818, + "server/scripts/verify-runner-vendor-dependencies.test.mjs": 1068, + "server/src/__tests__/abandoned-workspace-files-hold.test.ts": 15152, + "server/src/__tests__/access-service.test.ts": 9874, + "server/src/__tests__/access-validators.test.ts": 1606, + "server/src/__tests__/activity-credential-access.test.ts": 6480, + "server/src/__tests__/activity-log-responsible-user.test.ts": 8056, + "server/src/__tests__/activity-service.test.ts": 11380, + "server/src/__tests__/adapter-cost-failure-paths.test.ts": 7243, + "server/src/__tests__/adapter-models.test.ts": 5837, + "server/src/__tests__/adapter-registry.test.ts": 6247, + "server/src/__tests__/adapter-session-codecs.test.ts": 1808, + "server/src/__tests__/admission-independent-of-cleanup.test.ts": 10330, + "server/src/__tests__/agent-auth-identity-transfer.test.ts": 7068, + "server/src/__tests__/agent-auth-jwt.test.ts": 1662, + "server/src/__tests__/agent-auth-middleware.test.ts": 6299, + "server/src/__tests__/agent-auth-prepared-statements.test.ts": 6177, + "server/src/__tests__/agent-avatars.test.ts": 7769, + "server/src/__tests__/agent-budget-configuration.test.ts": 7808, + "server/src/__tests__/agent-chat-messages.test.ts": 34676, + "server/src/__tests__/agent-commentary-daytona-smoke.test.ts": 2229, + "server/src/__tests__/agent-commentary-helper.test.ts": 12029, + "server/src/__tests__/agent-commentary-reader.test.ts": 6994, + "server/src/__tests__/agent-commentary-skills.test.ts": 1745, + "server/src/__tests__/agent-commentary.integration.test.ts": 16813, + "server/src/__tests__/agent-config-read-access.test.ts": 9434, + "server/src/__tests__/agent-configuration-revision.test.ts": 1934, + "server/src/__tests__/agent-configuration-save.test.ts": 9334, + "server/src/__tests__/agent-connection-catalog.integration.test.ts": 7637, + "server/src/__tests__/agent-conversation-delivery.test.ts": 9155, + "server/src/__tests__/agent-conversations.test.ts": 30413, + "server/src/__tests__/agent-default-configure-grants.test.ts": 6637, + "server/src/__tests__/agent-directory-lock-crash-point.test.ts": 6090, + "server/src/__tests__/agent-directory-probe.test.ts": 3480, + "server/src/__tests__/agent-directory-remote-checkpoint-lock.test.ts": 11799, + "server/src/__tests__/agent-directory-working-copies.test.ts": 110993, + "server/src/__tests__/agent-file-checkpoint-locking.test.ts": 10603, + "server/src/__tests__/agent-file-checkpoints.test.ts": 5828, + "server/src/__tests__/agent-file-durability.test.ts": 19117, + "server/src/__tests__/agent-file-restore-locking.test.ts": 7419, + "server/src/__tests__/agent-harness-verification-preflight.test.ts": 7845, + "server/src/__tests__/agent-harness-verification-provider-api.test.ts": 10297, + "server/src/__tests__/agent-harness-verification-remote.test.ts": 6926, + "server/src/__tests__/agent-harness-verification.test.ts": 6941, + "server/src/__tests__/agent-hire-ai-connections.test.ts": 28940, + "server/src/__tests__/agent-identity-master-key.test.ts": 1135, + "server/src/__tests__/agent-identity.test.ts": 31776, + "server/src/__tests__/agent-instance-secrets.test.ts": 10141, + "server/src/__tests__/agent-instruction-copy-retry-backoff.test.ts": 10912, + "server/src/__tests__/agent-instruction-git-exclusion.test.ts": 3116, + "server/src/__tests__/agent-instruction-revisions.test.ts": 6931, + "server/src/__tests__/agent-instruction-working-copies.test.ts": 37991, + "server/src/__tests__/agent-instructions-service.test.ts": 6897, + "server/src/__tests__/agent-interaction-acceptance.test.ts": 85112, + "server/src/__tests__/agent-interaction-mutations.test.ts": 9010, + "server/src/__tests__/agent-interaction-permissions.test.ts": 29587, + "server/src/__tests__/agent-interaction-policy.test.ts": 2520, + "server/src/__tests__/agent-invokability.test.ts": 1853, + "server/src/__tests__/agent-jwt-request-authentication.test.ts": 7439, + "server/src/__tests__/agent-observability-test.test.ts": 2108, + "server/src/__tests__/agent-observability.test.ts": 9432, + "server/src/__tests__/agent-permission-grants.test.ts": 6963, + "server/src/__tests__/agent-permissions-service.test.ts": 1282, + "server/src/__tests__/agent-persona-persistence.test.ts": 5549, + "server/src/__tests__/agent-profile-avatar.test.ts": 10716, + "server/src/__tests__/agent-project-access.test.ts": 8430, + "server/src/__tests__/agent-provider-rate-limits.test.ts": 7894, + "server/src/__tests__/agent-record-read-projections.test.ts": 7836, + "server/src/__tests__/agent-refusal-finality.test.ts": 5599, + "server/src/__tests__/agent-reporting-chain.test.ts": 11480, + "server/src/__tests__/agent-run-authentication.test.ts": 7411, + "server/src/__tests__/agent-runner-platform.test.ts": 5151, + "server/src/__tests__/agent-runtime-assignments.test.ts": 10426, + "server/src/__tests__/agent-runtime-connector-access.test.ts": 9324, + "server/src/__tests__/agent-runtime-hooks.test.ts": 21201, + "server/src/__tests__/agent-runtime-settings.test.ts": 1539, + "server/src/__tests__/agent-runtime-skills.test.ts": 8161, + "server/src/__tests__/agent-runtime-tool-definitions.test.ts": 13696, + "server/src/__tests__/agent-scaling-load-model.test.ts": 55895, + "server/src/__tests__/agent-setup-connection-intents.test.ts": 10060, + "server/src/__tests__/agent-shortname-collision.test.ts": 7092, + "server/src/__tests__/agent-skill-contract.test.ts": 776, + "server/src/__tests__/agent-task-hierarchy-depth.test.ts": 8587, + "server/src/__tests__/agent-task-run-telemetry.test.ts": 3688, "server/src/__tests__/agent-timer-deadlines.test.ts": 49401, - "server/src/__tests__/agent-volume-free-config-patch.test.ts": 6705, - "server/src/__tests__/agentmail-api.test.ts": 2507, - "server/src/__tests__/agents-adapter-config-user-secret.test.ts": 6673, - "server/src/__tests__/agents-claude-oauth-binding.test.ts": 8312, - "server/src/__tests__/agents-paperclip-runner-skills.test.ts": 823, - "server/src/__tests__/agents-pending-approval-config.test.ts": 6979, - "server/src/__tests__/agents-service-clear-error.test.ts": 5735, - "server/src/__tests__/agents-service-secret-bindings.test.ts": 6251, - "server/src/__tests__/aggregator-app-discovery.test.ts": 207, - "server/src/__tests__/aggregator-app-sync.test.ts": 8843, - "server/src/__tests__/ai-auth-failure.test.ts": 868, - "server/src/__tests__/ai-connection-binding-mode.test.ts": 4265, - "server/src/__tests__/ai-connection-session.test.ts": 6480, - "server/src/__tests__/ai-connections.test.ts": 75384, - "server/src/__tests__/ai-legacy-compatibility.test.ts": 5866, - "server/src/__tests__/ai-provider-routing.test.ts": 839, - "server/src/__tests__/announcement-animation.test.ts": 1972, - "server/src/__tests__/announcement-feed.test.ts": 1706, - "server/src/__tests__/announcement-publisher.test.ts": 1546, - "server/src/__tests__/antigravity-ai-connections.integration.test.ts": 9347, - "server/src/__tests__/antigravity-ai-runtime.test.ts": 5349, - "server/src/__tests__/antigravity-connection-models.test.ts": 412, - "server/src/__tests__/antigravity-connection-probe.test.ts": 739, - "server/src/__tests__/antigravity-local-ai-login.test.ts": 2207, - "server/src/__tests__/antigravity-managed-subscription.test.ts": 2538, - "server/src/__tests__/api-compression.test.ts": 262, - "server/src/__tests__/api-server-timing.test.ts": 226, - "server/src/__tests__/app-hmr-port.test.ts": 8984, - "server/src/__tests__/app-private-hostname-gate.test.ts": 7543, - "server/src/__tests__/app-vite-dev-routing.test.ts": 6632, - "server/src/__tests__/approval-queue-seeding-work.test.ts": 30216, - "server/src/__tests__/approval-retention-work.test.ts": 29241, - "server/src/__tests__/approvals-service.test.ts": 3795, - "server/src/__tests__/archived-nested-repository.test.ts": 17837, - "server/src/__tests__/artifact-review-documents-service.test.ts": 2993, - "server/src/__tests__/assigned-work-invariant.test.ts": 20750, - "server/src/__tests__/assigned-work-sweep-round-trips.test.ts": 10045, - "server/src/__tests__/assistant-connections-guidance.test.ts": 2971, - "server/src/__tests__/attachment-types.test.ts": 114, - "server/src/__tests__/attention-audience-service.test.ts": 18156, - "server/src/__tests__/attention-close.test.ts": 24541, - "server/src/__tests__/attention-current-cards.test.ts": 16322, - "server/src/__tests__/attention-escalation-owners.test.ts": 13588, - "server/src/__tests__/attention-excerpt.test.ts": 4548, - "server/src/__tests__/attention-obligations.test.ts": 11888, - "server/src/__tests__/attention-receipts.test.ts": 15661, - "server/src/__tests__/attention-retention-candidates.test.ts": 6329, + "server/src/__tests__/agent-volume-free-config-patch.test.ts": 6909, + "server/src/__tests__/agentmail-api.test.ts": 3318, + "server/src/__tests__/agents-adapter-config-user-secret.test.ts": 7788, + "server/src/__tests__/agents-claude-oauth-binding.test.ts": 9167, + "server/src/__tests__/agents-paperclip-runner-skills.test.ts": 1727, + "server/src/__tests__/agents-pending-approval-config.test.ts": 11998, + "server/src/__tests__/agents-service-clear-error.test.ts": 7321, + "server/src/__tests__/agents-service-secret-bindings.test.ts": 7450, + "server/src/__tests__/aggregator-app-discovery.test.ts": 1113, + "server/src/__tests__/aggregator-app-sync.test.ts": 9054, + "server/src/__tests__/ai-auth-failure.test.ts": 1892, + "server/src/__tests__/ai-connection-binding-mode.test.ts": 7792, + "server/src/__tests__/ai-connection-session.test.ts": 6830, + "server/src/__tests__/ai-connections.test.ts": 62434, + "server/src/__tests__/ai-legacy-compatibility.test.ts": 7545, + "server/src/__tests__/ai-provider-routing.test.ts": 1945, + "server/src/__tests__/announcement-animation.test.ts": 2350, + "server/src/__tests__/announcement-feed.test.ts": 2274, + "server/src/__tests__/announcement-publisher.test.ts": 2273, + "server/src/__tests__/antigravity-ai-connections.integration.test.ts": 9951, + "server/src/__tests__/antigravity-ai-runtime.test.ts": 7446, + "server/src/__tests__/antigravity-connection-models.test.ts": 1130, + "server/src/__tests__/antigravity-connection-probe.test.ts": 2751, + "server/src/__tests__/antigravity-local-ai-login.test.ts": 2883, + "server/src/__tests__/antigravity-managed-subscription.test.ts": 3205, + "server/src/__tests__/api-compression.test.ts": 1020, + "server/src/__tests__/api-server-timing.test.ts": 728, + "server/src/__tests__/app-hmr-port.test.ts": 9594, + "server/src/__tests__/app-permission-save.test.ts": 8509, + "server/src/__tests__/app-private-hostname-gate.test.ts": 9394, + "server/src/__tests__/app-vite-dev-routing.test.ts": 10177, + "server/src/__tests__/approval-queue-seeding-work.test.ts": 42153, + "server/src/__tests__/approval-retention-work.test.ts": 28754, + "server/src/__tests__/approvals-service.test.ts": 7905, + "server/src/__tests__/archived-nested-repository.test.ts": 16037, + "server/src/__tests__/artifact-review-documents-service.test.ts": 3519, + "server/src/__tests__/assigned-work-invariant.test.ts": 35951, + "server/src/__tests__/assigned-work-recheck-idle.test.ts": 53061, + "server/src/__tests__/assigned-work-stalled-queued-run.test.ts": 13543, + "server/src/__tests__/assigned-work-sweep-round-trips.test.ts": 15224, + "server/src/__tests__/attachment-types.test.ts": 1034, + "server/src/__tests__/attention-audience-service.test.ts": 17695, + "server/src/__tests__/attention-close.test.ts": 28295, + "server/src/__tests__/attention-current-cards.test.ts": 13125, + "server/src/__tests__/attention-escalation-owners.test.ts": 13872, + "server/src/__tests__/attention-excerpt.test.ts": 9944, + "server/src/__tests__/attention-obligations.test.ts": 12566, + "server/src/__tests__/attention-receipts.test.ts": 12603, + "server/src/__tests__/attention-retention-candidates.test.ts": 6627, "server/src/__tests__/attention-retention-work.test.ts": 77085, - "server/src/__tests__/attention-service.test.ts": 106641, - "server/src/__tests__/attention-source-eligibility.test.ts": 1738, - "server/src/__tests__/attention-summary-counts.test.ts": 54463, - "server/src/__tests__/authorization-privacy-query.test.ts": 8610, - "server/src/__tests__/authorization-run-context.test.ts": 2761, - "server/src/__tests__/authorization-service.test.ts": 6860, - "server/src/__tests__/aws-secrets-manager-provider.test.ts": 260, - "server/src/__tests__/batched-chat-authorization.integration.test.ts": 5804, - "server/src/__tests__/better-auth-credential-signup.integration.test.ts": 2400, - "server/src/__tests__/better-auth.test.ts": 2118, - "server/src/__tests__/blocked-inbox-review-wait-scope.test.ts": 4674, + "server/src/__tests__/attention-service.test.ts": 106942, + "server/src/__tests__/attention-source-eligibility.test.ts": 1808, + "server/src/__tests__/attention-summary-counts.test.ts": 80693, + "server/src/__tests__/authorization-privacy-query.test.ts": 8222, + "server/src/__tests__/authorization-request-reads.test.ts": 9787, + "server/src/__tests__/authorization-run-context.test.ts": 3242, + "server/src/__tests__/authorization-service.test.ts": 6576, + "server/src/__tests__/automatic-run-brake-import.test.ts": 5272, + "server/src/__tests__/automatic-run-brake-recovery-passes.test.ts": 32314, + "server/src/__tests__/automatic-run-brake.test.ts": 22864, + "server/src/__tests__/automatic-run-start-gate.test.ts": 50100, + "server/src/__tests__/aws-secrets-manager-provider.test.ts": 750, + "server/src/__tests__/batched-chat-authorization.integration.test.ts": 6015, + "server/src/__tests__/better-auth-credential-signup.integration.test.ts": 2931, + "server/src/__tests__/better-auth.test.ts": 2196, + "server/src/__tests__/blocked-inbox-review-wait-scope.test.ts": 6326, "server/src/__tests__/blocker-workspace-history-performance.test.ts": 48579, - "server/src/__tests__/board-access-denial.test.ts": 5978, - "server/src/__tests__/board-claim.test.ts": 5825, - "server/src/__tests__/board-mutation-guard.test.ts": 195, - "server/src/__tests__/board-native-attachments.integration.test.ts": 8849, - "server/src/__tests__/board-skill-ui-guidance.test.ts": 101, - "server/src/__tests__/body-limits.test.ts": 100, - "server/src/__tests__/braintrust-connection.test.ts": 9877, - "server/src/__tests__/browser-tracing-config.test.ts": 881, - "server/src/__tests__/browser-use-connection.test.ts": 28787, - "server/src/__tests__/browser-use-viewport.test.ts": 1087, - "server/src/__tests__/browser-use-work.test.ts": 1562, - "server/src/__tests__/browser-use.test.ts": 875, - "server/src/__tests__/budget-control-publication.test.ts": 8280, - "server/src/__tests__/budget-enforcement-scoping.test.ts": 15522, - "server/src/__tests__/budget-enforcement-worker.test.ts": 1658, - "server/src/__tests__/budget-evaluation-work.test.ts": 11458, - "server/src/__tests__/budget-live-attempts.test.ts": 10691, - "server/src/__tests__/budget-policy-write-contention.test.ts": 6619, - "server/src/__tests__/budgets-history.test.ts": 6335, - "server/src/__tests__/budgets-service.test.ts": 7956, - "server/src/__tests__/build-commit.test.ts": 110, - "server/src/__tests__/build-version.test.ts": 100, - "server/src/__tests__/built-in-agents.test.ts": 30639, - "server/src/__tests__/bundled-plugin-package.test.ts": 1766, - "server/src/__tests__/bundled-plugin-registration.test.ts": 7795, - "server/src/__tests__/bundled-plugin-runtime.test.ts": 197, - "server/src/__tests__/bundled-plugins.test.ts": 260, - "server/src/__tests__/case-handoff-legacy.integration.test.ts": 15623, - "server/src/__tests__/case-history-api-discovery.test.ts": 5799, - "server/src/__tests__/case-mutation-fence.integration.test.ts": 10324, - "server/src/__tests__/change-consent-gate.test.ts": 3282, - "server/src/__tests__/chat-action-work.test.ts": 5108, - "server/src/__tests__/chat-admission-condition.test.ts": 2643, + "server/src/__tests__/board-access-denial.test.ts": 6323, + "server/src/__tests__/board-claim.test.ts": 6225, + "server/src/__tests__/board-mutation-guard.test.ts": 1052, + "server/src/__tests__/board-native-attachments.integration.test.ts": 8898, + "server/src/__tests__/body-limits.test.ts": 730, + "server/src/__tests__/braintrust-connection.test.ts": 12515, + "server/src/__tests__/browser-tracing-config.test.ts": 1554, + "server/src/__tests__/browser-use-connection.test.ts": 40117, + "server/src/__tests__/browser-use-viewport.test.ts": 1596, + "server/src/__tests__/browser-use-work.test.ts": 1905, + "server/src/__tests__/browser-use.test.ts": 1691, + "server/src/__tests__/budget-control-publication.test.ts": 10444, + "server/src/__tests__/budget-enforcement-scoping.test.ts": 15337, + "server/src/__tests__/budget-enforcement-worker.test.ts": 2322, + "server/src/__tests__/budget-evaluation-work.test.ts": 17407, + "server/src/__tests__/budget-live-attempts.test.ts": 9385, + "server/src/__tests__/budget-policy-write-contention.test.ts": 7527, + "server/src/__tests__/budgets-history.test.ts": 7267, + "server/src/__tests__/budgets-service.test.ts": 9228, + "server/src/__tests__/build-commit.test.ts": 715, + "server/src/__tests__/build-version.test.ts": 807, + "server/src/__tests__/built-in-agents.test.ts": 32604, + "server/src/__tests__/bundled-plugin-package.test.ts": 1829, + "server/src/__tests__/bundled-plugin-registration.test.ts": 10188, + "server/src/__tests__/bundled-plugin-runtime.test.ts": 923, + "server/src/__tests__/bundled-plugins.test.ts": 1485, + "server/src/__tests__/case-handoff-legacy.integration.test.ts": 16308, + "server/src/__tests__/case-history-api-discovery.test.ts": 6863, + "server/src/__tests__/case-mutation-fence.integration.test.ts": 9507, + "server/src/__tests__/change-consent-gate.test.ts": 3689, + "server/src/__tests__/chat-action-work.test.ts": 6415, + "server/src/__tests__/chat-admission-condition.test.ts": 2780, "server/src/__tests__/chat-channels.integration.test.ts": 428744, - "server/src/__tests__/chat-completion-delivery.test.ts": 13635, - "server/src/__tests__/chat-completion-proof.test.ts": 2039, - "server/src/__tests__/chat-delivery-work.test.ts": 5063, - "server/src/__tests__/chat-execution-defaults.test.ts": 4456, - "server/src/__tests__/chat-failed-run-retry-boundary.test.ts": 7414, - "server/src/__tests__/chat-interaction-publications.test.ts": 6547, - "server/src/__tests__/chat-native-progress-statement.test.ts": 6543, - "server/src/__tests__/chat-native-progress-work.test.ts": 13613, - "server/src/__tests__/chat-project-tools.test.ts": 25910, - "server/src/__tests__/chat-receiver-work.test.ts": 19666, - "server/src/__tests__/chat-run-milestone-candidates.test.ts": 2157, - "server/src/__tests__/chat-run-milestone-governed-work.test.ts": 11885, - "server/src/__tests__/chat-run-milestone-identity-work.test.ts": 8150, - "server/src/__tests__/chat-run-milestone-recovery-work.test.ts": 7372, - "server/src/__tests__/chat-run-milestone-resource-work.test.ts": 7082, - "server/src/__tests__/chat-run-milestone-work.test.ts": 23691, - "server/src/__tests__/chat-webhook-diagnostics.test.ts": 8042, - "server/src/__tests__/chat-webhook-public-url.test.ts": 1537, - "server/src/__tests__/claude-local-adapter-environment.test.ts": 1619, - "server/src/__tests__/claude-local-adapter.test.ts": 1015, - "server/src/__tests__/claude-local-execute.test.ts": 15610, - "server/src/__tests__/claude-local-skill-sync.test.ts": 1081, - "server/src/__tests__/cleanup-removal-service.test.ts": 9243, - "server/src/__tests__/cli-auth-terminal-guidance.test.ts": 2766, - "server/src/__tests__/cli-invocation-safety.test.ts": 1410, - "server/src/__tests__/closed-native-receipt-accounting.test.ts": 40305, - "server/src/__tests__/cloud-bundled-package-digest.test.ts": 1211, - "server/src/__tests__/cloud-configuration-migration-postgres.test.ts": 7377, - "server/src/__tests__/cloud-configuration-readers.test.ts": 5688, - "server/src/__tests__/cloud-control-task-drain.test.ts": 1877, - "server/src/__tests__/cloud-image-bundled-plugins.test.ts": 225, - "server/src/__tests__/cloud-image-sentry.test.ts": 176, - "server/src/__tests__/cloud-instance.test.ts": 112, - "server/src/__tests__/cloud-lifecycle-sync.test.ts": 156, - "server/src/__tests__/cloud-portfolio-error.test.ts": 100, - "server/src/__tests__/cloud-runtime-config.test.ts": 4958, - "server/src/__tests__/cloud-runtime-identity.test.ts": 5704, - "server/src/__tests__/cloud-tenant-actor-round-trips.test.ts": 10898, - "server/src/__tests__/cloud-tenant-company-provisioning.test.ts": 6821, - "server/src/__tests__/cloud-tenant-transient-db-retry.test.ts": 5590, - "server/src/__tests__/cloud-warm-standby.test.ts": 6748, - "server/src/__tests__/codex-auth-reconciliation.test.ts": 1673, - "server/src/__tests__/codex-local-adapter-environment.test.ts": 1118, - "server/src/__tests__/codex-local-adapter.test.ts": 1087, - "server/src/__tests__/codex-local-execute.test.ts": 11068, - "server/src/__tests__/codex-local-skill-injection.test.ts": 1069, - "server/src/__tests__/codex-local-skill-sync.test.ts": 972, - "server/src/__tests__/commentary-permission-migration.test.ts": 2208, - "server/src/__tests__/committed-chat-response-authority.test.ts": 1562, - "server/src/__tests__/companies-service.test.ts": 12070, - "server/src/__tests__/company-artifacts-service.test.ts": 7924, - "server/src/__tests__/company-cloud-floor.test.ts": 4304, - "server/src/__tests__/company-import-cloud-floor.test.ts": 5532, - "server/src/__tests__/company-model-service-settings-guidance.test.ts": 2884, - "server/src/__tests__/company-portability-import-batching.test.ts": 7275, - "server/src/__tests__/company-quota-windows.test.ts": 1655, - "server/src/__tests__/company-search-extract-service.test.ts": 2856, - "server/src/__tests__/company-search-service.test.ts": 8360, - "server/src/__tests__/company-skill-import-boundary.test.ts": 6917, - "server/src/__tests__/company-skill-policy-service.test.ts": 7187, - "server/src/__tests__/company-skill-test-runs-service.test.ts": 10660, - "server/src/__tests__/company-skills-catalog-service.test.ts": 14066, - "server/src/__tests__/company-skills-detail.test.ts": 6527, - "server/src/__tests__/company-skills-empty-runtime.test.ts": 5607, - "server/src/__tests__/company-skills-observability.test.ts": 6776, - "server/src/__tests__/company-skills-runtime-concurrency.test.ts": 7450, - "server/src/__tests__/company-skills-runtime-selection.test.ts": 8243, - "server/src/__tests__/company-skills-service.test.ts": 70678, - "server/src/__tests__/company-skills.test.ts": 4765, - "server/src/__tests__/company-transfer-runs.test.ts": 2580, - "server/src/__tests__/company-work-batch.test.ts": 100, - "server/src/__tests__/completed-turn-cleanup-hold-settle.test.ts": 15081, - "server/src/__tests__/composio-app-setup.test.ts": 10148, - "server/src/__tests__/config-file.test.ts": 1027, - "server/src/__tests__/config-tailnet-bind-detection.test.ts": 4162, - "server/src/__tests__/configured-secret-guidance.test.ts": 970, - "server/src/__tests__/confirmation-comment-resolution.test.ts": 10126, - "server/src/__tests__/connection-aggregator-fallback.test.ts": 21686, - "server/src/__tests__/connection-grant-resolution.test.ts": 5367, - "server/src/__tests__/connection-install-capabilities.test.ts": 3611, - "server/src/__tests__/connection-instructions.test.ts": 7367, - "server/src/__tests__/connection-intents-service.test.ts": 12614, - "server/src/__tests__/connection-management.integration.test.ts": 204513, - "server/src/__tests__/connection-profile-configuration.test.ts": 6081, - "server/src/__tests__/connector-tool-policy.test.ts": 5872, - "server/src/__tests__/container-init-reaping.test.ts": 100, - "server/src/__tests__/context-compaction.test.ts": 2276, - "server/src/__tests__/controller-instance-lease.test.ts": 26422, - "server/src/__tests__/conversation-settlement-transfer.test.ts": 8641, - "server/src/__tests__/coordinator-handoff.test.ts": 8985, - "server/src/__tests__/copilot-connection-probe.test.ts": 1367, - "server/src/__tests__/cost-data-quality.test.ts": 7002, - "server/src/__tests__/crash-point-call-sites.test.ts": 5185, - "server/src/__tests__/cross-issue-influence-limit-postgres.test.ts": 2470, - "server/src/__tests__/cross-issue-influence-limit.test.ts": 1553, - "server/src/__tests__/cursor-local-adapter-environment.test.ts": 2737, - "server/src/__tests__/cursor-local-adapter.test.ts": 880, - "server/src/__tests__/cursor-local-execute.test.ts": 3194, - "server/src/__tests__/cursor-local-skill-injection.test.ts": 870, - "server/src/__tests__/cursor-local-skill-sync.test.ts": 942, - "server/src/__tests__/custom-image-cleanup-work.test.ts": 1627, + "server/src/__tests__/chat-completion-delivery.test.ts": 19576, + "server/src/__tests__/chat-completion-proof.test.ts": 2281, + "server/src/__tests__/chat-delivery-work.test.ts": 6220, + "server/src/__tests__/chat-execution-defaults.test.ts": 6424, + "server/src/__tests__/chat-failed-run-retry-boundary.test.ts": 8628, + "server/src/__tests__/chat-interaction-publications.test.ts": 7703, + "server/src/__tests__/chat-native-progress-statement.test.ts": 9096, + "server/src/__tests__/chat-native-progress-work.test.ts": 15340, + "server/src/__tests__/chat-project-tools.test.ts": 31556, + "server/src/__tests__/chat-receiver-work.test.ts": 21267, + "server/src/__tests__/chat-run-milestone-candidates.test.ts": 6827, + "server/src/__tests__/chat-run-milestone-governed-work.test.ts": 10752, + "server/src/__tests__/chat-run-milestone-identity-work.test.ts": 8727, + "server/src/__tests__/chat-run-milestone-recovery-work.test.ts": 9193, + "server/src/__tests__/chat-run-milestone-resource-work.test.ts": 8027, + "server/src/__tests__/chat-run-milestone-toast.test.ts": 7000, + "server/src/__tests__/chat-run-milestone-work.test.ts": 55190, + "server/src/__tests__/chat-webhook-diagnostics.test.ts": 8238, + "server/src/__tests__/chat-webhook-public-url.test.ts": 2429, + "server/src/__tests__/claude-local-adapter-environment.test.ts": 2899, + "server/src/__tests__/claude-local-adapter.test.ts": 1851, + "server/src/__tests__/claude-local-execute.test.ts": 29948, + "server/src/__tests__/claude-local-skill-sync.test.ts": 1418, + "server/src/__tests__/cleanup-removal-service.test.ts": 8452, + "server/src/__tests__/cli-invocation-safety.test.ts": 2771, + "server/src/__tests__/closed-native-receipt-accounting.test.ts": 38079, + "server/src/__tests__/cloud-bundled-package-digest.test.ts": 2275, + "server/src/__tests__/cloud-configuration-migration-postgres.test.ts": 7737, + "server/src/__tests__/cloud-configuration-readers.test.ts": 5910, + "server/src/__tests__/cloud-control-task-drain.test.ts": 2141, + "server/src/__tests__/cloud-image-bundled-plugins.test.ts": 850, + "server/src/__tests__/cloud-image-sentry.test.ts": 1184, + "server/src/__tests__/cloud-instance.test.ts": 710, + "server/src/__tests__/cloud-lifecycle-sync.test.ts": 878, + "server/src/__tests__/cloud-portfolio-error.test.ts": 619, + "server/src/__tests__/cloud-posthog-browser.test.ts": 9482, + "server/src/__tests__/cloud-posthog-config.test.ts": 702, + "server/src/__tests__/cloud-runtime-config.test.ts": 6702, + "server/src/__tests__/cloud-runtime-identity.test.ts": 7463, + "server/src/__tests__/cloud-tenant-actor-round-trips.test.ts": 10396, + "server/src/__tests__/cloud-tenant-actor-statements.test.ts": 8162, + "server/src/__tests__/cloud-tenant-company-provisioning.test.ts": 5911, + "server/src/__tests__/cloud-tenant-transient-db-retry.test.ts": 7596, + "server/src/__tests__/cloud-warm-standby.test.ts": 6419, + "server/src/__tests__/codex-auth-reconciliation.test.ts": 2055, + "server/src/__tests__/codex-local-adapter-environment.test.ts": 1855, + "server/src/__tests__/codex-local-adapter.test.ts": 1429, + "server/src/__tests__/codex-local-execute.test.ts": 11921, + "server/src/__tests__/codex-local-skill-injection.test.ts": 1686, + "server/src/__tests__/codex-local-skill-sync.test.ts": 1906, + "server/src/__tests__/committed-chat-response-authority.test.ts": 1818, + "server/src/__tests__/companies-service.test.ts": 13659, + "server/src/__tests__/company-artifacts-service.test.ts": 13229, + "server/src/__tests__/company-cloud-floor.test.ts": 7990, + "server/src/__tests__/company-import-cloud-floor.test.ts": 8056, + "server/src/__tests__/company-portability-import-batching.test.ts": 8431, + "server/src/__tests__/company-quota-windows.test.ts": 2490, + "server/src/__tests__/company-search-extract-service.test.ts": 2861, + "server/src/__tests__/company-search-service.test.ts": 9014, + "server/src/__tests__/company-skill-import-boundary.test.ts": 8177, + "server/src/__tests__/company-skill-policy-service.test.ts": 6978, + "server/src/__tests__/company-skill-test-runs-service.test.ts": 17462, + "server/src/__tests__/company-skills-catalog-service.test.ts": 19294, + "server/src/__tests__/company-skills-detail.test.ts": 7054, + "server/src/__tests__/company-skills-empty-runtime.test.ts": 7582, + "server/src/__tests__/company-skills-list-statements.test.ts": 9172, + "server/src/__tests__/company-skills-observability.test.ts": 7541, + "server/src/__tests__/company-skills-runtime-concurrency.test.ts": 8240, + "server/src/__tests__/company-skills-runtime-selection.test.ts": 10199, + "server/src/__tests__/company-skills-service.test.ts": 72609, + "server/src/__tests__/company-skills.test.ts": 6274, + "server/src/__tests__/company-transfer-runs.test.ts": 2009, + "server/src/__tests__/company-work-batch.test.ts": 714, + "server/src/__tests__/completed-turn-cleanup-hold-settle.test.ts": 13362, + "server/src/__tests__/composio-app-setup.test.ts": 9173, + "server/src/__tests__/config-file.test.ts": 1133, + "server/src/__tests__/config-tailnet-bind-detection.test.ts": 3389, + "server/src/__tests__/configured-secret-guidance.test.ts": 2076, + "server/src/__tests__/confirmation-comment-resolution.test.ts": 9855, + "server/src/__tests__/connection-aggregator-fallback.test.ts": 31814, + "server/src/__tests__/connection-grant-resolution.test.ts": 7038, + "server/src/__tests__/connection-install-capabilities.test.ts": 7067, + "server/src/__tests__/connection-instructions.test.ts": 8449, + "server/src/__tests__/connection-intents-service.test.ts": 15849, + "server/src/__tests__/connection-management.integration.test.ts": 185806, + "server/src/__tests__/connection-profile-configuration.test.ts": 7082, + "server/src/__tests__/connector-tool-policy.test.ts": 6365, + "server/src/__tests__/container-init-reaping.test.ts": 696, + "server/src/__tests__/context-compaction.test.ts": 2386, + "server/src/__tests__/continuation-delivery-unwakeable-agent-idle.test.ts": 12925, + "server/src/__tests__/controller-instance-lease.test.ts": 26788, + "server/src/__tests__/conversation-settlement-transfer.test.ts": 12265, + "server/src/__tests__/coordinator-handoff.test.ts": 12393, + "server/src/__tests__/copilot-connection-probe.test.ts": 2255, + "server/src/__tests__/cost-data-quality.test.ts": 9192, + "server/src/__tests__/crash-point-call-sites.test.ts": 7935, + "server/src/__tests__/cross-issue-influence-limit-postgres.test.ts": 3536, + "server/src/__tests__/cross-issue-influence-limit.test.ts": 1740, + "server/src/__tests__/cursor-local-adapter-environment.test.ts": 4080, + "server/src/__tests__/cursor-local-adapter.test.ts": 1644, + "server/src/__tests__/cursor-local-execute.test.ts": 2646, + "server/src/__tests__/cursor-local-skill-injection.test.ts": 1651, + "server/src/__tests__/cursor-local-skill-sync.test.ts": 1896, + "server/src/__tests__/custom-image-cleanup-work.test.ts": 2507, "server/src/__tests__/customer-success-cloud.test.ts": 1410, - "server/src/__tests__/customer-success.test.ts": 6101, - "server/src/__tests__/dashboard-disconnect-retry.test.ts": 3300, - "server/src/__tests__/dashboard-service.test.ts": 6795, - "server/src/__tests__/database-backup-catalog-guidance.test.ts": 2324, - "server/src/__tests__/database-backup-owner.test.ts": 6151, - "server/src/__tests__/database-backup-qualification-guards.test.ts": 1524, - "server/src/__tests__/database-backup-work.test.ts": 1320, - "server/src/__tests__/database-operation-attribution.test.ts": 1860, - "server/src/__tests__/daytona-connection.test.ts": 17254, - "server/src/__tests__/daytona-http-boundary.test.ts": 997, - "server/src/__tests__/db-errors.test.ts": 129, - "server/src/__tests__/deadline-work.test.ts": 1806, - "server/src/__tests__/decision-effect-recovery-work.test.ts": 12877, - "server/src/__tests__/decision-expiry-work.test.ts": 10492, - "server/src/__tests__/decision-history.test.ts": 6828, - "server/src/__tests__/decision-model-provider.test.ts": 924, - "server/src/__tests__/decision-models.test.ts": 10903, - "server/src/__tests__/decision-retention-materialization-security.test.ts": 22201, - "server/src/__tests__/decision-retention-service.test.ts": 9859, - "server/src/__tests__/decision-target-work.test.ts": 15085, - "server/src/__tests__/decision-training.test.ts": 8963, - "server/src/__tests__/decision-wakeup.test.ts": 100, - "server/src/__tests__/decisions-service.test.ts": 14295, + "server/src/__tests__/customer-success-run-liveness.test.ts": 7151, + "server/src/__tests__/customer-success.test.ts": 9098, + "server/src/__tests__/dashboard-disconnect-retry.test.ts": 3423, + "server/src/__tests__/dashboard-service.test.ts": 7126, + "server/src/__tests__/database-backup-owner.test.ts": 8776, + "server/src/__tests__/database-backup-qualification-guards.test.ts": 1930, + "server/src/__tests__/database-backup-work.test.ts": 1755, + "server/src/__tests__/database-operation-attribution.test.ts": 2025, + "server/src/__tests__/daytona-connection.test.ts": 16846, + "server/src/__tests__/daytona-http-boundary.test.ts": 1518, + "server/src/__tests__/db-errors.test.ts": 834, + "server/src/__tests__/deadline-work.test.ts": 1862, + "server/src/__tests__/decision-effect-recovery-work.test.ts": 24365, + "server/src/__tests__/decision-expiry-work.test.ts": 16024, + "server/src/__tests__/decision-history.test.ts": 9747, + "server/src/__tests__/decision-model-provider.test.ts": 2162, + "server/src/__tests__/decision-models.test.ts": 12584, + "server/src/__tests__/decision-retention-materialization-security.test.ts": 16798, + "server/src/__tests__/decision-retention-service.test.ts": 11706, + "server/src/__tests__/decision-target-work.test.ts": 14584, + "server/src/__tests__/decision-training.test.ts": 12154, + "server/src/__tests__/decision-wakeup.test.ts": 888, + "server/src/__tests__/decisions-service.test.ts": 20736, + "server/src/__tests__/deferred-chat-wake-sweep.test.ts": 25678, "server/src/__tests__/deferred-execution-receipt-work.test.ts": 292434, - "server/src/__tests__/delivery-work-coordinator.test.ts": 5572, - "server/src/__tests__/deployment-connections.test.ts": 17961, - "server/src/__tests__/deployment-notifications.test.ts": 3172, - "server/src/__tests__/dev-runner-native-binary.test.ts": 822, - "server/src/__tests__/dev-runner-options.test.ts": 103, - "server/src/__tests__/dev-runner-output.test.ts": 121, - "server/src/__tests__/dev-runner-paths.test.ts": 107, - "server/src/__tests__/dev-runner-snapshot.test.ts": 103, - "server/src/__tests__/dev-runner-worktree.test.ts": 132, - "server/src/__tests__/dev-server-status.test.ts": 236, - "server/src/__tests__/dev-watch-ignore.test.ts": 100, - "server/src/__tests__/device-login-credential-read.test.ts": 786, - "server/src/__tests__/device-login-reaper.test.ts": 4901, - "server/src/__tests__/device-login-service.test.ts": 5969, - "server/src/__tests__/disposition-repair.test.ts": 5061, - "server/src/__tests__/distribution-plugin-catalog.test.ts": 200, - "server/src/__tests__/docker-build-stamp.test.ts": 116, - "server/src/__tests__/docker-entrypoint.test.ts": 775, - "server/src/__tests__/docker-image-layer-reuse.test.ts": 102, - "server/src/__tests__/docker-runner-workflows.test.ts": 126, - "server/src/__tests__/document-annotations-service.test.ts": 5956, - "server/src/__tests__/documents-service.test.ts": 2945, - "server/src/__tests__/documents.test.ts": 1545, - "server/src/__tests__/dot-invitations.test.ts": 5359, - "server/src/__tests__/dot-oauth-onboarding.test.ts": 7402, - "server/src/__tests__/duplex-observability-recorder.test.ts": 100, - "server/src/__tests__/durable-chat-wakeup.test.ts": 36619, - "server/src/__tests__/durable-directory.test.ts": 1689, - "server/src/__tests__/effective-run-config-fingerprints.test.ts": 915, - "server/src/__tests__/email-address-check.test.ts": 5850, - "server/src/__tests__/email-channels.integration.test.ts": 45062, - "server/src/__tests__/email-idle-work.test.ts": 4869, - "server/src/__tests__/embedded-postgres-supervisor.test.ts": 134, - "server/src/__tests__/env-file-policy.test.ts": 100, - "server/src/__tests__/environment-acquisition-diagnostics.test.ts": 2913, - "server/src/__tests__/environment-capability-contract.test.ts": 4560, - "server/src/__tests__/environment-cleanup-work.test.ts": 29939, - "server/src/__tests__/environment-config.test.ts": 5225, - "server/src/__tests__/environment-custom-image-terminal-ws.test.ts": 2779, - "server/src/__tests__/environment-custom-images-service.test.ts": 11463, - "server/src/__tests__/environment-driver-traits.test.ts": 122, - "server/src/__tests__/environment-execution-target-capabilities.test.ts": 1012, - "server/src/__tests__/environment-execution-target-duplex-kill-switch.test.ts": 1109, - "server/src/__tests__/environment-execution-target-duplex.test.ts": 5268, - "server/src/__tests__/environment-execution-target.test.ts": 951, - "server/src/__tests__/environment-lease-owner-stamps.test.ts": 6068, - "server/src/__tests__/environment-live-ssh.test.ts": 944, - "server/src/__tests__/environment-login-probe-lease-ownership.test.ts": 8515, - "server/src/__tests__/environment-pending-cleanup-queue-owner.test.ts": 8880, - "server/src/__tests__/environment-probe.test.ts": 4838, - "server/src/__tests__/environment-retained-orphan-sandbox.test.ts": 10012, - "server/src/__tests__/environment-run-lease-ownership.test.ts": 9884, - "server/src/__tests__/environment-run-orchestrator.test.ts": 4979, - "server/src/__tests__/environment-runtime-driver-contract.test.ts": 6663, - "server/src/__tests__/environment-runtime-duplex-bridge-input.test.ts": 6050, - "server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts": 34891, - "server/src/__tests__/environment-runtime.test.ts": 94123, - "server/src/__tests__/environment-service.test.ts": 7724, - "server/src/__tests__/environment-skills.test.ts": 10827, - "server/src/__tests__/environment-sync-out-error.test.ts": 843, - "server/src/__tests__/environment-task-authority.integration.test.ts": 5884, - "server/src/__tests__/environment-task-runtime.test.ts": 4402, - "server/src/__tests__/environment-test-harness.test.ts": 931, - "server/src/__tests__/ephemeral-enrollment-replay.test.ts": 6961, - "server/src/__tests__/ephemeral-server-contract.test.ts": 6057, - "server/src/__tests__/ephemeral-server-data.test.ts": 7265, - "server/src/__tests__/ephemeral-server-startup-run-state.test.ts": 6145, - "server/src/__tests__/error-handler-client-abort.test.ts": 4309, - "server/src/__tests__/error-handler-tool-gateway.test.ts": 5363, - "server/src/__tests__/error-handler.test.ts": 5158, - "server/src/__tests__/eval-feedback-recovery.integration.test.ts": 10146, - "server/src/__tests__/execution-control-work.test.ts": 17970, - "server/src/__tests__/execution-lock-orphan-cleanup.test.ts": 8222, - "server/src/__tests__/execution-preparation-phases.test.ts": 2168, - "server/src/__tests__/execution-workspace-compaction.test.ts": 12618, - "server/src/__tests__/execution-workspace-policy.test.ts": 828, - "server/src/__tests__/execution-workspace-reopen.test.ts": 14909, - "server/src/__tests__/execution-workspace-runtime-control-conflict.test.ts": 5286, - "server/src/__tests__/execution-workspaces-service.test.ts": 57701, - "server/src/__tests__/export-fidelity.test.ts": 2273, - "server/src/__tests__/external-object-idle-schedule.test.ts": 116, - "server/src/__tests__/external-object-refresh-work.test.ts": 18749, - "server/src/__tests__/external-objects-service.test.ts": 6519, - "server/src/__tests__/fast-response-models.test.ts": 831, - "server/src/__tests__/fast-response-provider.test.ts": 1256, - "server/src/__tests__/fast-responses.test.ts": 9033, - "server/src/__tests__/feedback-flush-controller.test.ts": 6268, - "server/src/__tests__/feedback-redaction.test.ts": 123, - "server/src/__tests__/feedback-service.test.ts": 6945, - "server/src/__tests__/feedback-share-client.test.ts": 113, - "server/src/__tests__/file-delivery-bridges.test.ts": 24738, - "server/src/__tests__/file-resources-git-scan-load.test.ts": 5145, - "server/src/__tests__/file-resources.test.ts": 10641, - "server/src/__tests__/first-admin-claim.test.ts": 2195, - "server/src/__tests__/folders-service.test.ts": 3270, - "server/src/__tests__/forbidden-tokens.test.ts": 124, - "server/src/__tests__/gateway-credential-expiry.test.ts": 9752, - "server/src/__tests__/gemini-local-adapter-environment.test.ts": 1113, - "server/src/__tests__/gemini-local-adapter.test.ts": 1002, - "server/src/__tests__/gemini-local-execute.test.ts": 1272, - "server/src/__tests__/gemini-local-skill-sync.test.ts": 973, - "server/src/__tests__/general-capability-classifier.test.ts": 5491, - "server/src/__tests__/generic-mcp-connection.test.ts": 51021, - "server/src/__tests__/git-credentials.test.ts": 5055, - "server/src/__tests__/git-expiration-auth-fallback.test.ts": 5260, - "server/src/__tests__/git-repository-excludes.test.ts": 4837, - "server/src/__tests__/git-reproducible-managed-checkouts.test.ts": 9035, - "server/src/__tests__/git-restore-point-expiration-config.test.ts": 848, + "server/src/__tests__/delivery-work-coordinator.test.ts": 7099, + "server/src/__tests__/deployment-connections.test.ts": 19322, + "server/src/__tests__/deployment-notifications.test.ts": 1913, + "server/src/__tests__/dev-runner-native-binary.test.ts": 2172, + "server/src/__tests__/dev-runner-options.test.ts": 916, + "server/src/__tests__/dev-runner-output.test.ts": 962, + "server/src/__tests__/dev-runner-paths.test.ts": 856, + "server/src/__tests__/dev-runner-snapshot.test.ts": 788, + "server/src/__tests__/dev-runner-worktree.test.ts": 602, + "server/src/__tests__/dev-server-status.test.ts": 902, + "server/src/__tests__/dev-watch-ignore.test.ts": 740, + "server/src/__tests__/device-login-credential-read.test.ts": 1337, + "server/src/__tests__/device-login-reaper.test.ts": 6125, + "server/src/__tests__/device-login-service.test.ts": 20142, + "server/src/__tests__/disposition-repair.test.ts": 6090, + "server/src/__tests__/distribution-plugin-catalog.test.ts": 874, + "server/src/__tests__/docker-build-stamp.test.ts": 960, + "server/src/__tests__/docker-entrypoint.test.ts": 1309, + "server/src/__tests__/docker-image-layer-reuse.test.ts": 886, + "server/src/__tests__/docker-runner-workflows.test.ts": 654, + "server/src/__tests__/document-annotations-service.test.ts": 8416, + "server/src/__tests__/documents-service.test.ts": 2904, + "server/src/__tests__/documents.test.ts": 2018, + "server/src/__tests__/dot-invitations.test.ts": 7733, + "server/src/__tests__/dot-oauth-onboarding.test.ts": 7834, + "server/src/__tests__/dot-runner.test.ts": 64825, + "server/src/__tests__/duplex-observability-recorder.test.ts": 754, + "server/src/__tests__/durable-chat-wakeup.test.ts": 42102, + "server/src/__tests__/durable-directory.test.ts": 2203, + "server/src/__tests__/effective-run-config-fingerprints.test.ts": 1190, + "server/src/__tests__/email-address-check.test.ts": 5253, + "server/src/__tests__/email-channels.integration.test.ts": 40296, + "server/src/__tests__/email-idle-work.test.ts": 6264, + "server/src/__tests__/embedded-postgres-supervisor.test.ts": 756, + "server/src/__tests__/env-file-policy.test.ts": 553, + "server/src/__tests__/environment-acquisition-diagnostics.test.ts": 3995, + "server/src/__tests__/environment-capability-contract.test.ts": 5627, + "server/src/__tests__/environment-cleanup-work.test.ts": 36256, + "server/src/__tests__/environment-config.test.ts": 7042, + "server/src/__tests__/environment-custom-image-terminal-ws.test.ts": 3365, + "server/src/__tests__/environment-custom-images-service.test.ts": 10627, + "server/src/__tests__/environment-driver-traits.test.ts": 688, + "server/src/__tests__/environment-execution-target-capabilities.test.ts": 1767, + "server/src/__tests__/environment-execution-target-duplex-kill-switch.test.ts": 2143, + "server/src/__tests__/environment-execution-target-duplex.test.ts": 6221, + "server/src/__tests__/environment-execution-target.test.ts": 2612, + "server/src/__tests__/environment-lease-owner-stamps.test.ts": 8560, + "server/src/__tests__/environment-live-ssh.test.ts": 1481, + "server/src/__tests__/environment-login-probe-lease-ownership.test.ts": 8123, + "server/src/__tests__/environment-pending-cleanup-queue-owner.test.ts": 8493, + "server/src/__tests__/environment-probe.test.ts": 6153, + "server/src/__tests__/environment-retained-orphan-listing-cost.test.ts": 17480, + "server/src/__tests__/environment-retained-orphan-sandbox.test.ts": 8688, + "server/src/__tests__/environment-run-lease-ownership.test.ts": 10538, + "server/src/__tests__/environment-run-orchestrator.test.ts": 11261, + "server/src/__tests__/environment-runtime-driver-contract.test.ts": 7717, + "server/src/__tests__/environment-runtime-duplex-bridge-input.test.ts": 6549, + "server/src/__tests__/environment-runtime-reusable-resume-replacement.test.ts": 37524, + "server/src/__tests__/environment-runtime.test.ts": 73957, + "server/src/__tests__/environment-service.test.ts": 13617, + "server/src/__tests__/environment-skills.test.ts": 11707, + "server/src/__tests__/environment-sync-out-error.test.ts": 1344, + "server/src/__tests__/environment-task-authority.integration.test.ts": 6554, + "server/src/__tests__/environment-task-runtime.test.ts": 6025, + "server/src/__tests__/environment-test-harness.test.ts": 1250, + "server/src/__tests__/ephemeral-enrollment-replay.test.ts": 6741, + "server/src/__tests__/ephemeral-server-contract.test.ts": 6420, + "server/src/__tests__/ephemeral-server-data.test.ts": 7443, + "server/src/__tests__/ephemeral-server-startup-run-state.test.ts": 9149, + "server/src/__tests__/error-handler-client-abort.test.ts": 6273, + "server/src/__tests__/error-handler-tool-gateway.test.ts": 6632, + "server/src/__tests__/error-handler.test.ts": 5911, + "server/src/__tests__/eval-feedback-recovery.integration.test.ts": 13456, + "server/src/__tests__/execution-control-work.test.ts": 16340, + "server/src/__tests__/execution-lock-orphan-cleanup.test.ts": 8988, + "server/src/__tests__/execution-preparation-phases.test.ts": 2629, + "server/src/__tests__/execution-workspace-compaction.test.ts": 11717, + "server/src/__tests__/execution-workspace-policy.test.ts": 1394, + "server/src/__tests__/execution-workspace-reopen.test.ts": 20305, + "server/src/__tests__/execution-workspace-runtime-control-conflict.test.ts": 5759, + "server/src/__tests__/execution-workspaces-service.test.ts": 50904, + "server/src/__tests__/export-fidelity.test.ts": 2537, + "server/src/__tests__/external-object-idle-schedule.test.ts": 941, + "server/src/__tests__/external-object-refresh-work.test.ts": 17969, + "server/src/__tests__/external-objects-service.test.ts": 7744, + "server/src/__tests__/failed-continuation-continues-again.test.ts": 34068, + "server/src/__tests__/fast-response-models.test.ts": 1365, + "server/src/__tests__/fast-response-provider.test.ts": 1810, + "server/src/__tests__/fast-responses.test.ts": 11499, + "server/src/__tests__/feedback-flush-controller.test.ts": 10231, + "server/src/__tests__/feedback-redaction.test.ts": 907, + "server/src/__tests__/feedback-service.test.ts": 7459, + "server/src/__tests__/feedback-share-client.test.ts": 754, + "server/src/__tests__/file-delivery-bridges.test.ts": 20870, + "server/src/__tests__/file-resources-git-scan-load.test.ts": 5770, + "server/src/__tests__/file-resources.test.ts": 23012, + "server/src/__tests__/first-admin-claim.test.ts": 2737, + "server/src/__tests__/folders-service.test.ts": 3571, + "server/src/__tests__/forbidden-tokens.test.ts": 705, + "server/src/__tests__/gateway-credential-expiry.test.ts": 9979, + "server/src/__tests__/gemini-local-adapter-environment.test.ts": 1230, + "server/src/__tests__/gemini-local-adapter.test.ts": 2193, + "server/src/__tests__/gemini-local-execute.test.ts": 2369, + "server/src/__tests__/gemini-local-skill-sync.test.ts": 1692, + "server/src/__tests__/general-capability-classifier.test.ts": 6292, + "server/src/__tests__/generic-mcp-connection.test.ts": 55072, + "server/src/__tests__/git-credentials.test.ts": 7716, + "server/src/__tests__/git-expiration-auth-fallback.test.ts": 5742, + "server/src/__tests__/git-mount-boundary.test.ts": 7144, + "server/src/__tests__/git-repository-excludes.test.ts": 7134, + "server/src/__tests__/git-reproducible-managed-checkouts.test.ts": 12319, + "server/src/__tests__/git-restore-point-expiration-config.test.ts": 1957, "server/src/__tests__/git-restore-point-expiration.test.ts": 49208, - "server/src/__tests__/git-restore-point-ledger-config.test.ts": 804, - "server/src/__tests__/git-restore-point-ledger.test.ts": 8059, - "server/src/__tests__/git-restore-point.test.ts": 6794, - "server/src/__tests__/git-workspace-activity.test.ts": 21794, - "server/src/__tests__/git-workspace-base-storage.test.ts": 5934, - "server/src/__tests__/git-workspace-contents.test.ts": 6266, - "server/src/__tests__/git-workspace-expiration-eligibility.test.ts": 25533, + "server/src/__tests__/git-restore-point-ledger-config.test.ts": 1562, + "server/src/__tests__/git-restore-point-ledger.test.ts": 8440, + "server/src/__tests__/git-restore-point.test.ts": 10673, + "server/src/__tests__/git-workspace-activity.test.ts": 15399, + "server/src/__tests__/git-workspace-base-storage.test.ts": 7180, + "server/src/__tests__/git-workspace-contents.test.ts": 6821, + "server/src/__tests__/git-workspace-expiration-eligibility.test.ts": 17358, "server/src/__tests__/git-workspace-expiration.test.ts": 198261, - "server/src/__tests__/git-workspace-fetch-head.test.ts": 6486, - "server/src/__tests__/git-workspace-restoration-diagnostic.test.ts": 5258, - "server/src/__tests__/github-catalog-timing.test.ts": 6994, - "server/src/__tests__/github-commit-details.test.ts": 5090, - "server/src/__tests__/github-connection-enrollment-work.test.ts": 6237, - "server/src/__tests__/github-connection-events.test.ts": 10510, - "server/src/__tests__/github-connection-work.test.ts": 15010, - "server/src/__tests__/github-grant-metadata.test.ts": 4848, - "server/src/__tests__/github-health-recovery.test.ts": 4795, - "server/src/__tests__/github-link-preview.test.ts": 4948, - "server/src/__tests__/github-operation-credentials.test.ts": 10104, - "server/src/__tests__/github-repository-catalog-failure.test.ts": 103, - "server/src/__tests__/github-review-check-state.test.ts": 2395, - "server/src/__tests__/github-review-wait.test.ts": 5160, - "server/src/__tests__/github-skill-source.test.ts": 24821, - "server/src/__tests__/github-workspace-delivery.test.ts": 5322, - "server/src/__tests__/goal-parent-company-validation.test.ts": 7745, - "server/src/__tests__/google-sheets-gallery.test.ts": 4889, - "server/src/__tests__/grok-bot-routine.test.ts": 23256, - "server/src/__tests__/grok-dispatch-work.test.ts": 13789, - "server/src/__tests__/grok-local-skill-sync.test.ts": 1079, - "server/src/__tests__/health-server-info-git-probe.test.ts": 5292, - "server/src/__tests__/health-workspace-readiness.test.ts": 5189, - "server/src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts": 17709, - "server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts": 18468, - "server/src/__tests__/heartbeat-agent-directory-busy.test.ts": 26791, - "server/src/__tests__/heartbeat-agent-session-message.test.ts": 5861, - "server/src/__tests__/heartbeat-agent-status-recovery.test.ts": 7729, - "server/src/__tests__/heartbeat-answer-behind-settling-run.test.ts": 13481, - "server/src/__tests__/heartbeat-archived-company-guard.test.ts": 7776, - "server/src/__tests__/heartbeat-auto-checkout.test.ts": 5431, - "server/src/__tests__/heartbeat-blocked-question-answer.test.ts": 19966, - "server/src/__tests__/heartbeat-case-handoff.test.ts": 9953, - "server/src/__tests__/heartbeat-case-terminal-handoff.test.ts": 9252, - "server/src/__tests__/heartbeat-chat-task-link.test.ts": 5542, - "server/src/__tests__/heartbeat-comment-wake-batching.test.ts": 77603, - "server/src/__tests__/heartbeat-context-compaction-execution.test.ts": 10899, - "server/src/__tests__/heartbeat-context-summary.test.ts": 6427, - "server/src/__tests__/heartbeat-cost-accounting.test.ts": 6011, - "server/src/__tests__/heartbeat-direct-adapter-native-isolation.test.ts": 17985, - "server/src/__tests__/heartbeat-execution-configuration.test.ts": 32962, - "server/src/__tests__/heartbeat-git-restore-point-resume.test.ts": 24433, - "server/src/__tests__/heartbeat-held-comment-wake.test.ts": 89702, - "server/src/__tests__/heartbeat-instruction-working-copy.test.ts": 17877, - "server/src/__tests__/heartbeat-issue-rewake-throttle.test.ts": 18318, - "server/src/__tests__/heartbeat-ledger-billing-code.test.ts": 6344, - "server/src/__tests__/heartbeat-list.test.ts": 6647, - "server/src/__tests__/heartbeat-local-environment.test.ts": 12862, - "server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts": 8890, - "server/src/__tests__/heartbeat-managed-clone-credentials.test.ts": 7354, - "server/src/__tests__/heartbeat-model-fallback-warning.test.ts": 4679, - "server/src/__tests__/heartbeat-native-cleanup-admission-hold.test.ts": 7482, - "server/src/__tests__/heartbeat-native-cleanup-admission.test.ts": 19319, - "server/src/__tests__/heartbeat-native-orphan-sweep-lease-race.test.ts": 6572, - "server/src/__tests__/heartbeat-native-predispatch-retry.test.ts": 21328, - "server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts": 10775, + "server/src/__tests__/git-workspace-fetch-head.test.ts": 7912, + "server/src/__tests__/git-workspace-restoration-diagnostic.test.ts": 7200, + "server/src/__tests__/github-catalog-timing.test.ts": 7201, + "server/src/__tests__/github-commit-details.test.ts": 6284, + "server/src/__tests__/github-connection-enrollment-work.test.ts": 8390, + "server/src/__tests__/github-connection-events.test.ts": 10696, + "server/src/__tests__/github-connection-work.test.ts": 17548, + "server/src/__tests__/github-grant-metadata.test.ts": 9430, + "server/src/__tests__/github-health-recovery.test.ts": 6236, + "server/src/__tests__/github-link-preview.test.ts": 7519, + "server/src/__tests__/github-operation-credentials.test.ts": 11571, + "server/src/__tests__/github-repository-catalog-failure.test.ts": 1001, + "server/src/__tests__/github-repository-token-cache.test.ts": 7295, + "server/src/__tests__/github-review-check-state.test.ts": 2857, + "server/src/__tests__/github-review-wait.test.ts": 4158, + "server/src/__tests__/github-skill-source.test.ts": 28979, + "server/src/__tests__/github-workspace-delivery.test.ts": 6042, + "server/src/__tests__/goal-parent-company-validation.test.ts": 10228, + "server/src/__tests__/google-sheets-gallery.test.ts": 6199, + "server/src/__tests__/google-workspace-injection-screening.test.ts": 11732, + "server/src/__tests__/google-workspace-rest-transport.test.ts": 11985, + "server/src/__tests__/grok-bot-routine.test.ts": 24423, + "server/src/__tests__/grok-dispatch-work.test.ts": 13302, + "server/src/__tests__/grok-local-skill-sync.test.ts": 2156, + "server/src/__tests__/health-server-info-git-probe.test.ts": 10496, + "server/src/__tests__/health-workspace-readiness.test.ts": 6479, + "server/src/__tests__/heartbeat-accepted-plan-workspace-refresh.test.ts": 26442, + "server/src/__tests__/heartbeat-active-run-output-watchdog.test.ts": 23228, + "server/src/__tests__/heartbeat-agent-directory-busy.test.ts": 22123, + "server/src/__tests__/heartbeat-agent-session-message.test.ts": 6730, + "server/src/__tests__/heartbeat-agent-status-recovery.test.ts": 8890, + "server/src/__tests__/heartbeat-answer-behind-settling-run.test.ts": 14143, + "server/src/__tests__/heartbeat-archived-company-guard.test.ts": 7700, + "server/src/__tests__/heartbeat-auto-checkout.test.ts": 8960, + "server/src/__tests__/heartbeat-blocked-question-answer.test.ts": 30782, + "server/src/__tests__/heartbeat-case-handoff.test.ts": 9748, + "server/src/__tests__/heartbeat-case-terminal-handoff.test.ts": 8571, + "server/src/__tests__/heartbeat-chat-task-link.test.ts": 8851, + "server/src/__tests__/heartbeat-comment-wake-batching.test.ts": 81437, + "server/src/__tests__/heartbeat-context-compaction-execution.test.ts": 14982, + "server/src/__tests__/heartbeat-context-summary.test.ts": 6453, + "server/src/__tests__/heartbeat-cost-accounting.test.ts": 8738, + "server/src/__tests__/heartbeat-direct-adapter-native-isolation.test.ts": 14982, + "server/src/__tests__/heartbeat-drain-native-resume-dispatch.test.ts": 7922, + "server/src/__tests__/heartbeat-execution-configuration.test.ts": 32284, + "server/src/__tests__/heartbeat-git-restore-point-resume.test.ts": 22905, + "server/src/__tests__/heartbeat-held-comment-wake.test.ts": 67821, + "server/src/__tests__/heartbeat-instruction-working-copy.test.ts": 21994, + "server/src/__tests__/heartbeat-issue-rewake-throttle.test.ts": 20323, + "server/src/__tests__/heartbeat-lease-release-before-runner-attach.test.ts": 14730, + "server/src/__tests__/heartbeat-ledger-billing-code.test.ts": 8743, + "server/src/__tests__/heartbeat-list.test.ts": 10959, + "server/src/__tests__/heartbeat-local-environment.test.ts": 13521, + "server/src/__tests__/heartbeat-lock-release-on-reassignment.test.ts": 10323, + "server/src/__tests__/heartbeat-managed-clone-credentials.test.ts": 8704, + "server/src/__tests__/heartbeat-model-fallback-warning.test.ts": 5766, + "server/src/__tests__/heartbeat-native-cleanup-admission-hold.test.ts": 12906, + "server/src/__tests__/heartbeat-native-cleanup-admission.test.ts": 20757, + "server/src/__tests__/heartbeat-native-early-hand-off.test.ts": 15018, + "server/src/__tests__/heartbeat-native-orphan-sweep-lease-race.test.ts": 8348, + "server/src/__tests__/heartbeat-native-predispatch-retry.test.ts": 34006, + "server/src/__tests__/heartbeat-native-remote-failure-retention.test.ts": 13612, "server/src/__tests__/heartbeat-native-restart-suspension.test.ts": 223420, - "server/src/__tests__/heartbeat-native-resume-lease-failure.test.ts": 8314, - "server/src/__tests__/heartbeat-native-runner-cancellation.test.ts": 6374, - "server/src/__tests__/heartbeat-native-status-context.test.ts": 5793, - "server/src/__tests__/heartbeat-observed-workspace-preservation.test.ts": 42071, - "server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts": 8499, - "server/src/__tests__/heartbeat-paused-assignee-new-task.test.ts": 8317, - "server/src/__tests__/heartbeat-pending-cleanup-sweep.test.ts": 11573, - "server/src/__tests__/heartbeat-plugin-environment.test.ts": 15612, - "server/src/__tests__/heartbeat-preparation-gap-spans.test.ts": 10421, - "server/src/__tests__/heartbeat-project-env.test.ts": 5900, - "server/src/__tests__/heartbeat-project-repositories.test.ts": 134606, - "server/src/__tests__/heartbeat-provider-limit-wait.test.ts": 20882, - "server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts": 37032, - "server/src/__tests__/heartbeat-reassignment-deferred-wake.test.ts": 15800, - "server/src/__tests__/heartbeat-referenced-projects.test.ts": 7018, - "server/src/__tests__/heartbeat-refused-assignment-wake.test.ts": 9590, - "server/src/__tests__/heartbeat-remote-referenced-projects.test.ts": 6122, - "server/src/__tests__/heartbeat-remote-workspace-busy.test.ts": 15160, + "server/src/__tests__/heartbeat-native-resume-lease-failure.test.ts": 9807, + "server/src/__tests__/heartbeat-native-runner-cancellation.test.ts": 8657, + "server/src/__tests__/heartbeat-native-status-context.test.ts": 7268, + "server/src/__tests__/heartbeat-native-stop-before-admission.test.ts": 11608, + "server/src/__tests__/heartbeat-observed-workspace-preservation.test.ts": 50141, + "server/src/__tests__/heartbeat-orphaned-active-lease-sweep.test.ts": 9957, + "server/src/__tests__/heartbeat-paused-assignee-new-task.test.ts": 10679, + "server/src/__tests__/heartbeat-pending-cleanup-sweep.test.ts": 10615, + "server/src/__tests__/heartbeat-person-tree-dispatch.test.ts": 26150, + "server/src/__tests__/heartbeat-plugin-environment.test.ts": 17979, + "server/src/__tests__/heartbeat-preparation-gap-spans.test.ts": 9938, + "server/src/__tests__/heartbeat-project-env.test.ts": 8109, + "server/src/__tests__/heartbeat-project-repositories.test.ts": 158961, + "server/src/__tests__/heartbeat-provider-limit-wait.test.ts": 24818, + "server/src/__tests__/heartbeat-queued-run-claim-isolation.test.ts": 29189, + "server/src/__tests__/heartbeat-reassignment-deferred-wake.test.ts": 13446, + "server/src/__tests__/heartbeat-referenced-projects.test.ts": 7393, + "server/src/__tests__/heartbeat-refused-assignment-wake.test.ts": 11095, + "server/src/__tests__/heartbeat-remote-referenced-projects.test.ts": 7645, + "server/src/__tests__/heartbeat-remote-workspace-busy.test.ts": 20229, "server/src/__tests__/heartbeat-repository-catalog-recovery.test.ts": 79077, - "server/src/__tests__/heartbeat-responsible-user-invariant.test.ts": 40419, - "server/src/__tests__/heartbeat-restart-claim-lapse.test.ts": 9114, - "server/src/__tests__/heartbeat-retry-scheduling.test.ts": 29924, - "server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts": 19247, - "server/src/__tests__/heartbeat-run-dispatch-lifecycle.test.ts": 4909, - "server/src/__tests__/heartbeat-run-dispatch-work.test.ts": 55625, - "server/src/__tests__/heartbeat-run-event-atomic-append.test.ts": 4300, - "server/src/__tests__/heartbeat-run-event-sequencing.test.ts": 9550, - "server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts": 8375, - "server/src/__tests__/heartbeat-run-log.test.ts": 5688, - "server/src/__tests__/heartbeat-run-output.test.ts": 32251, - "server/src/__tests__/heartbeat-run-privacy-disconnect-retry.test.ts": 2061, - "server/src/__tests__/heartbeat-run-scratch-recovery.test.ts": 7024, - "server/src/__tests__/heartbeat-run-start-handover.test.ts": 17503, - "server/src/__tests__/heartbeat-run-status-payload.test.ts": 5036, - "server/src/__tests__/heartbeat-run-summary.test.ts": 146, - "server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts": 7587, - "server/src/__tests__/heartbeat-running-followup.test.ts": 4677, - "server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts": 9948, - "server/src/__tests__/heartbeat-runtime-services.test.ts": 19999, - "server/src/__tests__/heartbeat-runtime-skills.test.ts": 21005, - "server/src/__tests__/heartbeat-runtime-state.test.ts": 7816, - "server/src/__tests__/heartbeat-scheduling-suppression.test.ts": 6382, - "server/src/__tests__/heartbeat-session-preparation.test.ts": 37766, - "server/src/__tests__/heartbeat-slack-invitation.test.ts": 17991, + "server/src/__tests__/heartbeat-responsible-user-invariant.test.ts": 45664, + "server/src/__tests__/heartbeat-restart-claim-lapse.test.ts": 8577, + "server/src/__tests__/heartbeat-retry-scheduling.test.ts": 54171, + "server/src/__tests__/heartbeat-reviewed-chat-binding.integration.test.ts": 20887, + "server/src/__tests__/heartbeat-run-dispatch-lifecycle.test.ts": 6351, + "server/src/__tests__/heartbeat-run-dispatch-work.test.ts": 51459, + "server/src/__tests__/heartbeat-run-event-atomic-append.test.ts": 15326, + "server/src/__tests__/heartbeat-run-event-sequencing.test.ts": 12287, + "server/src/__tests__/heartbeat-run-lease-release-terminalization.test.ts": 11461, + "server/src/__tests__/heartbeat-run-log.test.ts": 6583, + "server/src/__tests__/heartbeat-run-output.test.ts": 34150, + "server/src/__tests__/heartbeat-run-privacy-disconnect-retry.test.ts": 2830, + "server/src/__tests__/heartbeat-run-scratch-recovery.test.ts": 10008, + "server/src/__tests__/heartbeat-run-start-handover.test.ts": 13908, + "server/src/__tests__/heartbeat-run-status-payload.test.ts": 7089, + "server/src/__tests__/heartbeat-run-summary.test.ts": 896, + "server/src/__tests__/heartbeat-run-terminalize-before-release.test.ts": 11221, + "server/src/__tests__/heartbeat-running-followup.test.ts": 4933, + "server/src/__tests__/heartbeat-runtime-mcp-servers.test.ts": 13449, + "server/src/__tests__/heartbeat-runtime-services.test.ts": 20472, + "server/src/__tests__/heartbeat-runtime-skills.test.ts": 17033, + "server/src/__tests__/heartbeat-runtime-state.test.ts": 8087, + "server/src/__tests__/heartbeat-scheduling-suppression.test.ts": 7131, + "server/src/__tests__/heartbeat-session-preparation.test.ts": 39528, + "server/src/__tests__/heartbeat-slack-invitation.test.ts": 25600, "server/src/__tests__/heartbeat-stale-queue-invalidation.test.ts": 145134, - "server/src/__tests__/heartbeat-start-lock.test.ts": 137, - "server/src/__tests__/heartbeat-startup-fresh-dispatch.test.ts": 10152, - "server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts": 5910, - "server/src/__tests__/heartbeat-subtask-acquired-repository.test.ts": 14084, - "server/src/__tests__/heartbeat-task-context.test.ts": 18787, - "server/src/__tests__/heartbeat-task-directory-restore.test.ts": 11508, - "server/src/__tests__/heartbeat-task-drain-admission-release.test.ts": 24835, - "server/src/__tests__/heartbeat-task-drain.test.ts": 5926, - "server/src/__tests__/heartbeat-task-session-reset.test.ts": 6725, - "server/src/__tests__/heartbeat-timer-wake-session-reset-pf4.test.ts": 6628, - "server/src/__tests__/heartbeat-undispatched-execution-wait.test.ts": 9752, - "server/src/__tests__/heartbeat-workspace-branch-containment.test.ts": 31957, - "server/src/__tests__/heartbeat-workspace-busy.test.ts": 62029, - "server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts": 16173, - "server/src/__tests__/heartbeat-workspace-ready-comment.test.ts": 5306, - "server/src/__tests__/heartbeat-workspace-session.test.ts": 6712, - "server/src/__tests__/heartbeat-workspace-source-trust.test.ts": 68708, - "server/src/__tests__/heartbeat-worktree-suppression.test.ts": 14571, - "server/src/__tests__/heartbeat-zombie-guard.test.ts": 5723, - "server/src/__tests__/helpers/external-test-database.test.ts": 121, - "server/src/__tests__/helpers/full-database-response-capture.test.ts": 421, - "server/src/__tests__/helpers/truncate-with-deadlock-retry.test.ts": 400, - "server/src/__tests__/hire-hook.test.ts": 1706, - "server/src/__tests__/hiring-operational-examples.test.ts": 1062, - "server/src/__tests__/historical-cleanup-verification.test.ts": 32747, - "server/src/__tests__/historical-provider-credentials.test.ts": 8909, - "server/src/__tests__/http-adapter-remote-fetch.test.ts": 152, - "server/src/__tests__/http-log-aborted-response.test.ts": 587, - "server/src/__tests__/http-log-policy.test.ts": 107, - "server/src/__tests__/http-log-redaction.test.ts": 4382, - "server/src/__tests__/human-directed-work.test.ts": 7807, - "server/src/__tests__/idle-accounting-work.test.ts": 9749, - "server/src/__tests__/idle-admission.test.ts": 675, + "server/src/__tests__/heartbeat-startup-fresh-dispatch.test.ts": 14060, + "server/src/__tests__/heartbeat-status-preserving-telemetry.test.ts": 7654, + "server/src/__tests__/heartbeat-stop-queued-task.test.ts": 71194, + "server/src/__tests__/heartbeat-subtask-acquired-repository.test.ts": 19535, + "server/src/__tests__/heartbeat-task-context.test.ts": 20582, + "server/src/__tests__/heartbeat-task-directory-restore.test.ts": 10598, + "server/src/__tests__/heartbeat-task-drain-admission-release.test.ts": 23078, + "server/src/__tests__/heartbeat-task-drain.test.ts": 8334, + "server/src/__tests__/heartbeat-task-session-reset.test.ts": 7866, + "server/src/__tests__/heartbeat-terminate-pending-native-retry.test.ts": 8453, + "server/src/__tests__/heartbeat-timer-wake-session-reset-pf4.test.ts": 8080, + "server/src/__tests__/heartbeat-undispatched-execution-wait.test.ts": 10407, + "server/src/__tests__/heartbeat-workspace-branch-containment.test.ts": 57923, + "server/src/__tests__/heartbeat-workspace-busy.test.ts": 85133, + "server/src/__tests__/heartbeat-workspace-finalize-branch.test.ts": 15287, + "server/src/__tests__/heartbeat-workspace-ready-comment.test.ts": 7488, + "server/src/__tests__/heartbeat-workspace-session.test.ts": 25884, + "server/src/__tests__/heartbeat-workspace-source-trust.test.ts": 83786, + "server/src/__tests__/heartbeat-worktree-suppression.test.ts": 16354, + "server/src/__tests__/heartbeat-zombie-guard.test.ts": 7385, + "server/src/__tests__/helpers/external-test-database.test.ts": 743, + "server/src/__tests__/helpers/full-database-response-capture.test.ts": 963, + "server/src/__tests__/helpers/truncate-with-deadlock-retry.test.ts": 743, + "server/src/__tests__/hire-hook.test.ts": 2353, + "server/src/__tests__/historical-cleanup-verification.test.ts": 29875, + "server/src/__tests__/historical-provider-credentials.test.ts": 8249, + "server/src/__tests__/http-adapter-remote-fetch.test.ts": 806, + "server/src/__tests__/http-log-aborted-response.test.ts": 1169, + "server/src/__tests__/http-log-policy.test.ts": 759, + "server/src/__tests__/http-log-redaction.test.ts": 6807, + "server/src/__tests__/human-directed-work.test.ts": 8399, + "server/src/__tests__/idle-accounting-work.test.ts": 7533, + "server/src/__tests__/idle-admission.test.ts": 1366, "server/src/__tests__/idle-completed-history.test.ts": 105817, - "server/src/__tests__/idle-connection-history.test.ts": 34042, - "server/src/__tests__/idle-database-backup-sync.test.ts": 189, - "server/src/__tests__/idle-database-backup.test.ts": 177, - "server/src/__tests__/idle-domain-deadlines-postgres.test.ts": 36766, - "server/src/__tests__/idle-incoming-wake.test.ts": 26232, + "server/src/__tests__/idle-connection-history.test.ts": 39494, + "server/src/__tests__/idle-database-backup-sync.test.ts": 890, + "server/src/__tests__/idle-database-backup.test.ts": 999, + "server/src/__tests__/idle-domain-deadlines-postgres.test.ts": 38880, + "server/src/__tests__/idle-incoming-wake.test.ts": 32015, "server/src/__tests__/idle-issue-schedule.test.ts": 45057, - "server/src/__tests__/idle-local-work.test.ts": 542, + "server/src/__tests__/idle-local-work.test.ts": 607, "server/src/__tests__/idle-native-finalization.test.ts": 47149, - "server/src/__tests__/idle-response-waits.test.ts": 39709, - "server/src/__tests__/idle-scheduled-work.test.ts": 428, - "server/src/__tests__/idle-sleep-diagnostics-postgres.test.ts": 16041, - "server/src/__tests__/idle-sleep-diagnostics.test.ts": 6110, - "server/src/__tests__/idle-sleep-preparation.test.ts": 6006, + "server/src/__tests__/idle-response-waits.test.ts": 37561, + "server/src/__tests__/idle-scheduled-work.test.ts": 669, + "server/src/__tests__/idle-sleep-diagnostics-postgres.test.ts": 13581, + "server/src/__tests__/idle-sleep-diagnostics.test.ts": 7789, + "server/src/__tests__/idle-sleep-preparation.test.ts": 6643, "server/src/__tests__/idle-sleep-safety.test.ts": 150013, - "server/src/__tests__/import-spool-cleanup-work.test.ts": 3117, - "server/src/__tests__/inbound-queue-discovery.test.ts": 8589, - "server/src/__tests__/inbox-dismissals.test.ts": 8929, - "server/src/__tests__/inbox-mine-candidates.test.ts": 7198, - "server/src/__tests__/instance-settings-cloud-defaults.test.ts": 5232, - "server/src/__tests__/instance-settings-managed-overlay.test.ts": 5669, - "server/src/__tests__/instance-settings-operator-defaults.test.ts": 4287, - "server/src/__tests__/instance-settings-service.test.ts": 4897, - "server/src/__tests__/instrumentation-signals.test.ts": 129, - "server/src/__tests__/instrumentation.test.ts": 225, - "server/src/__tests__/interaction-resolution-cross-issue-cap-postgres.test.ts": 9009, - "server/src/__tests__/interrupted-preparation-hold-settle.test.ts": 14970, - "server/src/__tests__/interrupted-preparation-restore-retry.test.ts": 8422, - "server/src/__tests__/invitation-token-redaction.test.ts": 104, - "server/src/__tests__/invite-join-grants.test.ts": 887, - "server/src/__tests__/invite-rate-limit.test.ts": 100, - "server/src/__tests__/invite-token-entropy.test.ts": 4428, + "server/src/__tests__/import-spool-cleanup-work.test.ts": 3447, + "server/src/__tests__/inbound-queue-discovery.test.ts": 8858, + "server/src/__tests__/inbox-dismissals.test.ts": 8425, + "server/src/__tests__/inbox-mine-candidates.test.ts": 7909, + "server/src/__tests__/instance-settings-cache.test.ts": 9036, + "server/src/__tests__/instance-settings-cloud-defaults.test.ts": 6290, + "server/src/__tests__/instance-settings-managed-overlay.test.ts": 6174, + "server/src/__tests__/instance-settings-operator-defaults.test.ts": 5978, + "server/src/__tests__/instance-settings-service.test.ts": 4759, + "server/src/__tests__/instrumentation-signals.test.ts": 1055, + "server/src/__tests__/instrumentation.test.ts": 1120, + "server/src/__tests__/interaction-resolution-cross-issue-cap-postgres.test.ts": 10860, + "server/src/__tests__/interrupted-preparation-hold-settle.test.ts": 15835, + "server/src/__tests__/interrupted-preparation-restore-retry.test.ts": 9335, + "server/src/__tests__/invitation-token-redaction.test.ts": 783, + "server/src/__tests__/invite-join-grants.test.ts": 1303, + "server/src/__tests__/invite-rate-limit.test.ts": 643, + "server/src/__tests__/invite-token-entropy.test.ts": 4983, "server/src/__tests__/isolated-repository-rehome.test.ts": 93407, - "server/src/__tests__/isolated-task-directory-retention-config.test.ts": 1092, - "server/src/__tests__/isolated-task-directory-retention.test.ts": 26103, - "server/src/__tests__/isolated-test-home.test.ts": 267, - "server/src/__tests__/issue-blocker-attention.test.ts": 7395, - "server/src/__tests__/issue-blocker-stall-waiter-statement.test.ts": 9914, - "server/src/__tests__/issue-blocker-stall-wakeups.test.ts": 22272, - "server/src/__tests__/issue-comment-receipt-postgres.test.ts": 6627, - "server/src/__tests__/issue-comment-redaction.test.ts": 7221, - "server/src/__tests__/issue-context-usage.test.ts": 2089, - "server/src/__tests__/issue-continuation-summary.test.ts": 1797, - "server/src/__tests__/issue-creation-source-read.test.ts": 2891, - "server/src/__tests__/issue-dependency-restore-wake-policy.test.ts": 1486, - "server/src/__tests__/issue-display-status.test.ts": 22416, - "server/src/__tests__/issue-execution-policy-persistence.test.ts": 5556, - "server/src/__tests__/issue-execution-policy.test.ts": 967, - "server/src/__tests__/issue-existing-branch-validation-status.test.ts": 5635, - "server/src/__tests__/issue-goal-fallback.test.ts": 100, - "server/src/__tests__/issue-graph-liveness-equivalence.test.ts": 1515, - "server/src/__tests__/issue-list-review-wait-authorization.integration.test.ts": 5717, - "server/src/__tests__/issue-liveness.test.ts": 910, - "server/src/__tests__/issue-monitor-scheduler.test.ts": 38235, - "server/src/__tests__/issue-read-filter-batching.test.ts": 19522, - "server/src/__tests__/issue-reassignment-queued-run.test.ts": 12280, + "server/src/__tests__/isolated-task-directory-retention-config.test.ts": 1632, + "server/src/__tests__/isolated-task-directory-retention.test.ts": 36349, + "server/src/__tests__/isolated-test-home.test.ts": 932, + "server/src/__tests__/issue-blocker-attention.test.ts": 12671, + "server/src/__tests__/issue-blocker-stall-waiter-statement.test.ts": 8086, + "server/src/__tests__/issue-blocker-stall-wakeups.test.ts": 22472, + "server/src/__tests__/issue-comment-receipt-postgres.test.ts": 6450, + "server/src/__tests__/issue-comment-redaction.test.ts": 10914, + "server/src/__tests__/issue-context-usage.test.ts": 1905, + "server/src/__tests__/issue-continuation-summary.test.ts": 1964, + "server/src/__tests__/issue-creation-source-read.test.ts": 3828, + "server/src/__tests__/issue-dependency-restore-wake-policy.test.ts": 2213, + "server/src/__tests__/issue-detail-statements.test.ts": 9613, + "server/src/__tests__/issue-display-status.test.ts": 20706, + "server/src/__tests__/issue-execution-policy-persistence.test.ts": 6060, + "server/src/__tests__/issue-execution-policy.test.ts": 1462, + "server/src/__tests__/issue-existing-branch-validation-status.test.ts": 7389, + "server/src/__tests__/issue-goal-fallback.test.ts": 727, + "server/src/__tests__/issue-graph-liveness-equivalence.test.ts": 2067, + "server/src/__tests__/issue-list-review-wait-authorization.integration.test.ts": 6933, + "server/src/__tests__/issue-liveness.test.ts": 1622, + "server/src/__tests__/issue-monitor-scheduler.test.ts": 34340, + "server/src/__tests__/issue-read-filter-batching.test.ts": 23819, + "server/src/__tests__/issue-reassignment-queued-run.test.ts": 8813, "server/src/__tests__/issue-recovery-actions.test.ts": 46806, + "server/src/__tests__/issue-recovery-activity-hints.test.ts": 112944, + "server/src/__tests__/issue-recovery-agent-row-write-census.test.ts": 74922, "server/src/__tests__/issue-recovery-assignments.test.ts": 133886, + "server/src/__tests__/issue-recovery-company-reload-census.test.ts": 120352, "server/src/__tests__/issue-recovery-conversations.test.ts": 74439, "server/src/__tests__/issue-recovery-deadlines.test.ts": 148225, "server/src/__tests__/issue-recovery-dependencies.test.ts": 178002, - "server/src/__tests__/issue-recovery-work-lifecycle.test.ts": 4702, - "server/src/__tests__/issue-references-service.test.ts": 2631, - "server/src/__tests__/issue-remove-cascade.test.ts": 6308, - "server/src/__tests__/issue-review-attention.test.ts": 6317, - "server/src/__tests__/issue-review-policy.test.ts": 2467, - "server/src/__tests__/issue-rewake-throttle.test.ts": 131, - "server/src/__tests__/issue-runtime-workspace-binding.test.ts": 6050, - "server/src/__tests__/issue-thread-interactions-service.test.ts": 33922, - "server/src/__tests__/issue-thread-interactions-telemetry.test.ts": 6510, - "server/src/__tests__/issue-tree-control-service-unit.test.ts": 4283, - "server/src/__tests__/issue-tree-control-service.test.ts": 7179, - "server/src/__tests__/issue-tree-pause-resume-run.test.ts": 54565, - "server/src/__tests__/issue-update-lock-contention-postgres.test.ts": 8215, - "server/src/__tests__/issues-assignee-unread.test.ts": 11836, - "server/src/__tests__/issues-creation-visibility.test.ts": 11090, - "server/src/__tests__/issues-list-query-parsing.test.ts": 12313, - "server/src/__tests__/issues-parent-id-alias.test.ts": 8102, - "server/src/__tests__/issues-unread-inbox.test.ts": 4545, - "server/src/__tests__/issues-user-context.test.ts": 5778, - "server/src/__tests__/join-request-dedupe.test.ts": 100, - "server/src/__tests__/join-request-retention-work.test.ts": 18416, - "server/src/__tests__/json-parse-error-handler.test.ts": 4912, - "server/src/__tests__/json-schema-secret-refs.test.ts": 100, - "server/src/__tests__/kimi-connection-probe.test.ts": 1324, - "server/src/__tests__/kimi-local-skill-sync.test.ts": 1043, - "server/src/__tests__/legacy-continuation-authority.test.ts": 14206, - "server/src/__tests__/legacy-finalization-regression.test.ts": 9831, - "server/src/__tests__/legacy-runtime-tool-refresh.test.ts": 1242, - "server/src/__tests__/legacy-workspace-rehome.test.ts": 18251, - "server/src/__tests__/legacy-workspace-restore-recovery.test.ts": 8575, - "server/src/__tests__/link-previews.test.ts": 1225, - "server/src/__tests__/live-events-run-read.test.ts": 8304, - "server/src/__tests__/live-events-toast.test.ts": 5627, - "server/src/__tests__/live-events-ws.test.ts": 5791, + "server/src/__tests__/issue-recovery-idle-backstop.test.ts": 270345, + "server/src/__tests__/issue-recovery-live-run-agent-census.test.ts": 144083, + "server/src/__tests__/issue-recovery-pass-reads.test.ts": 18095, + "server/src/__tests__/issue-recovery-recorded-decision-idle.test.ts": 33312, + "server/src/__tests__/issue-recovery-review-wait-pass.test.ts": 8021, + "server/src/__tests__/issue-recovery-saved-deferrals.test.ts": 11424, + "server/src/__tests__/issue-recovery-signal-fanout.test.ts": 11432, + "server/src/__tests__/issue-recovery-terminal-run-settling.test.ts": 8681, + "server/src/__tests__/issue-recovery-work-debug-attribution.test.ts": 41278, + "server/src/__tests__/issue-recovery-work-lifecycle.test.ts": 6108, + "server/src/__tests__/issue-references-service.test.ts": 3501, + "server/src/__tests__/issue-remove-cascade.test.ts": 5867, + "server/src/__tests__/issue-review-attention.test.ts": 7811, + "server/src/__tests__/issue-review-policy.test.ts": 2666, + "server/src/__tests__/issue-rewake-throttle.test.ts": 595, + "server/src/__tests__/issue-runs-read-cost.test.ts": 11092, + "server/src/__tests__/issue-runtime-workspace-binding.test.ts": 8013, + "server/src/__tests__/issue-thread-interactions-service.test.ts": 23650, + "server/src/__tests__/issue-thread-interactions-telemetry.test.ts": 7122, + "server/src/__tests__/issue-tree-control-service-unit.test.ts": 4369, + "server/src/__tests__/issue-tree-control-service.test.ts": 7372, + "server/src/__tests__/issue-tree-pause-resume-run.test.ts": 65684, + "server/src/__tests__/issue-update-lock-contention-postgres.test.ts": 7884, + "server/src/__tests__/issues-assignee-unread.test.ts": 16311, + "server/src/__tests__/issues-creation-visibility.test.ts": 12304, + "server/src/__tests__/issues-list-query-parsing.test.ts": 12785, + "server/src/__tests__/issues-parent-id-alias.test.ts": 12056, + "server/src/__tests__/issues-unread-inbox.test.ts": 7414, + "server/src/__tests__/issues-user-context.test.ts": 7168, + "server/src/__tests__/join-request-dedupe.test.ts": 783, + "server/src/__tests__/join-request-retention-work.test.ts": 17441, + "server/src/__tests__/json-parse-error-handler.test.ts": 5885, + "server/src/__tests__/json-schema-secret-refs.test.ts": 1028, + "server/src/__tests__/kimi-connection-probe.test.ts": 1393, + "server/src/__tests__/kimi-local-skill-sync.test.ts": 2070, + "server/src/__tests__/legacy-continuation-authority.test.ts": 18643, + "server/src/__tests__/legacy-finalization-regression.test.ts": 9718, + "server/src/__tests__/legacy-runtime-tool-refresh.test.ts": 1803, + "server/src/__tests__/legacy-workspace-rehome.test.ts": 16273, + "server/src/__tests__/legacy-workspace-restore-lock-contention.test.ts": 6556, + "server/src/__tests__/legacy-workspace-restore-recovery.test.ts": 9551, + "server/src/__tests__/link-preview-store.integration.test.ts": 9626, + "server/src/__tests__/link-previews.test.ts": 2127, + "server/src/__tests__/live-events-run-read.test.ts": 11582, + "server/src/__tests__/live-events-toast.test.ts": 6468, + "server/src/__tests__/live-events-ws.test.ts": 7141, "server/src/__tests__/live-recovery-work.test.ts": 207953, - "server/src/__tests__/liveness.test.ts": 5732, - "server/src/__tests__/local-agent-process-boundary.test.ts": 9276, - "server/src/__tests__/local-ai-credential-file.test.ts": 109, - "server/src/__tests__/local-ai-credentials.test.ts": 1447, - "server/src/__tests__/local-ai-login-policy.test.ts": 100, - "server/src/__tests__/local-encrypted-cipher.test.ts": 191, - "server/src/__tests__/local-service-supervisor.test.ts": 8056, - "server/src/__tests__/log-redaction.test.ts": 122, - "server/src/__tests__/logger-invitation-redaction.test.ts": 324, - "server/src/__tests__/logger-tz.test.ts": 119, - "server/src/__tests__/login-cleanup-work.test.ts": 14900, - "server/src/__tests__/login-session-runtime.test.ts": 4073, - "server/src/__tests__/maintenance-harness-resources.test.ts": 183, - "server/src/__tests__/maintenance-postgres-proxy.test.ts": 2208, - "server/src/__tests__/managed-cloud-prerequisites.test.ts": 2057, - "server/src/__tests__/managed-config.test.ts": 906, - "server/src/__tests__/managed-instance-default.test.ts": 6015, - "server/src/__tests__/managed-loopback-auth.test.ts": 2107, - "server/src/__tests__/managed-plugin-environments.test.ts": 7378, - "server/src/__tests__/managed-plugin-worker-env.test.ts": 1044, - "server/src/__tests__/managed-repository-checkout.test.ts": 7092, - "server/src/__tests__/managed-runtime-public-url.test.ts": 942, - "server/src/__tests__/managed-skill-content.test.ts": 119948, - "server/src/__tests__/managed-worktree-inspection.test.ts": 5910, - "server/src/__tests__/mcp-apps.test.ts": 11205, - "server/src/__tests__/mcp-http.test.ts": 1003, - "server/src/__tests__/mcp-protocol-versions.test.ts": 8555, - "server/src/__tests__/mcp-skills.test.ts": 10023, - "server/src/__tests__/memory-connectors.test.ts": 4948, - "server/src/__tests__/merged-pr-confirmation-sweep.test.ts": 5334, - "server/src/__tests__/merged-pr-confirmation-work.test.ts": 13583, - "server/src/__tests__/missing-empty-task-directory.test.ts": 5187, - "server/src/__tests__/monthly-spend-service.test.ts": 4775, - "server/src/__tests__/muse-client-contract.test.ts": 10478, - "server/src/__tests__/muse-control.test.ts": 117248, - "server/src/__tests__/muse-terminal-settlement.test.ts": 27119, - "server/src/__tests__/native-cancellation-delivery.test.ts": 5578, - "server/src/__tests__/native-cancellation-request.integration.test.ts": 6790, - "server/src/__tests__/native-connection-baseline-fixture.test.ts": 11273, - "server/src/__tests__/native-environment-settlement-work.test.ts": 18049, - "server/src/__tests__/native-event-boundary-golden.test.ts": 2915, - "server/src/__tests__/native-exhausted-finalization-retry.test.ts": 8427, - "server/src/__tests__/native-finalization-migration.test.ts": 4250, - "server/src/__tests__/native-finalization-recovery.test.ts": 8517, - "server/src/__tests__/native-finalization-retry-budget.test.ts": 6107, - "server/src/__tests__/native-finalization-settled-candidates.test.ts": 6662, - "server/src/__tests__/native-harness-backup-expiration-config.test.ts": 872, + "server/src/__tests__/live-runs-batched-reads.test.ts": 15576, + "server/src/__tests__/liveness.test.ts": 5462, + "server/src/__tests__/local-agent-process-boundary.test.ts": 13010, + "server/src/__tests__/local-ai-credential-file.test.ts": 539, + "server/src/__tests__/local-ai-credentials.test.ts": 2157, + "server/src/__tests__/local-ai-login-policy.test.ts": 690, + "server/src/__tests__/local-encrypted-cipher.test.ts": 1057, + "server/src/__tests__/local-service-supervisor.test.ts": 9920, + "server/src/__tests__/log-redaction.test.ts": 905, + "server/src/__tests__/logger-invitation-redaction.test.ts": 918, + "server/src/__tests__/logger-tz.test.ts": 673, + "server/src/__tests__/login-cleanup-work.test.ts": 13356, + "server/src/__tests__/login-session-runtime.test.ts": 6254, + "server/src/__tests__/maintenance-harness-resources.test.ts": 839, + "server/src/__tests__/maintenance-postgres-proxy.test.ts": 2460, + "server/src/__tests__/managed-cloud-prerequisites.test.ts": 2259, + "server/src/__tests__/managed-config.test.ts": 1647, + "server/src/__tests__/managed-instance-default.test.ts": 7354, + "server/src/__tests__/managed-loopback-auth.test.ts": 2257, + "server/src/__tests__/managed-plugin-environments.test.ts": 8655, + "server/src/__tests__/managed-plugin-worker-env.test.ts": 1655, + "server/src/__tests__/managed-repository-checkout.test.ts": 5948, + "server/src/__tests__/managed-runtime-public-url.test.ts": 1800, + "server/src/__tests__/managed-skill-content.test.ts": 152199, + "server/src/__tests__/managed-worktree-inspection.test.ts": 8358, + "server/src/__tests__/mcp-apps.test.ts": 10157, + "server/src/__tests__/mcp-elicitation.test.ts": 18313, + "server/src/__tests__/mcp-error-message.test.ts": 843, + "server/src/__tests__/mcp-http.test.ts": 1731, + "server/src/__tests__/mcp-protocol-versions.test.ts": 9056, + "server/src/__tests__/mcp-skills.test.ts": 11975, + "server/src/__tests__/mcp-task-work.test.ts": 602, + "server/src/__tests__/mcp-tasks-demo-server.test.ts": 27076, + "server/src/__tests__/mcp-tasks.test.ts": 42151, + "server/src/__tests__/memory-connectors.test.ts": 5709, + "server/src/__tests__/merged-pr-confirmation-sweep.test.ts": 8317, + "server/src/__tests__/merged-pr-confirmation-work.test.ts": 17605, + "server/src/__tests__/missing-empty-task-directory.test.ts": 6123, + "server/src/__tests__/monthly-spend-service.test.ts": 7225, + "server/src/__tests__/muse-client-contract.test.ts": 13742, + "server/src/__tests__/muse-control.test.ts": 107452, + "server/src/__tests__/muse-terminal-settlement.test.ts": 25265, + "server/src/__tests__/native-cancellation-delivery.test.ts": 6799, + "server/src/__tests__/native-cancellation-request.integration.test.ts": 8844, + "server/src/__tests__/native-connection-baseline-fixture.test.ts": 12137, + "server/src/__tests__/native-environment-settlement-work.test.ts": 19901, + "server/src/__tests__/native-event-boundary-golden.test.ts": 3132, + "server/src/__tests__/native-exhausted-finalization-retry.test.ts": 9032, + "server/src/__tests__/native-failed-run-owner-release-idle.test.ts": 13796, + "server/src/__tests__/native-finalization-recovery.test.ts": 7766, + "server/src/__tests__/native-finalization-retry-budget.test.ts": 5766, + "server/src/__tests__/native-finalization-settled-candidates.test.ts": 7997, + "server/src/__tests__/native-harness-backup-expiration-config.test.ts": 1632, "server/src/__tests__/native-harness-backup-expiration.test.ts": 34702, - "server/src/__tests__/native-interaction-bridge-closed.test.ts": 5990, - "server/src/__tests__/native-interaction-bridge.test.ts": 7933, - "server/src/__tests__/native-observer-replay.test.ts": 6632, - "server/src/__tests__/native-plan-proposal-sync.test.ts": 6829, - "server/src/__tests__/native-procedure-measurement.test.ts": 5212, - "server/src/__tests__/native-question-process-handoff.test.ts": 22874, - "server/src/__tests__/native-recovery-dispatch-lease-reacquire.test.ts": 4782, - "server/src/__tests__/native-recovery-notice-work.test.ts": 14039, - "server/src/__tests__/native-result-commit-work.test.ts": 16361, - "server/src/__tests__/native-run-projection-work.test.ts": 38079, - "server/src/__tests__/native-runner-input-boundary.test.ts": 272, - "server/src/__tests__/native-runtime-response-delivery.test.ts": 6301, - "server/src/__tests__/native-sandbox-lifecycle.test.ts": 4523, - "server/src/__tests__/native-session-resumption.test.ts": 28107, - "server/src/__tests__/native-settled-process-release.test.ts": 13012, - "server/src/__tests__/native-startup-cleanup-recovery.test.ts": 12397, + "server/src/__tests__/native-interaction-bridge-closed.test.ts": 5482, + "server/src/__tests__/native-interaction-bridge.test.ts": 7765, + "server/src/__tests__/native-observer-replay.test.ts": 8254, + "server/src/__tests__/native-plan-proposal-sync.test.ts": 6802, + "server/src/__tests__/native-procedure-measurement.test.ts": 6774, + "server/src/__tests__/native-question-process-handoff.test.ts": 28851, + "server/src/__tests__/native-recovery-dispatch-lease-reacquire.test.ts": 6988, + "server/src/__tests__/native-recovery-notice-work.test.ts": 15693, + "server/src/__tests__/native-result-commit-idle.test.ts": 28978, + "server/src/__tests__/native-result-commit-work.test.ts": 14821, + "server/src/__tests__/native-retention-blocker-batch.test.ts": 14621, + "server/src/__tests__/native-run-projection-work.test.ts": 36499, + "server/src/__tests__/native-runner-input-boundary.test.ts": 671, + "server/src/__tests__/native-runtime-response-delivery.test.ts": 7102, + "server/src/__tests__/native-sandbox-lifecycle.test.ts": 7167, + "server/src/__tests__/native-session-resumption.test.ts": 30914, + "server/src/__tests__/native-settled-process-release.test.ts": 12518, + "server/src/__tests__/native-startup-cleanup-recovery.test.ts": 13606, "server/src/__tests__/native-status-arbiter-corpus.test.ts": 98250, "server/src/__tests__/native-status-reassessment-work.test.ts": 57482, - "server/src/__tests__/native-workspace-finalization-work.test.ts": 12818, - "server/src/__tests__/native-workspace-sync-history.test.ts": 45036, - "server/src/__tests__/native-workspace-sync-retention-config.test.ts": 790, - "server/src/__tests__/native-workspace-sync-retention.test.ts": 9186, - "server/src/__tests__/native-workspace-sync.test.ts": 1653, + "server/src/__tests__/native-tool-call-loop-continuation.test.ts": 12786, + "server/src/__tests__/native-workspace-finalization-work.test.ts": 12186, + "server/src/__tests__/native-workspace-sync-history.test.ts": 38523, + "server/src/__tests__/native-workspace-sync-retention-config.test.ts": 1494, + "server/src/__tests__/native-workspace-sync-retention.test.ts": 7658, + "server/src/__tests__/native-workspace-sync.test.ts": 2469, "server/src/__tests__/nested-clone-migration.test.ts": 78158, - "server/src/__tests__/oauth-client-metadata.test.ts": 4610, - "server/src/__tests__/onboarding-approval-history.test.ts": 18623, - "server/src/__tests__/onboarding-first-task-admission.test.ts": 36543, - "server/src/__tests__/onepassword-connection.test.ts": 8535, - "server/src/__tests__/online-workspace-migration-compatibility.test.ts": 9767, - "server/src/__tests__/openclaw-gateway-adapter.test.ts": 1169, - "server/src/__tests__/opencode-local-adapter.test.ts": 1057, - "server/src/__tests__/opencode-local-skill-sync.test.ts": 977, - "server/src/__tests__/owner-chat-instruction-authority.test.ts": 10797, - "server/src/__tests__/owner-gone-attestation.test.ts": 8525, + "server/src/__tests__/oauth-client-metadata.test.ts": 10057, + "server/src/__tests__/onboarding-approval-history.test.ts": 21935, + "server/src/__tests__/onboarding-first-task-admission.test.ts": 43108, + "server/src/__tests__/onepassword-connection.test.ts": 10517, + "server/src/__tests__/online-workspace-migration-compatibility.test.ts": 9742, + "server/src/__tests__/openclaw-gateway-adapter.test.ts": 2147, + "server/src/__tests__/opencode-local-adapter.test.ts": 1878, + "server/src/__tests__/opencode-local-skill-sync.test.ts": 1868, + "server/src/__tests__/owner-chat-instruction-authority.test.ts": 11490, + "server/src/__tests__/owner-gone-attestation.test.ts": 10180, "server/src/__tests__/ownership-reconciliation-report.test.ts": 73104, - "server/src/__tests__/paperclip-env.test.ts": 970, - "server/src/__tests__/paperclip-issue-update-helper.test.ts": 5059, - "server/src/__tests__/paperclip-semantic-conformance.test.ts": 10533, - "server/src/__tests__/paperclip-skill-utils.test.ts": 8268, - "server/src/__tests__/parse-status-filter.test.ts": 4523, - "server/src/__tests__/persisted-workspace-source.test.ts": 7541, - "server/src/__tests__/person-only-page-guidance.test.ts": 2645, - "server/src/__tests__/photon/channel.integration.test.ts": 33692, - "server/src/__tests__/photon/photon.test.ts": 1295, - "server/src/__tests__/pi-local-adapter-environment.test.ts": 1124, - "server/src/__tests__/pi-local-execute.test.ts": 1327, - "server/src/__tests__/pi-local-skill-sync.test.ts": 917, - "server/src/__tests__/plan-task-fixture.test.ts": 14085, - "server/src/__tests__/plugin-access-authorization-host-services.test.ts": 7774, - "server/src/__tests__/plugin-agent-sessions.test.ts": 6393, - "server/src/__tests__/plugin-config-startup-delivery.test.ts": 2595, - "server/src/__tests__/plugin-config-validator.test.ts": 1151, - "server/src/__tests__/plugin-database.test.ts": 2675, - "server/src/__tests__/plugin-dev-watcher.test.ts": 337, - "server/src/__tests__/plugin-environment-driver-ready-recovery.test.ts": 12061, - "server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts": 1463, - "server/src/__tests__/plugin-environment-driver-seam.test.ts": 1213, - "server/src/__tests__/plugin-environment-driver-selection.test.ts": 2310, - "server/src/__tests__/plugin-execution-workspace-bridge.test.ts": 112, - "server/src/__tests__/plugin-fresh-workspaces.integration.test.ts": 7216, - "server/src/__tests__/plugin-host-services-span.test.ts": 6347, - "server/src/__tests__/plugin-idle-manager.test.ts": 10006, - "server/src/__tests__/plugin-idle-rpc.test.ts": 2293, - "server/src/__tests__/plugin-inspection-concurrency.test.ts": 1651, - "server/src/__tests__/plugin-install-autobuild.test.ts": 7586, - "server/src/__tests__/plugin-install-guard.test.ts": 1748, - "server/src/__tests__/plugin-lifecycle-delivery.test.ts": 9362, - "server/src/__tests__/plugin-lifecycle-restart.test.ts": 2011, - "server/src/__tests__/plugin-loader-activation-timeout.test.ts": 18507, - "server/src/__tests__/plugin-loader-error-retry.test.ts": 2007, - "server/src/__tests__/plugin-local-folders.test.ts": 205, - "server/src/__tests__/plugin-managed-agents.test.ts": 9851, - "server/src/__tests__/plugin-managed-routine-guidance.test.ts": 3062, - "server/src/__tests__/plugin-managed-routines.test.ts": 8386, - "server/src/__tests__/plugin-managed-skills.test.ts": 11147, - "server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts": 6014, - "server/src/__tests__/plugin-orchestration-apis.test.ts": 14048, - "server/src/__tests__/plugin-organization-switcher.test.ts": 1020, - "server/src/__tests__/plugin-project-snapshots.test.ts": 123, - "server/src/__tests__/plugin-runner-task.integration.test.ts": 9288, - "server/src/__tests__/plugin-sandbox-provider-config-validation.test.ts": 1880, + "server/src/__tests__/paperclip-env.test.ts": 1678, + "server/src/__tests__/paperclip-issue-update-helper.test.ts": 6452, + "server/src/__tests__/paperclip-semantic-conformance.test.ts": 11359, + "server/src/__tests__/paperclip-skill-utils.test.ts": 9225, + "server/src/__tests__/parse-status-filter.test.ts": 5230, + "server/src/__tests__/persisted-workspace-source.test.ts": 8968, + "server/src/__tests__/photon/channel.integration.test.ts": 38384, + "server/src/__tests__/photon/photon.test.ts": 1559, + "server/src/__tests__/pi-local-adapter-environment.test.ts": 2327, + "server/src/__tests__/pi-local-execute.test.ts": 2644, + "server/src/__tests__/pi-local-skill-sync.test.ts": 1664, + "server/src/__tests__/plan-task-fixture.test.ts": 12701, + "server/src/__tests__/plugin-access-authorization-host-services.test.ts": 7499, + "server/src/__tests__/plugin-agent-sessions.test.ts": 8062, + "server/src/__tests__/plugin-config-startup-delivery.test.ts": 2482, + "server/src/__tests__/plugin-config-validator.test.ts": 1779, + "server/src/__tests__/plugin-connectors-circleback-parity.test.ts": 10883, + "server/src/__tests__/plugin-connectors-plugin-transport.test.ts": 10639, + "server/src/__tests__/plugin-database.test.ts": 2041, + "server/src/__tests__/plugin-dev-watcher.test.ts": 943, + "server/src/__tests__/plugin-environment-driver-ready-recovery.test.ts": 10383, + "server/src/__tests__/plugin-environment-driver-sandbox-capabilities.test.ts": 1855, + "server/src/__tests__/plugin-environment-driver-seam.test.ts": 1700, + "server/src/__tests__/plugin-environment-driver-selection.test.ts": 2905, + "server/src/__tests__/plugin-execution-workspace-bridge.test.ts": 792, + "server/src/__tests__/plugin-fresh-workspaces.integration.test.ts": 8075, + "server/src/__tests__/plugin-host-services-span.test.ts": 7416, + "server/src/__tests__/plugin-idle-manager.test.ts": 11378, + "server/src/__tests__/plugin-idle-rpc.test.ts": 3073, + "server/src/__tests__/plugin-inspection-concurrency.test.ts": 2286, + "server/src/__tests__/plugin-install-autobuild.test.ts": 9089, + "server/src/__tests__/plugin-install-guard.test.ts": 2486, + "server/src/__tests__/plugin-lifecycle-delivery.test.ts": 11826, + "server/src/__tests__/plugin-lifecycle-restart.test.ts": 2624, + "server/src/__tests__/plugin-loader-activation-timeout.test.ts": 18736, + "server/src/__tests__/plugin-loader-error-retry.test.ts": 2060, + "server/src/__tests__/plugin-local-folders.test.ts": 818, + "server/src/__tests__/plugin-managed-agents.test.ts": 13067, + "server/src/__tests__/plugin-managed-routines.test.ts": 8478, + "server/src/__tests__/plugin-managed-skills.test.ts": 14142, + "server/src/__tests__/plugin-operational-reads-tenant-scope.test.ts": 9099, + "server/src/__tests__/plugin-orchestration-apis.test.ts": 15274, + "server/src/__tests__/plugin-organization-switcher.test.ts": 1610, + "server/src/__tests__/plugin-project-snapshots.test.ts": 763, + "server/src/__tests__/plugin-runner-task.integration.test.ts": 9392, + "server/src/__tests__/plugin-sandbox-provider-config-validation.test.ts": 1723, + "server/src/__tests__/plugin-sandbox-provider-schema-census.test.ts": 7215, "server/src/__tests__/plugin-scheduled-work.test.ts": 69649, - "server/src/__tests__/plugin-sdk-orchestration-contract.test.ts": 833, - "server/src/__tests__/plugin-sdk-testing.test.ts": 713, - "server/src/__tests__/plugin-secrets-handler.test.ts": 6443, - "server/src/__tests__/plugin-task-credential-writeback.test.ts": 11033, - "server/src/__tests__/plugin-telemetry-bridge.test.ts": 6283, - "server/src/__tests__/plugin-tenant-isolation.test.ts": 6879, - "server/src/__tests__/plugin-tool-dispatcher-pluginDbId.test.ts": 1508, - "server/src/__tests__/plugin-ui-static.test.ts": 4643, - "server/src/__tests__/plugin-warm-tasks.integration.test.ts": 6968, - "server/src/__tests__/plugin-worker-manager-daytona-close.test.ts": 7013, - "server/src/__tests__/plugin-worker-manager-duplex.test.ts": 5430, - "server/src/__tests__/plugin-worker-manager.test.ts": 5939, - "server/src/__tests__/plugin-workspace-terminal-retry.integration.test.ts": 8888, - "server/src/__tests__/plugin-workspaces.integration.test.ts": 20121, - "server/src/__tests__/prepared-chat-authorization.integration.test.ts": 6555, - "server/src/__tests__/prepared-statements-driver.test.ts": 5597, - "server/src/__tests__/prepared-statements.test.ts": 698, - "server/src/__tests__/primary-agent-guidance.test.ts": 2474, - "server/src/__tests__/primary-agent.test.ts": 6771, - "server/src/__tests__/principal-access-compatibility.test.ts": 2361, - "server/src/__tests__/privacy-production-review.test.ts": 9442, - "server/src/__tests__/private-hostname-guard.test.ts": 192, - "server/src/__tests__/private-json-etag.test.ts": 192, - "server/src/__tests__/project-archive-restore-guidance.test.ts": 1988, - "server/src/__tests__/project-environments.test.ts": 21031, - "server/src/__tests__/project-git-authorization.test.ts": 8187, - "server/src/__tests__/project-goal-validation.test.ts": 6590, - "server/src/__tests__/project-icon-persistence.test.ts": 6466, - "server/src/__tests__/project-instance-secrets.test.ts": 6248, - "server/src/__tests__/project-list-metrics.test.ts": 5068, - "server/src/__tests__/project-repositories-persistence.test.ts": 6125, - "server/src/__tests__/project-repositories.test.ts": 5320, - "server/src/__tests__/project-shortname-resolution.test.ts": 5131, - "server/src/__tests__/project-skill-setup-identity.test.ts": 1726, - "server/src/__tests__/project-skill-sources.test.ts": 16536, - "server/src/__tests__/project-tools-pagination.test.ts": 1532, - "server/src/__tests__/project-workspace-provider.integration.test.ts": 25787, - "server/src/__tests__/project-workspace-root-provenance.test.ts": 6136, - "server/src/__tests__/prompt-injection-gateway.test.ts": 13402, - "server/src/__tests__/prompt-injection-prevention.test.ts": 11698, - "server/src/__tests__/prompt-injection-provider.test.ts": 1448, - "server/src/__tests__/provider-trace-retention-work.test.ts": 1799, - "server/src/__tests__/provider-trace-store.test.ts": 1669, - "server/src/__tests__/public-mcp-client-metadata.test.ts": 943, - "server/src/__tests__/public-mcp-dispatch-shutdown.test.ts": 5224, - "server/src/__tests__/public-mcp.test.ts": 29631, - "server/src/__tests__/qa-routine-secrets-e2e.test.ts": 8219, - "server/src/__tests__/question-response-delivery.test.ts": 8952, - "server/src/__tests__/queued-comment-consumption.test.ts": 11480, - "server/src/__tests__/quota-windows-service.test.ts": 5097, - "server/src/__tests__/quota-windows.test.ts": 970, - "server/src/__tests__/railway-connection.test.ts": 10085, - "server/src/__tests__/railway-ssh.test.ts": 1950, - "server/src/__tests__/railway.test.ts": 849, - "server/src/__tests__/recovery-classifiers.test.ts": 4909, - "server/src/__tests__/recovery-cutover.test.ts": 711, - "server/src/__tests__/recovery-deadline-bootstrap.test.ts": 5105, - "server/src/__tests__/recovery-deadline-ordinary-bootstrap.test.ts": 5272, - "server/src/__tests__/recovery-durable-wait-projection.test.ts": 16352, - "server/src/__tests__/recovery-observability.test.ts": 7103, - "server/src/__tests__/recovery-postgres-mode.test.ts": 129, - "server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts": 10358, + "server/src/__tests__/plugin-sdk-orchestration-contract.test.ts": 1606, + "server/src/__tests__/plugin-sdk-testing.test.ts": 1647, + "server/src/__tests__/plugin-secrets-handler.test.ts": 6466, + "server/src/__tests__/plugin-task-credential-writeback.test.ts": 11130, + "server/src/__tests__/plugin-telemetry-bridge.test.ts": 7306, + "server/src/__tests__/plugin-tenant-isolation.test.ts": 9176, + "server/src/__tests__/plugin-tool-dispatcher-pluginDbId.test.ts": 1874, + "server/src/__tests__/plugin-ui-static.test.ts": 6492, + "server/src/__tests__/plugin-warm-tasks.integration.test.ts": 9651, + "server/src/__tests__/plugin-worker-manager-daytona-close.test.ts": 9454, + "server/src/__tests__/plugin-worker-manager-duplex.test.ts": 5839, + "server/src/__tests__/plugin-worker-manager.test.ts": 9117, + "server/src/__tests__/plugin-workspace-terminal-retry.integration.test.ts": 8780, + "server/src/__tests__/plugin-workspaces.integration.test.ts": 18587, + "server/src/__tests__/posthog-direct-event-shape.test.ts": 778, + "server/src/__tests__/posthog-direct-telemetry.test.ts": 732, + "server/src/__tests__/posthog-direct-transport.test.ts": 738, + "server/src/__tests__/prepared-chat-authorization.integration.test.ts": 7032, + "server/src/__tests__/prepared-statements-driver.test.ts": 6492, + "server/src/__tests__/prepared-statements.test.ts": 754, + "server/src/__tests__/primary-agent-guidance.test.ts": 4120, + "server/src/__tests__/primary-agent.test.ts": 8618, + "server/src/__tests__/principal-access-compatibility.test.ts": 2399, + "server/src/__tests__/privacy-production-review.test.ts": 14500, + "server/src/__tests__/private-hostname-guard.test.ts": 1023, + "server/src/__tests__/private-json-etag.test.ts": 839, + "server/src/__tests__/project-environments.test.ts": 17546, + "server/src/__tests__/project-git-authorization.test.ts": 9603, + "server/src/__tests__/project-goal-validation.test.ts": 8467, + "server/src/__tests__/project-icon-persistence.test.ts": 8529, + "server/src/__tests__/project-instance-secrets.test.ts": 7685, + "server/src/__tests__/project-list-metrics.test.ts": 6276, + "server/src/__tests__/project-repositories-persistence.test.ts": 7238, + "server/src/__tests__/project-repositories.test.ts": 6198, + "server/src/__tests__/project-shortname-resolution.test.ts": 5523, + "server/src/__tests__/project-skill-setup-identity.test.ts": 2350, + "server/src/__tests__/project-skill-sources.test.ts": 18035, + "server/src/__tests__/project-tools-pagination.test.ts": 2909, + "server/src/__tests__/project-workspace-provider.integration.test.ts": 19935, + "server/src/__tests__/project-workspace-root-provenance.test.ts": 6628, + "server/src/__tests__/prompt-injection-gateway.test.ts": 13919, + "server/src/__tests__/prompt-injection-prevention.test.ts": 11057, + "server/src/__tests__/prompt-injection-provider.test.ts": 2399, + "server/src/__tests__/provider-trace-retention-work.test.ts": 2344, + "server/src/__tests__/provider-trace-store.test.ts": 1880, + "server/src/__tests__/public-mcp-client-metadata.test.ts": 1695, + "server/src/__tests__/public-mcp-dispatch-shutdown.test.ts": 5856, + "server/src/__tests__/public-mcp.test.ts": 36323, + "server/src/__tests__/qa-routine-secrets-e2e.test.ts": 8585, + "server/src/__tests__/question-response-delivery.test.ts": 19309, + "server/src/__tests__/queued-comment-consumption.test.ts": 10130, + "server/src/__tests__/queued-run-dispatch-stacking.test.ts": 98136, + "server/src/__tests__/quota-windows-service.test.ts": 5777, + "server/src/__tests__/quota-windows.test.ts": 1542, + "server/src/__tests__/railway-connection.test.ts": 9611, + "server/src/__tests__/railway-ssh.test.ts": 2622, + "server/src/__tests__/railway.test.ts": 1635, + "server/src/__tests__/recovery-classifiers.test.ts": 6462, + "server/src/__tests__/recovery-cutover.test.ts": 1141, + "server/src/__tests__/recovery-deadline-bootstrap.test.ts": 6390, + "server/src/__tests__/recovery-deadline-ordinary-bootstrap.test.ts": 4981, + "server/src/__tests__/recovery-durable-wait-projection.test.ts": 16751, + "server/src/__tests__/recovery-observability.test.ts": 7801, + "server/src/__tests__/recovery-postgres-mode.test.ts": 539, + "server/src/__tests__/recovery-settled-records-census.test.ts": 221352, + "server/src/__tests__/recovery-stale-issue-lock-sweep.test.ts": 12088, "server/src/__tests__/recovery-wake-herd.test.ts": 51736, - "server/src/__tests__/redact-sensitive.test.ts": 122, - "server/src/__tests__/released-writer-escalation.test.ts": 8504, - "server/src/__tests__/remote-http-endpoint-guard.test.ts": 105, - "server/src/__tests__/remote-http-rebinding.test.ts": 1857, - "server/src/__tests__/remote-mcp-connectors.test.ts": 9454, - "server/src/__tests__/remote-mcp-pending.test.ts": 4839, - "server/src/__tests__/remote-mcp-protocol.test.ts": 1061, - "server/src/__tests__/remote-mcp-redaction.test.ts": 112, - "server/src/__tests__/remote-pi-companion.test.ts": 1565, - "server/src/__tests__/remote-snapshot-ledger-settlement.test.ts": 12793, - "server/src/__tests__/remote-workspace-file-resources.test.ts": 29328, - "server/src/__tests__/remove-test-home.test.ts": 113, - "server/src/__tests__/repository-admission-tracing.test.ts": 7963, - "server/src/__tests__/repository-object-cache.test.ts": 6061, - "server/src/__tests__/repository-root-reader-queries.test.ts": 7523, - "server/src/__tests__/required-quality-review.test.ts": 8746, - "server/src/__tests__/rerun-survival.integration.test.ts": 5067, - "server/src/__tests__/resource-lifecycle-events.test.ts": 10140, - "server/src/__tests__/retained-native-session-cleanup-work.test.ts": 13607, - "server/src/__tests__/retained-ui-assets.test.ts": 787, - "server/src/__tests__/reusable-leases-default.test.ts": 862, - "server/src/__tests__/review-attention-classification-equivalence.test.ts": 29263, - "server/src/__tests__/routable-blocked.test.ts": 100, - "server/src/__tests__/routine-execution-status-work.test.ts": 32219, - "server/src/__tests__/routine-execution-status-worker.test.ts": 1830, - "server/src/__tests__/routine-run-telemetry.test.ts": 6745, - "server/src/__tests__/routine-schedule-work.test.ts": 23344, - "server/src/__tests__/routine-status-reconciliation.test.ts": 16336, - "server/src/__tests__/routine-webhook-secret-guidance.test.ts": 2681, - "server/src/__tests__/routines-service.test.ts": 25523, - "server/src/__tests__/run-authority-read-projections.test.ts": 6404, - "server/src/__tests__/run-continuations.test.ts": 1614, - "server/src/__tests__/run-evidence-migration-work.test.ts": 1423, + "server/src/__tests__/redact-sensitive.test.ts": 630, + "server/src/__tests__/released-writer-escalation.test.ts": 8430, + "server/src/__tests__/remote-http-endpoint-guard.test.ts": 706, + "server/src/__tests__/remote-http-rebinding.test.ts": 2590, + "server/src/__tests__/remote-mcp-connectors.test.ts": 14953, + "server/src/__tests__/remote-mcp-pending.test.ts": 6482, + "server/src/__tests__/remote-mcp-protocol.test.ts": 1672, + "server/src/__tests__/remote-mcp-redaction.test.ts": 792, + "server/src/__tests__/remote-pi-companion.test.ts": 2478, + "server/src/__tests__/remote-snapshot-ledger-settlement.test.ts": 10754, + "server/src/__tests__/remote-workspace-file-resources.test.ts": 35772, + "server/src/__tests__/remove-test-home.test.ts": 635, + "server/src/__tests__/repository-admission-tracing.test.ts": 7623, + "server/src/__tests__/repository-object-cache.test.ts": 7765, + "server/src/__tests__/repository-root-reader-queries.test.ts": 7210, + "server/src/__tests__/required-quality-review.test.ts": 12059, + "server/src/__tests__/rerun-survival.integration.test.ts": 6052, + "server/src/__tests__/resolved-dependency-candidates.test.ts": 11212, + "server/src/__tests__/resource-lifecycle-events.test.ts": 13915, + "server/src/__tests__/retained-native-session-cleanup-work.test.ts": 16414, + "server/src/__tests__/retained-ui-assets.test.ts": 1152, + "server/src/__tests__/reusable-leases-default.test.ts": 1637, + "server/src/__tests__/review-attention-classification-equivalence.test.ts": 16260, + "server/src/__tests__/routable-blocked.test.ts": 721, + "server/src/__tests__/routine-execution-status-work.test.ts": 36142, + "server/src/__tests__/routine-execution-status-worker.test.ts": 1822, + "server/src/__tests__/routine-run-telemetry.test.ts": 9883, + "server/src/__tests__/routine-schedule-work.test.ts": 21858, + "server/src/__tests__/routine-status-reconciliation.test.ts": 19810, + "server/src/__tests__/routines-service.test.ts": 35301, + "server/src/__tests__/run-authority-read-projections.test.ts": 6981, + "server/src/__tests__/run-continuations.test.ts": 1464, + "server/src/__tests__/run-evidence-migration-work.test.ts": 1802, "server/src/__tests__/run-failure-sentry-real-sdk.test.ts": 792, - "server/src/__tests__/run-failure-sentry.test.ts": 12394, - "server/src/__tests__/run-identity-projections.test.ts": 6474, - "server/src/__tests__/run-identity.test.ts": 9013, - "server/src/__tests__/run-liveness.test.ts": 904, - "server/src/__tests__/run-secret-redaction.test.ts": 1650, - "server/src/__tests__/run-start-handover.test.ts": 27406, - "server/src/__tests__/run-trust-preset.test.ts": 6401, - "server/src/__tests__/runner-api-recovery.test.ts": 367, - "server/src/__tests__/runner-connection-eval-fixtures.test.ts": 18415, - "server/src/__tests__/runner-image-identity.test.ts": 259, - "server/src/__tests__/runner-image-layout.test.ts": 3065, - "server/src/__tests__/runner-image-oci.test.ts": 1391, - "server/src/__tests__/runner-image-publish.test.ts": 790, - "server/src/__tests__/runner-image-resolve.test.ts": 298, - "server/src/__tests__/runner-image-workflow.test.ts": 186, - "server/src/__tests__/runner-project-icon-contract.test.ts": 1556, - "server/src/__tests__/runtime-api.test.ts": 1584, - "server/src/__tests__/runtime-skill-cache.test.ts": 14600, - "server/src/__tests__/runtime-skill-preservation.test.ts": 8299, - "server/src/__tests__/sandbox-creation-intent-ownership.test.ts": 6017, - "server/src/__tests__/sandbox-creation-operations.test.ts": 68832, - "server/src/__tests__/sandbox-orphan-cleanup-spool.test.ts": 489, - "server/src/__tests__/sandbox-provider-runtime.test.ts": 113, - "server/src/__tests__/sandbox-provider-schema-reads.test.ts": 5590, - "server/src/__tests__/sandbox-snapshot-qualification.test.ts": 1705, - "server/src/__tests__/satisfied-connection-intents.test.ts": 48722, - "server/src/__tests__/scheduled-work-postgres.test.ts": 11440, - "server/src/__tests__/scheduled-work.test.ts": 1552, - "server/src/__tests__/scoped-deadline-work.test.ts": 2606, - "server/src/__tests__/secret-binding-discovery.test.ts": 3207, - "server/src/__tests__/secret-entry-guidance.test.ts": 2681, - "server/src/__tests__/secret-provider-registry.test.ts": 212, - "server/src/__tests__/secret-sensitive-request-error.test.ts": 4899, - "server/src/__tests__/secrets-service-dangling-user-secret.test.ts": 5695, - "server/src/__tests__/secrets-service-user-secret-owner-scoped.test.ts": 5259, - "server/src/__tests__/secrets-service.test.ts": 12809, - "server/src/__tests__/sentry-directory-merge-lock.test.ts": 1297, - "server/src/__tests__/sentry-dsn.test.ts": 104, - "server/src/__tests__/sentry-dynamic-import-provenance.test.ts": 101, - "server/src/__tests__/sentry-links.test.ts": 111, - "server/src/__tests__/sentry.test.ts": 10828, - "server/src/__tests__/server-info.test.ts": 314, - "server/src/__tests__/server-package-build-script.test.ts": 114, - "server/src/__tests__/server-package-otel-peer-metadata.test.ts": 116, - "server/src/__tests__/server-package-sentry-peer-metadata.test.ts": 108, - "server/src/__tests__/server-startup-feedback-export.test.ts": 23170, - "server/src/__tests__/service-read-disconnect-retry.test.ts": 8549, - "server/src/__tests__/service-version.test.ts": 100, - "server/src/__tests__/shared-telemetry-events.test.ts": 112, - "server/src/__tests__/sidebar-badges.test.ts": 5535, - "server/src/__tests__/skill-default-cadence-prewire.test.ts": 2564, - "server/src/__tests__/skill-import-discovery.test.ts": 2434, - "server/src/__tests__/skill-package-store.test.ts": 22100, - "server/src/__tests__/skill-repository-dependencies.test.ts": 431, - "server/src/__tests__/skill-repository-package.test.ts": 887, - "server/src/__tests__/skill-source-branches.test.ts": 850, - "server/src/__tests__/skill-source-git-snapshot.test.ts": 8009, - "server/src/__tests__/skill-source-github-access.test.ts": 5202, - "server/src/__tests__/skill-source-retry.test.ts": 107, - "server/src/__tests__/skill-source-scan-limit.test.ts": 100, - "server/src/__tests__/skill-sources.test.ts": 21765, - "server/src/__tests__/skill-update-diff.test.ts": 140, - "server/src/__tests__/skill-version-cache.test.ts": 11284, - "server/src/__tests__/skill-version-retention-config.test.ts": 884, - "server/src/__tests__/skill-version-retention-work.test.ts": 1895, - "server/src/__tests__/skill-version-retention.test.ts": 31244, - "server/src/__tests__/skills-catalog-service.test.ts": 166, - "server/src/__tests__/slack-authorization-revision.test.ts": 9189, - "server/src/__tests__/slack-cloud-forms.test.ts": 1481, - "server/src/__tests__/slack-cloud-owner-work.test.ts": 28349, - "server/src/__tests__/slack-conversation-lifecycle.test.ts": 28236, - "server/src/__tests__/slack-development-manager.test.ts": 1007, - "server/src/__tests__/slack-form-publication-readiness.test.ts": 4407, - "server/src/__tests__/slack-tool-preparation.test.ts": 9216, - "server/src/__tests__/sleep-backup-observation.test.ts": 157, - "server/src/__tests__/sleep-early-diagnostics.test.ts": 100, - "server/src/__tests__/sleep-idle-work-capture.test.ts": 1260, - "server/src/__tests__/sleep-incoming-http-observation.test.ts": 1533, - "server/src/__tests__/sleep-managed-fixture.test.ts": 1781, - "server/src/__tests__/sleep-otel-export.test.ts": 2098, - "server/src/__tests__/smoke-lab.test.ts": 7039, - "server/src/__tests__/snapshot-attempt-upload-abort.test.ts": 6470, - "server/src/__tests__/source-trust.test.ts": 2225, - "server/src/__tests__/speko-call-report.test.ts": 812, - "server/src/__tests__/speko-delivery-diagnostics.test.ts": 850, - "server/src/__tests__/speko-protocol.test.ts": 941, - "server/src/__tests__/speko-provider.test.ts": 725, - "server/src/__tests__/startup-readiness-boundary.test.ts": 312, - "server/src/__tests__/startup-refusals.test.ts": 125, - "server/src/__tests__/static-index-html.test.ts": 175, - "server/src/__tests__/static-ui-cache.test.ts": 114, - "server/src/__tests__/static-ui-compression.test.ts": 283, - "server/src/__tests__/static-ui-idle.test.ts": 633, - "server/src/__tests__/status-card-compile-prompt.test.ts": 4802, + "server/src/__tests__/run-failure-sentry.test.ts": 12278, + "server/src/__tests__/run-identity-projections.test.ts": 9405, + "server/src/__tests__/run-identity.test.ts": 9202, + "server/src/__tests__/run-liveness.test.ts": 1616, + "server/src/__tests__/run-output-secret-env-redaction.test.ts": 10436, + "server/src/__tests__/run-secret-redaction.test.ts": 1973, + "server/src/__tests__/run-start-handover.test.ts": 28002, + "server/src/__tests__/run-trust-preset.test.ts": 6908, + "server/src/__tests__/runner-api-recovery.test.ts": 741, + "server/src/__tests__/runner-connection-eval-fixtures.test.ts": 19765, + "server/src/__tests__/runner-image-identity.test.ts": 922, + "server/src/__tests__/runner-image-layout.test.ts": 4389, + "server/src/__tests__/runner-image-oci.test.ts": 2163, + "server/src/__tests__/runner-image-publish.test.ts": 1084, + "server/src/__tests__/runner-image-resolve.test.ts": 1066, + "server/src/__tests__/runner-image-workflow.test.ts": 618, + "server/src/__tests__/runner-lockfile-guards.test.ts": 897, + "server/src/__tests__/runner-project-icon-contract.test.ts": 2838, + "server/src/__tests__/runtime-api.test.ts": 1890, + "server/src/__tests__/runtime-skill-cache.test.ts": 12608, + "server/src/__tests__/runtime-skill-preservation.test.ts": 8112, + "server/src/__tests__/sandbox-creation-intent-ownership.test.ts": 8743, + "server/src/__tests__/sandbox-creation-operations.test.ts": 90610, + "server/src/__tests__/sandbox-orphan-cleanup-spool.test.ts": 722, + "server/src/__tests__/sandbox-provider-runtime.test.ts": 935, + "server/src/__tests__/sandbox-provider-schema-reads.test.ts": 8056, + "server/src/__tests__/sandbox-snapshot-qualification.test.ts": 1475, + "server/src/__tests__/satisfied-connection-intents.test.ts": 54642, + "server/src/__tests__/scheduled-work-postgres.test.ts": 8449, + "server/src/__tests__/scheduled-work.test.ts": 2510, + "server/src/__tests__/scoped-deadline-work-notifications.test.ts": 3476, + "server/src/__tests__/scoped-deadline-work.test.ts": 2998, + "server/src/__tests__/secret-binding-discovery.test.ts": 4155, + "server/src/__tests__/secret-entry-guidance.test.ts": 4334, + "server/src/__tests__/secret-provider-registry.test.ts": 852, + "server/src/__tests__/secret-sensitive-request-error.test.ts": 6141, + "server/src/__tests__/secrets-service-dangling-user-secret.test.ts": 8044, + "server/src/__tests__/secrets-service-user-secret-owner-scoped.test.ts": 6675, + "server/src/__tests__/secrets-service.test.ts": 24412, + "server/src/__tests__/sentry-directory-merge-lock.test.ts": 2031, + "server/src/__tests__/sentry-dsn.test.ts": 793, + "server/src/__tests__/sentry-dynamic-import-provenance.test.ts": 772, + "server/src/__tests__/sentry-links.test.ts": 568, + "server/src/__tests__/sentry.test.ts": 9899, + "server/src/__tests__/server-info.test.ts": 1027, + "server/src/__tests__/server-metrics.test.ts": 2049, + "server/src/__tests__/server-package-build-script.test.ts": 667, + "server/src/__tests__/server-package-otel-peer-metadata.test.ts": 774, + "server/src/__tests__/server-package-sentry-peer-metadata.test.ts": 685, + "server/src/__tests__/server-startup-feedback-export.test.ts": 28040, + "server/src/__tests__/service-read-disconnect-retry.test.ts": 8867, + "server/src/__tests__/service-version.test.ts": 926, + "server/src/__tests__/settled-native-process-rechecks.test.ts": 19494, + "server/src/__tests__/shared-telemetry-events.test.ts": 729, + "server/src/__tests__/shutdown-settled-process-release.test.ts": 13293, + "server/src/__tests__/sidebar-badges.test.ts": 6174, + "server/src/__tests__/skill-default-cadence-prewire.test.ts": 3897, + "server/src/__tests__/skill-import-discovery.test.ts": 3222, + "server/src/__tests__/skill-package-store.test.ts": 21032, + "server/src/__tests__/skill-repository-dependencies.test.ts": 1475, + "server/src/__tests__/skill-repository-package.test.ts": 2022, + "server/src/__tests__/skill-source-branches.test.ts": 1557, + "server/src/__tests__/skill-source-git-snapshot.test.ts": 9014, + "server/src/__tests__/skill-source-github-access.test.ts": 7001, + "server/src/__tests__/skill-source-retry.test.ts": 1015, + "server/src/__tests__/skill-source-scan-limit.test.ts": 806, + "server/src/__tests__/skill-sources.test.ts": 16101, + "server/src/__tests__/skill-update-diff.test.ts": 709, + "server/src/__tests__/skill-version-cache.test.ts": 10506, + "server/src/__tests__/skill-version-retention-config.test.ts": 1526, + "server/src/__tests__/skill-version-retention-work.test.ts": 1585, + "server/src/__tests__/skill-version-retention.test.ts": 31824, + "server/src/__tests__/skills-catalog-service.test.ts": 719, + "server/src/__tests__/slack-authorization-revision.test.ts": 9033, + "server/src/__tests__/slack-cloud-forms.test.ts": 1936, + "server/src/__tests__/slack-cloud-owner-work.test.ts": 27508, + "server/src/__tests__/slack-conversation-lifecycle.test.ts": 31522, + "server/src/__tests__/slack-development-manager.test.ts": 1178, + "server/src/__tests__/slack-form-publication-readiness.test.ts": 5820, + "server/src/__tests__/slack-tool-preparation.test.ts": 7909, + "server/src/__tests__/sleep-backup-observation.test.ts": 808, + "server/src/__tests__/sleep-early-diagnostics.test.ts": 752, + "server/src/__tests__/sleep-idle-work-capture.test.ts": 2055, + "server/src/__tests__/sleep-incoming-http-observation.test.ts": 1944, + "server/src/__tests__/sleep-managed-fixture.test.ts": 2145, + "server/src/__tests__/sleep-otel-export.test.ts": 2809, + "server/src/__tests__/smoke-lab.test.ts": 10012, + "server/src/__tests__/snapshot-attempt-upload-abort.test.ts": 6889, + "server/src/__tests__/source-trust.test.ts": 4414, + "server/src/__tests__/speko-call-report.test.ts": 1931, + "server/src/__tests__/speko-delivery-diagnostics.test.ts": 1620, + "server/src/__tests__/speko-protocol.test.ts": 1952, + "server/src/__tests__/speko-provider.test.ts": 1729, + "server/src/__tests__/ssh-tailscale-connection.test.ts": 1635, + "server/src/__tests__/startup-readiness-boundary.test.ts": 1011, + "server/src/__tests__/startup-refusals.test.ts": 579, + "server/src/__tests__/static-index-html.test.ts": 982, + "server/src/__tests__/static-ui-cache.test.ts": 710, + "server/src/__tests__/static-ui-compression.test.ts": 927, + "server/src/__tests__/static-ui-idle.test.ts": 1062, + "server/src/__tests__/status-card-compile-prompt.test.ts": 8912, "server/src/__tests__/status-card-evaluation-work.test.ts": 67793, - "server/src/__tests__/status-card-idle-schedule.test.ts": 1578, - "server/src/__tests__/status-card-notifications.test.ts": 1511, - "server/src/__tests__/status-card-update-engine.test.ts": 1033, - "server/src/__tests__/status-cards.test.ts": 17604, - "server/src/__tests__/storage-immutable-namespace.test.ts": 274, - "server/src/__tests__/storage-local-provider.test.ts": 150, - "server/src/__tests__/storage-outage-wait.test.ts": 19875, - "server/src/__tests__/storage-request-stats.test.ts": 100, - "server/src/__tests__/storage-s3-credential-rotation.test.ts": 20326, - "server/src/__tests__/storage-s3-failure-diagnostics.test.ts": 894, - "server/src/__tests__/storage-s3-multipart-backoff.test.ts": 381, - "server/src/__tests__/storage-s3-multipart-shutdown.test.ts": 628, - "server/src/__tests__/storage-s3-multipart-throttle.test.ts": 1286, - "server/src/__tests__/storage-s3-multipart.test.ts": 4600, - "server/src/__tests__/storage-s3-request-timeout-retry.test.ts": 549, - "server/src/__tests__/storage-s3-transient-retry.test.ts": 1574, - "server/src/__tests__/subscription-refresh.test.ts": 2143, - "server/src/__tests__/subscriptions.test.ts": 7552, - "server/src/__tests__/subtask-workspace-independence.test.ts": 7472, - "server/src/__tests__/summary-slots.test.ts": 10397, - "server/src/__tests__/task-admission-deadline.test.ts": 1656, - "server/src/__tests__/task-cold-open.test.ts": 8326, - "server/src/__tests__/task-creation-recovery.integration.test.ts": 16169, - "server/src/__tests__/task-interruption-automatic-path.test.ts": 6829, - "server/src/__tests__/task-interruption-query.test.ts": 9330, - "server/src/__tests__/task-list-projection-query.test.ts": 8921, - "server/src/__tests__/task-search-quality.test.ts": 6890, - "server/src/__tests__/task-search-query.test.ts": 1376, - "server/src/__tests__/task-toast-eligibility.test.ts": 2546, - "server/src/__tests__/task-watchdogs-classifier.test.ts": 4742, - "server/src/__tests__/task-watchdogs-incident-fixture.test.ts": 100, - "server/src/__tests__/task-watchdogs-scheduler.test.ts": 13259, - "server/src/__tests__/task-workspace-admission.test.ts": 4728, - "server/src/__tests__/task-workspace-api.test.ts": 21824, - "server/src/__tests__/task-workspace-binding.test.ts": 12870, - "server/src/__tests__/task-workspace-child-trust.test.ts": 9714, - "server/src/__tests__/task-workspace-repositories-persistence.test.ts": 8755, - "server/src/__tests__/task-workspace-repositories-trust.test.ts": 18341, - "server/src/__tests__/task-workspace-repositories.test.ts": 5422, - "server/src/__tests__/task-workspace-source-copy-privacy.test.ts": 5200, - "server/src/__tests__/task-workspace-tools.test.ts": 1696, - "server/src/__tests__/teams-catalog-install-no-overrides.test.ts": 15211, - "server/src/__tests__/teams-catalog-service.test.ts": 2201, - "server/src/__tests__/telemetry-client-flush.test.ts": 100, - "server/src/__tests__/telemetry-startup.test.ts": 148, - "server/src/__tests__/terminal-workspace-work.test.ts": 1365, - "server/src/__tests__/tool-access-connector-telemetry.test.ts": 6533, - "server/src/__tests__/tool-access-oauth-protocol.integration.test.ts": 23637, - "server/src/__tests__/tool-access-policy-service.test.ts": 31407, - "server/src/__tests__/tool-access-service.test.ts": 94837, - "server/src/__tests__/tool-catalog-publication.test.ts": 8954, - "server/src/__tests__/tool-connection-health-work.test.ts": 51391, - "server/src/__tests__/tool-connection-installs.test.ts": 9200, - "server/src/__tests__/tool-connection-removal.test.ts": 11543, - "server/src/__tests__/tool-connection-review-counts-http.test.ts": 9379, - "server/src/__tests__/tool-connection-review-counts.test.ts": 2426, - "server/src/__tests__/tool-connection-visibility.test.ts": 4354, - "server/src/__tests__/tool-content-guards.test.ts": 983, - "server/src/__tests__/tool-effective-assignments.test.ts": 15545, - "server/src/__tests__/tool-gateway-connector-telemetry.test.ts": 10136, - "server/src/__tests__/tool-gateway-discovery-http.test.ts": 9167, - "server/src/__tests__/tool-gateway-listing-memory.test.ts": 13248, - "server/src/__tests__/tool-gateway-service.test.ts": 99897, - "server/src/__tests__/tool-gateway.test.ts": 92537, - "server/src/__tests__/tool-grant-scope.test.ts": 8797, - "server/src/__tests__/tool-oauth-legacy-backfill.test.ts": 5447, - "server/src/__tests__/tool-profile-entry-order.test.ts": 4975, - "server/src/__tests__/tool-profile-entry-validation.test.ts": 8294, - "server/src/__tests__/tool-profile-matching.test.ts": 1386, - "server/src/__tests__/tool-profile-pending-projection.test.ts": 1556, - "server/src/__tests__/tool-profile-review-service.test.ts": 5558, - "server/src/__tests__/tool-review-queue-unsigned-request.test.ts": 5058, - "server/src/__tests__/trust-preset-resolver.test.ts": 803, - "server/src/__tests__/trust-proxy.test.ts": 159, - "server/src/__tests__/ui-branding.test.ts": 100, - "server/src/__tests__/unikraft-connection.test.ts": 10487, - "server/src/__tests__/unikraft-http-boundary.test.ts": 324, - "server/src/__tests__/user-facing-wording-guidance.test.ts": 129, - "server/src/__tests__/version.test.ts": 129, - "server/src/__tests__/vite-html-renderer.test.ts": 110, - "server/src/__tests__/vitest-chat-shards.test.ts": 12299, - "server/src/__tests__/voice-call-reports.test.ts": 10312, - "server/src/__tests__/voice-inbound-cleanup.test.ts": 11036, - "server/src/__tests__/voice-inbound-retention.test.ts": 4787, - "server/src/__tests__/voice-recovery-work.test.ts": 21440, - "server/src/__tests__/voice-session-store.integration.test.ts": 71170, - "server/src/__tests__/work-product-runtime-reconciliation.test.ts": 5536, - "server/src/__tests__/work-product-workspace-validation.test.ts": 5701, - "server/src/__tests__/work-products.test.ts": 5761, - "server/src/__tests__/work-scheduler.test.ts": 104, - "server/src/__tests__/work-timeline-service.test.ts": 16293, - "server/src/__tests__/workspace-authorization-query.test.ts": 6429, - "server/src/__tests__/workspace-cleanup-retained-local-dir.test.ts": 4625, - "server/src/__tests__/workspace-compaction.test.ts": 632, - "server/src/__tests__/workspace-delivery-cleanup.integration.test.ts": 9635, - "server/src/__tests__/workspace-history-user-journey.test.ts": 8457, - "server/src/__tests__/workspace-host-provision.test.ts": 1701, - "server/src/__tests__/workspace-instance-cleanup.test.ts": 199, - "server/src/__tests__/workspace-login-handoff-endpoint.test.ts": 1926, - "server/src/__tests__/workspace-login-handoff-issuer.test.ts": 1709, - "server/src/__tests__/workspace-login-handoff.test.ts": 130, - "server/src/__tests__/workspace-operations-reconciliation.test.ts": 6718, - "server/src/__tests__/workspace-preferences.test.ts": 5528, - "server/src/__tests__/workspace-preparation-history.test.ts": 10493, - "server/src/__tests__/workspace-provider-failure.test.ts": 806, - "server/src/__tests__/workspace-readiness.test.ts": 1639, - "server/src/__tests__/workspace-reaper-cooldown-config.test.ts": 869, - "server/src/__tests__/workspace-runtime-control-recovery.test.ts": 5932, - "server/src/__tests__/workspace-runtime-exposure-reservation.test.ts": 10497, + "server/src/__tests__/status-card-idle-schedule.test.ts": 2123, + "server/src/__tests__/status-card-notifications.test.ts": 1933, + "server/src/__tests__/status-card-update-engine.test.ts": 1508, + "server/src/__tests__/status-cards.test.ts": 30724, + "server/src/__tests__/storage-immutable-namespace.test.ts": 844, + "server/src/__tests__/storage-local-provider.test.ts": 1103, + "server/src/__tests__/storage-outage-wait.test.ts": 20089, + "server/src/__tests__/storage-request-stats.test.ts": 992, + "server/src/__tests__/storage-s3-credential-rotation.test.ts": 20958, + "server/src/__tests__/storage-s3-failure-diagnostics.test.ts": 2064, + "server/src/__tests__/storage-s3-multipart-backoff.test.ts": 1071, + "server/src/__tests__/storage-s3-multipart-shutdown.test.ts": 1193, + "server/src/__tests__/storage-s3-multipart-throttle.test.ts": 1546, + "server/src/__tests__/storage-s3-multipart.test.ts": 5750, + "server/src/__tests__/storage-s3-request-timeout-retry.test.ts": 1418, + "server/src/__tests__/storage-s3-transient-retry.test.ts": 2135, + "server/src/__tests__/subscription-refresh.test.ts": 1981, + "server/src/__tests__/subscriptions.test.ts": 8141, + "server/src/__tests__/subtask-workspace-independence.test.ts": 9363, + "server/src/__tests__/summary-slots.test.ts": 10159, + "server/src/__tests__/task-admission-deadline.test.ts": 1965, + "server/src/__tests__/task-cold-open.test.ts": 9608, + "server/src/__tests__/task-creation-recovery.integration.test.ts": 16295, + "server/src/__tests__/task-interruption-automatic-path.test.ts": 7737, + "server/src/__tests__/task-interruption-query.test.ts": 12709, + "server/src/__tests__/task-list-projection-query.test.ts": 10090, + "server/src/__tests__/task-search-quality.test.ts": 9039, + "server/src/__tests__/task-search-query.test.ts": 1878, + "server/src/__tests__/task-toast-eligibility.test.ts": 3061, + "server/src/__tests__/task-watchdogs-classifier.test.ts": 7353, + "server/src/__tests__/task-watchdogs-incident-fixture.test.ts": 876, + "server/src/__tests__/task-watchdogs-scheduler.test.ts": 20633, + "server/src/__tests__/task-workspace-admission.test.ts": 5703, + "server/src/__tests__/task-workspace-api.test.ts": 21431, + "server/src/__tests__/task-workspace-binding.test.ts": 13977, + "server/src/__tests__/task-workspace-child-trust.test.ts": 10214, + "server/src/__tests__/task-workspace-repositories-persistence.test.ts": 9190, + "server/src/__tests__/task-workspace-repositories-trust.test.ts": 18584, + "server/src/__tests__/task-workspace-repositories.test.ts": 6126, + "server/src/__tests__/task-workspace-source-copy-privacy.test.ts": 7089, + "server/src/__tests__/task-workspace-tools.test.ts": 1981, + "server/src/__tests__/teams-catalog-install-no-overrides.test.ts": 13040, + "server/src/__tests__/teams-catalog-service.test.ts": 3466, + "server/src/__tests__/telemetry-client-flush.test.ts": 855, + "server/src/__tests__/telemetry-startup.test.ts": 752, + "server/src/__tests__/terminal-workspace-deadlines.test.ts": 42823, + "server/src/__tests__/terminal-workspace-idle.test.ts": 10197, + "server/src/__tests__/terminal-workspace-page-batch.test.ts": 8055, + "server/src/__tests__/terminal-workspace-rotation-limits.test.ts": 26808, + "server/src/__tests__/terminal-workspace-work.test.ts": 1814, + "server/src/__tests__/tool-access-client-credentials.test.ts": 15803, + "server/src/__tests__/tool-access-connector-telemetry.test.ts": 7389, + "server/src/__tests__/tool-access-oauth-protocol.integration.test.ts": 22446, + "server/src/__tests__/tool-access-policy-index.test.ts": 11475, + "server/src/__tests__/tool-access-policy-service.test.ts": 20356, + "server/src/__tests__/tool-access-service.test.ts": 75593, + "server/src/__tests__/tool-call-progress-store.test.ts": 5943, + "server/src/__tests__/tool-call-progress.test.ts": 5991, + "server/src/__tests__/tool-catalog-publication.test.ts": 9966, + "server/src/__tests__/tool-connection-content-deletion-canary.test.ts": 47442, + "server/src/__tests__/tool-connection-content-deletion.test.ts": 10204, + "server/src/__tests__/tool-connection-health-work.test.ts": 52429, + "server/src/__tests__/tool-connection-installs.test.ts": 8725, + "server/src/__tests__/tool-connection-removal.test.ts": 13402, + "server/src/__tests__/tool-connection-review-counts-http.test.ts": 12844, + "server/src/__tests__/tool-connection-review-counts.test.ts": 3160, + "server/src/__tests__/tool-connection-visibility.test.ts": 5441, + "server/src/__tests__/tool-content-guards.test.ts": 1410, + "server/src/__tests__/tool-effective-assignments.test.ts": 16297, + "server/src/__tests__/tool-gateway-agent-errors.test.ts": 6669, + "server/src/__tests__/tool-gateway-connector-telemetry.test.ts": 12455, + "server/src/__tests__/tool-gateway-discovery-http.test.ts": 12542, + "server/src/__tests__/tool-gateway-listing-memory.test.ts": 15052, + "server/src/__tests__/tool-gateway-service.test.ts": 150610, + "server/src/__tests__/tool-gateway.test.ts": 70985, + "server/src/__tests__/tool-grant-scope.test.ts": 9162, + "server/src/__tests__/tool-oauth-legacy-backfill.test.ts": 5584, + "server/src/__tests__/tool-profile-entry-order.test.ts": 5397, + "server/src/__tests__/tool-profile-entry-validation.test.ts": 11324, + "server/src/__tests__/tool-profile-matching.test.ts": 2298, + "server/src/__tests__/tool-profile-pending-projection.test.ts": 2578, + "server/src/__tests__/tool-profile-review-service.test.ts": 5277, + "server/src/__tests__/tool-review-queue-unsigned-request.test.ts": 4895, + "server/src/__tests__/trust-preset-resolver.test.ts": 1528, + "server/src/__tests__/trust-proxy.test.ts": 825, + "server/src/__tests__/ui-branding.test.ts": 721, + "server/src/__tests__/unikraft-connection.test.ts": 9573, + "server/src/__tests__/unikraft-http-boundary.test.ts": 928, + "server/src/__tests__/version.test.ts": 967, + "server/src/__tests__/vite-html-renderer.test.ts": 743, + "server/src/__tests__/vitest-chat-shards.test.ts": 13174, + "server/src/__tests__/voice-call-reports.test.ts": 9524, + "server/src/__tests__/voice-inbound-cleanup.test.ts": 9552, + "server/src/__tests__/voice-inbound-retention.test.ts": 4727, + "server/src/__tests__/voice-recovery-work.test.ts": 25368, + "server/src/__tests__/voice-session-store.integration.test.ts": 78942, + "server/src/__tests__/warm-sandbox-expiry.test.ts": 8140, + "server/src/__tests__/work-product-runtime-reconciliation.test.ts": 7198, + "server/src/__tests__/work-product-workspace-validation.test.ts": 5809, + "server/src/__tests__/work-products.test.ts": 6136, + "server/src/__tests__/work-scheduler.test.ts": 748, + "server/src/__tests__/work-timeline-service.test.ts": 17371, + "server/src/__tests__/workspace-authorization-query.test.ts": 9652, + "server/src/__tests__/workspace-cleanup-retained-local-dir.test.ts": 6489, + "server/src/__tests__/workspace-compaction.test.ts": 1500, + "server/src/__tests__/workspace-delivery-cleanup.integration.test.ts": 11616, + "server/src/__tests__/workspace-history-user-journey.test.ts": 11436, + "server/src/__tests__/workspace-host-provision.test.ts": 2015, + "server/src/__tests__/workspace-instance-cleanup.test.ts": 652, + "server/src/__tests__/workspace-login-handoff-endpoint.test.ts": 2386, + "server/src/__tests__/workspace-login-handoff-issuer.test.ts": 1893, + "server/src/__tests__/workspace-login-handoff.test.ts": 825, + "server/src/__tests__/workspace-operations-reconciliation.test.ts": 8506, + "server/src/__tests__/workspace-preferences.test.ts": 6065, + "server/src/__tests__/workspace-preparation-history.test.ts": 15947, + "server/src/__tests__/workspace-provider-failure.test.ts": 1400, + "server/src/__tests__/workspace-readiness.test.ts": 1955, + "server/src/__tests__/workspace-reaper-cooldown-config.test.ts": 1871, + "server/src/__tests__/workspace-runtime-control-recovery.test.ts": 7273, + "server/src/__tests__/workspace-runtime-exposure-reservation.test.ts": 9335, "server/src/__tests__/workspace-runtime-https-live-exercise.test.ts": 2771, - "server/src/__tests__/workspace-runtime-lease-ownership.test.ts": 12542, - "server/src/__tests__/workspace-runtime-leases.test.ts": 3930, - "server/src/__tests__/workspace-runtime-lifecycle.test.ts": 5215, - "server/src/__tests__/workspace-runtime-start-terminality.test.ts": 7532, - "server/src/__tests__/workspace-runtime.test.ts": 89434, - "server/src/__tests__/workspace-worktree-concurrency.test.ts": 30618, - "server/src/__tests__/worktree-config.test.ts": 1492, - "server/src/__tests__/worktree-seed-server-spawn.test.ts": 8096, - "server/src/__tests__/write-build-stamp.test.ts": 146, - "server/src/__tests__/write-path-membership.test.ts": 4976, - "server/src/adapters/claude-agent-id-header.test.ts": 100, - "server/src/adapters/cloud-external-adapters.test.ts": 7383, - "server/src/adapters/http/execute.test.ts": 902, - "server/src/adapters/plugin-loader.test.ts": 135, - "server/src/adapters/registry.test.ts": 4528, - "server/src/embedded-postgres-owner.test.ts": 100, - "server/src/event-loop-stall-monitor.test.ts": 1880, - "server/src/http/server.test.ts": 2686, - "server/src/lib/request-promise-memo.test.ts": 106, - "server/src/lib/single-flight.test.ts": 358, - "server/src/maintenance/ephemeral-migration-service.test.ts": 307, - "server/src/maintenance/native-harness-prestage-runtime.test.ts": 8024, - "server/src/maintenance/native-harness-prestage.test.ts": 373, - "server/src/maintenance/online-workspace-migration.test.ts": 5765, - "server/src/middleware/cloud-tenant-actor.test.ts": 5789, - "server/src/middleware/cloud-tenant-sync-postgres.test.ts": 14342, - "server/src/modules/active-run-watchdog/adapters/process.test.ts": 926, - "server/src/modules/active-run-watchdog/application/use-cases.test.ts": 134, - "server/src/modules/active-run-watchdog/domain/policy.test.ts": 107, - "server/src/modules/agent-lifecycle/__tests__/diagnostics.test.ts": 5587, - "server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts": 4916, - "server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts": 9964, - "server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts": 15899, - "server/src/modules/agent-lifecycle/__tests__/policy-sweep.test.ts": 4569, - "server/src/modules/agent-lifecycle/__tests__/resource-wait-stop.test.ts": 9331, - "server/src/modules/agent-lifecycle/__tests__/restart-verification.test.ts": 5501, - "server/src/modules/agent-lifecycle/__tests__/setup.test.ts": 8743, - "server/src/modules/agent-lifecycle/__tests__/verification-retry.test.ts": 6172, - "server/src/modules/execution-admission/adapters/postgres.test.ts": 5450, - "server/src/modules/execution-admission/domain/policy.test.ts": 121, - "server/src/modules/external-agents/cloud-principal-http.test.ts": 5280, - "server/src/modules/external-agents/cloud-principal-log.test.ts": 290, - "server/src/modules/external-agents/original-token-principal.test.ts": 5252, - "server/src/modules/run-dispatch/adapters/postgres.test.ts": 16524, - "server/src/modules/run-dispatch/application/use-cases.test.ts": 111, - "server/src/modules/run-dispatch/domain/policy.test.ts": 133, - "server/src/modules/run-dispatch/domain/wake-context.test.ts": 135, - "server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts": 7879, - "server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts": 6190, - "server/src/modules/wake-queue/adapters/operator-stop.test.ts": 4766, - "server/src/modules/wake-queue/adapters/postgres.test.ts": 19044, - "server/src/modules/wake-queue/adapters/promoted-retry-scope.test.ts": 5452, - "server/src/modules/wake-queue/adapters/queued-comment-postgres.test.ts": 6904, - "server/src/modules/wake-queue/adapters/queued-operator-stop-postgres.test.ts": 6702, - "server/src/modules/wake-queue/adapters/release-run-read.test.ts": 2366, - "server/src/modules/wake-queue/adapters/retryable-before-provider-work.test.ts": 5796, - "server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts": 133, - "server/src/modules/wake-queue/application/use-cases.test.ts": 5061, - "server/src/modules/wake-queue/domain/context.test.ts": 4490, - "server/src/modules/wake-queue/domain/policy.test.ts": 105, - "server/src/realtime/live-event-delivery.cost.test.ts": 451, - "server/src/realtime/live-event-delivery.test.ts": 396, - "server/src/realtime/runner-prp-outbound.test.ts": 209, - "server/src/realtime/runner-prp-ws.test.ts": 2277, - "server/src/routes/adapters.test.ts": 4758, - "server/src/routes/chat-channels.identity.test.ts": 7737, - "server/src/routes/chat-channels.webhook.test.ts": 7547, - "server/src/routes/connection-intents.test.ts": 4868, - "server/src/routes/ephemeral-enrollment.test.ts": 1674, - "server/src/routes/issues-wake-diagnostics.test.ts": 5478, - "server/src/routes/setup-token-route.test.ts": 6041, - "server/src/routes/tool-access-connection-intent.test.ts": 6018, - "server/src/routes/voice-sessions.auth.test.ts": 4329, - "server/src/runtime-tools-token.test.ts": 100, - "server/src/services/__tests__/git-connection-failure.test.ts": 100, - "server/src/services/__tests__/mcp-connection-failure.test.ts": 132, - "server/src/services/__tests__/process-loss-diagnostics.test.ts": 132, - "server/src/services/__tests__/run-failure-diagnostics.test.ts": 988, - "server/src/services/__tests__/run-failure-report-native-usage-limit.test.ts": 6056, - "server/src/services/__tests__/run-failure-report-project-access.test.ts": 6554, - "server/src/services/__tests__/run-failure-report-reviewed-chat.test.ts": 5729, - "server/src/services/__tests__/run-failure-report.test.ts": 12077, - "server/src/services/__tests__/sentry-run-links.test.ts": 1942, - "server/src/services/acknowledged-native-stop.test.ts": 2567, - "server/src/services/adapter-execution-control.test.ts": 800, - "server/src/services/adapter-execution-phase.test.ts": 121, - "server/src/services/adapter-login-lease.test.ts": 100, - "server/src/services/adapter-models-env.test.ts": 100, - "server/src/services/adapter-registry-bootstrap.reconcile.test.ts": 4133, - "server/src/services/adapter-registry-bootstrap.test.ts": 4610, - "server/src/services/adapter-settings-local.test.ts": 1888, - "server/src/services/adapter-settings-postgres.test.ts": 5425, - "server/src/services/agent-budget-hold-activity.test.ts": 6164, - "server/src/services/agent-cost-history-deletion.test.ts": 5461, - "server/src/services/agent-environment-test-status.test.ts": 5335, - "server/src/services/agent-interaction-delivery.test.ts": 7053, - "server/src/services/agent-runner-selection.test.ts": 3016, - "server/src/services/ai-account-identity.test.ts": 1087, - "server/src/services/ai-auth-failure.test.ts": 892, - "server/src/services/ai-connection-configuration-failure.test.ts": 113, - "server/src/services/ai-connection-usage.test.ts": 1049, - "server/src/services/anthropic-pricing.test.ts": 1016, - "server/src/services/app-webhook.test.ts": 137, - "server/src/services/approved-execution-wait.test.ts": 119, - "server/src/services/attention-audience.test.ts": 3892, - "server/src/services/attention-resolver-audience.test.ts": 4941, - "server/src/services/board-auth.test.ts": 7558, - "server/src/services/budget-live-usage.test.ts": 1940, - "server/src/services/budget-resume-continuation.test.ts": 9610, - "server/src/services/budget-tracing.test.ts": 1432, - "server/src/services/bundled-skill-release-validation.test.ts": 2278, - "server/src/services/case-agent-read.test.ts": 1635, - "server/src/services/case-deletion.test.ts": 5450, - "server/src/services/case-handoff-privacy.test.ts": 5023, - "server/src/services/case-handoffs.test.ts": 39942, - "server/src/services/case-task-documents.test.ts": 5895, - "server/src/services/chat-channels/authorization-run-read.test.ts": 2169, - "server/src/services/chat-channels/github/retry.test.ts": 4247, - "server/src/services/chat-channels/github/review-heading.test.ts": 104, - "server/src/services/chat-channels/github/review-instructions.test.ts": 1581, - "server/src/services/chat-channels/github/webhook-ingress.test.ts": 8359, - "server/src/services/chat-channels/inbound/wakeup-authorization-error.test.ts": 102, - "server/src/services/chat-channels/run-origin.test.ts": 6490, - "server/src/services/chat-channels/slack/adapter.test.ts": 1704, - "server/src/services/chat-channels/slack/cards.test.ts": 1901, - "server/src/services/chat-channels/slack/cloud-callback.test.ts": 3380, - "server/src/services/chat-channels/slack/cloud-drain.test.ts": 4860, - "server/src/services/chat-channels/slack/cloud-enrollment.test.ts": 1457, - "server/src/services/chat-channels/slack/cloud-event.test.ts": 5305, - "server/src/services/chat-channels/slack/cloud-ingress.test.ts": 1785, - "server/src/services/chat-channels/slack/cloud-signing-secret.test.ts": 100, - "server/src/services/chat-channels/slack/cloud-test-prewire.test.ts": 741, - "server/src/services/chat-channels/slack/configured-coverage.test.ts": 1849, - "server/src/services/chat-channels/slack/form-ack-work.test.ts": 1675, - "server/src/services/chat-channels/slack/form-canonical-state.test.ts": 1590, - "server/src/services/chat-channels/slack/form-enrollment-identity.test.ts": 1777, - "server/src/services/chat-channels/slack/form-owner-rearm.test.ts": 4448, - "server/src/services/chat-channels/slack/form-retirement.test.ts": 1762, - "server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts": 1449, - "server/src/services/chat-channels/slack/idle-incoming.test.ts": 1803, - "server/src/services/chat-channels/slack/question-forms.test.ts": 100, - "server/src/services/chat-channels/slack/receipt-timing.test.ts": 100, - "server/src/services/chat-channels/slack/signing-secret-preflight.test.ts": 5238, - "server/src/services/chat-channels/slack/wake-authority.test.ts": 142, - "server/src/services/chat-communication-guidance.test.ts": 849, - "server/src/services/chat-control-admission-retry.test.ts": 4941, - "server/src/services/chat-discord-adapter-patch.test.ts": 4039, - "server/src/services/chat-discord-command-registration-store.test.ts": 6290, - "server/src/services/chat-discord-command-registration.test.ts": 324, - "server/src/services/chat-discord-modal-wire.test.ts": 2857, - "server/src/services/chat-discord-native-command.test.ts": 3351, - "server/src/services/chat-discord-native-commands.test.ts": 645, - "server/src/services/chat-discord-native-interaction.test.ts": 6165, - "server/src/services/chat-discord-native-modal.test.ts": 3325, - "server/src/services/chat-discord-question-forms.test.ts": 211, - "server/src/services/chat-discord.test.ts": 566, - "server/src/services/chat-github-attachments.test.ts": 3415, - "server/src/services/chat-github-events.test.ts": 1746, - "server/src/services/chat-github-management.test.ts": 1816, - "server/src/services/chat-github-provider-stress.test.ts": 3177, - "server/src/services/chat-github-receipt-reactions.test.ts": 393, - "server/src/services/chat-github-review-policy.test.ts": 944, - "server/src/services/chat-github-review-repair.test.ts": 6402, - "server/src/services/chat-github-tools.test.ts": 2595, - "server/src/services/chat-github-webhook-config.test.ts": 221, - "server/src/services/chat-github-wizard-origin.test.ts": 4081, - "server/src/services/chat-inbound-wakeup-publications.test.ts": 4684, - "server/src/services/chat-interaction-arbitration.test.ts": 2400, - "server/src/services/chat-interaction-continuation.test.ts": 8450, - "server/src/services/chat-interaction-forms.test.ts": 1504, - "server/src/services/chat-interaction-publications.test.ts": 4885, - "server/src/services/chat-monitor-continuation.test.ts": 11788, - "server/src/services/chat-outbound-attachment-hydration.test.ts": 6720, - "server/src/services/chat-provider-inventory.test.ts": 147, - "server/src/services/chat-provider-lifecycle.test.ts": 158, - "server/src/services/chat-provider-links.test.ts": 113, - "server/src/services/chat-publication-batches.test.ts": 936, - "server/src/services/chat-publication-errors.test.ts": 139, - "server/src/services/chat-publication-projection.test.ts": 163, - "server/src/services/chat-publication-ready-stream.test.ts": 3129, - "server/src/services/chat-publication-reconciliation.test.ts": 100, - "server/src/services/chat-publication-stream.test.ts": 1459, - "server/src/services/chat-publication-text-parts.test.ts": 23160, - "server/src/services/chat-question-forms.test.ts": 1777, - "server/src/services/chat-reply-lineage-context.test.ts": 7543, - "server/src/services/chat-run-publications.test.ts": 4982, - "server/src/services/chat-sdk-runtime.adapters.test.ts": 5403, - "server/src/services/chat-sdk-runtime.test.ts": 3092, - "server/src/services/chat-sdk-state.test.ts": 109, - "server/src/services/chat-slack-native-modal.test.ts": 3101, - "server/src/services/chat-slack-receipts.test.ts": 4484, - "server/src/services/chat-slack-sessions.test.ts": 109, - "server/src/services/chat-task-url.test.ts": 5681, - "server/src/services/chat-teams-credentials.test.ts": 871, - "server/src/services/chat-teams-file-consent-runtime.test.ts": 3352, - "server/src/services/chat-teams-file-consent.contract.test.ts": 1028, - "server/src/services/chat-teams-file-consent.test.ts": 434, - "server/src/services/chat-teams-file-publication.test.ts": 5822, - "server/src/services/chat-teams-file-transfers.test.ts": 18726, - "server/src/services/chat-teams-inline-image-intake.test.ts": 3279, - "server/src/services/chat-teams-inline-images.test.ts": 3209, - "server/src/services/chat-teams-native-modal.test.ts": 2898, - "server/src/services/chat-teams-personal-recipient.test.ts": 864, - "server/src/services/chat-telegram-draft-stop.test.ts": 349, - "server/src/services/chat-telegram-ephemeral-runtime.test.ts": 3275, - "server/src/services/chat-telegram-ephemeral.test.ts": 201, - "server/src/services/chat-telegram-media-intake.test.ts": 2879, - "server/src/services/chat-telegram-photo.test.ts": 261, - "server/src/services/chat-telegram-rich-intake.test.ts": 2503, - "server/src/services/chat-telegram-stop-subscription.test.ts": 126, - "server/src/services/chat-telegram-video-note.test.ts": 2836, - "server/src/services/cloud-runtime-identity.test.ts": 1610, - "server/src/services/cloud-warm-standby.test.ts": 1621, - "server/src/services/connection-credential-state.test.ts": 5612, - "server/src/services/connector-runtime.test.ts": 4446, - "server/src/services/connector-telemetry.test.ts": 1870, - "server/src/services/connectors/onepassword/onepassword.test.ts": 216, - "server/src/services/connectors/onepassword/worker.test.ts": 177, - "server/src/services/connectors/slack-access.test.ts": 1563, - "server/src/services/connectors/slack-authority.test.ts": 5308, - "server/src/services/connectors/slack-endpoint-preparation.test.ts": 212, - "server/src/services/connectors/slack-native-search.test.ts": 983, - "server/src/services/connectors/supabase/index.test.ts": 1065, - "server/src/services/connectors/vercel/index.test.ts": 328, - "server/src/services/controller-process-identity.test.ts": 5331, - "server/src/services/controller-process-space-identity.test.ts": 3768, - "server/src/services/conversation-continuation.test.ts": 3143, - "server/src/services/covered-historical-workspace-source.integration.test.ts": 12724, - "server/src/services/decision-signing.test.ts": 138, - "server/src/services/deferred-execution-wait.test.ts": 5414, - "server/src/services/environment-custom-image-terminal-sessions.test.ts": 118, - "server/src/services/environment-lease-fault-injection.test.ts": 1409, - "server/src/services/environment-provider-unavailable-error.test.ts": 873, - "server/src/services/environment-runtime-reusable-lease-probe.test.ts": 5150, - "server/src/services/ephemeral-enrollment.test.ts": 4766, - "server/src/services/execution-allowlist.test.ts": 100, - "server/src/services/execution-blocker-read.test.ts": 8112, - "server/src/services/execution-continuation-history-read.test.ts": 6016, - "server/src/services/execution-continuation-provenance.test.ts": 5899, - "server/src/services/execution-continuation.test.ts": 6180, - "server/src/services/execution-control-reconciliation.test.ts": 6215, - "server/src/services/execution-policy-bootstrap.test.ts": 3095, - "server/src/services/execution-preparation-timing.test.ts": 1416, - "server/src/services/execution-projection-external-provider.test.ts": 5343, - "server/src/services/execution-projection-read-retry.test.ts": 7380, - "server/src/services/execution-projection-recovery.test.ts": 4728, - "server/src/services/execution-projection.test.ts": 4824, - "server/src/services/execution-recovery-attempt.test.ts": 5604, - "server/src/services/execution-recovery-dead-controller.test.ts": 5649, - "server/src/services/execution-recovery-resolution.test.ts": 4936, - "server/src/services/execution-timing-context.test.ts": 1860, - "server/src/services/execution-transaction-timing.test.ts": 5465, - "server/src/services/explicit-native-continuation.test.ts": 114104, - "server/src/services/finalized-workspace-recovery-migration.test.ts": 10515, - "server/src/services/fireflies-webhook.test.ts": 131, - "server/src/services/fresh-continuation-fallback.test.ts": 53372, - "server/src/services/fresh-continuation-move-forward-offer.test.ts": 18963, - "server/src/services/fresh-continuation-retry-delivery.test.ts": 16891, - "server/src/services/github-connection-events.test.ts": 4945, - "server/src/services/gmail-archive-tool-policy.test.ts": 113, - "server/src/services/gmail-tool-governance.test.ts": 5144, - "server/src/services/google-chat-tool-policy.test.ts": 960, - "server/src/services/governed-wait-runner-loss.test.ts": 38505, - "server/src/services/grok-bot/webhook.test.ts": 223, - "server/src/services/heartbeat-github-launchers.test.ts": 1445, - "server/src/services/heartbeat-run-runtime-status.test.ts": 148, - "server/src/services/heartbeat-runner-provider-config.test.ts": 1398, - "server/src/services/heartbeat-stop-metadata.test.ts": 1024, - "server/src/services/heartbeat/agent-status.test.ts": 19139, - "server/src/services/heartbeat/budget-cancellation.test.ts": 21249, - "server/src/services/heartbeat/dispatch-work.test.ts": 36040, - "server/src/services/heartbeat/environment-selection.test.ts": 20913, - "server/src/services/heartbeat/external-provider.test.ts": 4733, - "server/src/services/heartbeat/idle-recovery-schedule.test.ts": 6524, - "server/src/services/heartbeat/instruction-working-copy.test.ts": 4600, - "server/src/services/heartbeat/legacy-process-settlement.test.ts": 2198, - "server/src/services/heartbeat/live-runner-adoption.test.ts": 100, - "server/src/services/heartbeat/native-lifecycle.test.ts": 1596, - "server/src/services/heartbeat/native-recovery-deadlines.test.ts": 5118, - "server/src/services/heartbeat/native-stop-evidence-read.test.ts": 13886, - "server/src/services/heartbeat/native-stop-pending.test.ts": 11475, - "server/src/services/heartbeat/preparation-timing-context.test.ts": 1862, - "server/src/services/heartbeat/preparation-timing.test.ts": 1350, - "server/src/services/heartbeat/process-identity-persistence.test.ts": 7029, - "server/src/services/heartbeat/process-settlement.test.ts": 1155, - "server/src/services/heartbeat/queue.test.ts": 58330, - "server/src/services/heartbeat/queued-run-dispatch-order.test.ts": 2110, - "server/src/services/heartbeat/recovery.test.ts": 46952, - "server/src/services/heartbeat/remote-workspace-source.test.ts": 7694, - "server/src/services/heartbeat/retries.test.ts": 10149, - "server/src/services/heartbeat/run-comment-selection.test.ts": 6202, - "server/src/services/heartbeat/run-completion-reviewed-chat-report.test.ts": 10584, - "server/src/services/heartbeat/run-completion.test.ts": 118297, - "server/src/services/heartbeat/run-control-reads.test.ts": 11003, - "server/src/services/heartbeat/run-control.test.ts": 48462, - "server/src/services/heartbeat/run-failure-cause.test.ts": 1649, - "server/src/services/heartbeat/run-lifecycle.test.ts": 26163, - "server/src/services/heartbeat/run-log.test.ts": 1600, - "server/src/services/heartbeat/run-output.test.ts": 14511, - "server/src/services/heartbeat/run-preparation.review-path.test.ts": 4938, - "server/src/services/heartbeat/run-preparation.test.ts": 6450, - "server/src/services/heartbeat/run-state.test.ts": 7638, - "server/src/services/heartbeat/runtime-execution.test.ts": 36754, - "server/src/services/heartbeat/runtime-selection.test.ts": 48451, - "server/src/services/heartbeat/scheduling.test.ts": 66355, - "server/src/services/heartbeat/system-notice-response.test.ts": 125, - "server/src/services/heartbeat/task-markdown.test.ts": 3903, - "server/src/services/heartbeat/upgrade-readiness-header-memo.test.ts": 6631, - "server/src/services/heartbeat/upgrade-readiness-post-result.test.ts": 7739, - "server/src/services/heartbeat/upgrade-readiness.test.ts": 12194, - "server/src/services/heartbeat/workspace-preparation.test.ts": 173473, - "server/src/services/heartbeat/workspaces.test.ts": 9244, - "server/src/services/hot-restart.test.ts": 1058, - "server/src/services/idle-api-activity.test.ts": 118, - "server/src/services/idle-api-wake-admission.test.ts": 100, - "server/src/services/idle-deadline-proof.test.ts": 5884, - "server/src/services/idle-incoming-wake-capability.test.ts": 1368, - "server/src/services/idle-incoming-wake.test.ts": 4535, - "server/src/services/inbox-mine-read.test.ts": 253, - "server/src/services/instance-settings-readonly.test.ts": 5286, - "server/src/services/isolated-remote-workspace-source-lock.test.ts": 8680, - "server/src/services/isolated-remote-workspace-source.test.ts": 4822, - "server/src/services/isolated-task-directory.test.ts": 1375, - "server/src/services/issue-comment-wakeup.test.ts": 100, - "server/src/services/issue-dependency-wakeups.test.ts": 1743, - "server/src/services/issue-prefix.test.ts": 1719, - "server/src/services/issue-question-context.test.ts": 2356, - "server/src/services/issue-queued-comment-queue.test.ts": 100, - "server/src/services/issue-read-timing.test.ts": 110, - "server/src/services/issue-thread-interaction-resolution.test.ts": 689, - "server/src/services/issue-thread-interactions.test.ts": 13375, - "server/src/services/legacy-controller-lease.test.ts": 25199, - "server/src/services/legacy-execution-recovery.test.ts": 5197, - "server/src/services/legacy-explicit-continuation-recovery.test.ts": 8915, - "server/src/services/legacy-preparation-retry-hold.test.ts": 8599, - "server/src/services/local-ai-browser-login.test.ts": 3786, - "server/src/services/login-command.test.ts": 4935, - "server/src/services/login-environment.test.ts": 2142, - "server/src/services/managed-config-capabilities.test.ts": 869, - "server/src/services/managed-environments-plugin-entries.test.ts": 4904, - "server/src/services/managed-environments.test.ts": 4771, - "server/src/services/managed-resource-drift.test.ts": 106, - "server/src/services/mcp-tool-names.test.ts": 100, - "server/src/services/muse-maintenance.test.ts": 17994, - "server/src/services/native-local-process-stop.test.ts": 2872, - "server/src/services/native-log-archive.integration.test.ts": 21359, - "server/src/services/native-preclaim-continuation.test.ts": 16040, - "server/src/services/native-runtime/acpx-qualification.test.ts": 1820, - "server/src/services/native-runtime/agent-chat-response-recovery.test.ts": 19727, - "server/src/services/native-runtime/agent-instruction-tools.integration.test.ts": 11168, - "server/src/services/native-runtime/agent-instruction-tools.test.ts": 3961, - "server/src/services/native-runtime/antigravity-candidate-admission.test.ts": 1388, - "server/src/services/native-runtime/antigravity-credential-recovery.test.ts": 1729, - "server/src/services/native-runtime/antigravity-runner-credentials.test.ts": 2182, - "server/src/services/native-runtime/artifact-transfer.integration.test.ts": 8284, - "server/src/services/native-runtime/artifact-transfer.test.ts": 4215, - "server/src/services/native-runtime/assigned-mcp-tools.test.ts": 7234, - "server/src/services/native-runtime/case-context-projection.test.ts": 4570, - "server/src/services/native-runtime/chat-attachment-read.test.ts": 10749, - "server/src/services/native-runtime/chat-attachment-reuse.test.ts": 6229, - "server/src/services/native-runtime/codex-model-fallback.test.ts": 1014, - "server/src/services/native-runtime/codex-runtime-compatibility.test.ts": 104, - "server/src/services/native-runtime/completion-contracts.test.ts": 4966, - "server/src/services/native-runtime/confirmation-comment-api.integration.test.ts": 17657, - "server/src/services/native-runtime/continuation-contract.test.ts": 6223, - "server/src/services/native-runtime/create-skill.integration.test.ts": 10733, - "server/src/services/native-runtime/current-wake-comments.test.ts": 6485, - "server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts": 4658, - "server/src/services/native-runtime/cursor-cloud-profile.test.ts": 1255, - "server/src/services/native-runtime/cursor-cloud-runtime.test.ts": 2603, - "server/src/services/native-runtime/evidence-classifier.test.ts": 2198, + "server/src/__tests__/workspace-runtime-lease-ownership.test.ts": 11219, + "server/src/__tests__/workspace-runtime-leases.test.ts": 4296, + "server/src/__tests__/workspace-runtime-lifecycle.test.ts": 7179, + "server/src/__tests__/workspace-runtime-start-terminality.test.ts": 9698, + "server/src/__tests__/workspace-runtime.test.ts": 102579, + "server/src/__tests__/workspace-worktree-concurrency.test.ts": 30390, + "server/src/__tests__/worktree-config.test.ts": 1938, + "server/src/__tests__/worktree-seed-server-spawn.test.ts": 8828, + "server/src/__tests__/write-build-stamp.test.ts": 1065, + "server/src/__tests__/write-path-membership.test.ts": 6313, + "server/src/adapters/claude-agent-id-header.test.ts": 829, + "server/src/adapters/cloud-external-adapters.test.ts": 10072, + "server/src/adapters/http/execute.test.ts": 1754, + "server/src/adapters/plugin-loader.test.ts": 759, + "server/src/adapters/registry.test.ts": 6375, + "server/src/embedded-postgres-owner.test.ts": 685, + "server/src/event-loop-stall-monitor.test.ts": 2403, + "server/src/google-workspace-rest-tools/allowlist.test.ts": 2706, + "server/src/google-workspace-rest-tools/boundary.test.ts": 1335, + "server/src/google-workspace-rest-tools/calendar/create-event.test.ts": 901, + "server/src/google-workspace-rest-tools/calendar/delete-event.test.ts": 748, + "server/src/google-workspace-rest-tools/calendar/event.test.ts": 883, + "server/src/google-workspace-rest-tools/calendar/get-event.test.ts": 1286, + "server/src/google-workspace-rest-tools/calendar/list-calendars.test.ts": 1007, + "server/src/google-workspace-rest-tools/calendar/list-events.test.ts": 857, + "server/src/google-workspace-rest-tools/calendar/respond-to-event.test.ts": 803, + "server/src/google-workspace-rest-tools/calendar/search-events.test.ts": 904, + "server/src/google-workspace-rest-tools/calendar/suggest-time.test.ts": 817, + "server/src/google-workspace-rest-tools/calendar/time.test.ts": 812, + "server/src/google-workspace-rest-tools/calendar/update-event.test.ts": 1496, + "server/src/google-workspace-rest-tools/docs/read-doc.test.ts": 940, + "server/src/google-workspace-rest-tools/docs/render.test.ts": 917, + "server/src/google-workspace-rest-tools/docs/request-kinds.test.ts": 899, + "server/src/google-workspace-rest-tools/docs/update-doc.test.ts": 942, + "server/src/google-workspace-rest-tools/documents-shared.test.ts": 1023, + "server/src/google-workspace-rest-tools/drive/annotations.test.ts": 900, + "server/src/google-workspace-rest-tools/drive/copy-file.test.ts": 661, + "server/src/google-workspace-rest-tools/drive/create-file.test.ts": 821, + "server/src/google-workspace-rest-tools/drive/download-file-content.test.ts": 730, + "server/src/google-workspace-rest-tools/drive/get-file-metadata.test.ts": 1277, + "server/src/google-workspace-rest-tools/drive/get-file-permissions.test.ts": 843, + "server/src/google-workspace-rest-tools/drive/list-recent-files.test.ts": 1087, + "server/src/google-workspace-rest-tools/drive/query.test.ts": 584, + "server/src/google-workspace-rest-tools/drive/read-file-content.test.ts": 969, + "server/src/google-workspace-rest-tools/drive/search-files.test.ts": 776, + "server/src/google-workspace-rest-tools/gmail/address.test.ts": 852, + "server/src/google-workspace-rest-tools/gmail/create-draft.test.ts": 1127, + "server/src/google-workspace-rest-tools/gmail/get-draft.test.ts": 1116, + "server/src/google-workspace-rest-tools/gmail/get-message.test.ts": 875, + "server/src/google-workspace-rest-tools/gmail/get-thread.test.ts": 819, + "server/src/google-workspace-rest-tools/gmail/list-drafts.test.ts": 887, + "server/src/google-workspace-rest-tools/gmail/list-labels.test.ts": 933, + "server/src/google-workspace-rest-tools/gmail/list-threads.test.ts": 902, + "server/src/google-workspace-rest-tools/gmail/parallel.test.ts": 1107, + "server/src/google-workspace-rest-tools/gmail/search-messages.test.ts": 622, + "server/src/google-workspace-rest-tools/gmail/search-threads.test.ts": 822, + "server/src/google-workspace-rest-tools/google-http.test.ts": 800, + "server/src/google-workspace-rest-tools/probe.test.ts": 880, + "server/src/google-workspace-rest-tools/result-budget.test.ts": 2010, + "server/src/google-workspace-rest-tools/server.test.ts": 1360, + "server/src/google-workspace-rest-tools/sheets/get-spreadsheet.test.ts": 879, + "server/src/google-workspace-rest-tools/sheets/get-values.test.ts": 1162, + "server/src/google-workspace-rest-tools/sheets/insert-dimension.test.ts": 896, + "server/src/google-workspace-rest-tools/sheets/range.test.ts": 737, + "server/src/google-workspace-rest-tools/sheets/update-spreadsheet.test.ts": 870, + "server/src/google-workspace-rest-tools/sheets/update-values.test.ts": 1144, + "server/src/google-workspace-rest-tools/sheets/wiring.test.ts": 1665, + "server/src/google-workspace-rest-tools/slides/read-presentation.test.ts": 1050, + "server/src/google-workspace-rest-tools/slides/render.test.ts": 814, + "server/src/google-workspace-rest-tools/slides/request-kinds.test.ts": 902, + "server/src/google-workspace-rest-tools/slides/update-presentation.test.ts": 1114, + "server/src/http/server.test.ts": 2908, + "server/src/lib/active-run-slots.test.ts": 868, + "server/src/lib/request-promise-memo.test.ts": 887, + "server/src/lib/single-flight.test.ts": 889, + "server/src/maintenance/ephemeral-migration-service.test.ts": 1291, + "server/src/maintenance/native-harness-prestage-runtime.test.ts": 9103, + "server/src/maintenance/native-harness-prestage.test.ts": 1031, + "server/src/maintenance/online-workspace-migration.test.ts": 6949, + "server/src/middleware/cloud-tenant-actor.test.ts": 6804, + "server/src/middleware/cloud-tenant-sync-postgres.test.ts": 22374, + "server/src/middleware/runner-call-outcome.test.ts": 3023, + "server/src/modules/active-run-watchdog/adapters/process.test.ts": 1696, + "server/src/modules/active-run-watchdog/application/use-cases.test.ts": 724, + "server/src/modules/active-run-watchdog/domain/policy.test.ts": 886, + "server/src/modules/agent-lifecycle/__tests__/diagnostics.test.ts": 8270, + "server/src/modules/agent-lifecycle/__tests__/driver-scope.test.ts": 7479, + "server/src/modules/agent-lifecycle/__tests__/environment-plugins.test.ts": 9410, + "server/src/modules/agent-lifecycle/__tests__/lifecycle.test.ts": 37484, + "server/src/modules/agent-lifecycle/__tests__/pending-backoff.test.ts": 6985, + "server/src/modules/agent-lifecycle/__tests__/policy-sweep.test.ts": 8793, + "server/src/modules/agent-lifecycle/__tests__/resource-wait-stop.test.ts": 11051, + "server/src/modules/agent-lifecycle/__tests__/restart-verification.test.ts": 7019, + "server/src/modules/agent-lifecycle/__tests__/setup.test.ts": 8764, + "server/src/modules/agent-lifecycle/__tests__/verification-retry.test.ts": 10040, + "server/src/modules/execution-admission/adapters/postgres.test.ts": 7352, + "server/src/modules/execution-admission/domain/policy.test.ts": 733, + "server/src/modules/external-agents/cloud-principal-http.test.ts": 6307, + "server/src/modules/external-agents/cloud-principal-log.test.ts": 1086, + "server/src/modules/external-agents/original-token-principal.test.ts": 6875, + "server/src/modules/run-dispatch/adapters/postgres.test.ts": 31715, + "server/src/modules/run-dispatch/application/use-cases.test.ts": 733, + "server/src/modules/run-dispatch/domain/policy.test.ts": 917, + "server/src/modules/run-dispatch/domain/wake-context.test.ts": 766, + "server/src/modules/wake-queue/adapters/chat-declined-outcome-reported.test.ts": 8840, + "server/src/modules/wake-queue/adapters/chat-wake-conversation-batch.test.ts": 8403, + "server/src/modules/wake-queue/adapters/chat-wake-delivered.test.ts": 7354, + "server/src/modules/wake-queue/adapters/operator-stop.test.ts": 5816, + "server/src/modules/wake-queue/adapters/postgres.test.ts": 38573, + "server/src/modules/wake-queue/adapters/promoted-retry-scope.test.ts": 6760, + "server/src/modules/wake-queue/adapters/queued-comment-postgres.test.ts": 6682, + "server/src/modules/wake-queue/adapters/queued-operator-stop-postgres.test.ts": 6080, + "server/src/modules/wake-queue/adapters/release-run-read.test.ts": 2580, + "server/src/modules/wake-queue/adapters/retryable-before-provider-work.test.ts": 5229, + "server/src/modules/wake-queue/application/queued-comment-use-cases.test.ts": 774, + "server/src/modules/wake-queue/application/use-cases.test.ts": 7492, + "server/src/modules/wake-queue/domain/context.test.ts": 6037, + "server/src/modules/wake-queue/domain/policy.test.ts": 1025, + "server/src/realtime/live-event-delivery.cost.test.ts": 897, + "server/src/realtime/live-event-delivery.test.ts": 745, + "server/src/realtime/runner-prp-outbound.test.ts": 806, + "server/src/realtime/runner-prp-ws.test.ts": 2722, + "server/src/routes/adapters.test.ts": 5585, + "server/src/routes/chat-channels.identity.test.ts": 7775, + "server/src/routes/chat-channels.webhook.test.ts": 7956, + "server/src/routes/connection-intents.test.ts": 5811, + "server/src/routes/ephemeral-enrollment.test.ts": 2108, + "server/src/routes/issues-wake-diagnostics.test.ts": 4963, + "server/src/routes/setup-token-route.test.ts": 9288, + "server/src/routes/tool-access-connection-intent.test.ts": 7464, + "server/src/routes/voice-sessions.auth.test.ts": 7695, + "server/src/runtime-tools-token.test.ts": 1406, + "server/src/services/__tests__/git-connection-failure.test.ts": 753, + "server/src/services/__tests__/mcp-connection-failure.test.ts": 688, + "server/src/services/__tests__/process-loss-diagnostics.test.ts": 880, + "server/src/services/__tests__/run-failure-diagnostics-provider-unavailable.test.ts": 1815, + "server/src/services/__tests__/run-failure-diagnostics.test.ts": 1637, + "server/src/services/__tests__/run-failure-report-native-usage-limit.test.ts": 7350, + "server/src/services/__tests__/run-failure-report-project-access.test.ts": 6454, + "server/src/services/__tests__/run-failure-report-reviewed-chat.test.ts": 7286, + "server/src/services/__tests__/run-failure-report.test.ts": 21951, + "server/src/services/__tests__/sentry-run-links.test.ts": 2351, + "server/src/services/acknowledged-native-stop.test.ts": 2689, + "server/src/services/adapter-execution-control.test.ts": 1434, + "server/src/services/adapter-execution-phase.test.ts": 682, + "server/src/services/adapter-login-lease.test.ts": 699, + "server/src/services/adapter-models-env.test.ts": 932, + "server/src/services/adapter-registry-bootstrap.reconcile.test.ts": 6276, + "server/src/services/adapter-registry-bootstrap.test.ts": 5086, + "server/src/services/adapter-settings-local.test.ts": 2366, + "server/src/services/adapter-settings-postgres.test.ts": 6481, + "server/src/services/agent-budget-hold-activity.test.ts": 8607, + "server/src/services/agent-cost-history-deletion.test.ts": 6277, + "server/src/services/agent-environment-test-status.test.ts": 5644, + "server/src/services/agent-identity-redaction.test.ts": 2040, + "server/src/services/agent-interaction-delivery.test.ts": 7079, + "server/src/services/agent-invented-host-links.test.ts": 1731, + "server/src/services/agent-runner-selection.test.ts": 5364, + "server/src/services/agent-start-lock.test.ts": 559, + "server/src/services/ai-account-identity.test.ts": 2027, + "server/src/services/ai-auth-failure.test.ts": 1974, + "server/src/services/ai-connection-configuration-failure.test.ts": 984, + "server/src/services/ai-connection-usage.test.ts": 1774, + "server/src/services/anthropic-pricing.test.ts": 1976, + "server/src/services/app-webhook.test.ts": 739, + "server/src/services/approved-execution-wait.test.ts": 947, + "server/src/services/attention-audience.test.ts": 7537, + "server/src/services/attention-resolver-audience.test.ts": 6558, + "server/src/services/board-auth.test.ts": 11874, + "server/src/services/budget-live-usage.test.ts": 2077, + "server/src/services/budget-resume-continuation.test.ts": 10211, + "server/src/services/budget-tracing.test.ts": 1887, + "server/src/services/bundled-skill-release-validation.test.ts": 2693, + "server/src/services/case-agent-read.test.ts": 2438, + "server/src/services/case-deletion.test.ts": 7502, + "server/src/services/case-handoff-privacy.test.ts": 7182, + "server/src/services/case-handoffs.test.ts": 59635, + "server/src/services/case-task-documents.test.ts": 7695, + "server/src/services/chat-channels/authorization-run-read.test.ts": 2401, + "server/src/services/chat-channels/discord/command-work.test.ts": 2014, + "server/src/services/chat-channels/github/response-run-state.test.ts": 8778, + "server/src/services/chat-channels/github/response-sweep-scope.test.ts": 6654, + "server/src/services/chat-channels/github/retry.test.ts": 6396, + "server/src/services/chat-channels/github/review-check-work.test.ts": 3215, + "server/src/services/chat-channels/github/review-heading.test.ts": 722, + "server/src/services/chat-channels/github/review-instructions.test.ts": 1825, + "server/src/services/chat-channels/github/terminal-response-work.test.ts": 12889, + "server/src/services/chat-channels/github/webhook-ingress.test.ts": 8916, + "server/src/services/chat-channels/inbound/wakeup-authorization-error.test.ts": 621, + "server/src/services/chat-channels/run-origin.test.ts": 6023, + "server/src/services/chat-channels/slack/adapter.test.ts": 2150, + "server/src/services/chat-channels/slack/cards.test.ts": 2222, + "server/src/services/chat-channels/slack/cloud-callback.test.ts": 5968, + "server/src/services/chat-channels/slack/cloud-drain.test.ts": 6585, + "server/src/services/chat-channels/slack/cloud-enrollment.test.ts": 1840, + "server/src/services/chat-channels/slack/cloud-event.test.ts": 7407, + "server/src/services/chat-channels/slack/cloud-ingress.test.ts": 1641, + "server/src/services/chat-channels/slack/cloud-signing-secret.test.ts": 762, + "server/src/services/chat-channels/slack/cloud-test-prewire.test.ts": 1160, + "server/src/services/chat-channels/slack/configured-coverage.test.ts": 1884, + "server/src/services/chat-channels/slack/form-ack-work.test.ts": 1521, + "server/src/services/chat-channels/slack/form-canonical-state.test.ts": 1916, + "server/src/services/chat-channels/slack/form-enrollment-identity.test.ts": 2248, + "server/src/services/chat-channels/slack/form-owner-rearm.test.ts": 7463, + "server/src/services/chat-channels/slack/form-retirement.test.ts": 1910, + "server/src/services/chat-channels/slack/idle-history-owner-proof.test.ts": 2696, + "server/src/services/chat-channels/slack/idle-incoming.test.ts": 2089, + "server/src/services/chat-channels/slack/question-forms.test.ts": 675, + "server/src/services/chat-channels/slack/receipt-timing.test.ts": 980, + "server/src/services/chat-channels/slack/signing-secret-preflight.test.ts": 5038, + "server/src/services/chat-channels/slack/wake-authority.test.ts": 778, + "server/src/services/chat-communication-guidance.test.ts": 1586, + "server/src/services/chat-control-admission-retry.test.ts": 5008, + "server/src/services/chat-discord-adapter-patch.test.ts": 4526, + "server/src/services/chat-discord-command-registration-store.test.ts": 7446, + "server/src/services/chat-discord-command-registration.test.ts": 1035, + "server/src/services/chat-discord-modal-wire.test.ts": 3594, + "server/src/services/chat-discord-native-command.test.ts": 3675, + "server/src/services/chat-discord-native-commands.test.ts": 1242, + "server/src/services/chat-discord-native-interaction.test.ts": 7411, + "server/src/services/chat-discord-native-modal.test.ts": 3894, + "server/src/services/chat-discord-question-forms.test.ts": 827, + "server/src/services/chat-discord.test.ts": 971, + "server/src/services/chat-github-attachments.test.ts": 4217, + "server/src/services/chat-github-events.test.ts": 2146, + "server/src/services/chat-github-management.test.ts": 1909, + "server/src/services/chat-github-provider-stress.test.ts": 4914, + "server/src/services/chat-github-receipt-reactions.test.ts": 1164, + "server/src/services/chat-github-review-policy.test.ts": 1649, + "server/src/services/chat-github-review-repair.test.ts": 9291, + "server/src/services/chat-github-sponsor.test.ts": 9091, + "server/src/services/chat-github-tools.test.ts": 2807, + "server/src/services/chat-github-webhook-config.test.ts": 1151, + "server/src/services/chat-github-wizard-origin.test.ts": 7549, + "server/src/services/chat-inbound-wakeup-publications.test.ts": 6742, + "server/src/services/chat-interaction-arbitration.test.ts": 2485, + "server/src/services/chat-interaction-continuation.test.ts": 8423, + "server/src/services/chat-interaction-forms.test.ts": 2800, + "server/src/services/chat-interaction-publications.test.ts": 6135, + "server/src/services/chat-monitor-continuation.test.ts": 19929, + "server/src/services/chat-outbound-attachment-hydration.test.ts": 8299, + "server/src/services/chat-provider-inventory.test.ts": 801, + "server/src/services/chat-provider-lifecycle.test.ts": 751, + "server/src/services/chat-provider-links.test.ts": 673, + "server/src/services/chat-publication-batches.test.ts": 1652, + "server/src/services/chat-publication-errors.test.ts": 796, + "server/src/services/chat-publication-projection.test.ts": 803, + "server/src/services/chat-publication-ready-stream.test.ts": 4895, + "server/src/services/chat-publication-reconciliation.test.ts": 588, + "server/src/services/chat-publication-stream.test.ts": 3093, + "server/src/services/chat-publication-text-parts.test.ts": 25286, + "server/src/services/chat-question-forms.test.ts": 3025, + "server/src/services/chat-reply-lineage-context.test.ts": 14144, + "server/src/services/chat-run-publications.test.ts": 7423, + "server/src/services/chat-sdk-runtime.adapters.test.ts": 6978, + "server/src/services/chat-sdk-runtime.test.ts": 3499, + "server/src/services/chat-sdk-state.test.ts": 739, + "server/src/services/chat-slack-native-modal.test.ts": 3468, + "server/src/services/chat-slack-receipts.test.ts": 5112, + "server/src/services/chat-slack-sessions.test.ts": 586, + "server/src/services/chat-task-url.test.ts": 7399, + "server/src/services/chat-teams-credentials.test.ts": 1618, + "server/src/services/chat-teams-file-consent-runtime.test.ts": 3781, + "server/src/services/chat-teams-file-consent.contract.test.ts": 1665, + "server/src/services/chat-teams-file-consent.test.ts": 938, + "server/src/services/chat-teams-file-publication.test.ts": 7058, + "server/src/services/chat-teams-file-transfers.test.ts": 13927, + "server/src/services/chat-teams-inline-image-intake.test.ts": 3602, + "server/src/services/chat-teams-inline-images.test.ts": 3962, + "server/src/services/chat-teams-native-modal.test.ts": 4291, + "server/src/services/chat-teams-personal-recipient.test.ts": 1336, + "server/src/services/chat-telegram-draft-stop.test.ts": 959, + "server/src/services/chat-telegram-ephemeral-runtime.test.ts": 3003, + "server/src/services/chat-telegram-ephemeral.test.ts": 829, + "server/src/services/chat-telegram-media-intake.test.ts": 3812, + "server/src/services/chat-telegram-photo.test.ts": 1200, + "server/src/services/chat-telegram-rich-intake.test.ts": 3535, + "server/src/services/chat-telegram-stop-subscription.test.ts": 610, + "server/src/services/chat-telegram-video-note.test.ts": 3826, + "server/src/services/cloud-runtime-identity.test.ts": 1908, + "server/src/services/cloud-warm-standby.test.ts": 2195, + "server/src/services/connection-credential-state.test.ts": 6131, + "server/src/services/connector-runtime.test.ts": 7537, + "server/src/services/connector-telemetry.test.ts": 1925, + "server/src/services/connectors/onepassword/onepassword.test.ts": 894, + "server/src/services/connectors/onepassword/worker.test.ts": 848, + "server/src/services/connectors/slack-access.test.ts": 1850, + "server/src/services/connectors/slack-authority.test.ts": 7577, + "server/src/services/connectors/slack-endpoint-preparation.test.ts": 610, + "server/src/services/connectors/slack-native-search.test.ts": 1525, + "server/src/services/connectors/supabase/index.test.ts": 1980, + "server/src/services/connectors/tailscale/connections.test.ts": 7964, + "server/src/services/connectors/tailscale/device-login-network.test.ts": 4073, + "server/src/services/connectors/tailscale/device-login.test.ts": 6990, + "server/src/services/connectors/tailscale/devices.test.ts": 757, + "server/src/services/connectors/tailscale/network.test.ts": 3992, + "server/src/services/connectors/tailscale/pairing.test.ts": 1019, + "server/src/services/connectors/vercel/index.test.ts": 935, + "server/src/services/controller-process-identity.test.ts": 7997, + "server/src/services/controller-process-space-identity.test.ts": 4092, + "server/src/services/conversation-continuation.test.ts": 2468, + "server/src/services/covered-historical-workspace-source.integration.test.ts": 13981, + "server/src/services/decision-signing.test.ts": 976, + "server/src/services/deferred-execution-wait.test.ts": 6593, + "server/src/services/environment-custom-image-terminal-sessions.test.ts": 751, + "server/src/services/environment-lease-fault-injection.test.ts": 1962, + "server/src/services/environment-lease-release-deferral.test.ts": 3484, + "server/src/services/environment-provider-unavailable-error.test.ts": 1654, + "server/src/services/environment-runtime-reusable-lease-probe.test.ts": 7560, + "server/src/services/ephemeral-enrollment.test.ts": 6429, + "server/src/services/execution-allowlist.test.ts": 841, + "server/src/services/execution-blocker-read.test.ts": 9947, + "server/src/services/execution-continuation-history-read.test.ts": 6235, + "server/src/services/execution-continuation-provenance.test.ts": 7312, + "server/src/services/execution-continuation.test.ts": 6146, + "server/src/services/execution-control-reconciliation.test.ts": 10688, + "server/src/services/execution-policy-bootstrap.test.ts": 3358, + "server/src/services/execution-preparation-timing.test.ts": 1906, + "server/src/services/execution-projection-agent-queue.test.ts": 8326, + "server/src/services/execution-projection-external-provider.test.ts": 6996, + "server/src/services/execution-projection-read-retry.test.ts": 8381, + "server/src/services/execution-projection-recovery.test.ts": 6830, + "server/src/services/execution-projection.test.ts": 6713, + "server/src/services/execution-recovery-attempt.test.ts": 5915, + "server/src/services/execution-recovery-dead-controller.test.ts": 6855, + "server/src/services/execution-recovery-resolution.test.ts": 6207, + "server/src/services/execution-timing-context.test.ts": 2970, + "server/src/services/execution-transaction-timing.test.ts": 6698, + "server/src/services/explicit-native-continuation.test.ts": 108543, + "server/src/services/finalized-workspace-recovery-migration.test.ts": 11370, + "server/src/services/fireflies-webhook.test.ts": 931, + "server/src/services/fresh-continuation-fallback.test.ts": 89949, + "server/src/services/fresh-continuation-move-forward-offer.test.ts": 24878, + "server/src/services/fresh-continuation-retry-delivery.test.ts": 16226, + "server/src/services/fresh-continuation-schedule-queries.test.ts": 13634, + "server/src/services/github-connection-events.test.ts": 6267, + "server/src/services/gmail-archive-tool-policy.test.ts": 829, + "server/src/services/gmail-tool-governance.test.ts": 6233, + "server/src/services/google-chat-tool-policy.test.ts": 1895, + "server/src/services/google-workspace-rest-dispatch.test.ts": 1779, + "server/src/services/governed-wait-runner-loss.test.ts": 59275, + "server/src/services/grok-bot/webhook.test.ts": 634, + "server/src/services/heartbeat-github-launchers.test.ts": 2107, + "server/src/services/heartbeat-run-runtime-status.test.ts": 672, + "server/src/services/heartbeat-runner-provider-config.test.ts": 3077, + "server/src/services/heartbeat-stop-metadata.test.ts": 2091, + "server/src/services/heartbeat/agent-directory-busy.test.ts": 5025, + "server/src/services/heartbeat/agent-status.test.ts": 25170, + "server/src/services/heartbeat/budget-cancellation.test.ts": 25772, + "server/src/services/heartbeat/dispatch-work.test.ts": 37986, + "server/src/services/heartbeat/environment-selection.test.ts": 22396, + "server/src/services/heartbeat/external-provider.test.ts": 4994, + "server/src/services/heartbeat/idle-recovery-schedule.test.ts": 6940, + "server/src/services/heartbeat/instruction-working-copy.test.ts": 5974, + "server/src/services/heartbeat/legacy-process-settlement.test.ts": 2588, + "server/src/services/heartbeat/live-runner-adoption.test.ts": 581, + "server/src/services/heartbeat/native-lifecycle.test.ts": 2522, + "server/src/services/heartbeat/native-recovery-deadlines.test.ts": 7505, + "server/src/services/heartbeat/native-stop-evidence-read.test.ts": 12601, + "server/src/services/heartbeat/native-stop-pending.test.ts": 8931, + "server/src/services/heartbeat/preparation-timing-context.test.ts": 1983, + "server/src/services/heartbeat/preparation-timing.test.ts": 2033, + "server/src/services/heartbeat/process-identity-persistence.test.ts": 9248, + "server/src/services/heartbeat/process-settlement.test.ts": 2031, + "server/src/services/heartbeat/queue.test.ts": 92223, + "server/src/services/heartbeat/queued-run-dispatch-order.test.ts": 2998, + "server/src/services/heartbeat/queued-run-line.test.ts": 3515, + "server/src/services/heartbeat/reattach-phase.test.ts": 12092, + "server/src/services/heartbeat/recovery.test.ts": 41466, + "server/src/services/heartbeat/remote-workspace-source.test.ts": 6797, + "server/src/services/heartbeat/retries.test.ts": 9945, + "server/src/services/heartbeat/run-comment-selection.test.ts": 8951, + "server/src/services/heartbeat/run-completion-reviewed-chat-report.test.ts": 14349, + "server/src/services/heartbeat/run-completion.test.ts": 151888, + "server/src/services/heartbeat/run-control-event-failure.test.ts": 9105, + "server/src/services/heartbeat/run-control-reads.test.ts": 9616, + "server/src/services/heartbeat/run-control.test.ts": 77061, + "server/src/services/heartbeat/run-failure-cause.test.ts": 2966, + "server/src/services/heartbeat/run-lifecycle.test.ts": 30357, + "server/src/services/heartbeat/run-log.test.ts": 2197, + "server/src/services/heartbeat/run-output.test.ts": 15553, + "server/src/services/heartbeat/run-preparation.review-path.test.ts": 6172, + "server/src/services/heartbeat/run-preparation.test.ts": 6679, + "server/src/services/heartbeat/run-state.test.ts": 8786, + "server/src/services/heartbeat/runtime-execution.test.ts": 42628, + "server/src/services/heartbeat/runtime-selection.test.ts": 75268, + "server/src/services/heartbeat/scheduling.test.ts": 64758, + "server/src/services/heartbeat/session-fingerprint-inputs.test.ts": 5895, + "server/src/services/heartbeat/system-notice-response.test.ts": 472, + "server/src/services/heartbeat/task-markdown.test.ts": 7244, + "server/src/services/heartbeat/upgrade-readiness-header-memo.test.ts": 7480, + "server/src/services/heartbeat/upgrade-readiness-post-result.test.ts": 11579, + "server/src/services/heartbeat/upgrade-readiness.test.ts": 13074, + "server/src/services/heartbeat/workspace-preparation.test.ts": 178931, + "server/src/services/heartbeat/workspaces.test.ts": 7521, + "server/src/services/hot-restart.test.ts": 1902, + "server/src/services/idle-api-activity.test.ts": 861, + "server/src/services/idle-api-wake-admission.test.ts": 773, + "server/src/services/idle-deadline-proof.test.ts": 6083, + "server/src/services/idle-incoming-wake-capability.test.ts": 1842, + "server/src/services/idle-incoming-wake.test.ts": 7303, + "server/src/services/inbox-mine-read.test.ts": 743, + "server/src/services/instance-settings-readonly.test.ts": 6178, + "server/src/services/isolated-remote-workspace-source-lock.test.ts": 10495, + "server/src/services/isolated-remote-workspace-source.test.ts": 5129, + "server/src/services/isolated-task-directory.test.ts": 1831, + "server/src/services/issue-comment-wakeup.test.ts": 585, + "server/src/services/issue-dependency-wakeups.test.ts": 1461, + "server/src/services/issue-prefix.test.ts": 2095, + "server/src/services/issue-question-context.test.ts": 2593, + "server/src/services/issue-queued-comment-queue.test.ts": 895, + "server/src/services/issue-read-timing.test.ts": 802, + "server/src/services/issue-thread-interaction-resolution.test.ts": 1491, + "server/src/services/issue-thread-interactions.test.ts": 14384, + "server/src/services/legacy-controller-lease.test.ts": 34340, + "server/src/services/legacy-execution-recovery.test.ts": 4882, + "server/src/services/legacy-explicit-continuation-recovery.test.ts": 9358, + "server/src/services/legacy-preparation-retry-hold.test.ts": 12289, + "server/src/services/legacy-source-unavailable-continuation.test.ts": 10232, + "server/src/services/local-ai-browser-login.test.ts": 5678, + "server/src/services/login-command.test.ts": 6475, + "server/src/services/login-environment.test.ts": 1622, + "server/src/services/managed-config-capabilities.test.ts": 1620, + "server/src/services/managed-environments-plugin-entries.test.ts": 6198, + "server/src/services/managed-environments.test.ts": 7180, + "server/src/services/managed-resource-drift.test.ts": 904, + "server/src/services/mcp-tool-names.test.ts": 765, + "server/src/services/muse-maintenance.test.ts": 17264, + "server/src/services/native-local-process-stop.test.ts": 3397, + "server/src/services/native-log-archive.integration.test.ts": 23689, + "server/src/services/native-preclaim-continuation.test.ts": 19224, + "server/src/services/native-runtime/acpx-qualification.test.ts": 3012, + "server/src/services/native-runtime/agent-chat-response-recovery.test.ts": 22254, + "server/src/services/native-runtime/agent-instruction-tools.integration.test.ts": 10416, + "server/src/services/native-runtime/agent-instruction-tools.test.ts": 5043, + "server/src/services/native-runtime/antigravity-candidate-admission.test.ts": 2463, + "server/src/services/native-runtime/antigravity-credential-recovery.test.ts": 2691, + "server/src/services/native-runtime/antigravity-runner-credentials.test.ts": 6700, + "server/src/services/native-runtime/artifact-transfer.integration.test.ts": 9481, + "server/src/services/native-runtime/artifact-transfer.test.ts": 4060, + "server/src/services/native-runtime/assigned-mcp-tools.test.ts": 15611, + "server/src/services/native-runtime/case-context-projection.test.ts": 6002, + "server/src/services/native-runtime/chat-attachment-read.test.ts": 11792, + "server/src/services/native-runtime/chat-attachment-reuse.test.ts": 8033, + "server/src/services/native-runtime/codex-model-fallback.test.ts": 1597, + "server/src/services/native-runtime/codex-runtime-compatibility.test.ts": 738, + "server/src/services/native-runtime/completion-contracts.test.ts": 7582, + "server/src/services/native-runtime/confirmation-comment-api.integration.test.ts": 24611, + "server/src/services/native-runtime/continuation-contract.test.ts": 7392, + "server/src/services/native-runtime/create-skill.integration.test.ts": 18316, + "server/src/services/native-runtime/current-wake-comments.test.ts": 8164, + "server/src/services/native-runtime/cursor-cloud-artifact-handoff.test.ts": 6960, + "server/src/services/native-runtime/cursor-cloud-profile.test.ts": 2677, + "server/src/services/native-runtime/cursor-cloud-runtime.test.ts": 2861, + "server/src/services/native-runtime/evidence-classifier.test.ts": 2774, "server/src/services/native-runtime/external-chat-wait.integration.test.ts": 181027, - "server/src/services/native-runtime/external-review-wait.test.ts": 5488, - "server/src/services/native-runtime/failed-action-chat-feedback.test.ts": 5582, - "server/src/services/native-runtime/first-turn-queued-input.test.ts": 6660, - "server/src/services/native-runtime/generate-image-tool.test.ts": 7681, - "server/src/services/native-runtime/grok-runner-credentials.test.ts": 100, - "server/src/services/native-runtime/handoff-plan-context.test.ts": 2435, - "server/src/services/native-runtime/historical-task-questions.test.ts": 10980, - "server/src/services/native-runtime/managed-native-credentials.test.ts": 100, - "server/src/services/native-runtime/model-rejected-retry.test.ts": 3123, - "server/src/services/native-runtime/muse-native-follow-up.test.ts": 8349, - "server/src/services/native-runtime/muse-native-visibility.test.ts": 10690, - "server/src/services/native-runtime/native-agent-runtime-inheritance.test.ts": 1333, - "server/src/services/native-runtime/native-artifact-preparation.test.ts": 5450, - "server/src/services/native-runtime/native-blocked-reply-recovery.test.ts": 6073, - "server/src/services/native-runtime/native-bootstrap-claim-time-proof.integration.test.ts": 6225, - "server/src/services/native-runtime/native-bootstrap-retry.integration.test.ts": 7731, - "server/src/services/native-runtime/native-cancellation-request.test.ts": 2529, - "server/src/services/native-runtime/native-cancelled-workspace-preservation.test.ts": 8780, - "server/src/services/native-runtime/native-case-handoff.test.ts": 7595, - "server/src/services/native-runtime/native-case-tools.integration.test.ts": 34399, - "server/src/services/native-runtime/native-chat-workspace.test.ts": 6161, - "server/src/services/native-runtime/native-closed-session-retry.integration.test.ts": 9370, + "server/src/services/native-runtime/external-review-wait.test.ts": 5796, + "server/src/services/native-runtime/failed-action-chat-feedback.test.ts": 7502, + "server/src/services/native-runtime/first-turn-queued-input.test.ts": 6718, + "server/src/services/native-runtime/generate-image-tool.test.ts": 9852, + "server/src/services/native-runtime/grok-runner-credentials.test.ts": 750, + "server/src/services/native-runtime/handoff-plan-context.test.ts": 2561, + "server/src/services/native-runtime/historical-task-questions.test.ts": 12136, + "server/src/services/native-runtime/managed-native-credentials.test.ts": 798, + "server/src/services/native-runtime/model-rejected-retry.test.ts": 2731, + "server/src/services/native-runtime/muse-native-follow-up.test.ts": 9157, + "server/src/services/native-runtime/muse-native-visibility.test.ts": 14758, + "server/src/services/native-runtime/native-agent-runtime-inheritance.test.ts": 2089, + "server/src/services/native-runtime/native-artifact-preparation.test.ts": 10641, + "server/src/services/native-runtime/native-blocked-reply-recovery.test.ts": 7382, + "server/src/services/native-runtime/native-bootstrap-claim-time-proof.integration.test.ts": 5878, + "server/src/services/native-runtime/native-bootstrap-proof.test.ts": 681, + "server/src/services/native-runtime/native-bootstrap-retry.integration.test.ts": 9069, + "server/src/services/native-runtime/native-cancellation-request.test.ts": 2580, + "server/src/services/native-runtime/native-cancelled-workspace-preservation-idle.test.ts": 6716, + "server/src/services/native-runtime/native-cancelled-workspace-preservation.test.ts": 10991, + "server/src/services/native-runtime/native-case-handoff.test.ts": 7463, + "server/src/services/native-runtime/native-case-tools.integration.test.ts": 41747, + "server/src/services/native-runtime/native-chat-workspace.test.ts": 6722, + "server/src/services/native-runtime/native-client-timeout-continuation.integration.test.ts": 9480, + "server/src/services/native-runtime/native-closed-session-retry.integration.test.ts": 11115, "server/src/services/native-runtime/native-codex-runner.integration.test.ts": 224015, - "server/src/services/native-runtime/native-codex-runner.test.ts": 5568, - "server/src/services/native-runtime/native-completion-feedback.test.ts": 12746, - "server/src/services/native-runtime/native-completion-format-feedback.test.ts": 3857, - "server/src/services/native-runtime/native-confirmation-replay.test.ts": 10948, - "server/src/services/native-runtime/native-continuation.test.ts": 4865, - "server/src/services/native-runtime/native-controller-host-recovery.test.ts": 6274, - "server/src/services/native-runtime/native-controller-identity.test.ts": 4398, + "server/src/services/native-runtime/native-codex-runner.test.ts": 7467, + "server/src/services/native-runtime/native-completion-feedback.test.ts": 15474, + "server/src/services/native-runtime/native-completion-format-feedback.test.ts": 5680, + "server/src/services/native-runtime/native-confirmation-replay.test.ts": 11599, + "server/src/services/native-runtime/native-continuation.test.ts": 6062, + "server/src/services/native-runtime/native-controller-host-recovery.test.ts": 8314, + "server/src/services/native-runtime/native-controller-identity.test.ts": 7251, "server/src/services/native-runtime/native-controller-migration.integration.test.ts": 40595, - "server/src/services/native-runtime/native-controller-recovery.integration.test.ts": 8527, - "server/src/services/native-runtime/native-controller-recovery.test.ts": 5372, - "server/src/services/native-runtime/native-controller-source-digest.test.ts": 1813, - "server/src/services/native-runtime/native-credential-store.test.ts": 1227, - "server/src/services/native-runtime/native-credential-update-owner.test.ts": 2396, - "server/src/services/native-runtime/native-credential-updates.test.ts": 2886, - "server/src/services/native-runtime/native-current-wake-completion-feedback.test.ts": 7722, - "server/src/services/native-runtime/native-deliverable-feedback.test.ts": 5449, - "server/src/services/native-runtime/native-deliverable-text.test.ts": 104, - "server/src/services/native-runtime/native-exact-resume-failure.test.ts": 135, - "server/src/services/native-runtime/native-execution-context-worker.test.ts": 3589, - "server/src/services/native-runtime/native-execution-context.test.ts": 139, - "server/src/services/native-runtime/native-execution-input.test.ts": 4620, - "server/src/services/native-runtime/native-execution-lease-reacquire.test.ts": 6036, - "server/src/services/native-runtime/native-execution-lease.test.ts": 4078, - "server/src/services/native-runtime/native-execution-policy-review-stage-race.test.ts": 5270, - "server/src/services/native-runtime/native-execution-policy-review-stage.test.ts": 8936, - "server/src/services/native-runtime/native-failed-run-owner-release.test.ts": 8907, - "server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts": 8793, - "server/src/services/native-runtime/native-failed-workspace-recovery.test.ts": 22379, - "server/src/services/native-runtime/native-failure-redaction.test.ts": 141, - "server/src/services/native-runtime/native-finalization-reconciler-timing.test.ts": 5308, - "server/src/services/native-runtime/native-finalization-recovery-state.test.ts": 5429, - "server/src/services/native-runtime/native-github-access.test.ts": 9579, - "server/src/services/native-runtime/native-governed-wait-lost-state-continuation.integration.test.ts": 7871, - "server/src/services/native-runtime/native-harness-backup-archive.test.ts": 239, - "server/src/services/native-runtime/native-harness-backup-cleanup.test.ts": 100, - "server/src/services/native-runtime/native-harness-backup-download-deadline.integration.test.ts": 12271, - "server/src/services/native-runtime/native-harness-backup-obligations.integration.test.ts": 10903, - "server/src/services/native-runtime/native-harness-backup-publication.test.ts": 668, - "server/src/services/native-runtime/native-harness-backup-stamp.test.ts": 175, + "server/src/services/native-runtime/native-controller-recovery.integration.test.ts": 24304, + "server/src/services/native-runtime/native-controller-recovery.test.ts": 7453, + "server/src/services/native-runtime/native-controller-source-digest.test.ts": 3848, + "server/src/services/native-runtime/native-coordinator-claim-deadlock.integration.test.ts": 8794, + "server/src/services/native-runtime/native-credential-store.test.ts": 2312, + "server/src/services/native-runtime/native-credential-update-owner.test.ts": 2890, + "server/src/services/native-runtime/native-credential-updates.test.ts": 3188, + "server/src/services/native-runtime/native-current-wake-completion-feedback.test.ts": 10199, + "server/src/services/native-runtime/native-cut-turn-start-retry.integration.test.ts": 9216, + "server/src/services/native-runtime/native-deliverable-feedback.test.ts": 7167, + "server/src/services/native-runtime/native-deliverable-text.test.ts": 771, + "server/src/services/native-runtime/native-environment-blocker.integration.test.ts": 10409, + "server/src/services/native-runtime/native-exact-resume-failure.test.ts": 729, + "server/src/services/native-runtime/native-execution-context-worker.test.ts": 3168, + "server/src/services/native-runtime/native-execution-context.test.ts": 742, + "server/src/services/native-runtime/native-execution-input.test.ts": 4490, + "server/src/services/native-runtime/native-execution-lease-batch.test.ts": 9912, + "server/src/services/native-runtime/native-execution-lease-reacquire.test.ts": 8502, + "server/src/services/native-runtime/native-execution-lease.test.ts": 7718, + "server/src/services/native-runtime/native-execution-policy-review-stage-race.test.ts": 7244, + "server/src/services/native-runtime/native-execution-policy-review-stage.test.ts": 8779, + "server/src/services/native-runtime/native-failed-run-owner-release.test.ts": 8360, + "server/src/services/native-runtime/native-failed-turn-continuation.integration.test.ts": 14062, + "server/src/services/native-runtime/native-failed-workspace-recovery.test.ts": 24768, + "server/src/services/native-runtime/native-failure-redaction.test.ts": 732, + "server/src/services/native-runtime/native-failure-write-lock-contention.integration.test.ts": 8216, + "server/src/services/native-runtime/native-finalization-reconciler-timing.test.ts": 6455, + "server/src/services/native-runtime/native-finalization-recovery-state.test.ts": 6133, + "server/src/services/native-runtime/native-github-access.test.ts": 26864, + "server/src/services/native-runtime/native-governed-wait-lost-state-continuation.integration.test.ts": 10705, + "server/src/services/native-runtime/native-harness-backup-archive.test.ts": 1080, + "server/src/services/native-runtime/native-harness-backup-cleanup.test.ts": 727, + "server/src/services/native-runtime/native-harness-backup-download-deadline.integration.test.ts": 16303, + "server/src/services/native-runtime/native-harness-backup-obligations.integration.test.ts": 8992, + "server/src/services/native-runtime/native-harness-backup-publication.test.ts": 1108, + "server/src/services/native-runtime/native-harness-backup-stamp.test.ts": 814, "server/src/services/native-runtime/native-harness-backup-storage.integration.test.ts": 52555, - "server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts": 8205, - "server/src/services/native-runtime/native-harness-filesystem-independence-continuation.integration.test.ts": 10809, + "server/src/services/native-runtime/native-harness-backup-throttle.integration.test.ts": 8957, + "server/src/services/native-runtime/native-harness-filesystem-independence-continuation.integration.test.ts": 9813, "server/src/services/native-runtime/native-harness-filesystem-independence.integration.test.ts": 98077, "server/src/services/native-runtime/native-harness-online-preservation.integration.test.ts": 40303, - "server/src/services/native-runtime/native-harness-original-volume.test.ts": 219, - "server/src/services/native-runtime/native-human-self-handoff.test.ts": 6354, - "server/src/services/native-runtime/native-idle-sleep-continuation.integration.test.ts": 11667, - "server/src/services/native-runtime/native-maintenance-no-launch.test.ts": 933, - "server/src/services/native-runtime/native-permission-decline.test.ts": 2310, - "server/src/services/native-runtime/native-permission-projection.test.ts": 5141, - "server/src/services/native-runtime/native-plan-wait-receipts.test.ts": 100, - "server/src/services/native-runtime/native-plan-wait.test.ts": 7407, - "server/src/services/native-runtime/native-plugin-workspace-finalization.test.ts": 117, - "server/src/services/native-runtime/native-post-result-failure.test.ts": 844, + "server/src/services/native-runtime/native-harness-original-volume.test.ts": 761, + "server/src/services/native-runtime/native-human-self-handoff.test.ts": 8019, + "server/src/services/native-runtime/native-idle-sleep-continuation.integration.test.ts": 12300, + "server/src/services/native-runtime/native-ingress-bootstrap-retry.integration.test.ts": 73631, + "server/src/services/native-runtime/native-maintenance-no-launch.test.ts": 1532, + "server/src/services/native-runtime/native-permission-decline.test.ts": 3219, + "server/src/services/native-runtime/native-permission-projection.test.ts": 7799, + "server/src/services/native-runtime/native-plan-wait-receipts.test.ts": 727, + "server/src/services/native-runtime/native-plan-wait.test.ts": 7632, + "server/src/services/native-runtime/native-plugin-workspace-finalization.test.ts": 967, + "server/src/services/native-runtime/native-post-result-failure.test.ts": 1776, "server/src/services/native-runtime/native-preserved-monitor-wait.test.ts": 49316, - "server/src/services/native-runtime/native-provider-artifact-capture-confinement.test.ts": 2347, - "server/src/services/native-runtime/native-provider-artifact-capture.test.ts": 2576, - "server/src/services/native-runtime/native-provider-artifact-gate.test.ts": 2414, - "server/src/services/native-runtime/native-provider-capacity.integration.test.ts": 13012, - "server/src/services/native-runtime/native-provider-failure.integration.test.ts": 10498, - "server/src/services/native-runtime/native-provider-failure.test.ts": 927, - "server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts": 2002, - "server/src/services/native-runtime/native-provider-overload.integration.test.ts": 9357, - "server/src/services/native-runtime/native-provider-pack-admission.test.ts": 10271, - "server/src/services/native-runtime/native-question-bridge.test.ts": 41120, - "server/src/services/native-runtime/native-reconciliation-timing.test.ts": 132, - "server/src/services/native-runtime/native-recoverable-lost-turn.integration.test.ts": 5316, - "server/src/services/native-runtime/native-recovered-owner-followup.test.ts": 17998, - "server/src/services/native-runtime/native-recovery-preparation-failure.test.ts": 5593, - "server/src/services/native-runtime/native-recovery-usage-delivery.test.ts": 5327, - "server/src/services/native-runtime/native-remote-retry-admission.test.ts": 22392, - "server/src/services/native-runtime/native-replacement-evidence.test.ts": 116, - "server/src/services/native-runtime/native-response-publication-retry.test.ts": 25599, - "server/src/services/native-runtime/native-restart-recovery-isolation.test.ts": 7426, - "server/src/services/native-runtime/native-restart-recovery.test.ts": 4657, - "server/src/services/native-runtime/native-retired-backup-source.integration.test.ts": 5956, - "server/src/services/native-runtime/native-review-participant.test.ts": 1666, - "server/src/services/native-runtime/native-review-prompt.test.ts": 100, + "server/src/services/native-runtime/native-provider-artifact-capture-confinement.test.ts": 3137, + "server/src/services/native-runtime/native-provider-artifact-capture.test.ts": 2369, + "server/src/services/native-runtime/native-provider-artifact-gate.test.ts": 3784, + "server/src/services/native-runtime/native-provider-capacity.integration.test.ts": 16101, + "server/src/services/native-runtime/native-provider-failure.integration.test.ts": 10393, + "server/src/services/native-runtime/native-provider-failure.test.ts": 1557, + "server/src/services/native-runtime/native-provider-limit-cooldown.integration.test.ts": 2728, + "server/src/services/native-runtime/native-provider-overload.integration.test.ts": 9905, + "server/src/services/native-runtime/native-provider-pack-admission.test.ts": 11771, + "server/src/services/native-runtime/native-provider-turn-wait.test.ts": 5879, + "server/src/services/native-runtime/native-question-bridge.test.ts": 44675, + "server/src/services/native-runtime/native-reconciliation-timing.test.ts": 854, + "server/src/services/native-runtime/native-recoverable-lost-turn.integration.test.ts": 5815, + "server/src/services/native-runtime/native-recovered-owner-followup.test.ts": 20680, + "server/src/services/native-runtime/native-recovery-preparation-failure.test.ts": 6054, + "server/src/services/native-runtime/native-recovery-usage-delivery.test.ts": 6172, + "server/src/services/native-runtime/native-remote-retry-admission.test.ts": 21484, + "server/src/services/native-runtime/native-replacement-evidence.test.ts": 710, + "server/src/services/native-runtime/native-response-publication-retry.test.ts": 21924, + "server/src/services/native-runtime/native-restart-recovery-isolation.test.ts": 10160, + "server/src/services/native-runtime/native-restart-recovery.test.ts": 6957, + "server/src/services/native-runtime/native-retired-backup-source.integration.test.ts": 7163, + "server/src/services/native-runtime/native-review-participant.test.ts": 2189, + "server/src/services/native-runtime/native-review-prompt.test.ts": 915, "server/src/services/native-runtime/native-routine-status.test.ts": 8773, - "server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts": 9178, - "server/src/services/native-runtime/native-run-log-recovery.test.ts": 4769, - "server/src/services/native-runtime/native-run-log-watermark.test.ts": 6891, - "server/src/services/native-runtime/native-run-trace-context.test.ts": 1932, - "server/src/services/native-runtime/native-run-trace.test.ts": 1462, - "server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts": 2211, - "server/src/services/native-runtime/native-run-wake-anchor.test.ts": 1593, - "server/src/services/native-runtime/native-runner-attachment-staging.test.ts": 4446, - "server/src/services/native-runtime/native-runner-checkpoint-authority.integration.test.ts": 6323, - "server/src/services/native-runtime/native-runner-checkpoint-retirement.test.ts": 100, - "server/src/services/native-runtime/native-runner-execution-driver.test.ts": 901, - "server/src/services/native-runtime/native-runner-file-handoff.test.ts": 9434, - "server/src/services/native-runtime/native-runner-ownership.test.ts": 2449, - "server/src/services/native-runtime/native-runner-recovery-contract.test.ts": 114, + "server/src/services/native-runtime/native-run-coordinator-store-intake.test.ts": 6721, + "server/src/services/native-runtime/native-run-failure-explanation.test.ts": 1908, + "server/src/services/native-runtime/native-run-finalizer-telemetry.test.ts": 12821, + "server/src/services/native-runtime/native-run-log-recovery.test.ts": 4775, + "server/src/services/native-runtime/native-run-log-watermark.test.ts": 10432, + "server/src/services/native-runtime/native-run-trace-context.test.ts": 1925, + "server/src/services/native-runtime/native-run-trace.test.ts": 2150, + "server/src/services/native-runtime/native-run-wake-anchor.integration.test.ts": 3132, + "server/src/services/native-runtime/native-run-wake-anchor.test.ts": 2452, + "server/src/services/native-runtime/native-runner-attachment-staging.test.ts": 6324, + "server/src/services/native-runtime/native-runner-checkpoint-authority.integration.test.ts": 8282, + "server/src/services/native-runtime/native-runner-checkpoint-retirement.test.ts": 734, + "server/src/services/native-runtime/native-runner-checkpoint-save.test.ts": 4730, + "server/src/services/native-runtime/native-runner-execution-driver.test.ts": 1523, + "server/src/services/native-runtime/native-runner-file-handoff.test.ts": 10846, + "server/src/services/native-runtime/native-runner-ownership.test.ts": 2881, + "server/src/services/native-runtime/native-runner-recovery-contract.test.ts": 769, "server/src/services/native-runtime/native-runner-restart-checkpoint-cost.integration.test.ts": 187000, "server/src/services/native-runtime/native-runner-restart-diskless.integration.test.ts": 172000, "server/src/services/native-runtime/native-runner-restart-lease-renewal.integration.test.ts": 119000, "server/src/services/native-runtime/native-runner-restart-preparation.integration.test.ts": 155000, "server/src/services/native-runtime/native-runner-restart-recovery.integration.test.ts": 51000, - "server/src/services/native-runtime/native-safe-replacement.test.ts": 54425, - "server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts": 8546, - "server/src/services/native-runtime/native-scheduled-resume-lock.test.ts": 8033, - "server/src/services/native-runtime/native-session-diagnostics.test.ts": 186, - "server/src/services/native-runtime/native-session-executor.test.ts": 129292, - "server/src/services/native-runtime/native-session-handoff.test.ts": 5861, - "server/src/services/native-runtime/native-session-resume-projection.test.ts": 5741, - "server/src/services/native-runtime/native-session-resume.test.ts": 31184, - "server/src/services/native-runtime/native-session-resumption-binding.test.ts": 11225, - "server/src/services/native-runtime/native-session-root-entries.test.ts": 121, - "server/src/services/native-runtime/native-skill-library-tools.integration.test.ts": 9220, - "server/src/services/native-runtime/native-skill-test-scope.test.ts": 13217, - "server/src/services/native-runtime/native-skill-test-status.test.ts": 5657, - "server/src/services/native-runtime/native-speed-budgets.test.ts": 1451, - "server/src/services/native-runtime/native-ssh-command-runner.test.ts": 617, - "server/src/services/native-runtime/native-staged-attachment-recovery.test.ts": 5837, - "server/src/services/native-runtime/native-stale-owner-completion.test.ts": 7283, - "server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts": 6973, - "server/src/services/native-runtime/native-startup-retry.integration.test.ts": 11097, - "server/src/services/native-runtime/native-stop-accounting.integration.test.ts": 8641, - "server/src/services/native-runtime/native-task-session-publication.test.ts": 7817, - "server/src/services/native-runtime/native-terminal-status-projection.test.ts": 7876, - "server/src/services/native-runtime/native-tool-trace.test.ts": 2237, - "server/src/services/native-runtime/native-usage-accounting.test.ts": 914, - "server/src/services/native-runtime/native-warm-capability.test.ts": 1649, + "server/src/services/native-runtime/native-safe-replacement.test.ts": 61717, + "server/src/services/native-runtime/native-scheduled-resume-continuation.integration.test.ts": 8229, + "server/src/services/native-runtime/native-scheduled-resume-lock.test.ts": 6627, + "server/src/services/native-runtime/native-session-diagnostics.test.ts": 2627, + "server/src/services/native-runtime/native-session-executor.test.ts": 145454, + "server/src/services/native-runtime/native-session-handoff.test.ts": 6818, + "server/src/services/native-runtime/native-session-resume-projection.test.ts": 7170, + "server/src/services/native-runtime/native-session-resume.test.ts": 18920, + "server/src/services/native-runtime/native-session-resumption-binding.test.ts": 13387, + "server/src/services/native-runtime/native-session-root-entries.test.ts": 769, + "server/src/services/native-runtime/native-skill-library-tools.integration.test.ts": 12497, + "server/src/services/native-runtime/native-skill-test-scope.test.ts": 12812, + "server/src/services/native-runtime/native-skill-test-status.test.ts": 7211, + "server/src/services/native-runtime/native-speed-budgets.test.ts": 1950, + "server/src/services/native-runtime/native-ssh-command-runner.test.ts": 6124, + "server/src/services/native-runtime/native-staged-attachment-recovery.test.ts": 7781, + "server/src/services/native-runtime/native-stale-owner-completion.test.ts": 7649, + "server/src/services/native-runtime/native-startup-rejected-retry.integration.test.ts": 9672, + "server/src/services/native-runtime/native-startup-retry.integration.test.ts": 14172, + "server/src/services/native-runtime/native-stop-accounting.integration.test.ts": 8429, + "server/src/services/native-runtime/native-task-session-publication.test.ts": 7352, + "server/src/services/native-runtime/native-terminal-status-projection.test.ts": 9374, + "server/src/services/native-runtime/native-tool-receipt-limit.integration.test.ts": 10117, + "server/src/services/native-runtime/native-tool-trace.test.ts": 2639, + "server/src/services/native-runtime/native-usage-accounting.test.ts": 1136, + "server/src/services/native-runtime/native-usage-delivery.integration.test.ts": 48647, + "server/src/services/native-runtime/native-warm-capability.test.ts": 3676, + "server/src/services/native-runtime/native-warm-checkpoint-ownership.integration.test.ts": 49030, + "server/src/services/native-runtime/native-warm-successor-runner-release.integration.test.ts": 9481, "server/src/services/native-runtime/native-warm-transition-restart.integration.test.ts": 2492, - "server/src/services/native-runtime/native-workspace-best-effort.test.ts": 1472, + "server/src/services/native-runtime/native-workspace-best-effort.test.ts": 1893, "server/src/services/native-runtime/native-workspace-export-resume.live.test.ts": 2865, - "server/src/services/native-runtime/native-workspace-export-retry.test.ts": 24255, - "server/src/services/native-runtime/native-workspace-finalization-supersession.test.ts": 6143, - "server/src/services/native-runtime/native-workspace-finalizer-failure.test.ts": 4672, - "server/src/services/native-runtime/native-workspace-finalizer.test.ts": 17754, - "server/src/services/native-runtime/native-workspace-lock-keepalive.test.ts": 391, - "server/src/services/native-runtime/native-workspace-owner-restart-recovery.test.ts": 7469, - "server/src/services/native-runtime/native-workspace-platform-proof.test.ts": 1788, - "server/src/services/native-runtime/native-workspace-queued-wake-recovery.test.ts": 7213, - "server/src/services/native-runtime/native-workspace-reconstruction.test.ts": 49929, - "server/src/services/native-runtime/native-workspace-warm-reuse.test.ts": 5922, - "server/src/services/native-runtime/off-loop-file-work.test.ts": 23229, - "server/src/services/native-runtime/paperclip-control-plane-port.test.ts": 50765, - "server/src/services/native-runtime/paperclip-control-plane-timing.test.ts": 4613, + "server/src/services/native-runtime/native-workspace-export-retry.test.ts": 22367, + "server/src/services/native-runtime/native-workspace-finalization-supersession.test.ts": 6795, + "server/src/services/native-runtime/native-workspace-finalizer-failure.test.ts": 7494, + "server/src/services/native-runtime/native-workspace-finalizer.test.ts": 22571, + "server/src/services/native-runtime/native-workspace-lock-keepalive.test.ts": 626, + "server/src/services/native-runtime/native-workspace-owner-restart-recovery.test.ts": 8020, + "server/src/services/native-runtime/native-workspace-platform-proof.test.ts": 1605, + "server/src/services/native-runtime/native-workspace-queued-wake-recovery.test.ts": 6366, + "server/src/services/native-runtime/native-workspace-reconstruction.test.ts": 50395, + "server/src/services/native-runtime/native-workspace-warm-reuse.test.ts": 8404, + "server/src/services/native-runtime/off-loop-file-work.test.ts": 24764, + "server/src/services/native-runtime/paperclip-control-plane-port.test.ts": 43404, + "server/src/services/native-runtime/paperclip-control-plane-timing.test.ts": 5089, "server/src/services/native-runtime/paperclip-runner-real-server.integration.test.ts": 2492, - "server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts": 13427, - "server/src/services/native-runtime/plugin-runner-credentials.test.ts": 1073, - "server/src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts": 5179, - "server/src/services/native-runtime/plugin-runner-task.test.ts": 2455, - "server/src/services/native-runtime/plugin-task-source-recovery.integration.test.ts": 17937, + "server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts": 34019, + "server/src/services/native-runtime/plugin-runner-credentials.test.ts": 1920, + "server/src/services/native-runtime/plugin-runner-eviction.integration.test.ts": 312473, + "server/src/services/native-runtime/plugin-runner-probe-runner-mismatch.test.ts": 7691, + "server/src/services/native-runtime/plugin-runner-probe.test.ts": 17478, + "server/src/services/native-runtime/plugin-runner-release-resume.integration.test.ts": 205790, + "server/src/services/native-runtime/plugin-runner-task-warm.integration.test.ts": 3229, + "server/src/services/native-runtime/plugin-runner-task.test.ts": 3630, + "server/src/services/native-runtime/plugin-task-source-recovery.integration.test.ts": 18697, "server/src/services/native-runtime/preserved-native-response-wait.integration.test.ts": 106952, - "server/src/services/native-runtime/provider-api-placement.test.ts": 4425, - "server/src/services/native-runtime/provider-pack-archive.test.ts": 25637, - "server/src/services/native-runtime/remote-attachment-staging.test.ts": 892, - "server/src/services/native-runtime/remote-deliverable-file.test.ts": 1213, - "server/src/services/native-runtime/remote-launch-assets.test.ts": 2124, - "server/src/services/native-runtime/remote-mcp-relay.test.ts": 919, - "server/src/services/native-runtime/remote-opencode-artifacts.test.ts": 1369, - "server/src/services/native-runtime/remote-provider-pack-authority.test.ts": 188, - "server/src/services/native-runtime/remote-provider-pack-verification.test.ts": 207, - "server/src/services/native-runtime/remote-provider-pack.test.ts": 303, - "server/src/services/native-runtime/remote-runner-launch-stderr.test.ts": 6717, - "server/src/services/native-runtime/remote-runner-recovery-diagnostics.test.ts": 356, - "server/src/services/native-runtime/remote-runner-recovery-probe.test.ts": 802, - "server/src/services/native-runtime/remote-runner-turn-proof.test.ts": 5022, - "server/src/services/native-runtime/remote-warm-session-recovery.test.ts": 5057, - "server/src/services/native-runtime/repeated-tool-failure-guard.test.ts": 5450, - "server/src/services/native-runtime/retained-provider-pack-source.test.ts": 4208, - "server/src/services/native-runtime/runner-api-artifacts.integration.test.ts": 11005, - "server/src/services/native-runtime/runner-api-artifacts.test.ts": 2858, - "server/src/services/native-runtime/runner-api-files.test.ts": 100, - "server/src/services/native-runtime/runner-api-log-redaction.test.ts": 158, - "server/src/services/native-runtime/runner-api-response.test.ts": 341, - "server/src/services/native-runtime/runner-api-rollout.test.ts": 115, - "server/src/services/native-runtime/runner-api.integration.test.ts": 67582, - "server/src/services/native-runtime/runner-api.test.ts": 3697, - "server/src/services/native-runtime/runner-bridge-tools.test.ts": 5268, - "server/src/services/native-runtime/runner-operation-timing.test.ts": 128, - "server/src/services/native-runtime/runner-prp-coordinator.test.ts": 7150, - "server/src/services/native-runtime/runner-task-attachments.test.ts": 9203, - "server/src/services/native-runtime/runner-tool-results.test.ts": 1198, - "server/src/services/native-runtime/runtime-asset-retention.test.ts": 4813, - "server/src/services/native-runtime/runtime-context.test.ts": 6252, - "server/src/services/native-runtime/runtime-mode.test.ts": 1654, - "server/src/services/native-runtime/runtime-request-resolution-authority.test.ts": 1643, - "server/src/services/native-runtime/sandbox-runner-port-holders.integration.test.ts": 6986, - "server/src/services/native-runtime/scheduled-resume-continuation.test.ts": 5145, - "server/src/services/native-runtime/setup-readiness.test.ts": 4983, - "server/src/services/native-runtime/status-arbiter.test.ts": 761, - "server/src/services/native-runtime/stopped-codex-turn.test.ts": 178, - "server/src/services/native-runtime/task-creation-backlog.test.ts": 6574, - "server/src/services/native-runtime/task-document-body.integration.test.ts": 16002, - "server/src/services/native-runtime/task-document-key-contract.test.ts": 5813, - "server/src/services/native-runtime/task-document-scope.integration.test.ts": 9528, - "server/src/services/native-runtime/task-monitor.integration.test.ts": 11342, - "server/src/services/native-runtime/task-reassignment.test.ts": 9912, - "server/src/services/native-runtime/tool-receipt-recovery.integration.test.ts": 7980, - "server/src/services/native-runtime/unread-steered-messages.test.ts": 2522, - "server/src/services/native-runtime/update-skill.integration.test.ts": 16877, - "server/src/services/native-runtime/volume-free-controller-state.test.ts": 206, - "server/src/services/native-runtime/warm-controller-journal.test.ts": 114, - "server/src/services/object-byte-journal.test.ts": 23412, - "server/src/services/object-run-log-store-tail-read.test.ts": 2230, - "server/src/services/object-run-log-store.test.ts": 7144, - "server/src/services/offline-workspace-operation-reconciliation.test.ts": 7082, - "server/src/services/onboarding-first-task-assets.test.ts": 1371, - "server/src/services/onboarding-greeting.test.ts": 738, - "server/src/services/online-legacy-workspace-recovery.test.ts": 6228, - "server/src/services/online-remote-workspace-recovery-hold.test.ts": 11709, - "server/src/services/openrouter-models.test.ts": 106, - "server/src/services/owner-proof.test.ts": 2545, - "server/src/services/paperclip-cloud-connector-enrollment.test.ts": 1516, - "server/src/services/paperclip-cloud-connector.test.ts": 1809, - "server/src/services/plugin-login-credential.test.ts": 122, - "server/src/services/plugin-task-panels.test.ts": 1409, - "server/src/services/presentation-ownership-read.test.ts": 12158, - "server/src/services/protected-environment-keys.test.ts": 1651, - "server/src/services/provider-fresh-workspace.test.ts": 5076, - "server/src/services/provider-quota-reset.test.ts": 134, - "server/src/services/provider-retry-after.test.ts": 5382, - "server/src/services/provider-trace-object-store.test.ts": 572, - "server/src/services/provider-trace-workspace-diff-reprojection.test.ts": 1964, - "server/src/services/public-mcp/client-mirror-ack.test.ts": 4367, - "server/src/services/public-mcp/client-mirror-envelope.test.ts": 1629, - "server/src/services/public-mcp/client-mirror-wire.test.ts": 270, - "server/src/services/public-mcp/cloud-event-authority.test.ts": 1569, - "server/src/services/public-mcp/device-cutover.test.ts": 1725, - "server/src/services/public-mcp/device-status-key-read.test.ts": 136, - "server/src/services/public-mcp/discovery.test.ts": 999, - "server/src/services/public-mcp/events-work.test.ts": 41449, - "server/src/services/public-mcp/idle-authorization-handoffs.test.ts": 1254, - "server/src/services/public-mcp/idle-client-mirror.test.ts": 1570, - "server/src/services/public-mcp/idle-device-status.test.ts": 1256, - "server/src/services/public-mcp/idle-event-schedule.test.ts": 1464, - "server/src/services/public-mcp/idle-sleep-proof.test.ts": 5612, - "server/src/services/public-mcp/idle-subscription-proof.test.ts": 1696, - "server/src/services/public-mcp/idle-transfer-schedule.test.ts": 1725, - "server/src/services/public-mcp/idle-wake-proof.test.ts": 1587, - "server/src/services/public-mcp/revocation-index-sync.test.ts": 1557, - "server/src/services/public-mcp/wake-admission.test.ts": 210, - "server/src/services/quarantined-task-retry.test.ts": 13348, - "server/src/services/question-interaction-answers.test.ts": 2912, - "server/src/services/question-pattern-validation.test.ts": 2258, - "server/src/services/queued-comment-history-read.test.ts": 6328, - "server/src/services/queued-run-dispatch-liveness.test.ts": 5004, - "server/src/services/recovery/assigned-work-invariant.test.ts": 5514, - "server/src/services/recovery/issue-state-read.test.ts": 6146, - "server/src/services/recovery/legacy-continuation.test.ts": 106, - "server/src/services/recovery/legacy-disposition-read.test.ts": 6448, - "server/src/services/recovery/native-runner-routing.test.ts": 4511, - "server/src/services/recovery/provider-failure-classification.test.ts": 4997, - "server/src/services/recovery/reconciliation-run-read.test.ts": 7433, - "server/src/services/recovery/review-path-recovery.test.ts": 5013, - "server/src/services/recovery/run-context-read.test.ts": 6546, - "server/src/services/recovery/run-result-read.test.ts": 5250, - "server/src/services/recovery/service.pause-durability.test.ts": 4917, - "server/src/services/recovery/status-only-context.test.ts": 100, - "server/src/services/recovery/stranded-notice.test.ts": 1761, - "server/src/services/recovery/successful-run-handoff.test.ts": 1374, - "server/src/services/remote-agent-profiles.test.ts": 1786, - "server/src/services/remote-url-credentials.test.ts": 100, - "server/src/services/remote-workspace-archive-worker.test.ts": 3852, + "server/src/services/native-runtime/provider-api-placement.test.ts": 6240, + "server/src/services/native-runtime/provider-pack-archive.test.ts": 109677, + "server/src/services/native-runtime/provider-pack-selection-harness.test.ts": 9565, + "server/src/services/native-runtime/remote-attachment-staging.test.ts": 1693, + "server/src/services/native-runtime/remote-deliverable-file.test.ts": 1985, + "server/src/services/native-runtime/remote-launch-assets.test.ts": 2643, + "server/src/services/native-runtime/remote-mcp-relay.test.ts": 2126, + "server/src/services/native-runtime/remote-opencode-artifacts.test.ts": 5149, + "server/src/services/native-runtime/remote-provider-pack-authority.test.ts": 2582, + "server/src/services/native-runtime/remote-provider-pack-verification.test.ts": 3567, + "server/src/services/native-runtime/remote-provider-pack.test.ts": 9463, + "server/src/services/native-runtime/remote-runner-launch-stderr.test.ts": 10257, + "server/src/services/native-runtime/remote-runner-lost-launch-ack.test.ts": 8266, + "server/src/services/native-runtime/remote-runner-recovery-diagnostics.test.ts": 2182, + "server/src/services/native-runtime/remote-runner-recovery-probe.test.ts": 1601, + "server/src/services/native-runtime/remote-runner-turn-proof.test.ts": 5366, + "server/src/services/native-runtime/remote-warm-session-recovery.test.ts": 8796, + "server/src/services/native-runtime/repeated-tool-failure-guard.test.ts": 6832, + "server/src/services/native-runtime/retained-provider-pack-source.test.ts": 6652, + "server/src/services/native-runtime/runner-api-artifacts.integration.test.ts": 17044, + "server/src/services/native-runtime/runner-api-artifacts.test.ts": 3247, + "server/src/services/native-runtime/runner-api-files.test.ts": 892, + "server/src/services/native-runtime/runner-api-log-redaction.test.ts": 820, + "server/src/services/native-runtime/runner-api-response.test.ts": 847, + "server/src/services/native-runtime/runner-api-rollout.test.ts": 941, + "server/src/services/native-runtime/runner-api.integration.test.ts": 65769, + "server/src/services/native-runtime/runner-api.test.ts": 5706, + "server/src/services/native-runtime/runner-bridge-tools.test.ts": 6981, + "server/src/services/native-runtime/runner-operation-timing.test.ts": 805, + "server/src/services/native-runtime/runner-prp-coordinator.test.ts": 8471, + "server/src/services/native-runtime/runner-task-attachments.test.ts": 10798, + "server/src/services/native-runtime/runner-tool-results.test.ts": 1978, + "server/src/services/native-runtime/runtime-asset-retention.test.ts": 7656, + "server/src/services/native-runtime/runtime-context.test.ts": 6461, + "server/src/services/native-runtime/runtime-mode.test.ts": 2850, + "server/src/services/native-runtime/runtime-request-resolution-authority.test.ts": 1527, + "server/src/services/native-runtime/sandbox-runner-port-holders.integration.test.ts": 9151, + "server/src/services/native-runtime/sandbox-runner-port-holders.test.ts": 6524, + "server/src/services/native-runtime/scheduled-resume-continuation.test.ts": 11093, + "server/src/services/native-runtime/setup-readiness.test.ts": 6542, + "server/src/services/native-runtime/status-arbiter.test.ts": 2765, + "server/src/services/native-runtime/stopped-codex-turn.test.ts": 784, + "server/src/services/native-runtime/task-creation-backlog.test.ts": 8780, + "server/src/services/native-runtime/task-document-body.integration.test.ts": 16703, + "server/src/services/native-runtime/task-document-key-contract.test.ts": 7712, + "server/src/services/native-runtime/task-document-scope.integration.test.ts": 13521, + "server/src/services/native-runtime/task-monitor.integration.test.ts": 11794, + "server/src/services/native-runtime/task-reassignment.test.ts": 11250, + "server/src/services/native-runtime/tool-input-variant-admission.test.ts": 6191, + "server/src/services/native-runtime/tool-receipt-recovery.integration.test.ts": 9465, + "server/src/services/native-runtime/unread-steered-messages.test.ts": 3706, + "server/src/services/native-runtime/update-skill.integration.test.ts": 13979, + "server/src/services/native-runtime/volume-free-controller-state.test.ts": 941, + "server/src/services/native-runtime/warm-controller-journal.test.ts": 776, + "server/src/services/object-byte-journal.test.ts": 83546, + "server/src/services/object-run-log-store-tail-read.test.ts": 3185, + "server/src/services/object-run-log-store.test.ts": 8991, + "server/src/services/offline-workspace-operation-reconciliation.test.ts": 8220, + "server/src/services/onboarding-first-task-assets.test.ts": 2563, + "server/src/services/onboarding-greeting.test.ts": 3260, + "server/src/services/online-legacy-workspace-recovery.test.ts": 6018, + "server/src/services/online-remote-workspace-recovery-hold.test.ts": 16840, + "server/src/services/openrouter-models.test.ts": 981, + "server/src/services/owner-proof.test.ts": 1859, + "server/src/services/paperclip-cloud-connector-enrollment.test.ts": 2243, + "server/src/services/paperclip-cloud-connector-principal.test.ts": 783, + "server/src/services/paperclip-cloud-connector.test.ts": 2044, + "server/src/services/plugin-login-credential.test.ts": 939, + "server/src/services/plugin-task-panels.test.ts": 1809, + "server/src/services/presentation-ownership-read.test.ts": 11169, + "server/src/services/protected-environment-keys.test.ts": 1949, + "server/src/services/provider-fresh-workspace.test.ts": 5566, + "server/src/services/provider-quota-reset.test.ts": 733, + "server/src/services/provider-retry-after.test.ts": 4974, + "server/src/services/provider-trace-object-store.test.ts": 784, + "server/src/services/provider-trace-workspace-diff-reprojection.test.ts": 2457, + "server/src/services/public-mcp/client-mirror-ack.test.ts": 2366, + "server/src/services/public-mcp/client-mirror-envelope.test.ts": 1824, + "server/src/services/public-mcp/client-mirror-wire.test.ts": 1073, + "server/src/services/public-mcp/cloud-event-authority.test.ts": 1920, + "server/src/services/public-mcp/device-cutover.test.ts": 2289, + "server/src/services/public-mcp/device-status-key-read.test.ts": 915, + "server/src/services/public-mcp/discovery.test.ts": 2147, + "server/src/services/public-mcp/events-work.test.ts": 32996, + "server/src/services/public-mcp/idle-authorization-handoffs.test.ts": 1895, + "server/src/services/public-mcp/idle-client-mirror.test.ts": 2297, + "server/src/services/public-mcp/idle-device-status.test.ts": 2262, + "server/src/services/public-mcp/idle-event-schedule.test.ts": 1615, + "server/src/services/public-mcp/idle-sleep-proof.test.ts": 7346, + "server/src/services/public-mcp/idle-subscription-proof.test.ts": 2275, + "server/src/services/public-mcp/idle-transfer-schedule.test.ts": 1862, + "server/src/services/public-mcp/idle-wake-proof.test.ts": 1661, + "server/src/services/public-mcp/revocation-index-sync.test.ts": 1970, + "server/src/services/public-mcp/wake-admission.test.ts": 1018, + "server/src/services/quarantined-task-retry.test.ts": 14656, + "server/src/services/question-interaction-answers.test.ts": 4315, + "server/src/services/question-pattern-validation.test.ts": 2675, + "server/src/services/queued-comment-history-read.test.ts": 7250, + "server/src/services/queued-run-dispatch-liveness.test.ts": 7279, + "server/src/services/recovery/assigned-work-invariant.test.ts": 5474, + "server/src/services/recovery/issue-state-read.test.ts": 8448, + "server/src/services/recovery/legacy-continuation.test.ts": 773, + "server/src/services/recovery/legacy-disposition-read.test.ts": 6591, + "server/src/services/recovery/native-runner-routing.test.ts": 7196, + "server/src/services/recovery/provider-failure-classification.test.ts": 8303, + "server/src/services/recovery/reconciliation-run-read.test.ts": 6847, + "server/src/services/recovery/review-path-recovery.test.ts": 5566, + "server/src/services/recovery/run-context-read.test.ts": 7429, + "server/src/services/recovery/run-result-read.test.ts": 6976, + "server/src/services/recovery/service.pause-durability.test.ts": 7577, + "server/src/services/recovery/status-only-context.test.ts": 579, + "server/src/services/recovery/stranded-notice.test.ts": 1926, + "server/src/services/recovery/successful-run-handoff.test.ts": 1860, + "server/src/services/remote-agent-profiles.test.ts": 2016, + "server/src/services/remote-url-credentials.test.ts": 767, + "server/src/services/remote-workspace-archive-worker.test.ts": 5150, "server/src/services/remote-workspace-cohort-migration.test.ts": 65834, - "server/src/services/remote-workspace-migration-concurrency.test.ts": 7992, + "server/src/services/remote-workspace-migration-concurrency.test.ts": 8274, "server/src/services/remote-workspace-migration.test.ts": 124839, - "server/src/services/remote-workspace-nested-verification.test.ts": 14833, + "server/src/services/remote-workspace-nested-verification.test.ts": 19868, "server/src/services/remote-workspace-online-source.test.ts": 61675, "server/src/services/remote-workspace-original-bare-source.integration.test.ts": 40278, - "server/src/services/remote-workspace-readonly-capture-budget.test.ts": 23682, - "server/src/services/remote-workspace-readonly-inventory.test.ts": 310, - "server/src/services/remote-workspace-recovery-receipt-fallback.test.ts": 8503, - "server/src/services/remote-workspace-reservation.test.ts": 6608, - "server/src/services/remote-workspace-save-concurrency.test.ts": 20608, - "server/src/services/remote-workspace-snapshot-archive-environments.test.ts": 1346, - "server/src/services/remote-workspace-snapshot-archive.test.ts": 28566, - "server/src/services/remote-workspace-snapshot-retention.test.ts": 10279, + "server/src/services/remote-workspace-readonly-capture-budget.test.ts": 21512, + "server/src/services/remote-workspace-readonly-inventory.test.ts": 1027, + "server/src/services/remote-workspace-recovery-receipt-fallback.test.ts": 11646, + "server/src/services/remote-workspace-reservation.test.ts": 7014, + "server/src/services/remote-workspace-save-concurrency.test.ts": 20703, + "server/src/services/remote-workspace-snapshot-archive-environments.test.ts": 2478, + "server/src/services/remote-workspace-snapshot-archive.test.ts": 36211, + "server/src/services/remote-workspace-snapshot-retention.test.ts": 20875, "server/src/services/remote-workspace-snapshot-reuse.test.ts": 38856, - "server/src/services/remote-workspace-snapshot-storage.test.ts": 14162, - "server/src/services/remote-workspace-transfer-timeout.test.ts": 3615, + "server/src/services/remote-workspace-snapshot-storage.test.ts": 14951, + "server/src/services/remote-workspace-transfer-timeout.test.ts": 2876, "server/src/services/remote-workspace-transport.test.ts": 49930, - "server/src/services/remote-workspace-unchanged-release.test.ts": 28153, + "server/src/services/remote-workspace-unchanged-release.test.ts": 29322, "server/src/services/remote-workspaces.integration.test.ts": 134113, - "server/src/services/responsible-user-denial-run-outcomes.test.ts": 1790, - "server/src/services/retained-google-credential-cleanup.test.ts": 597, - "server/src/services/retry-workspace-continuity.test.ts": 11176, - "server/src/services/routines-formatter-cache.test.ts": 6140, - "server/src/services/run-accounting-contention.test.ts": 10532, - "server/src/services/run-cancellation.test.ts": 135, - "server/src/services/run-cost-accounting.test.ts": 18108, - "server/src/services/run-log-store-cancellation.test.ts": 1227, - "server/src/services/run-log-store.test.ts": 1864, - "server/src/services/run-scratch.test.ts": 138, - "server/src/services/runner-environment-lifecycle.test.ts": 1561, - "server/src/services/runner-goal-control-broker.test.ts": 122, - "server/src/services/runner-goals.test.ts": 4399, - "server/src/services/runner-lost-mid-turn-continuation.test.ts": 36119, - "server/src/services/runtime-accounting-totals.test.ts": 2267, - "server/src/services/runtime-exposure/broker-client.test.ts": 280, - "server/src/services/runtime-exposure/exposure-manager.test.ts": 841, - "server/src/services/runtime-exposure/loopback-listener.test.ts": 123, - "server/src/services/runtime-exposure/port-pair.test.ts": 1100, - "server/src/services/runtime-exposure/port-reservation.test.ts": 882, - "server/src/services/runtime-exposure/tailscale-hostname.test.ts": 100, - "server/src/services/safe-native-chat-progress.test.ts": 109, - "server/src/services/sandbox-absence-proof.test.ts": 1824, - "server/src/services/sandbox-disk-full-fault.test.ts": 1657, - "server/src/services/saved-bootstrap-continuation.test.ts": 10729, - "server/src/services/saved-work-retry-eligibility.test.ts": 9699, - "server/src/services/server-replacement-interruption.test.ts": 5089, - "server/src/services/session-workspace-cwd.test.ts": 100, - "server/src/services/setup-token-reaper.test.ts": 5676, - "server/src/services/setup-token-session.test.ts": 5938, - "server/src/services/setup-token-transport-binding.test.ts": 5048, - "server/src/services/skill-local-import-boundary.test.ts": 209, - "server/src/services/skill-package-recovery.test.ts": 2497, - "server/src/services/skill-package-work.test.ts": 11649, - "server/src/services/skill-source-idle-schedule.test.ts": 1648, - "server/src/services/skill-source-sync-work.test.ts": 21978, - "server/src/services/skill-tools.test.ts": 860, - "server/src/services/skill-version-cache-lock.test.ts": 5772, - "server/src/services/slack-mcp-error.test.ts": 149, - "server/src/services/superseded-workspace-export-recovery.test.ts": 10452, - "server/src/services/system-recovery-state.test.ts": 5356, - "server/src/services/task-interruption-presentation.test.ts": 4308, - "server/src/services/task-retry.test.ts": 29613, - "server/src/services/tool-access/github-access-errors.test.ts": 100, - "server/src/services/tool-access/github-default-owner.test.ts": 100, - "server/src/services/tool-action-replay-intent.test.ts": 126, - "server/src/services/tool-approval-target.test.ts": 116, - "server/src/services/tool-discovery-scheduler.test.ts": 100, - "server/src/services/tool-profile-binding-precedence.test.ts": 122, - "server/src/services/unrecoverable-saved-work-retry.test.ts": 13212, - "server/src/services/usage-receipts-read.test.ts": 5630, - "server/src/services/vercel-connect.test.ts": 160, - "server/src/services/verified-preparation-log.test.ts": 2923, - "server/src/services/workspace-git-operation-scheduler.test.ts": 1822, - "server/src/services/workspace-git-snapshot-streaming.test.ts": 33931, - "server/src/services/workspace-git-source-roots.test.ts": 1978, + "server/src/services/responsible-user-denial-run-outcomes.test.ts": 1512, + "server/src/services/retained-google-credential-cleanup.test.ts": 779, + "server/src/services/retry-workspace-continuity.test.ts": 10510, + "server/src/services/routines-formatter-cache.test.ts": 9160, + "server/src/services/run-accounting-contention.test.ts": 9693, + "server/src/services/run-cancellation.test.ts": 697, + "server/src/services/run-cost-accounting.test.ts": 23211, + "server/src/services/run-dispatch-notifications.test.ts": 807, + "server/src/services/run-intake-stall-watch.test.ts": 6858, + "server/src/services/run-log-store-cancellation.test.ts": 2613, + "server/src/services/run-log-store.test.ts": 3536, + "server/src/services/run-scratch.test.ts": 690, + "server/src/services/runner-environment-lifecycle.test.ts": 2598, + "server/src/services/runner-goal-control-broker.test.ts": 792, + "server/src/services/runner-goals.test.ts": 6758, + "server/src/services/runner-lost-mid-turn-continuation.test.ts": 26927, + "server/src/services/runtime-accounting-totals.test.ts": 2201, + "server/src/services/runtime-exposure/broker-client.test.ts": 936, + "server/src/services/runtime-exposure/exposure-manager.test.ts": 1462, + "server/src/services/runtime-exposure/loopback-listener.test.ts": 745, + "server/src/services/runtime-exposure/port-pair.test.ts": 1478, + "server/src/services/runtime-exposure/port-reservation.test.ts": 1447, + "server/src/services/runtime-exposure/tailscale-hostname.test.ts": 765, + "server/src/services/safe-native-chat-progress.test.ts": 775, + "server/src/services/sandbox-absence-proof.test.ts": 1956, + "server/src/services/sandbox-disk-full-fault.test.ts": 1964, + "server/src/services/saved-bootstrap-continuation.test.ts": 11165, + "server/src/services/saved-work-recovery-overdue.test.ts": 13858, + "server/src/services/saved-work-retry-eligibility.test.ts": 11506, + "server/src/services/server-replacement-interruption.test.ts": 6088, + "server/src/services/session-workspace-cwd.test.ts": 1011, + "server/src/services/setup-token-reaper.test.ts": 5332, + "server/src/services/setup-token-session.test.ts": 7573, + "server/src/services/setup-token-transport-binding.test.ts": 4616, + "server/src/services/skill-local-import-boundary.test.ts": 937, + "server/src/services/skill-package-recovery.test.ts": 3323, + "server/src/services/skill-package-work.test.ts": 9936, + "server/src/services/skill-source-idle-schedule.test.ts": 1902, + "server/src/services/skill-source-sync-work.test.ts": 19860, + "server/src/services/skill-tools.test.ts": 1373, + "server/src/services/skill-version-cache-lock.test.ts": 7117, + "server/src/services/slack-mcp-error.test.ts": 562, + "server/src/services/ssh-remote-workspace.integration.test.ts": 332029, + "server/src/services/superseded-workspace-export-recovery.test.ts": 13089, + "server/src/services/system-recovery-state.test.ts": 6030, + "server/src/services/task-interruption-presentation.test.ts": 6837, + "server/src/services/task-retry-refusal.test.ts": 6327, + "server/src/services/task-retry.test.ts": 42006, + "server/src/services/tool-access/github-access-errors.test.ts": 742, + "server/src/services/tool-access/github-default-owner.test.ts": 726, + "server/src/services/tool-action-replay-intent.test.ts": 889, + "server/src/services/tool-approval-target.test.ts": 595, + "server/src/services/tool-discovery-scheduler.test.ts": 1016, + "server/src/services/tool-profile-binding-precedence.test.ts": 758, + "server/src/services/unrecoverable-saved-work-retry.test.ts": 14901, + "server/src/services/usage-receipts-read.test.ts": 6401, + "server/src/services/vercel-connect.test.ts": 853, + "server/src/services/verified-preparation-log.test.ts": 3682, + "server/src/services/workspace-git-operation-scheduler.test.ts": 2337, + "server/src/services/workspace-git-snapshot-streaming.test.ts": 40665, + "server/src/services/workspace-git-source-roots.test.ts": 2933, "server/src/services/workspace-recovery-admission.test.ts": 219865, - "server/src/services/workspace-recovery-capture-policy.test.ts": 12812, - "server/src/services/workspace-recovery-dependency-finalize.test.ts": 10692, + "server/src/services/workspace-recovery-capture-policy.test.ts": 13345, + "server/src/services/workspace-recovery-dependency-finalize.test.ts": 11990, "server/src/services/workspace-recovery-disk-full.test.ts": 23363, "server/src/services/workspace-recovery-fallback.test.ts": 29586, "server/src/services/workspace-recovery-passive-fairness.test.ts": 25923, @@ -1844,23 +2031,23 @@ "server/src/services/workspace-recovery-preparation-proof.test.ts": 60597, "server/src/services/workspace-recovery-preparation.test.ts": 102797, "server/src/services/workspace-recovery-retry-copyback.test.ts": 126213, - "server/src/services/workspace-recovery-scheduled-preparation.test.ts": 18536, - "server/src/services/workspace-recovery-source.test.ts": 8790, - "server/src/services/workspace-recovery-stop-proof.test.ts": 18322, + "server/src/services/workspace-recovery-scheduled-preparation.test.ts": 20606, + "server/src/services/workspace-recovery-source.test.ts": 10414, + "server/src/services/workspace-recovery-stop-proof.test.ts": 20908, "server/src/services/workspace-recovery-warm-handoff.test.ts": 215408, - "server/src/services/workspace-restore-reconciliation.test.ts": 6783, - "server/src/services/workspace-runtime-exposure-backfill.test.ts": 4411, - "server/src/services/workspace-runtime-exposure.test.ts": 18223, - "server/src/services/workspace-runtime-read-model.test.ts": 1580, - "server/src/services/workspace-runtime-readiness.test.ts": 5008, - "server/src/services/workspace-runtime-ready-comment.test.ts": 5073, - "server/src/shutdown.test.ts": 313, - "server/src/startup-recovery-timing.test.ts": 124, - "server/src/startup-timeline.test.ts": 134, - "server/src/storage/config.test.ts": 834, - "server/src/storage/file-crypto-pool.test.ts": 274, - "server/src/storage/s3-credential-refresh.test.ts": 648, - "server/src/storage/storage-unavailable.test.ts": 127, - "server/src/url-utils.test.ts": 117 + "server/src/services/workspace-restore-reconciliation.test.ts": 6919, + "server/src/services/workspace-runtime-exposure-backfill.test.ts": 6047, + "server/src/services/workspace-runtime-exposure.test.ts": 24475, + "server/src/services/workspace-runtime-read-model.test.ts": 1829, + "server/src/services/workspace-runtime-readiness.test.ts": 6288, + "server/src/services/workspace-runtime-ready-comment.test.ts": 5962, + "server/src/shutdown.test.ts": 848, + "server/src/startup-recovery-timing.test.ts": 696, + "server/src/startup-timeline.test.ts": 808, + "server/src/storage/config.test.ts": 2013, + "server/src/storage/file-crypto-pool.test.ts": 1615, + "server/src/storage/s3-credential-refresh.test.ts": 1512, + "server/src/storage/storage-unavailable.test.ts": 823, + "server/src/url-utils.test.ts": 756 } } diff --git a/scripts/local-verify/plan.mjs b/scripts/local-verify/plan.mjs index a29085fc7ad..d311f471caf 100644 --- a/scripts/local-verify/plan.mjs +++ b/scripts/local-verify/plan.mjs @@ -13,7 +13,7 @@ function inventory(root, env, group) { : ["--shard-index", "0", "--shard-count", "1"]; return JSON.parse(execFileSync(process.execPath, [path.join(root, "scripts/run-vitest-stable.mjs"), ...args, ...shards, "--dry-run"], { - cwd: root, env, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, + cwd: root, env: { ...env, PAPERCLIP_CI_FULL: "1" }, encoding: "utf8", maxBuffer: 16 * 1024 * 1024, })); } @@ -39,13 +39,18 @@ export async function planVerification({ root, env, diff, full = false }) { if (uncovered.length) throw new Error(`Changes outside resolved test graphs: ${uncovered.join(", ")}`); const byProject = new Map(graphs.map(graph => [graph.project, graph])); const manifest = { version: 1, head: diff.head, lanes: {} }, jobs = [], selectedFiles = new Set(); + const scheduleChat = () => { + if (selectedFiles.has(chatSuite)) return; + if (byProject.get("@paperclipai/server")?.selected.includes(chatSuite)) { + selectedFiles.add(chatSuite); + for (let index = 0; index < 6; index++) jobs.push({ id: `chat-${index + 1}`, cacheable: false, args: ["--mode", "general", "--group", "general-chat", + "--shard-index", String(index), "--shard-count", "6", "--serial-chat"] }); + } + }; + const matrixHasChat = (lanes.general_tests ?? []).some((entry) => entry.group === "general-chat"); for (const group of groups) { if (group === "general-chat") { - if (byProject.get("@paperclipai/server")?.selected.includes(chatSuite)) { - selectedFiles.add(chatSuite); - for (let index = 0; index < 6; index++) jobs.push({ id: `chat-${index + 1}`, cacheable: false, args: ["--mode", "general", "--group", group, - "--shard-index", String(index), "--shard-count", "6", "--serial-chat"] }); - } + scheduleChat(); continue; } const value = inventories.get(group); @@ -70,6 +75,7 @@ export async function planVerification({ root, env, diff, full = false }) { cacheable: files === reusable, selected: true, args: ["--mode", group === "serialized" ? "serialized" : "general", ...(group === "serialized" ? [] : ["--group", group]), "--shard-index", String(index), "--shard-count", String(partitions.length)] }); } + if (matrixHasChat) scheduleChat(); const expected = new Set(graphs.flatMap(graph => graph.selected)); if (expected.size !== selectedFiles.size || [...expected].some(file => !selectedFiles.has(file))) { throw new Error("Selected tests are not completely covered by local runner ownership"); diff --git a/scripts/run-vitest-stable.mjs b/scripts/run-vitest-stable.mjs index 473403a99cc..e9473d83c9c 100644 --- a/scripts/run-vitest-stable.mjs +++ b/scripts/run-vitest-stable.mjs @@ -1,12 +1,19 @@ #!/usr/bin/env node import { spawn } from "node:child_process"; -import { mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; +import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, statSync, writeFileSync } from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { loadShardDurations, selectGeneralServerShard } from "./general-server-shard.mjs"; import { invocationEnv } from "./ci-profile/record.mjs"; import { vitestRetryArgs } from "./ci/vitest-retry.mjs"; +import { + PR_WORKFLOW_NAME, + isNightlyExclusionEnabled, + loadNightlyOnlySuites, + resolveNightlyOnlySuitesPath, +} from "./ci/nightly-only-suites.mjs"; +import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs"; import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs"; import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs"; @@ -120,11 +127,35 @@ const nativeRunnerSuites = [ // caller of the same group keeps the suite in the server shards, so a renamed or // unknown workflow degrades to today's slower-but-covered behavior rather // than dropping the suite. -const prWorkflowName = "PR"; +const prWorkflowName = PR_WORKFLOW_NAME; const nativeRunnerSuiteRunsInRustCachedLane = process.env.GITHUB_WORKFLOW === prWorkflowName; const withoutChatExcludedSuites = nativeRunnerSuiteRunsInRustCachedLane ? [chatSuite, ...nativeRunnerSuites] : [chatSuite]; +const nightlyOnlySuitesPath = resolveNightlyOnlySuitesPath({ repoRoot }); +const strictlySerialServerTests = new Set([]); + +let allNightlyOnlySuites; +try { + allNightlyOnlySuites = loadNightlyOnlySuites(nightlyOnlySuitesPath); +} catch (error) { + fail(error.message); +} +const nightlyExclusionActive = isNightlyExclusionEnabled(); +const activeNightlyOnlySuites = nightlyExclusionActive ? allNightlyOnlySuites : new Set(); + +function activeNativeRunnerSuites() { + return nativeRunnerSuites.filter((file) => !activeNightlyOnlySuites.has(file)); +} + +function resolveServerParallelWorkers(defaultWorkers) { + const raw = process.env.PAPERCLIP_VITEST_MAX_WORKERS?.trim(); + if (!raw) { + return defaultWorkers; + } + return parsePositiveInteger(raw, "PAPERCLIP_VITEST_MAX_WORKERS"); +} + // Release verification selects this explicit group and runs the omitted suites // in its cached Runner job. Local callers keep the complete default group. const generalServerGroups = [ @@ -132,11 +163,18 @@ const generalServerGroups = [ generalServerWithoutChatGroupName, generalServerWithoutChatOrNativeRunnerGroupName, ]; -function excludedServerSuites(groupName) { +function baseExcludedServerSuites(groupName) { if (groupName === generalServerWithoutChatOrNativeRunnerGroupName) return [chatSuite, ...nativeRunnerSuites]; if (groupName === generalServerWithoutChatGroupName) return withoutChatExcludedSuites; return []; } +function excludedServerSuites(groupName) { + const base = baseExcludedServerSuites(groupName); + if (groupName === generalServerGroupName || activeNightlyOnlySuites.size === 0) { + return base; + } + return [...new Set([...base, ...activeNightlyOnlySuites])]; +} const generalWorkspacesAGroupName = "general-workspaces-a"; const generalWorkspacesBGroupName = "general-workspaces-b"; const generalWorkspacesCGroupName = "general-workspaces-c"; @@ -512,17 +550,20 @@ async function runGeneralSuites(routeTests, chatShards) { } } -async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null) { - // With shard args, lean on Vitest's native --shard: each matrix job runs the - // same per-project invocations but only its slice of each project's test - // files. Vitest's sharding is deterministic for an identical file list, so - // the matrix jobs form a complete, non-overlapping cover of every project. +async function runProjectGroup(projects, groupName, shardIndex = null, shardCount = null, excludedFiles = []) { + // Run the whole group in a single multi-project Vitest invocation so Vitest + // boots once and shares module transform/worker pool overhead across packages. + // With shard args, Vitest's native --shard deterministically partitions the + // combined file list across runners into a complete, non-overlapping cover. const shardArgs = shardCount !== null && shardCount > 1 ? [`--shard=${shardIndex + 1}/${shardCount}`] : []; const shardSuffix = shardArgs.length > 0 ? ` shard ${shardIndex + 1}/${shardCount}` : ""; - for (const project of projects) { - await runVitest(["--project", project, ...shardArgs], `${groupName} project ${project}${shardSuffix}`); - } + const excludeArgs = excludedFiles.flatMap((file) => ["--exclude", file]); + const projectArgs = projects.flatMap((project) => ["--project", project]); + const label = projects.length === 1 + ? `${groupName} project ${projects[0]}${shardSuffix}` + : `${groupName} (${projects.length} projects)${shardSuffix}`; + await runVitest([...projectArgs, ...excludeArgs, ...shardArgs], label); } function chatShardWorkers(index, count) { @@ -533,10 +574,50 @@ function chatShardWorkers(index, count) { })); } +function groupUsesPostgres(opts, sel) { + if (sel) { + return Boolean(sel["@paperclipai/server"]?.length || sel["@paperclipai/db"]?.length); + } + if (opts.mode === serializedModeName || opts.mode === allModeName) { + return true; + } + if (opts.mode === generalModeName) { + if (opts.group === null) return true; + return ( + generalServerGroups.includes(opts.group) || + opts.group === generalChatGroupName || + opts.group === generalServerNativeRunnerGroupName || + opts.group === generalWorkspacesCGroupName + ); + } + return false; +} + +function hasScheduledSuitesForRun(opts, sel) { + if (sel) { + return Object.values(sel).some((files) => files.length > 0); + } + if (opts.mode === serializedModeName) { + return selectSerializedSuites(activeRouteTests, opts.shardIndex, opts.shardCount).length > 0; + } + if (opts.mode === generalModeName && opts.group === generalServerNativeRunnerGroupName) { + return activeNativeRunnerSuites().length > 0; + } + if (opts.mode === generalModeName && generalServerGroups.includes(opts.group)) { + const excluded = new Set(excludedServerSuites(opts.group)); + const files = generalServerTestFiles.filter((file) => !excluded.has(file)); + if (opts.shardCount !== null && opts.shardCount > 1) { + return selectGeneralServerShard(files, opts.shardIndex, opts.shardCount, generalServerShardDurations).length > 0; + } + return files.length > 0; + } + return true; +} + async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCount = null, additionalExcludedSuites = []) { if (groupName === generalChatGroupName) { - // Each invocation gets its own temporary home and embedded PostgreSQL. - // Wait for both children even on failure so no sibling is abandoned. + // Each invocation gets its own temporary home and disposable PostgreSQL database. + // Wait for all children even on failure so no sibling is abandoned. const args = ["--project", "@paperclipai/server", ...serializedServerVitestArgs, chatSuite]; const workers = chatShardWorkers(shardIndex, shardCount); const collected = await collectVitestList(args, isolatedTestEnv(), "all"); @@ -548,13 +629,18 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo return; } if (groupName === generalServerNativeRunnerGroupName) { + const suites = activeNativeRunnerSuites(); + if (suites.length === 0) { + console.log("\n[test:run] native runner vertical-slice suite: 0 suites after nightly filtering; skipping"); + return; + } await runVitest( ["--project", "@paperclipai/server", // Each file owns its database, home, and processes. Keep cases serial, // but overlap long real lease windows in four isolated fork workers. ...(hasSharedTestDatabase ? serializedServerVitestArgs - : ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=4"]), - ...nativeRunnerSuites], + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]), + ...suites], "native runner vertical-slice suite", ); return; @@ -576,16 +662,18 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo return; } + const workers = resolveServerParallelWorkers(4); await runVitest( [ "--project", "@paperclipai/server", - // Files have separate fork processes and isolated homes/configs. - // Keep each file's cases serial; overlap three independent files. - // An explicit shared test database cannot be isolated this way. + // Files have separate fork processes, isolated homes/configs, and + // disposable per-file databases on the shared test PostgreSQL server. + // Keep each file's cases serial; overlap independent files across workers. + // An explicit shared mutable test database cannot be isolated this way. ...(hasSharedTestDatabase ? serializedServerVitestArgs - : ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=3"]), + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${workers}`]), ...shardFiles, ], `${groupName} shard ${shardIndex + 1}/${shardCount}`, @@ -593,9 +681,16 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo return; } + if (files.length === 0) { + console.log(`\n[test:run] ${groupName}: 0 suites after filtering; skipping`); + return; + } + const excludeRouteArgs = routeTests.flatMap((file) => ["--exclude", file.serverPath]); for (const suite of excludedSuites) { - excludeRouteArgs.push("--exclude", suite.replace(/^server\//, "")); + if (suite.startsWith("server/")) { + excludeRouteArgs.push("--exclude", suite.replace(/^server\//, "")); + } } await runVitest( [ @@ -612,8 +707,8 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo if (groupName === generalWorkspacesAGroupName) { // The ui project dominates this lane (~224s of a 319s job in actions run // 31371439296, 2026-08-10, where workspaces-a was the slowest PR check). - // Its 439 test files shard cleanly with Vitest's native --shard, so the - // lane splits across runners without a duration manifest. + // Its test files shard cleanly with Vitest's native --shard, so the lane + // splits across runners without a duration manifest. await runProjectGroup(generalWorkspacesAProjects, groupName, shardIndex, shardCount); return; } @@ -624,20 +719,27 @@ async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCo } if (groupName === generalWorkspacesCGroupName) { - await runProjectGroup(generalWorkspacesCProjects, groupName); + const dbNightlyExcludes = [...activeNightlyOnlySuites] + .filter((file) => file.startsWith("packages/db/")) + .map((file) => file.replace(/^packages\/db\//, "")); + await runProjectGroup(generalWorkspacesCProjects, groupName, null, null, dbNightlyExcludes); return; } fail(`Unknown group "${groupName}".`); } -async function runSerializedSuites(routeTests, shardIndex, shardCount) { - const shardTests = selectSerializedSuites(routeTests, shardIndex, shardCount); +async function runSerializedSuites(suites, shardIndex, shardCount) { + const shardTests = selectSerializedSuites(suites, shardIndex, shardCount); console.log( - `\n[test:run] serialized shard ${shardIndex + 1}/${shardCount} running ${shardTests.length} of ${routeTests.length} suites`, + `\n[test:run] serialized shard ${shardIndex + 1}/${shardCount} running ${shardTests.length} of ${suites.length} suites`, ); - if (shardTests.length > 0) { + if (shardTests.length === 0) { + return; + } + + if (hasSharedTestDatabase) { await runVitest( [ "--project", @@ -649,6 +751,40 @@ async function runSerializedSuites(routeTests, shardIndex, shardCount) { ], `serialized shard ${shardIndex + 1}/${shardCount}`, ); + return; + } + + const parallelTests = shardTests.filter((test) => !strictlySerialServerTests.has(test.repoPath)); + const serialOnlyTests = shardTests.filter((test) => strictlySerialServerTests.has(test.repoPath)); + + if (parallelTests.length > 0) { + const workers = resolveServerParallelWorkers(3); + await runVitest( + [ + "--project", + "@paperclipai/server", + ...parallelTests.map((test) => test.repoPath), + "--pool=forks", + "--isolate", + "--fileParallelism", + `--maxWorkers=${workers}`, + ], + `serialized shard ${shardIndex + 1}/${shardCount}`, + ); + } + + if (serialOnlyTests.length > 0) { + await runVitest( + [ + "--project", + "@paperclipai/server", + ...serialOnlyTests.map((test) => test.repoPath), + "--pool=forks", + "--isolate", + ...serializedServerVitestArgs, + ], + `serialized shard ${shardIndex + 1}/${shardCount} (strictly serial)`, + ); } } @@ -659,11 +795,12 @@ const routeTests = walk(serverTestsDir) serverPath: toServerPath(file), })) .sort((a, b) => a.repoPath.localeCompare(b.repoPath)); +const activeRouteTests = routeTests.filter((test) => !activeNightlyOnlySuites.has(test.repoPath)); // Every server test file that the general-server group is responsible for, // i.e. the whole server project minus the route/authz suites that run in the // dedicated serialized shards. The default server config keeps files serial; -// the sharded entry point overlaps two isolated files per runner unless an +// the sharded entry point overlaps isolated files per runner unless an // explicit shared test database requires serial execution. // Suites are partitioned by recorded duration (scripts/general-server-shard.mjs) // rather than round-robin, so one slow suite cluster can't stretch a single shard. @@ -688,11 +825,16 @@ const selection = process.env.PAPERCLIP_CI_TEST_SELECTION ? selectedShard(loadSelection(), options, selectionProjects) : null; if (selection?.["@paperclipai/server"]) { const owned = new Set(options.mode === serializedModeName ? routeTests.map((test) => test.repoPath) - : generalServerTestFiles.filter((file) => !excludedServerSuites(options.group).includes(file))); + : generalServerTestFiles.filter((file) => !baseExcludedServerSuites(options.group).includes(file))); for (const file of selection["@paperclipai/server"]) { if (!owned.has(file)) fail(`Selected test belongs to another server lane: ${file}`); } } +if (selection && activeNightlyOnlySuites.size > 0) { + for (const [project, files] of Object.entries(selection)) { + selection[project] = files.filter((file) => !activeNightlyOnlySuites.has(file)); + } +} if (selection && options.dryRun) { writeFileSync(1, JSON.stringify({ selection })); process.exit(0); @@ -700,11 +842,41 @@ if (selection && options.dryRun) { const defaultChatShards = !selection && options.group === null && options.mode !== serializedModeName && !hasSharedTestDatabase ? Array.from({ length: 6 }, (_, index) => ({ index, count: 6 })) : null; + +function dryRunExcludedNightlySuites() { + if (activeNightlyOnlySuites.size === 0) { + return []; + } + if (options.mode === serializedModeName) { + return routeTests + .map((test) => test.repoPath) + .filter((file) => activeNightlyOnlySuites.has(file)); + } + if (options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName) { + return nativeRunnerSuites.filter((file) => activeNightlyOnlySuites.has(file)); + } + if ( + options.mode === generalModeName && + (options.group === generalServerWithoutChatGroupName || + options.group === generalServerWithoutChatOrNativeRunnerGroupName) + ) { + const baseExcluded = new Set(baseExcludedServerSuites(options.group)); + return generalServerTestFiles.filter( + (file) => !baseExcluded.has(file) && activeNightlyOnlySuites.has(file), + ); + } + if (options.mode === generalModeName && options.group === generalWorkspacesCGroupName) { + return [...activeNightlyOnlySuites].filter((file) => file.startsWith("packages/db/")).sort(); + } + return []; +} + if (options.dryRun) { + const serializedPool = options.mode === serializedModeName ? activeRouteTests : routeTests; const serializedSuites = options.mode === serializedModeName - ? selectSerializedSuites(routeTests, options.shardIndex, options.shardCount) - : routeTests; + ? selectSerializedSuites(serializedPool, options.shardIndex, options.shardCount) + : serializedPool; // The inventory exceeds pipe buffers; flush it before the immediate exit. writeFileSync(1, JSON.stringify( @@ -714,14 +886,16 @@ if (options.dryRun) { shardCount: options.shardCount, group: options.group, availableGeneralGroups: allowedGeneralGroupNames, - serializedSuiteCount: routeTests.length, + nightlyExclusionActive, + excludedNightlySuites: dryRunExcludedNightlySuites(), + serializedSuiteCount: serializedPool.length, selectedSerializedSuites: serializedSuites.map((routeTest) => routeTest.repoPath), generalServerSuiteCount: generalServerTestFiles.length, selectedGeneralServerSuites: defaultChatShards ? generalServerTestFiles.filter(file => file !== chatSuite) : options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName - ? nativeRunnerSuites + ? activeNativeRunnerSuites() : options.mode === generalModeName && generalServerGroups.includes(options.group) && options.shardCount !== null @@ -757,25 +931,41 @@ if (options.dryRun) { } try { - if (selection) { + if (shouldWrapWithSharedPostgres({ + repoRoot, + dryRun: options.dryRun, + hasSharedTestDatabase, + usesPostgres: groupUsesPostgres(options, selection), + hasScheduledSuites: hasScheduledSuitesForRun(options, selection), + })) { + await runUnderSharedPostgres({ + repoRoot, + runnerScriptPath: fileURLToPath(import.meta.url), + }); + } else if (selection) { for (const [project, files] of Object.entries(selection)) { + if (files.length === 0) continue; const serverArgs = project !== "@paperclipai/server" ? [] - : options.mode === serializedModeName || hasSharedTestDatabase + : hasSharedTestDatabase ? ["--pool=forks", "--isolate", ...serializedServerVitestArgs] - : ["--pool=forks", "--isolate", "--fileParallelism", "--maxWorkers=3"]; + : options.mode === serializedModeName + ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(3)}`] + : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveServerParallelWorkers(4)}`]; await runVitest(["--project", project, ...serverArgs, ...files], `selected ${project}: ${files.length} files`, null, true); } - } else if (options.mode === generalModeName || options.mode === allModeName) { - if (options.group) { - await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount); - } else { - await runGeneralSuites(routeTests, defaultChatShards); + } else { + if (options.mode === generalModeName || options.mode === allModeName) { + if (options.group) { + await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount); + } else { + await runGeneralSuites(routeTests, defaultChatShards); + } } - } - if (!selection && (options.mode === serializedModeName || options.mode === allModeName)) { - await runSerializedSuites(routeTests, options.shardIndex ?? 0, options.shardCount ?? 1); + if (options.mode === serializedModeName || options.mode === allModeName) { + await runSerializedSuites(activeRouteTests, options.shardIndex ?? 0, options.shardCount ?? 1); + } } } catch (error) { console.error(`[test:run] ${error.message}`); diff --git a/scripts/serialized-shard-durations.json b/scripts/serialized-shard-durations.json index c53a03a733c..06ae70c20ed 100644 --- a/scripts/serialized-shard-durations.json +++ b/scripts/serialized-shard-durations.json @@ -3,202 +3,196 @@ "unit": "ms", "sources": [ { - "run": 43133035381, + "pull": 22679, + "run": 45238253588, "attempt": 1, - "sha": "42fd790e80953000a7be99eff30fb9a81bf9c7b7", - "url": "https://github.com/paperclipai/paperclip/actions/runs/43133035381" - }, - { - "run": 43134251278, - "attempt": 2, - "sha": "9dfdeaad8662d9cd73a93490d09516877ef8a276", - "url": "https://github.com/paperclipai/paperclip/actions/runs/43134251278" - }, - { - "run": 43145252393, - "attempt": 2, - "sha": "7d9973405c8726d6aadc7d0e6b4f6076085ebc45", - "url": "https://github.com/paperclipai/paperclip/actions/runs/43145252393" + "sha": "8d513d5b1ab8fbfa2905d41be44c165b03a8a320", + "url": "https://github.com/paperclipai/paperclip/actions/runs/45238253588" } ], "coverage": { - "measured": 173, - "withSetup": 173, - "inventory": 173 + "measured": 178, + "withSetup": 178, + "inventory": 178 }, "durations": { - "server/src/__tests__/access-routes-hidden-floor.test.ts": 4459, - "server/src/__tests__/access-routes-permissions-upgrade.test.ts": 5465, - "server/src/__tests__/activity-routes.test.ts": 10563, - "server/src/__tests__/adapter-auth-signal-routes.test.ts": 9084, - "server/src/__tests__/adapter-model-refresh-routes.test.ts": 4075, - "server/src/__tests__/adapter-routes-authz.test.ts": 10176, - "server/src/__tests__/adapter-routes.test.ts": 3958, - "server/src/__tests__/agent-action-audit-routes.test.ts": 5904, - "server/src/__tests__/agent-adapter-validation-routes.test.ts": 50458, - "server/src/__tests__/agent-cross-tenant-authz-routes.test.ts": 4272, - "server/src/__tests__/agent-device-login-routes.test.ts": 6231, - "server/src/__tests__/agent-hire-auth-inheritance-routes.test.ts": 8399, - "server/src/__tests__/agent-hire-idempotency-routes.test.ts": 6320, - "server/src/__tests__/agent-instructions-routes.test.ts": 3851, - "server/src/__tests__/agent-live-run-routes.test.ts": 47196, - "server/src/__tests__/agent-permissions-routes.test.ts": 5042, - "server/src/__tests__/agent-runner-qualification-routes.test.ts": 5808, - "server/src/__tests__/agent-secrets-routes.test.ts": 5616, - "server/src/__tests__/agent-skills-routes.test.ts": 4780, - "server/src/__tests__/agent-task-hierarchy-depth-routes.test.ts": 5914, - "server/src/__tests__/agent-test-environment-routes.test.ts": 4386, - "server/src/__tests__/ai-connection-router.test.ts": 28008, - "server/src/__tests__/announcements-routes.test.ts": 4480, - "server/src/__tests__/approval-routes-idempotency.test.ts": 4100, - "server/src/__tests__/artifact-review-document-routes.test.ts": 6376, - "server/src/__tests__/assets.test.ts": 5477, - "server/src/__tests__/auth-routes.test.ts": 4182, - "server/src/__tests__/auth-session-route.test.ts": 3352, - "server/src/__tests__/authz-company-access.test.ts": 1190, - "server/src/__tests__/authz-existence-oracle-guard.test.ts": 100, - "server/src/__tests__/authz-secret-context.test.ts": 1184, - "server/src/__tests__/board-bootstrap-routes.test.ts": 5136, - "server/src/__tests__/board-chat-route-feature-flag.test.ts": 815, - "server/src/__tests__/bootstrap-claim-routes.test.ts": 3801, - "server/src/__tests__/browser-use-route-scope.test.ts": 3617, - "server/src/__tests__/built-in-agent-routes.test.ts": 9291, - "server/src/__tests__/cases-routes.test.ts": 11134, - "server/src/__tests__/cli-auth-routes.test.ts": 17169, - "server/src/__tests__/cloud-routes.test.ts": 3736, - "server/src/__tests__/companies-route-cross-company-authz.test.ts": 15423, - "server/src/__tests__/companies-route-path-guard.test.ts": 3778, - "server/src/__tests__/company-branding-route.test.ts": 6936, - "server/src/__tests__/company-default-decision-owner-route.test.ts": 6504, - "server/src/__tests__/company-import-transfer-routes.test.ts": 4904, - "server/src/__tests__/company-portability-routes.test.ts": 5250, - "server/src/__tests__/company-portability.test.ts": 9588, - "server/src/__tests__/company-search-extract-routes.test.ts": 4424, - "server/src/__tests__/company-search-rate-limit-routes.test.ts": 4412, - "server/src/__tests__/company-skill-policy-routes.test.ts": 4527, - "server/src/__tests__/company-skills-import-authz-routes.test.ts": 5740, - "server/src/__tests__/company-skills-routes.test.ts": 3796, - "server/src/__tests__/company-user-directory-route.test.ts": 3829, - "server/src/__tests__/cost-data-quality-routes.test.ts": 3649, - "server/src/__tests__/costs-service.test.ts": 5218, - "server/src/__tests__/decision-queues-routes.test.ts": 6413, - "server/src/__tests__/document-annotation-routes.test.ts": 6425, - "server/src/__tests__/email-routes-provider-errors.test.ts": 3667, - "server/src/__tests__/environment-custom-image-routes.test.ts": 3810, - "server/src/__tests__/environment-instance-routes.test.ts": 3784, - "server/src/__tests__/environment-routes.test.ts": 3862, - "server/src/__tests__/environment-selection-route-guards.test.ts": 4439, - "server/src/__tests__/execution-workspace-runtime-lease-route.test.ts": 5683, - "server/src/__tests__/execution-workspaces-routes.test.ts": 3883, - "server/src/__tests__/express5-auth-wildcard.test.ts": 120, - "server/src/__tests__/external-object-routes.test.ts": 4334, - "server/src/__tests__/folders-routes.test.ts": 3921, - "server/src/__tests__/health-dev-server-token.test.ts": 4171, - "server/src/__tests__/health.test.ts": 3773, - "server/src/__tests__/heartbeat-dependency-scheduling.test.ts": 50657, + "server/src/__tests__/access-routes-hidden-floor.test.ts": 7709, + "server/src/__tests__/access-routes-permissions-upgrade.test.ts": 7117, + "server/src/__tests__/activity-routes.test.ts": 21578, + "server/src/__tests__/adapter-auth-signal-routes.test.ts": 17029, + "server/src/__tests__/adapter-model-refresh-routes.test.ts": 6222, + "server/src/__tests__/adapter-routes-authz.test.ts": 19486, + "server/src/__tests__/adapter-routes.test.ts": 17941, + "server/src/__tests__/agent-action-audit-routes.test.ts": 10946, + "server/src/__tests__/agent-adapter-validation-routes.test.ts": 100370, + "server/src/__tests__/agent-cross-tenant-authz-routes.test.ts": 6553, + "server/src/__tests__/agent-device-login-routes.test.ts": 23028, + "server/src/__tests__/agent-hire-auth-inheritance-routes.test.ts": 23298, + "server/src/__tests__/agent-hire-idempotency-routes.test.ts": 8900, + "server/src/__tests__/agent-instructions-routes.test.ts": 7607, + "server/src/__tests__/agent-live-run-routes.test.ts": 85464, + "server/src/__tests__/agent-permissions-routes.test.ts": 19196, + "server/src/__tests__/agent-runner-qualification-routes.test.ts": 8686, + "server/src/__tests__/agent-secrets-routes.test.ts": 8763, + "server/src/__tests__/agent-skills-routes.test.ts": 7999, + "server/src/__tests__/agent-task-hierarchy-depth-routes.test.ts": 10309, + "server/src/__tests__/agent-test-environment-routes.test.ts": 19471, + "server/src/__tests__/ai-connection-router.test.ts": 42177, + "server/src/__tests__/announcements-routes.test.ts": 6400, + "server/src/__tests__/approval-routes-idempotency.test.ts": 5399, + "server/src/__tests__/artifact-review-document-routes.test.ts": 9350, + "server/src/__tests__/assets.test.ts": 9131, + "server/src/__tests__/auth-routes.test.ts": 7299, + "server/src/__tests__/auth-session-route.test.ts": 5366, + "server/src/__tests__/authz-company-access.test.ts": 1619, + "server/src/__tests__/authz-existence-oracle-guard.test.ts": 569, + "server/src/__tests__/authz-secret-context.test.ts": 1421, + "server/src/__tests__/board-bootstrap-routes.test.ts": 5950, + "server/src/__tests__/board-chat-route-feature-flag.test.ts": 1578, + "server/src/__tests__/board-route-statement-census.test.ts": 8356, + "server/src/__tests__/bootstrap-claim-routes.test.ts": 5323, + "server/src/__tests__/browser-use-route-scope.test.ts": 4166, + "server/src/__tests__/built-in-agent-routes.test.ts": 14052, + "server/src/__tests__/cases-routes.test.ts": 15579, + "server/src/__tests__/cli-auth-routes.test.ts": 26031, + "server/src/__tests__/cloud-routes.test.ts": 7000, + "server/src/__tests__/companies-route-cross-company-authz.test.ts": 19290, + "server/src/__tests__/companies-route-path-guard.test.ts": 4572, + "server/src/__tests__/company-branding-route.test.ts": 13767, + "server/src/__tests__/company-default-decision-owner-route.test.ts": 9824, + "server/src/__tests__/company-import-transfer-routes.test.ts": 7926, + "server/src/__tests__/company-portability-routes.test.ts": 16020, + "server/src/__tests__/company-portability.test.ts": 11437, + "server/src/__tests__/company-search-extract-routes.test.ts": 6767, + "server/src/__tests__/company-search-rate-limit-routes.test.ts": 6118, + "server/src/__tests__/company-skill-policy-routes.test.ts": 6222, + "server/src/__tests__/company-skills-import-authz-routes.test.ts": 7892, + "server/src/__tests__/company-skills-routes.test.ts": 6446, + "server/src/__tests__/company-user-directory-route.test.ts": 6130, + "server/src/__tests__/cost-data-quality-routes.test.ts": 5213, + "server/src/__tests__/costs-service.test.ts": 5309, + "server/src/__tests__/decision-queues-routes.test.ts": 6023, + "server/src/__tests__/document-annotation-routes.test.ts": 10105, + "server/src/__tests__/email-routes-provider-errors.test.ts": 5765, + "server/src/__tests__/environment-custom-image-routes.test.ts": 6238, + "server/src/__tests__/environment-instance-routes.test.ts": 6976, + "server/src/__tests__/environment-routes.test.ts": 14035, + "server/src/__tests__/environment-selection-route-guards.test.ts": 7244, + "server/src/__tests__/execution-workspace-runtime-lease-route.test.ts": 7541, + "server/src/__tests__/execution-workspaces-routes.test.ts": 5986, + "server/src/__tests__/express5-auth-wildcard.test.ts": 836, + "server/src/__tests__/external-object-routes.test.ts": 7481, + "server/src/__tests__/folders-routes.test.ts": 3807, + "server/src/__tests__/health-dev-server-token.test.ts": 7458, + "server/src/__tests__/health.test.ts": 5117, + "server/src/__tests__/heartbeat-dependency-scheduling.test.ts": 79302, "server/src/__tests__/heartbeat-issue-liveness-escalation.test.ts": 54768, "server/src/__tests__/heartbeat-process-recovery.test.ts": 344017, - "server/src/__tests__/heartbeat-run-privacy-routes.test.ts": 9270, - "server/src/__tests__/inbox-agent-policy-routes.test.ts": 4707, - "server/src/__tests__/inbox-archive-routes.test.ts": 7445, - "server/src/__tests__/inbox-mine-routes.test.ts": 7381, - "server/src/__tests__/instance-database-backups-routes.test.ts": 3506, - "server/src/__tests__/instance-settings-routes.test.ts": 4187, - "server/src/__tests__/invite-accept-existing-member.test.ts": 3588, - "server/src/__tests__/invite-accept-gateway-defaults.test.ts": 4603, - "server/src/__tests__/invite-accept-replay.test.ts": 4210, - "server/src/__tests__/invite-create-route.test.ts": 6191, - "server/src/__tests__/invite-expiry.test.ts": 4468, - "server/src/__tests__/invite-join-manager.test.ts": 4095, - "server/src/__tests__/invite-list-route.test.ts": 3806, - "server/src/__tests__/invite-logo-route.test.ts": 4470, - "server/src/__tests__/invite-onboarding-text.test.ts": 4598, - "server/src/__tests__/invite-rate-limit-route.test.ts": 5758, - "server/src/__tests__/invite-summary-route.test.ts": 6219, - "server/src/__tests__/invite-test-resolution-route.test.ts": 4021, - "server/src/__tests__/invite-url-public-base-url.test.ts": 4803, - "server/src/__tests__/issue-access-grants-routes.test.ts": 7311, - "server/src/__tests__/issue-activity-events-routes.test.ts": 8154, - "server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts": 15844, - "server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts": 4282, - "server/src/__tests__/issue-assignee-invokability-routes.test.ts": 3973, - "server/src/__tests__/issue-attachment-routes.test.ts": 4512, - "server/src/__tests__/issue-blocker-diagnostics-routes.test.ts": 5372, - "server/src/__tests__/issue-chat-bootstrap-routes.test.ts": 7382, - "server/src/__tests__/issue-closed-workspace-routes.test.ts": 3977, - "server/src/__tests__/issue-comment-attribution-audit-routes.test.ts": 5540, - "server/src/__tests__/issue-comment-cancel-routes.test.ts": 3798, - "server/src/__tests__/issue-comment-reopen-routes.test.ts": 6776, - "server/src/__tests__/issue-confirm-run-stopped-routes.test.ts": 7677, - "server/src/__tests__/issue-create-deduplication-routes.test.ts": 6041, - "server/src/__tests__/issue-created-from-routes.test.ts": 5645, - "server/src/__tests__/issue-creation-source-routes.test.ts": 6585, - "server/src/__tests__/issue-dependency-wakeups-routes.test.ts": 8660, - "server/src/__tests__/issue-document-restore-routes.test.ts": 6269, - "server/src/__tests__/issue-execution-policy-routes.test.ts": 4346, - "server/src/__tests__/issue-feedback-routes.test.ts": 4382, - "server/src/__tests__/issue-identifier-routes.test.ts": 5515, - "server/src/__tests__/issue-list-assignee-filter-routes.test.ts": 12312, - "server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts": 4929, - "server/src/__tests__/issue-onboarding-first-task-routes.test.ts": 13445, - "server/src/__tests__/issue-queued-comments-routes.test.ts": 118620, - "server/src/__tests__/issue-scheduled-retry-routes.test.ts": 14427, - "server/src/__tests__/issue-stale-execution-lock-routes.test.ts": 7268, - "server/src/__tests__/issue-stalled-review-decision-routes.test.ts": 6458, - "server/src/__tests__/issue-status-version-route-service.test.ts": 5591, - "server/src/__tests__/issue-subtree-diagnostics-routes.test.ts": 6142, - "server/src/__tests__/issue-summaries-routes.test.ts": 5147, - "server/src/__tests__/issue-telemetry-routes.test.ts": 4790, - "server/src/__tests__/issue-thread-interaction-routes.test.ts": 14207, - "server/src/__tests__/issue-tree-control-routes.test.ts": 3888, - "server/src/__tests__/issue-update-comment-wakeup-routes.test.ts": 4533, - "server/src/__tests__/issue-wake-diagnostics-routes.test.ts": 5628, - "server/src/__tests__/issue-watchdogs-routes.test.ts": 11962, - "server/src/__tests__/issue-workspace-command-authz.test.ts": 4185, - "server/src/__tests__/issues-checkout-wakeup.test.ts": 100, - "server/src/__tests__/issues-goal-context-routes.test.ts": 4365, - "server/src/__tests__/issues-service.test.ts": 39512, - "server/src/__tests__/link-preview-routes.test.ts": 3783, - "server/src/__tests__/llms-routes.test.ts": 4025, - "server/src/__tests__/low-trust-red-team-routes.test.ts": 40548, + "server/src/__tests__/heartbeat-run-privacy-routes.test.ts": 25152, + "server/src/__tests__/inbox-agent-policy-routes.test.ts": 9188, + "server/src/__tests__/inbox-archive-routes.test.ts": 8268, + "server/src/__tests__/inbox-mine-routes.test.ts": 10977, + "server/src/__tests__/instance-database-backups-routes.test.ts": 6034, + "server/src/__tests__/instance-server-metrics-routes.test.ts": 16867, + "server/src/__tests__/instance-settings-routes.test.ts": 5803, + "server/src/__tests__/invite-accept-existing-member.test.ts": 6558, + "server/src/__tests__/invite-accept-gateway-defaults.test.ts": 8151, + "server/src/__tests__/invite-accept-replay.test.ts": 6489, + "server/src/__tests__/invite-create-route.test.ts": 9982, + "server/src/__tests__/invite-expiry.test.ts": 4886, + "server/src/__tests__/invite-join-manager.test.ts": 6003, + "server/src/__tests__/invite-list-route.test.ts": 5932, + "server/src/__tests__/invite-logo-route.test.ts": 5533, + "server/src/__tests__/invite-onboarding-text.test.ts": 7361, + "server/src/__tests__/invite-rate-limit-route.test.ts": 6103, + "server/src/__tests__/invite-summary-route.test.ts": 8714, + "server/src/__tests__/invite-test-resolution-route.test.ts": 6673, + "server/src/__tests__/invite-url-public-base-url.test.ts": 6521, + "server/src/__tests__/issue-access-grants-routes.test.ts": 9735, + "server/src/__tests__/issue-activity-events-routes.test.ts": 15122, + "server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts": 17814, + "server/src/__tests__/issue-assigned-backlog-contract-routes.test.ts": 7165, + "server/src/__tests__/issue-assignee-invokability-routes.test.ts": 7237, + "server/src/__tests__/issue-attachment-routes.test.ts": 17644, + "server/src/__tests__/issue-blocker-diagnostics-routes.test.ts": 9650, + "server/src/__tests__/issue-chat-bootstrap-routes.test.ts": 10756, + "server/src/__tests__/issue-closed-workspace-routes.test.ts": 7089, + "server/src/__tests__/issue-comment-attribution-audit-routes.test.ts": 8446, + "server/src/__tests__/issue-comment-cancel-routes.test.ts": 6164, + "server/src/__tests__/issue-comment-reopen-routes.test.ts": 19442, + "server/src/__tests__/issue-confirm-run-stopped-routes.test.ts": 9839, + "server/src/__tests__/issue-create-deduplication-routes.test.ts": 9136, + "server/src/__tests__/issue-created-from-routes.test.ts": 7614, + "server/src/__tests__/issue-creation-source-routes.test.ts": 10770, + "server/src/__tests__/issue-dependency-wakeups-routes.test.ts": 12551, + "server/src/__tests__/issue-document-restore-routes.test.ts": 10496, + "server/src/__tests__/issue-execution-policy-routes.test.ts": 8945, + "server/src/__tests__/issue-feedback-routes.test.ts": 5778, + "server/src/__tests__/issue-identifier-routes.test.ts": 7007, + "server/src/__tests__/issue-list-assignee-filter-routes.test.ts": 27792, + "server/src/__tests__/issue-list-updatedsince-filter-routes.test.ts": 8596, + "server/src/__tests__/issue-onboarding-first-task-routes.test.ts": 14748, + "server/src/__tests__/issue-queued-comments-routes.test.ts": 99424, + "server/src/__tests__/issue-scheduled-retry-routes.test.ts": 22055, + "server/src/__tests__/issue-stale-execution-lock-routes.test.ts": 9935, + "server/src/__tests__/issue-stalled-review-decision-routes.test.ts": 17957, + "server/src/__tests__/issue-status-version-route-service.test.ts": 8577, + "server/src/__tests__/issue-subtree-diagnostics-routes.test.ts": 7841, + "server/src/__tests__/issue-summaries-routes.test.ts": 9355, + "server/src/__tests__/issue-telemetry-routes.test.ts": 10283, + "server/src/__tests__/issue-thread-interaction-routes.test.ts": 17322, + "server/src/__tests__/issue-tree-control-routes.test.ts": 6060, + "server/src/__tests__/issue-update-comment-wakeup-routes.test.ts": 7306, + "server/src/__tests__/issue-wake-diagnostics-routes.test.ts": 15170, + "server/src/__tests__/issue-watchdogs-routes.test.ts": 15822, + "server/src/__tests__/issue-workspace-command-authz.test.ts": 6275, + "server/src/__tests__/issues-checkout-wakeup.test.ts": 1065, + "server/src/__tests__/issues-goal-context-routes.test.ts": 6658, + "server/src/__tests__/issues-service.test.ts": 35882, + "server/src/__tests__/link-preview-routes.test.ts": 6145, + "server/src/__tests__/llms-routes.test.ts": 6553, + "server/src/__tests__/low-trust-red-team-routes.test.ts": 51564, "server/src/__tests__/maintenance-server-routes.test.ts": 276429, - "server/src/__tests__/managed-agent-profile-routes-authz.test.ts": 3791, - "server/src/__tests__/multilingual-issues-routes.test.ts": 5790, - "server/src/__tests__/muse-qualification-routes.test.ts": 3804, - "server/src/__tests__/onboarding-seed-route.test.ts": 6481, - "server/src/__tests__/openapi-routes.test.ts": 5123, - "server/src/__tests__/openclaw-invite-prompt-route.test.ts": 3811, - "server/src/__tests__/opencode-local-adapter-environment.test.ts": 6723, - "server/src/__tests__/openrouter-attribution.test.ts": 685, - "server/src/__tests__/permissions-upgrade-boundary-routes.test.ts": 6152, - "server/src/__tests__/plugin-install-route-security.test.ts": 5289, - "server/src/__tests__/plugin-routes-authz.test.ts": 3612, - "server/src/__tests__/plugin-scoped-api-routes.test.ts": 3890, - "server/src/__tests__/project-decision-owner-route.test.ts": 6221, - "server/src/__tests__/project-goal-telemetry-routes.test.ts": 4390, - "server/src/__tests__/project-routes-env.test.ts": 4228, - "server/src/__tests__/project-workspace-managed-sandbox-routes.test.ts": 6636, - "server/src/__tests__/projects-list-archived-routes.test.ts": 5176, - "server/src/__tests__/redaction.test.ts": 160, - "server/src/__tests__/resource-memberships-routes.test.ts": 5530, - "server/src/__tests__/routine-document-annotation-routes.test.ts": 4747, - "server/src/__tests__/routines-e2e.test.ts": 15930, - "server/src/__tests__/routines-routes.test.ts": 11937, - "server/src/__tests__/secret-proposals-routes.test.ts": 15931, - "server/src/__tests__/secrets-routes-claude-oauth-service.test.ts": 5401, - "server/src/__tests__/secrets-routes.test.ts": 4414, - "server/src/__tests__/sidebar-preferences-routes.test.ts": 6241, - "server/src/__tests__/skill-update-diff-routes.test.ts": 4160, - "server/src/__tests__/subscription-routes.test.ts": 3452, - "server/src/__tests__/summary-slot-routes.test.ts": 8150, - "server/src/__tests__/task-connector-read-routes.test.ts": 6479, - "server/src/__tests__/task-title-routes.test.ts": 13501, - "server/src/__tests__/teams-catalog-routes.test.ts": 7702, - "server/src/__tests__/user-profile-routes.test.ts": 4153, - "server/src/__tests__/workspace-command-authz.test.ts": 100, - "server/src/__tests__/workspace-preferences-routes.test.ts": 3922, - "server/src/__tests__/workspace-restore-repair-route.test.ts": 7023, - "server/src/__tests__/workspace-runtime-routes-authz.test.ts": 4185, - "server/src/__tests__/workspace-runtime-service-authz.test.ts": 2027 + "server/src/__tests__/managed-agent-profile-routes-authz.test.ts": 6245, + "server/src/__tests__/multilingual-issues-routes.test.ts": 8186, + "server/src/__tests__/muse-qualification-routes.test.ts": 5311, + "server/src/__tests__/native-child-task-read-routes.test.ts": 8905, + "server/src/__tests__/onboarding-seed-route.test.ts": 7929, + "server/src/__tests__/openapi-routes.test.ts": 19600, + "server/src/__tests__/openclaw-invite-prompt-route.test.ts": 6484, + "server/src/__tests__/opencode-local-adapter-environment.test.ts": 7463, + "server/src/__tests__/openrouter-attribution.test.ts": 1697, + "server/src/__tests__/openrouter-catalog-error-handler.test.ts": 3983, + "server/src/__tests__/permissions-upgrade-boundary-routes.test.ts": 8104, + "server/src/__tests__/plugin-install-route-security.test.ts": 8271, + "server/src/__tests__/plugin-routes-authz.test.ts": 14858, + "server/src/__tests__/plugin-scoped-api-routes.test.ts": 13393, + "server/src/__tests__/project-decision-owner-route.test.ts": 10045, + "server/src/__tests__/project-goal-telemetry-routes.test.ts": 5925, + "server/src/__tests__/project-routes-env.test.ts": 8038, + "server/src/__tests__/project-workspace-managed-sandbox-routes.test.ts": 9106, + "server/src/__tests__/projects-list-archived-routes.test.ts": 7611, + "server/src/__tests__/redaction.test.ts": 654, + "server/src/__tests__/resource-memberships-routes.test.ts": 7719, + "server/src/__tests__/routine-document-annotation-routes.test.ts": 6388, + "server/src/__tests__/routines-e2e.test.ts": 42624, + "server/src/__tests__/routines-routes.test.ts": 25919, + "server/src/__tests__/secret-proposals-routes.test.ts": 34207, + "server/src/__tests__/secrets-routes-claude-oauth-service.test.ts": 8198, + "server/src/__tests__/secrets-routes.test.ts": 6718, + "server/src/__tests__/sidebar-preferences-routes.test.ts": 7854, + "server/src/__tests__/skill-update-diff-routes.test.ts": 7253, + "server/src/__tests__/subscription-routes.test.ts": 5517, + "server/src/__tests__/summary-slot-routes.test.ts": 13804, + "server/src/__tests__/tailscale-connection-routes.test.ts": 5215, + "server/src/__tests__/task-connector-read-routes.test.ts": 10338, + "server/src/__tests__/task-title-routes.test.ts": 25360, + "server/src/__tests__/teams-catalog-routes.test.ts": 12771, + "server/src/__tests__/user-profile-routes.test.ts": 6490, + "server/src/__tests__/workspace-command-authz.test.ts": 668, + "server/src/__tests__/workspace-preferences-routes.test.ts": 5757, + "server/src/__tests__/workspace-restore-repair-route.test.ts": 9418, + "server/src/__tests__/workspace-runtime-routes-authz.test.ts": 6436, + "server/src/__tests__/workspace-runtime-service-authz.test.ts": 2659 } } diff --git a/scripts/typecheck-test-programs.mjs b/scripts/typecheck-test-programs.mjs index edddf04d3ce..e5d1bb13a7f 100644 --- a/scripts/typecheck-test-programs.mjs +++ b/scripts/typecheck-test-programs.mjs @@ -12,17 +12,19 @@ // The script then fails if a tracked test file is in no program. tsc decides that, // not a glob: `include` silently drops foo.test.tsx when foo.test.ts exists. // -// Usage: node scripts/typecheck-test-programs.mjs [--low-memory] [tsconfig ...] -// Naming a tsconfig runs only that program and skips the coverage check. +// Usage: node scripts/typecheck-test-programs.mjs [--low-memory] [--checkers ] [--concurrency ] [tsconfig ...] +// Naming a tsconfig runs only that program and skips the coverage check unless --check-file or --force-coverage is given. -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import { existsSync } from "node:fs"; +import { availableParallelism } from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { linkExcludedPlugins } from "./link-plugin-dev-sdk.mjs"; -import { LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.mjs"; +import { emitOnlyTscArgs, lowMemoryTscArgs, LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.mjs"; import { PROJECTS } from "./typecheck-test-projects.mjs"; +export const DEFAULT_CONCURRENCY = 3; export const PROVIDER_WORKSPACE = "scripts/typecheck-sandbox-providers"; export const SANDBOX_PROVIDERS = [ @@ -60,6 +62,126 @@ export const PROGRAMS = [ // server/scripts/typecheck-layers.mjs reads this tree. Everything else must be in a program. export const CHECKED_ELSEWHERE = ["server/src/"]; +export const SANDBOX_PROVIDER_PROGRAMS = SANDBOX_PROVIDERS.map((directory) => `${directory}/tsconfig.test.json`); + +const GLOBAL_PROGRAM_INPUTS = new Set([ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "tsconfig.base.json", + ".npmrc", + "scripts/run-tsc.mjs", + "scripts/ci-typecheck-lane.mjs", + "scripts/typecheck-test-programs.mjs", + "scripts/typecheck-test-projects.mjs", +]); + +const PLAYWRIGHT_TEST_PREFIXES = [ + "tests/tsconfig.playwright.json", + "tests/ai-connections-app/", + "tests/ai-connections-review/", + "tests/canary-onboarding/", + "tests/hiring-ai-connections/", + "tests/html-preview/", + "tests/perf/", + "tests/release-smoke/", + "tests/storybook-visual/", + "ui/src/", +]; + +const hasPrefix = (files, prefixes) => + files.some((file) => prefixes.some((prefix) => file === prefix || file.startsWith(prefix))); + +/** + * Selects the test programs, preparation needs, and coverage scope affected by `changedFiles` in PR mode. + * Returns full coverage when `changedFiles` is null/undefined or touches global typecheck inputs. + */ +export function selectTestPrograms(changedFiles, programs = PROGRAMS) { + if (!Array.isArray(changedFiles)) { + return { + programs: [...programs], + includeProviders: true, + includeRunnerEval: true, + checkCoverage: true, + changedTestFiles: null, + }; + } + if (changedFiles.some((file) => GLOBAL_PROGRAM_INPUTS.has(file) || file.startsWith("patches/"))) { + return { + programs: [...programs], + includeProviders: true, + includeRunnerEval: true, + checkCoverage: true, + changedTestFiles: null, + }; + } + + const sharedChanged = hasPrefix(changedFiles, ["packages/shared/"]); + const sdkOrSharedChanged = + sharedChanged || + hasPrefix(changedFiles, [ + "packages/plugins/sdk/", + "scripts/typecheck-sandbox-providers/", + "scripts/link-plugin-dev-sdk.mjs", + ]); + const runnerChanged = hasPrefix(changedFiles, ["packages/paperclip-runner/", "packages/paperclip-eval-kernel/"]); + const cloudflareChanged = hasPrefix(changedFiles, ["packages/plugins/sandbox-providers/cloudflare/"]); + + const selected = programs.filter((program) => { + if (program === "packages/db/tsconfig.test.json") { + return sharedChanged || hasPrefix(changedFiles, ["packages/db/"]); + } + if (program === "packages/kv-demo-mcp-server/tsconfig.test.json") { + return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/kv-demo-mcp-server/"]); + } + if (program.startsWith("packages/paperclip-runner/")) { + return sharedChanged || runnerChanged; + } + if (program === "packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json") { + return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/plugins/examples/plugin-orchestration-smoke-example/"]); + } + if (program === "packages/plugins/plugin-workspace-diff/tsconfig.test.json") { + return sdkOrSharedChanged || hasPrefix(changedFiles, ["packages/plugins/plugin-workspace-diff/"]); + } + if (program === "packages/plugins/sdk/tsconfig.test.json") { + return sdkOrSharedChanged; + } + if (program.startsWith("packages/plugins/sandbox-providers/")) { + if (sdkOrSharedChanged) return true; + const directory = path.posix.dirname(program); + if (directory.startsWith("packages/plugins/sandbox-providers/cloudflare")) return cloudflareChanged; + return hasPrefix(changedFiles, [`${directory}/`]); + } + if (program === "scripts/scale-ramp/tsconfig.json") { + return hasPrefix(changedFiles, ["scripts/scale-ramp/", "scripts/scale-agents-ramp.ts"]); + } + if (program === "tests/runner-acceptance/tsconfig.json") { + return sharedChanged || runnerChanged || hasPrefix(changedFiles, ["tests/runner-acceptance/"]); + } + if (program === "tests/tsconfig.playwright.json") { + return sharedChanged || hasPrefix(changedFiles, PLAYWRIGHT_TEST_PREFIXES); + } + // Fail closed for any newly added program without an explicit rule. + return true; + }); + + const providerSet = new Set(SANDBOX_PROVIDER_PROGRAMS); + const includeProviders = selected.some((program) => providerSet.has(program)); + const includeRunnerEval = selected.some((program) => program.startsWith("packages/paperclip-runner/")); + const changedTestFiles = changedFiles.filter( + (file) => /\.(test|spec)\.tsx?$/.test(file) && !CHECKED_ELSEWHERE.some((prefix) => file.startsWith(prefix)), + ); + const tsconfigChanged = changedFiles.some((file) => /(?:^|\/)tsconfig(?:\.[^/]+)?\.json$/.test(file)); + + return { + programs: selected, + includeProviders, + includeRunnerEval, + checkCoverage: changedTestFiles.length > 0 || tsconfigChanged, + changedTestFiles: tsconfigChanged ? null : changedTestFiles.length > 0 ? changedTestFiles : null, + }; +} + const PREPARE_STEPS = [ ["--filter", "@paperclipai/plugin-sdk", "ensure-build-deps"], ["--filter", "@paperclipai/paperclip-runner", "run", "ensure:eval-build-deps"], @@ -114,6 +236,56 @@ function listProgramFiles(config, { cwd, env }) { }; } +function listProgramFilesAsync(config, { cwd, env }) { + const tsc = path.join(cwd, "node_modules", "typescript", "bin", "tsc"); + return new Promise((resolve, reject) => { + const chunks = []; + const child = spawn(process.execPath, [tsc, "-p", config, "--listFilesOnly"], { + cwd, + env, + stdio: ["ignore", "pipe", "pipe"], + }); + child.stdout.on("data", (chunk) => chunks.push(chunk)); + child.stderr.on("data", (chunk) => chunks.push(chunk)); + child.on("error", reject); + child.on("close", (code, signal) => { + const output = Buffer.concat(chunks).toString("utf8"); + resolve({ + status: signal ? 1 : (code ?? 1), + output, + files: output + .split("\n") + .filter(Boolean) + .map((file) => path.relative(cwd, file).split(path.sep).join("/")), + }); + }); + }); +} + +function runTscAsync(args, { cwd = process.cwd(), env = process.env } = {}) { + const tsc = path.join(cwd, "node_modules", "typescript", "bin", "tsc"); + return new Promise((resolve, reject) => { + const started = Date.now(); + const chunks = []; + const child = spawn(process.execPath, [tsc, ...args, ...lowMemoryTscArgs(env), ...emitOnlyTscArgs(env)], { + cwd, + env, + stdio: ["ignore", "pipe", "pipe"], + }); + child.stdout.on("data", (chunk) => chunks.push(chunk)); + child.stderr.on("data", (chunk) => chunks.push(chunk)); + child.on("error", reject); + child.on("close", (code, signal) => { + resolve({ + status: signal ? 1 : (code ?? 1), + signal, + output: Buffer.concat(chunks).toString("utf8"), + durationMs: Date.now() - started, + }); + }); + }); +} + function listWorkspaceConfigs(root) { const result = spawnSync("pnpm", ["ls", "-r", "--depth", "-1", "--json"], { cwd: root, @@ -160,18 +332,105 @@ export function checkCoverage({ return findUncheckedTests({ trackedFiles: trackedFiles(root), checkedFiles }); } +/** + * Parallel coverage check. When `onlyFiles` is provided, stops as soon as every + * tracked target test file is confirmed to belong to a typechecked program. + */ +export async function checkCoverageAsync({ + root, + env = process.env, + programs = PROGRAMS, + includeProviders = true, + onlyFiles = null, + concurrency = Math.min(4, availableParallelism()), + workspaceConfigs = listWorkspaceConfigs, + trackedFiles = listTrackedFiles, + listFilesAsync = listProgramFilesAsync, + logError = console.error, +}) { + const tracked = trackedFiles(root); + const checkedElsewhere = includeProviders + ? CHECKED_ELSEWHERE + : [...CHECKED_ELSEWHERE, "packages/plugins/sandbox-providers/"]; + + let remaining = null; + if (Array.isArray(onlyFiles)) { + const trackedSet = new Set(tracked); + const candidates = findUncheckedTests({ + trackedFiles: onlyFiles.filter((file) => trackedSet.has(file)), + checkedFiles: [], + checkedElsewhere, + }); + if (candidates.length === 0) return []; + remaining = new Set(candidates); + } + + const providerSet = new Set(SANDBOX_PROVIDER_PROGRAMS); + const coveragePrograms = includeProviders ? programs : programs.filter((program) => !providerSet.has(program)); + const projectConfigs = PROJECTS.map((project) => `${project}/tsconfig.json`); + let configs = [...workspaceConfigs(root), ...projectConfigs, ...coveragePrograms]; + + if (remaining) { + const targets = [...remaining]; + const matchesTargetDir = (config) => { + const dir = path.posix.dirname(config); + if (dir === ".") return false; + return targets.some((file) => file.startsWith(`${dir}/`)); + }; + configs = [ + ...configs.filter((config) => matchesTargetDir(config)), + ...configs.filter((config) => !matchesTargetDir(config)), + ]; + } + + const checkedFiles = []; + const queue = [...configs]; + let failed = false; + const workerCount = Math.max(1, Math.min(concurrency, queue.length)); + async function worker() { + while (!failed && !(remaining && remaining.size === 0)) { + const config = queue.shift(); + if (!config) return; + const listing = await listFilesAsync(config, { cwd: root, env }); + if (listing.status !== 0) { + logError(`typecheck:test-programs: could not list the files of ${config}\n${listing.output ?? ""}`); + failed = true; + return; + } + if (remaining) { + for (const file of listing.files) remaining.delete(file); + } else { + checkedFiles.push(...listing.files); + } + } + } + await Promise.all(Array.from({ length: workerCount }, worker)); + if (failed) return null; + if (remaining) return [...remaining]; + return findUncheckedTests({ trackedFiles: tracked, checkedFiles, checkedElsewhere }); +} + export function prepareTestPrograms({ root, env = process.env, + includeProviders = true, + includeRunnerEval = true, + includePluginSdk = true, pnpm = runPnpm, linkPlugins = linkExcludedPlugins, log = console.log, logError = console.error, }) { - for (const args of PREPARE_STEPS) { + const steps = PREPARE_STEPS.filter((args) => { + if (!includePluginSdk && args.includes("@paperclipai/plugin-sdk")) return false; + if (!includeRunnerEval && args.includes("@paperclipai/paperclip-runner")) return false; + return true; + }); + for (const args of steps) { const status = pnpm(args, { cwd: root, env }); if (status !== 0) return status; } + if (!includeProviders) return 0; const install = (directory, frozenArgs, resolveArgs) => { const cwd = path.join(root, directory); let status = pnpm(frozenArgs, { cwd, env }); @@ -203,6 +462,10 @@ export function typecheckTestPrograms({ programs = PROGRAMS, coverage = true, prepare = true, + includeProviders = true, + includeRunnerEval = true, + includePluginSdk = true, + checkers, pnpm = runPnpm, linkPlugins = linkExcludedPlugins, run = runTsc, @@ -211,14 +474,25 @@ export function typecheckTestPrograms({ logError = console.error, }) { if (prepare) { - const prepared = prepareTestPrograms({ root, env, pnpm, linkPlugins, log, logError }); + const prepared = prepareTestPrograms({ + root, + env, + includeProviders, + includeRunnerEval, + includePluginSdk, + pnpm, + linkPlugins, + log, + logError, + }); if (prepared !== 0) return prepared; } + const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : []; let exitCode = 0; for (const config of programs) { log(`typecheck:test-programs: ${config}`); - const { status, signal } = run(["-p", config], { cwd: root, env }); + const { status, signal } = run(["-p", config, ...checkerArgs], { cwd: root, env }); if (signal) return status || 1; if (status !== 0) exitCode = status; } @@ -237,32 +511,175 @@ export function typecheckTestPrograms({ return exitCode; } +export async function typecheckTestProgramsAsync({ + root, + env = process.env, + programs = PROGRAMS, + coverage = true, + coverageFiles = null, + prepare = true, + includeProviders = true, + includeRunnerEval = true, + includePluginSdk = true, + concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism())), + checkers, + pnpm = runPnpm, + linkPlugins = linkExcludedPlugins, + runAsync = runTscAsync, + checkFilesAsync = checkCoverageAsync, + log = console.log, + logError = console.error, +}) { + if (prepare) { + const prepared = prepareTestPrograms({ + root, + env, + includeProviders, + includeRunnerEval, + includePluginSdk, + pnpm, + linkPlugins, + log, + logError, + }); + if (prepared !== 0) return prepared; + } + + const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : []; + let exitCode = 0; + let aborted = false; + const queue = [...programs]; + const workerCount = Math.max(1, Math.min(concurrency, queue.length)); + async function worker() { + while (!aborted) { + const config = queue.shift(); + if (!config) return; + const result = await runAsync(["-p", config, ...checkerArgs], { cwd: root, env }); + const elapsed = typeof result.durationMs === "number" ? ` (${(result.durationMs / 1000).toFixed(1)}s)` : ""; + log(`typecheck:test-programs: ${config}${elapsed}`); + if (result.output) { + const trimmed = result.output.endsWith("\n") ? result.output.slice(0, -1) : result.output; + if (result.status === 0 && !result.signal) log(trimmed); + else logError(trimmed); + } + if (result.signal) { + aborted = true; + exitCode ||= result.status || 1; + return; + } + if (result.status !== 0) exitCode = result.status; + } + } + if (programs.length > 0) { + await Promise.all(Array.from({ length: workerCount }, worker)); + } + if (aborted) return exitCode || 1; + if (!coverage) return exitCode; + + const unchecked = await checkFilesAsync({ + root, + env, + includeProviders, + onlyFiles: coverageFiles, + logError, + }); + if (unchecked === null) return exitCode || 1; + if (unchecked.length > 0) { + logError( + `typecheck:test-programs: ${unchecked.length} test files are in no typechecked program. ` + + `Add them to a program in scripts/typecheck-test-programs.mjs. A foo.test.tsx beside a foo.test.ts needs a new name.\n` + + unchecked.map((file) => ` ${file}`).join("\n"), + ); + return exitCode || 1; + } + return exitCode; +} + if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - const flags = args.filter((arg) => arg.startsWith("--")); - const programs = args.filter((arg) => !arg.startsWith("--")); - const unknownFlags = flags.filter((flag) => !["--low-memory", "--prepare-only", "--skip-prepare"].includes(flag)); + let lowMemory = false; + let prepareOnly = false; + let skipPrepare = false; + let includeProviders = true; + let includeRunnerEval = true; + let includePluginSdk = true; + let noCoverage = false; + let forceCoverage = false; + let coverageOnly = false; + let concurrency = Math.max(1, Math.min(DEFAULT_CONCURRENCY, availableParallelism())); + let checkers; + const checkFiles = []; + const programs = []; + const unknownFlags = []; + let optionError = null; + + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (arg === "--low-memory") lowMemory = true; + else if (arg === "--prepare-only") prepareOnly = true; + else if (arg === "--skip-prepare") skipPrepare = true; + else if (arg === "--no-providers") includeProviders = false; + else if (arg === "--no-runner-eval") includeRunnerEval = false; + else if (arg === "--skip-plugin-sdk") includePluginSdk = false; + else if (arg === "--no-coverage") noCoverage = true; + else if (arg === "--force-coverage") forceCoverage = true; + else if (arg === "--coverage-only") coverageOnly = true; + else if (arg === "--concurrency") { + concurrency = Number(args[++i]); + if (!Number.isInteger(concurrency) || concurrency < 1) optionError = "--concurrency requires a positive integer"; + } else if (arg === "--checkers") { + checkers = Number(args[++i]); + if (!Number.isInteger(checkers) || checkers < 1) optionError = "--checkers requires a positive integer"; + } else if (arg === "--check-file") { + const file = args[++i]; + if (!file || file.startsWith("--")) optionError = "--check-file requires a path"; + else checkFiles.push(file); + } else if (arg.startsWith("--")) { + unknownFlags.push(arg); + } else { + programs.push(arg); + } + } + const unknown = programs.filter((program) => !PROGRAMS.includes(program)); const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); - const env = flags.includes("--low-memory") ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env; + const env = lowMemory ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env; + if (unknownFlags.length > 0) { console.error(`Unknown option: ${unknownFlags.join(", ")}`); process.exitCode = 2; - } else if (flags.includes("--prepare-only") && (flags.includes("--skip-prepare") || programs.length > 0)) { + } else if (optionError) { + console.error(optionError); + process.exitCode = 2; + } else if (prepareOnly && (skipPrepare || programs.length > 0)) { console.error("--prepare-only takes no programs and cannot be combined with --skip-prepare"); process.exitCode = 2; } else if (unknown.length > 0) { console.error(`Unknown program: ${unknown.join(", ")}. Known programs:\n ${PROGRAMS.join("\n ")}`); process.exitCode = 2; - } else if (flags.includes("--prepare-only")) { - process.exitCode = prepareTestPrograms({ root, env }); - } else { - process.exitCode = typecheckTestPrograms({ + } else if (prepareOnly) { + process.exitCode = prepareTestPrograms({ root, env, - programs: programs.length > 0 ? programs : PROGRAMS, - coverage: programs.length === 0, - prepare: !flags.includes("--skip-prepare"), + includeProviders, + includeRunnerEval, + includePluginSdk, + }); + } else { + const selectedPrograms = coverageOnly ? [] : programs.length > 0 ? programs : PROGRAMS; + const coverage = !noCoverage && (coverageOnly || forceCoverage || checkFiles.length > 0 || programs.length === 0); + process.exitCode = await typecheckTestProgramsAsync({ + root, + env, + programs: selectedPrograms, + coverage, + coverageFiles: checkFiles.length > 0 && !forceCoverage ? checkFiles : null, + prepare: !skipPrepare, + includeProviders, + includeRunnerEval, + includePluginSdk, + concurrency, + checkers, }); } } diff --git a/scripts/typecheck-test-programs.test.mjs b/scripts/typecheck-test-programs.test.mjs index 179892e81fa..158d32308f3 100644 --- a/scripts/typecheck-test-programs.test.mjs +++ b/scripts/typecheck-test-programs.test.mjs @@ -7,14 +7,18 @@ import { test } from "node:test"; import { fileURLToPath } from "node:url"; import { checkCoverage, + checkCoverageAsync, findUncheckedTests, LOCKED_PROVIDERS, PROGRAMS, prepareTestPrograms, PROVIDER_WORKSPACE, RESOLVE_ARGS, + SANDBOX_PROVIDER_PROGRAMS, SANDBOX_PROVIDERS, + selectTestPrograms, typecheckTestPrograms, + typecheckTestProgramsAsync, } from "./typecheck-test-programs.mjs"; const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -260,3 +264,150 @@ test("a real type error in a test-style program makes tsc exit non-zero", () => rmSync(directory, { recursive: true, force: true }); } }); + +test("selectTestPrograms skips sandbox providers and examples unless their inputs or SDK/shared changed", () => { + const full = selectTestPrograms(null); + assert.deepEqual(full.programs, PROGRAMS); + assert.equal(full.includeProviders, true); + assert.equal(full.checkCoverage, true); + + const serverOnly = selectTestPrograms(["server/src/services/issues.ts", "server/src/__tests__/issues.test.ts"]); + assert.deepEqual(serverOnly.programs, []); + assert.equal(serverOnly.includeProviders, false); + assert.equal(serverOnly.includeRunnerEval, false); + assert.equal(serverOnly.checkCoverage, false); + + const daytonaOnly = selectTestPrograms(["packages/plugins/sandbox-providers/daytona/src/plugin.ts"]); + assert.deepEqual(daytonaOnly.programs, ["packages/plugins/sandbox-providers/daytona/tsconfig.test.json"]); + assert.equal(daytonaOnly.includeProviders, true); + assert.equal(daytonaOnly.includeRunnerEval, false); + + const cloudflare = selectTestPrograms(["packages/plugins/sandbox-providers/cloudflare/src/plugin.ts"]); + assert.deepEqual(cloudflare.programs, [ + "packages/plugins/sandbox-providers/cloudflare/tsconfig.test.json", + "packages/plugins/sandbox-providers/cloudflare/bridge-template/tsconfig.test.json", + ]); + assert.equal(cloudflare.includeProviders, true); + + const sdkChange = selectTestPrograms(["packages/plugins/sdk/src/index.ts"]); + assert.equal(sdkChange.includeProviders, true); + for (const providerProgram of SANDBOX_PROVIDER_PROGRAMS) { + assert.ok(sdkChange.programs.includes(providerProgram), providerProgram); + } + assert.ok(sdkChange.programs.includes("packages/kv-demo-mcp-server/tsconfig.test.json")); + assert.ok(sdkChange.programs.includes("packages/plugins/examples/plugin-orchestration-smoke-example/tsconfig.test.json")); + + const uiWithTest = selectTestPrograms(["ui/src/components/Card.tsx", "ui/src/components/Card.test.tsx"]); + assert.deepEqual(uiWithTest.programs, ["tests/tsconfig.playwright.json"]); + assert.equal(uiWithTest.includeProviders, false); + assert.equal(uiWithTest.checkCoverage, true); + assert.deepEqual(uiWithTest.changedTestFiles, ["ui/src/components/Card.test.tsx"]); + + const tsconfigEdit = selectTestPrograms(["ui/tsconfig.json"]); + assert.equal(tsconfigEdit.checkCoverage, true); + assert.equal(tsconfigEdit.changedTestFiles, null); +}); + +test("prepareTestPrograms can skip sandbox provider installs, runner eval prep, and plugin SDK", () => { + const { options, calls } = harness(); + assert.equal( + prepareTestPrograms({ ...options, includeProviders: false, includeRunnerEval: false, includePluginSdk: false }), + 0, + ); + assert.deepEqual(calls.pnpm, []); + assert.equal(calls.linked, 0); + + const evalOnly = harness(); + assert.equal( + prepareTestPrograms({ ...evalOnly.options, includeProviders: false, includeRunnerEval: true, includePluginSdk: false }), + 0, + ); + assert.equal(evalOnly.calls.pnpm.length, 1); + assert.ok(evalOnly.calls.pnpm[0].args.includes("ensure:eval-build-deps")); + assert.equal(evalOnly.calls.linked, 0); +}); + +test("typecheckTestProgramsAsync runs programs concurrently up to the limit and preserves failure/signal semantics", async () => { + let active = 0; + let peak = 0; + const started = []; + const status = await typecheckTestProgramsAsync({ + root: "/repo", + programs: ["a/tsconfig.test.json", "b/tsconfig.test.json", "c/tsconfig.test.json", "d/tsconfig.test.json"], + prepare: false, + coverage: false, + concurrency: 2, + checkers: 1, + log: () => {}, + logError: () => {}, + runAsync: async (args) => { + started.push(args); + active += 1; + peak = Math.max(peak, active); + await new Promise((resolve) => setTimeout(resolve, 10)); + active -= 1; + return { status: args[1].startsWith("b/") ? 2 : 0, signal: null, output: "", durationMs: 10 }; + }, + }); + assert.equal(status, 2); + assert.equal(peak, 2); + assert.equal(started.length, 4); + assert.deepEqual(started[0], ["-p", "a/tsconfig.test.json", "--checkers", "1"]); + + // A killed compiler stops queuing further programs. + const killedStarts = []; + const killedStatus = await typecheckTestProgramsAsync({ + root: "/repo", + programs: ["a/tsconfig.test.json", "b/tsconfig.test.json", "c/tsconfig.test.json"], + prepare: false, + coverage: false, + concurrency: 1, + log: () => {}, + logError: () => {}, + runAsync: async (args) => { + killedStarts.push(args[1]); + return { status: 1, signal: "SIGKILL", output: "", durationMs: 5 }; + }, + }); + assert.equal(killedStatus, 1); + assert.deepEqual(killedStarts, ["a/tsconfig.test.json"]); +}); + +test("checkCoverageAsync checks targeted files with early exit and skips uninstalled providers", async () => { + const listed = []; + const covered = await checkCoverageAsync({ + root: "/repo", + includeProviders: false, + onlyFiles: ["ui/src/Card.test.tsx"], + concurrency: 1, + workspaceConfigs: () => ["cli/tsconfig.json", "ui/tsconfig.json"], + trackedFiles: () => ["ui/src/Card.test.tsx", "packages/plugins/sandbox-providers/daytona/src/x.test.ts"], + listFilesAsync: async (config) => { + listed.push(config); + return { + status: 0, + output: "", + files: config === "ui/tsconfig.json" ? ["ui/src/Card.test.tsx"] : [], + }; + }, + logError: () => {}, + }); + assert.deepEqual(covered, []); + // Prioritized ui/tsconfig.json first and stopped immediately once covered. + assert.deepEqual(listed, ["ui/tsconfig.json"]); + + const uncovered = await checkCoverageAsync({ + root: "/repo", + includeProviders: false, + onlyFiles: ["ui/src/Orphan.test.tsx"], + concurrency: 2, + workspaceConfigs: () => ["ui/tsconfig.json"], + trackedFiles: () => ["ui/src/Orphan.test.tsx"], + listFilesAsync: async (config) => { + assert.ok(!SANDBOX_PROVIDER_PROGRAMS.includes(config), `should skip uninstalled provider ${config}`); + return { status: 0, output: "", files: [] }; + }, + logError: () => {}, + }); + assert.deepEqual(uncovered, ["ui/src/Orphan.test.tsx"]); +}); diff --git a/scripts/typecheck-test-projects.mjs b/scripts/typecheck-test-projects.mjs index 50ffb7b5cfb..8748f166b2d 100644 --- a/scripts/typecheck-test-projects.mjs +++ b/scripts/typecheck-test-projects.mjs @@ -11,15 +11,18 @@ // --reuse-declarations skips the build. Use it only straight after a server // typecheck on the same commit, because stale declarations pass silently. // -// Usage: node scripts/typecheck-test-projects.mjs [--low-memory] [--reuse-declarations] [project ...] +// Usage: node scripts/typecheck-test-projects.mjs [--low-memory] [--checkers ] [--reuse-declarations] [project ...] import { spawnSync } from "node:child_process"; +import { existsSync, readdirSync, readFileSync } from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { LOW_MEMORY_VARIABLE, runTsc } from "./run-tsc.mjs"; import { runPnpm } from "./typecheck-low-memory.mjs"; import { isTestFile, typecheckLayers } from "../server/scripts/typecheck-layers.mjs"; +const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); + export const PROJECTS = [ "server/src/__tests__/helpers/maintenance", "tests/e2e", @@ -29,6 +32,310 @@ export const PROJECTS = [ "tests/speko-native", ]; +const GLOBAL_PROJECT_INPUTS = new Set([ + "package.json", + "pnpm-lock.yaml", + "pnpm-workspace.yaml", + "tsconfig.base.json", + ".npmrc", + "scripts/run-tsc.mjs", + "scripts/ci-typecheck-lane.mjs", + "scripts/typecheck-test-projects.mjs", + "server/scripts/typecheck-layers.mjs", + "server/src/types/express.d.ts", + "server/tsconfig.json", +]); + +const SOURCE_FILE_PATTERN = /\.(?:[cm]?[jt]s|[jt]sx)$/; +const RESOLVE_EXTENSIONS = [".ts", ".tsx", ".mts", ".cts", ".mjs", ".cjs", ".js", ".jsx", ".json"]; +const IMPORT_SPECIFIER_PATTERN = + /(?:(?:import|export)\s+(?:type\s+)?(?:[^;]*?\s+from\s+)?|import\s*\()[\s\n]*["']([^"']+)["']/g; + +const toPosix = (value) => value.split(path.sep).join("/"); +const stripSourceExtension = (value) => value.replace(/\.(?:[cm]?[jt]s|[jt]sx)$/, ""); + +const rootGraphCaches = new Map(); + +function getRootCache(root) { + let cache = rootGraphCaches.get(root); + if (cache) return cache; + cache = { + dirFiles: new Map(), + fileEdges: new Map(), + workspacePackages: null, + projects: new Map(), + }; + rootGraphCaches.set(root, cache); + return cache; +} + +function getDirFiles(cache, dir) { + let set = cache.dirFiles.get(dir); + if (set) return set; + set = new Set(); + try { + for (const entry of readdirSync(dir, { withFileTypes: true })) { + if (entry.isFile()) set.add(entry.name); + } + } catch {} + cache.dirFiles.set(dir, set); + return set; +} + +function hasFile(cache, absPath) { + return getDirFiles(cache, path.dirname(absPath)).has(path.basename(absPath)); +} + +function loadWorkspacePackages(root, cache) { + if (cache.workspacePackages) return cache.workspacePackages; + const map = new Map(); + const registerDir = (absDir) => { + const pkgPath = path.join(absDir, "package.json"); + if (!hasFile(cache, pkgPath)) return; + try { + const pkg = JSON.parse(readFileSync(pkgPath, "utf8")); + if (typeof pkg?.name === "string" && pkg.name.length > 0) { + const relDir = toPosix(path.relative(root, absDir)); + map.set(pkg.name, relDir ? `${relDir}/` : ""); + } + } catch {} + }; + const walkPackages = (absDir, depth) => { + if (depth > 3) return; + registerDir(absDir); + let entries; + try { + entries = readdirSync(absDir, { withFileTypes: true }); + } catch { + return; + } + for (const entry of entries) { + if (!entry.isDirectory() || entry.name === "node_modules" || entry.name === "dist" || entry.name.startsWith(".")) { + continue; + } + walkPackages(path.join(absDir, entry.name), depth + 1); + } + }; + for (const top of ["cli", "server", "ui"]) registerDir(path.join(root, top)); + walkPackages(path.join(root, "packages"), 0); + cache.workspacePackages = map; + return map; +} + +function resolveCandidateFile(cache, basePath) { + if (hasFile(cache, basePath)) return basePath; + const stripped = basePath.replace(/\.(?:[cm]?js|jsx)$/, ""); + for (const ext of RESOLVE_EXTENSIONS) { + if (hasFile(cache, `${stripped}${ext}`)) return `${stripped}${ext}`; + } + for (const ext of RESOLVE_EXTENSIONS) { + const indexPath = path.join(stripped, `index${ext}`); + if (hasFile(cache, indexPath)) return indexPath; + } + return null; +} + +function resolvePathAliases(specifier, projectDir, pathsConfig) { + if (!pathsConfig || typeof pathsConfig !== "object") return []; + const targets = []; + for (const [pattern, replacements] of Object.entries(pathsConfig)) { + if (!Array.isArray(replacements)) continue; + const starIndex = pattern.indexOf("*"); + if (starIndex === -1) { + if (specifier !== pattern) continue; + for (const replacement of replacements) { + if (typeof replacement === "string") targets.push(path.resolve(projectDir, replacement)); + } + continue; + } + const prefix = pattern.slice(0, starIndex); + const suffix = pattern.slice(starIndex + 1); + if (!specifier.startsWith(prefix) || !specifier.endsWith(suffix)) continue; + const captured = specifier.slice(prefix.length, specifier.length - suffix.length); + for (const replacement of replacements) { + if (typeof replacement === "string") { + targets.push(path.resolve(projectDir, replacement.replace("*", captured))); + } + } + } + return targets; +} + +function extractFileSpecifiers(cache, absFile) { + let cached = cache.fileEdges.get(absFile); + if (cached) return cached; + const specifiers = []; + try { + const source = readFileSync(absFile, "utf8"); + IMPORT_SPECIFIER_PATTERN.lastIndex = 0; + let match; + while ((match = IMPORT_SPECIFIER_PATTERN.exec(source))) { + specifiers.push(match[1].split("?")[0]); + } + } catch {} + cache.fileEdges.set(absFile, specifiers); + return specifiers; +} + +function walkSourceFiles(absDir, out = []) { + let entries; + try { + entries = readdirSync(absDir, { withFileTypes: true }); + } catch { + return out; + } + for (const entry of entries) { + if (entry.name === "node_modules" || entry.name === "dist") continue; + const full = path.join(absDir, entry.name); + if (entry.isDirectory()) walkSourceFiles(full, out); + else if (SOURCE_FILE_PATTERN.test(entry.name)) out.push(full); + } + return out; +} + +function expandTsconfigIncludes(root, projectDir, includeEntries, cache) { + const files = []; + const patterns = []; + if (!Array.isArray(includeEntries)) return { files, patterns }; + for (const entry of includeEntries) { + if (typeof entry !== "string") continue; + const resolved = path.resolve(projectDir, entry); + if (!entry.includes("*")) { + if (hasFile(cache, resolved)) files.push(resolved); + const rel = toPosix(path.relative(root, resolved)); + if (!rel.startsWith("..")) patterns.push(rel); + continue; + } + // Single-segment wildcard pattern (e.g. "../../maintenance-*.test.ts", "../../server/test-baselines/*.ts") + if (!entry.includes("**")) { + const dir = path.dirname(resolved); + const basePattern = path.basename(resolved); + const regex = new RegExp(`^${basePattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*")}$`); + for (const fileName of getDirFiles(cache, dir)) { + if (regex.test(fileName)) files.push(path.join(dir, fileName)); + } + const relDir = toPosix(path.relative(root, dir)); + if (!relDir.startsWith("..")) { + patterns.push({ dir: relDir ? `${relDir}/` : "", regex }); + } + } + } + return { files, patterns }; +} + +export function collectProjectDependencies(project, root = REPO_ROOT) { + const cache = getRootCache(root); + const existing = cache.projects.get(project); + if (existing) return existing; + + const projectDir = path.join(root, project); + if (!existsSync(projectDir)) return null; + + const workspacePackages = loadWorkspacePackages(root, cache); + let tsconfig = null; + const tsconfigPath = path.join(projectDir, "tsconfig.json"); + if (hasFile(cache, tsconfigPath)) { + try { + tsconfig = JSON.parse(readFileSync(tsconfigPath, "utf8")); + } catch {} + } + const pathsConfig = tsconfig?.compilerOptions?.paths ?? null; + const { files: includeFiles, patterns: includePatterns } = expandTsconfigIncludes( + root, + projectDir, + tsconfig?.include, + cache, + ); + + const visited = new Set(); + const unresolvedStems = new Set(); + const prefixes = new Set([`${toPosix(project)}/`]); + const queue = [...walkSourceFiles(projectDir), ...includeFiles]; + for (const file of queue) visited.add(file); + + const enqueueTarget = (absBase) => { + const resolved = resolveCandidateFile(cache, absBase); + if (resolved) { + if (!resolved.includes(`${path.sep}node_modules${path.sep}`) && !visited.has(resolved)) { + visited.add(resolved); + queue.push(resolved); + } + return; + } + const rel = toPosix(path.relative(root, absBase)); + if (!rel.startsWith("..") && !rel.includes("node_modules/")) { + unresolvedStems.add(stripSourceExtension(rel)); + } + }; + + while (queue.length > 0) { + const current = queue.pop(); + const specifiers = extractFileSpecifiers(cache, current); + for (const specifier of specifiers) { + if (specifier.startsWith(".")) { + enqueueTarget(path.resolve(path.dirname(current), specifier)); + continue; + } + const aliasTargets = resolvePathAliases(specifier, projectDir, pathsConfig); + if (aliasTargets.length > 0) { + for (const target of aliasTargets) enqueueTarget(target); + continue; + } + const pkgName = specifier.startsWith("@") + ? specifier.split("/").slice(0, 2).join("/") + : specifier.split("/")[0]; + const workspaceDir = workspacePackages.get(pkgName); + if (workspaceDir) prefixes.add(workspaceDir); + } + } + + const files = new Set(); + for (const absFile of visited) { + const rel = toPosix(path.relative(root, absFile)); + if (!rel.startsWith("..")) files.add(rel); + } + + const deps = { files, unresolvedStems, prefixes, includePatterns }; + cache.projects.set(project, deps); + return deps; +} + +function matchesProjectDependencies(file, deps) { + if (deps.files.has(file)) return true; + if (deps.unresolvedStems.has(stripSourceExtension(file))) return true; + for (const prefix of deps.prefixes) { + if (file === prefix || file.startsWith(prefix)) return true; + } + for (const pattern of deps.includePatterns) { + if (typeof pattern === "string") { + if (file === pattern) return true; + } else if (file.startsWith(pattern.dir)) { + const rest = file.slice(pattern.dir.length); + if (!rest.includes("/") && pattern.regex.test(rest)) return true; + } + } + return false; +} + +/** + * Selects the test projects affected by `changedFiles` in PR mode using each project's + * static import graph and tsconfig includes. Returns all `projects` when `changedFiles` + * is null/undefined or touches global inputs. + */ +export function selectTestProjects(changedFiles, projects = PROJECTS, { root = REPO_ROOT } = {}) { + if (!Array.isArray(changedFiles)) return [...projects]; + const normalizedFiles = changedFiles.map(toPosix); + if (normalizedFiles.some((file) => GLOBAL_PROJECT_INPUTS.has(file) || file.startsWith("patches/"))) { + return [...projects]; + } + return projects.filter((project) => { + const deps = collectProjectDependencies(project, root); + // Fail closed for any new or missing project whose import graph cannot be inspected. + if (!deps) return true; + return normalizedFiles.some((file) => matchesProjectDependencies(file, deps)); + }); +} + // The same steps as the server's typecheck script. export const PREPARE_STEPS = [ ["--filter", "@paperclipai/paperclip-runner", "run", "build:typescript"], @@ -65,6 +372,7 @@ export function typecheckTestProjects({ root, projects = PROJECTS, reuseDeclarations = false, + checkers, env = process.env, pnpm = runPnpm, run = runTsc, @@ -82,6 +390,7 @@ export function typecheckTestProjects({ const layers = typecheckLayers({ serverRoot, declarationsOnly: true, + checkers, run: (args, options) => run(args, { ...options, env }), log, }); @@ -89,11 +398,12 @@ export function typecheckTestProjects({ if (layers !== 0) return layers; } + const checkerArgs = Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : []; let exitCode = 0; for (const project of projects) { log(`typecheck:test-projects: ${project}`); const config = path.posix.join(project, "tsconfig.layers.json"); - const { status, signal } = run(["-p", config], { cwd: root, env }); + const { status, signal } = run(["-p", config, ...checkerArgs], { cwd: root, env }); if (signal) return status || 1; if (status !== 0) exitCode = status; @@ -117,13 +427,34 @@ export function typecheckTestProjects({ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - const flags = args.filter((arg) => arg.startsWith("--")); - const projects = args.filter((arg) => !arg.startsWith("--")); - const unknownFlags = flags.filter((flag) => !["--low-memory", "--reuse-declarations"].includes(flag)); + let lowMemory = false; + let reuseDeclarations = false; + let checkers; + const projects = []; + const unknownFlags = []; + let invalidCheckers = false; + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (arg === "--low-memory") { + lowMemory = true; + } else if (arg === "--reuse-declarations") { + reuseDeclarations = true; + } else if (arg === "--checkers") { + checkers = Number(args[++i]); + if (!Number.isInteger(checkers) || checkers < 1) invalidCheckers = true; + } else if (arg.startsWith("--")) { + unknownFlags.push(arg); + } else { + projects.push(arg); + } + } const unknown = projects.filter((project) => !PROJECTS.includes(project)); if (unknownFlags.length > 0) { console.error(`Unknown option: ${unknownFlags.join(", ")}`); process.exitCode = 2; + } else if (invalidCheckers) { + console.error("--checkers requires a positive integer"); + process.exitCode = 2; } else if (unknown.length > 0) { console.error(`Unknown project: ${unknown.join(", ")}. Known projects: ${PROJECTS.join(", ")}`); process.exitCode = 2; @@ -131,8 +462,9 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me process.exitCode = typecheckTestProjects({ root: path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), projects: projects.length > 0 ? projects : PROJECTS, - reuseDeclarations: flags.includes("--reuse-declarations"), - env: args.includes("--low-memory") ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env, + reuseDeclarations, + checkers, + env: lowMemory ? { ...process.env, [LOW_MEMORY_VARIABLE]: "1" } : process.env, }); } } diff --git a/server/scripts/typecheck-layers.mjs b/server/scripts/typecheck-layers.mjs index 840b1a5c142..dbd7a634d72 100644 --- a/server/scripts/typecheck-layers.mjs +++ b/server/scripts/typecheck-layers.mjs @@ -25,7 +25,7 @@ // `tsconfig.layers.json` that references tsconfig.declarations.json in the output // directory. --declarations-only builds those layers and skips the test layers. // -// Usage: node scripts/typecheck-layers.mjs [--declarations-only] +// Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer ] [--checkers ] import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import path from "node:path"; @@ -260,14 +260,18 @@ export function listLayers(serverRoot) { return planServerLayers(serverRoot).map((layer) => ({ name: layer.name, emitsDeclarations: emitsDeclarations(layer) })); } -function checkOneLayer({ serverRoot, name, run, log, logError }) { +function checkerTscArgs(checkers) { + return Number.isInteger(checkers) && checkers >= 1 ? ["--checkers", String(checkers)] : []; +} + +function checkOneLayer({ serverRoot, name, checkers, run, log, logError }) { const config = path.join(OUTPUT_DIRECTORY, `tsconfig.${name}.json`); if (!existsSync(path.join(serverRoot, config))) { logError(`typecheck:layers: ${config} does not exist. Run typecheck-layers.mjs --declarations-only first.`); return 2; } log(`typecheck:layers: ${name}`); - const { status, signal } = run(["-p", config], { cwd: serverRoot }); + const { status, signal } = run(["-p", config, ...checkerTscArgs(checkers)], { cwd: serverRoot }); if (signal) { logError(`typecheck:layers: ${name}: compiler terminated by ${signal} (tsc -p ${config}, cwd: ${serverRoot})`); return status || 1; @@ -279,11 +283,12 @@ export function typecheckLayers({ serverRoot, declarationsOnly = false, layer: only, + checkers, run = runTsc, log = console.log, logError = console.error, }) { - if (only) return checkOneLayer({ serverRoot, name: only, run, log, logError }); + if (only) return checkOneLayer({ serverRoot, name: only, checkers, run, log, logError }); const layers = planServerLayers(serverRoot); const planned = new Set(layers.map((layer) => layer.name)); const emptyLayers = new Set(["below", "cycle", "above", "tests"].filter((name) => !planned.has(name))); @@ -305,12 +310,13 @@ export function typecheckLayers({ `${JSON.stringify(declarationsConfig(layers), null, 2)}\n`, ); + const extraArgs = checkerTscArgs(checkers); let exitCode = 0; for (const layer of layers) { if (declarationsOnly && !emitsDeclarations(layer)) continue; log(`typecheck:layers: ${layer.name} (${layer.sourceFiles.length} files)`); const config = path.join(OUTPUT_DIRECTORY, `tsconfig.${layer.name}.json`); - const { status, signal } = run(["-p", config], { cwd: serverRoot }); + const { status, signal } = run(["-p", config, ...extraArgs], { cwd: serverRoot }); // A killed process leaves no declarations, so later layers would only add noise. if (signal) { logError(`typecheck:layers: ${layer.name}: compiler terminated by ${signal} (tsc -p ${config}, cwd: ${serverRoot})`); @@ -325,20 +331,34 @@ export function typecheckLayers({ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { const args = process.argv.slice(2); - const layerIndex = args.indexOf("--layer"); - const layer = layerIndex === -1 ? undefined : args[layerIndex + 1]; - const rest = args.filter((_, index) => layerIndex === -1 || (index !== layerIndex && index !== layerIndex + 1)); - const valid = - rest.every((arg) => arg === "--declarations-only") && - (layerIndex === -1 || (Boolean(layer) && !layer.startsWith("--") && rest.length === 0)); + let declarationsOnly = false; + let layer; + let checkers; + let valid = true; + for (let i = 0; i < args.length; i += 1) { + const arg = args[i]; + if (arg === "--declarations-only") { + declarationsOnly = true; + } else if (arg === "--layer") { + layer = args[++i]; + if (!layer || layer.startsWith("--")) valid = false; + } else if (arg === "--checkers") { + checkers = Number(args[++i]); + if (!Number.isInteger(checkers) || checkers < 1) valid = false; + } else { + valid = false; + } + } + if (declarationsOnly && layer) valid = false; if (!valid) { - console.error("Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer ]"); + console.error("Usage: node scripts/typecheck-layers.mjs [--declarations-only | --layer ] [--checkers ]"); process.exitCode = 2; } else { process.exitCode = typecheckLayers({ serverRoot: path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."), - declarationsOnly: args.includes("--declarations-only"), + declarationsOnly, layer, + checkers, }); } } diff --git a/server/scripts/typecheck-layers.test.mjs b/server/scripts/typecheck-layers.test.mjs index 123d5e6a928..86baa6b3a3d 100644 --- a/server/scripts/typecheck-layers.test.mjs +++ b/server/scripts/typecheck-layers.test.mjs @@ -8,7 +8,13 @@ import { afterEach, describe, expect, it } from "vitest"; import { emitOnlyTscArgs, lowMemoryTscArgs, runTsc } from "../../scripts/run-tsc.mjs"; import { STEPS, typecheckLowMemory } from "../../scripts/typecheck-low-memory.mjs"; -import { findServerSource, PREPARE_STEPS, PROJECTS, typecheckTestProjects } from "../../scripts/typecheck-test-projects.mjs"; +import { + findServerSource, + PREPARE_STEPS, + PROJECTS, + selectTestProjects, + typecheckTestProjects, +} from "../../scripts/typecheck-test-projects.mjs"; import { declarationsConfig, layerConfig, listLayers, listSourceFiles, planLayers, readImports, typecheckLayers } from "./typecheck-layers.mjs"; const serverRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); @@ -318,6 +324,41 @@ describe("typecheckLayers", () => { ]); }); + it("passes --checkers to tsc for declaration layers and single-layer checks when requested", () => { + const root = serverFixture(); + const declArgs = []; + expect( + typecheckLayers({ + serverRoot: root, + declarationsOnly: true, + checkers: 2, + log: () => {}, + run: (args) => { + declArgs.push(args); + return { status: 0, signal: null }; + }, + }), + ).toBe(0); + expect(declArgs.every((args) => args.slice(-2).join(" ") === "--checkers 2")).toBe(true); + + const layerArgs = []; + expect( + typecheckLayers({ + serverRoot: root, + layer: "tests", + checkers: 1, + log: () => {}, + run: (args) => { + layerArgs.push(args); + return { status: 0, signal: null }; + }, + }), + ).toBe(0); + expect(layerArgs).toEqual([ + ["-p", path.join("node_modules", ".cache", "paperclip-typecheck", "tsconfig.tests.json"), "--checkers", "1"], + ]); + }); + it("reports type errors from every layer", () => { const root = serverFixture(); const configs = []; @@ -845,6 +886,40 @@ describe("typecheckTestProjects", () => { path.join(serverRoot, "node_modules", ".cache", "paperclip-typecheck", "tsconfig.declarations.json"), ]); }); + + it("forwards --checkers to tsc when checking test projects", () => { + const tscArgs = []; + const status = typecheckTestProjects({ + root: repositoryFixture(), + projects: ["tests/a"], + reuseDeclarations: true, + checkers: 1, + log: () => {}, + listFiles: () => ({ status: 0, files: [] }), + run: (args) => { + tscArgs.push(args); + return { status: 0, signal: null }; + }, + }); + expect(status).toBe(0); + expect(tscArgs).toEqual([["-p", "tests/a/tsconfig.layers.json", "--checkers", "1"]]); + }); + + it("selectTestProjects skips untouched tests/* projects in PR mode and fails closed on global or unknown inputs", () => { + expect(selectTestProjects(null)).toEqual(PROJECTS); + expect(selectTestProjects(["tsconfig.base.json"])).toEqual(PROJECTS); + expect(selectTestProjects(["server/src/services/isolated-unreferenced-feature.ts"])).toEqual([]); + expect(selectTestProjects(["server/src/services/issues.ts"])).toContain("server/src/__tests__/helpers/maintenance"); + expect(selectTestProjects(["server/src/services/issues.ts"])).toContain("tests/runner-e2e"); + expect(selectTestProjects(["ui/src/lib/company-routes.ts"])).toEqual(["tests/runner-e2e"]); + expect(selectTestProjects(["ui/src/components/Sidebar.tsx"])).toEqual([]); + expect(selectTestProjects(["tests/restart-chaos/invariants.ts"])).toEqual(["tests/restart-chaos"]); + expect(selectTestProjects(["tests/lifecycle-baseline/authority.test.ts"])).toEqual(["tests/lifecycle-baseline"]); + expect(selectTestProjects(["tests/speko-native/app.ts"])).toEqual(["tests/speko-native"]); + expect(selectTestProjects(["tests/runner-e2e/catalog.ts"])).toEqual(["tests/e2e", "tests/restart-chaos", "tests/runner-e2e"]); + expect(selectTestProjects(["packages/shared/src/constants.ts"])).toEqual(PROJECTS); + expect(selectTestProjects(["ui/src/components/Sidebar.tsx"], ["tests/custom-new"])).toEqual(["tests/custom-new"]); + }); }); describe("runTsc", () => { diff --git a/server/src/__tests__/agent-observability-status-guidance.test.ts b/server/src/__tests__/agent-observability-status-guidance.test.ts deleted file mode 100644 index db82ffdfb77..00000000000 --- a/server/src/__tests__/agent-observability-status-guidance.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { expect, it } from "vitest"; -import { runnerApiOperation, searchRunnerApi, withCompanyPagePaths } from "../services/native-runtime/runner-api-catalog.js"; - -const STATUS = "GET /api/companies/{companyId}/observability/status"; - -it.each([ - "test collector configuration", - "agent traces otlp collector", - "observability export enabled", -])("search %j finds the agent-readable trace export status", (query) => { - expect(searchRunnerApi({ query, limit: 10 }).results.map(row => row.operationId)).toContain(STATUS); -}); - -it("lets the company's agents read trace export status, and keeps the settings board-only", () => { - expect(runnerApiOperation(STATUS).authorization).toEqual({ actor: "board_or_agent" }); - expect(runnerApiOperation("GET /api/companies/{companyId}/observability").authorization).toEqual({ actor: "board" }); -}); - -it("hands the agent real company page paths instead of the // placeholder", () => { - const found = searchRunnerApi({ query: STATUS, limit: 1 }); - expect(JSON.stringify(found)).toContain("//company/settings"); - const localized = withCompanyPagePaths(found, "COM"); - expect(JSON.stringify(localized)).not.toContain(""); - expect(localized.results[0]!.description).toContain("/COM/company/settings"); - // The shared catalog is not mutated. - expect(runnerApiOperation(STATUS).description).toContain("//company/settings"); - expect(withCompanyPagePaths(found, null)).toBe(found); -}); diff --git a/server/src/__tests__/assistant-connections-guidance.test.ts b/server/src/__tests__/assistant-connections-guidance.test.ts deleted file mode 100644 index 563b3e04891..00000000000 --- a/server/src/__tests__/assistant-connections-guidance.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { expect, it } from "vitest"; -import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; -import { validateRunnerApiCall } from "../services/native-runtime/runner-api-client.js"; - -const context = { companyId: "00000000-0000-4000-8000-000000000121", issueId: "00000000-0000-4000-8000-000000000122", runId: "00000000-0000-4000-8000-000000000123", workMode: "standard" }; - -it("tells agents searching for assistant disconnection that only the person can do it, and where", () => { - for (const query of ["chat client assistant disconnect connection", "assistant connections revoke list", "mcp connection revoke REST"]) { - const found = searchRunnerApi({ query, limit: 10 }).results; - const revoke = found.find(row => row.operationId === "DELETE /api/mcp/connections/{id}"); - expect(revoke, query).toBeDefined(); - expect(revoke!.description).toContain("[Assistant connections](//apps/assistant-connection)"); - expect(revoke!.description).toContain("only the signed-in person"); - expect(revoke!.description).toContain("Do not search for another route"); - expect(revoke!.description).toContain("OAuth token revocation sent by the connected assistant itself"); - expect(revoke!.description).toMatch(/already created keep their assignees and running work/); - } - const list = searchRunnerApi({ query: "GET /api/mcp/connections" }).results[0]!; - expect(list.description).toContain("[Assistant connections](//apps/assistant-connection)"); -}); - -it("says the call_api protocol rejection is final instead of inviting another search", () => { - expect(() => validateRunnerApiCall({ operationId: "GET /api/mcp/connections" }, context)) - .toThrow(/no other API route substitutes for it\. Read its catalog description for details\./); -}); - -it("points at the catalog description only when the protocol endpoint has one", () => { - const undocumented = searchRunnerApi({ query: "POST /api/mcp/project-tools" }).results.find(row => row.operationId === "POST /api/mcp/project-tools"); - expect(undocumented?.description).toBe(""); - let message = ""; - try { validateRunnerApiCall({ operationId: "POST /api/mcp/project-tools" }, context); } catch (error) { message = (error as Error).message; } - expect(message).toContain("no other API route substitutes for it."); - expect(message).not.toContain("catalog description"); -}); - -it("does not claim a non-guidance protocol description says who can use the endpoint", () => { - let message = ""; - try { validateRunnerApiCall({ operationId: "GET /api/companies/{companyId}/events/ws" }, context); } catch (error) { message = (error as Error).message; } - expect(message).toContain("Read its catalog description for details."); - expect(message).not.toContain("who can use it"); -}); diff --git a/server/src/__tests__/board-skill-ui-guidance.test.ts b/server/src/__tests__/board-skill-ui-guidance.test.ts deleted file mode 100644 index d177137832d..00000000000 --- a/server/src/__tests__/board-skill-ui-guidance.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { readFileSync } from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { describe, expect, it } from "vitest"; - -const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); -const read = (relPath: string) => readFileSync(path.join(repoRoot, relPath), "utf8"); - -// Chat agents answer "how do I find X?" from the board skill; without this section they -// had no source for the web UI's quick search and told people to ask in chat instead. -describe("paperclip-board skill web UI guidance", () => { - const skill = read("skills/paperclip-board/SKILL.md"); - const palette = read("ui/src/components/CommandPalette.tsx"); - const section = skill.slice(skill.indexOf("## Finding Things in the Web UI"), skill.indexOf("## Presentation Rules")); - - it("documents the quick-search shortcut the command palette actually binds", () => { - expect(section.length).toBeGreaterThan(0); - expect(palette).toMatch(/e\.key === "k" && \(e\.metaKey \|\| e\.ctrlKey\)/); - expect(section).toContain("**Cmd+K**"); - expect(section).toContain("**Ctrl+K**"); - }); - - it("documents the handoff to full search and the search route it opens", () => { - expect(palette).toMatch(/event\.key === "Enter" && \(event\.metaKey \|\| event\.ctrlKey\)/); - expect(palette).toContain("Search all for"); - expect(section).toContain("**Search all**"); - expect(section).toContain("Cmd/Ctrl+Enter"); - expect(read("ui/src/App.tsx")).toContain(' { - // The classic sidebar Search item is a link to the full search page, not the overlay. - expect(read("ui/src/components/Sidebar.tsx")).toMatch(/]*\bto="\/search" label="Search"/); - expect(section).toMatch(/sidebar \*\*Search\*\* item[^\n]*opens the full search page/); - expect(section).not.toMatch(/search icon[^\n]*opens over the current page/i); - }); - - it("does not claim operators narrow the quick-search results", () => { - // The palette sends only the parsed free text; operators apply after the full-search handoff. - expect(palette).toMatch(/issuesApi\.list\(selectedCompanyId!, \{ q: quickSearchQuery, limit: 10/); - expect(section).toContain("they do not narrow the quick-search results"); - }); - - it("tells the agent it cannot operate the person's browser", () => { - expect(section).toMatch(/cannot press keys, focus fields, or open the palette/); - }); - - it("is discoverable from the skill description", () => { - const frontmatter = skill.slice(0, skill.indexOf("\n---", 4)); - expect(frontmatter).toContain("finding things in the Paperclip web UI"); - }); -}); diff --git a/server/src/__tests__/chat-channels.integration.test.ts b/server/src/__tests__/chat-channels.integration.test.ts index 43981c3a167..3b43fae37df 100644 --- a/server/src/__tests__/chat-channels.integration.test.ts +++ b/server/src/__tests__/chat-channels.integration.test.ts @@ -67973,30 +67973,31 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { }); it.each([ - "settled", - "distinct_account", - "null_account", - "wrong_account", - "missing_account", - "malformed_account", - "missing_thread", - "older_warm_run", - "committed_marker", - "foreign_marker", - "prepared_marker", - "pending_lease_cleanup", - "missing_receipt", - "activation_prepared", - "changed_checkpoint", - "late_event", - "leased", - "wrong_thread", - "source_edited", - "different_error", - ].flatMap((mode) => [ - "runner_state_identity_mismatch", - "runner_state_identity_mismatch: prior_owner_active", - ].map((errorMessage) => ({ mode, errorMessage }))))( + ...[ + "settled", + "distinct_account", + "null_account", + "wrong_account", + "missing_account", + "malformed_account", + "missing_thread", + "older_warm_run", + "committed_marker", + "foreign_marker", + "prepared_marker", + "pending_lease_cleanup", + "missing_receipt", + "activation_prepared", + "changed_checkpoint", + "late_event", + "leased", + "wrong_thread", + "source_edited", + "different_error", + ].map((mode) => ({ mode, errorMessage: "runner_state_identity_mismatch" })), + { mode: "settled", errorMessage: "runner_state_identity_mismatch: prior_owner_active" }, + { mode: "pending_lease_cleanup", errorMessage: "runner_state_identity_mismatch: prior_owner_active" }, + ])( "retries only the original pre-provider Telegram request after exact cleanup: $mode ($errorMessage)", async ({ mode, errorMessage }) => { const context = await committedChatResponseRecoveryFixture("telegram"); @@ -68392,8 +68393,10 @@ describeEmbeddedPostgres("chat channel control-plane integration", () => { }, ); - it.each((["github", "telegram"] as const).flatMap(provider => - (["unregistered", "pending", "historical_sibling", "foreign_source_hold", "automatic_scheduled", "automatic_running", "automatic_awaiting_evidence", "exhausted", "wrong_generation", "paused_endpoint", "paused_after_wait", "paused_agent_after_wait", "edited_after_wait", "superseded_after_wait"] as const).map(gate => ({ provider, gate }))))( + it.each([ + ...(["unregistered", "pending", "historical_sibling", "foreign_source_hold", "automatic_scheduled", "automatic_running", "automatic_awaiting_evidence", "exhausted", "wrong_generation", "paused_endpoint", "paused_after_wait", "paused_agent_after_wait", "edited_after_wait", "superseded_after_wait"] as const).map(gate => ({ provider: "github" as const, gate })), + ...(["unregistered", "pending", "paused_endpoint", "superseded_after_wait"] as const).map(gate => ({ provider: "telegram" as const, gate })), + ])( "holds an ordinary $provider Retry behind its exact remote recovery: $gate", async ({ provider, gate }) => { const context = await failedChatRetryFixture(provider, undefined, true); try { diff --git a/server/src/__tests__/cli-auth-terminal-guidance.test.ts b/server/src/__tests__/cli-auth-terminal-guidance.test.ts deleted file mode 100644 index e9e28151590..00000000000 --- a/server/src/__tests__/cli-auth-terminal-guidance.test.ts +++ /dev/null @@ -1,27 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; - -// A chat agent asked to "connect my terminal to Paperclip as me" searched the -// API catalog, found the CLI auth operations without any statement of who starts -// the flow, and spent its whole turn reading source code to find the command. -describe("CLI terminal login guidance in the agent API catalog", () => { - it.each([ - "connect my terminal to Paperclip as me", - "terminal connect CLI login pair device link personal access", - "cli-auth login code approve session token terminal", - ])("search %j finds the person-run CLI login command", query => { - const { results } = searchRunnerApi({ query, limit: 5 }); - const challenge = results.find(operation => operation.operationId === "POST /api/cli-auth/challenges"); - expect(challenge, query).toBeDefined(); - expect(challenge!.description).toContain("`npx paperclipai auth login --api-base `"); - expect(challenge!.description).toContain("never by an agent on their behalf"); - expect(challenge!.description).toContain("leave it as that placeholder instead of looking it up"); - expect(challenge!.description).toMatch(/never hand out an agent key, create or approve a challenge yourself, or ask for the person's password/); - }); - - it("tells agents that only the signed-in person can approve", () => { - const { results } = searchRunnerApi({ query: "POST /api/cli-auth/challenges/{id}/approve" }); - expect(results[0]?.description).toContain("agent API keys receive 401"); - expect(results[0]?.description).toContain("`npx paperclipai auth login`"); - }); -}); diff --git a/server/src/__tests__/commentary-permission-migration.test.ts b/server/src/__tests__/commentary-permission-migration.test.ts deleted file mode 100644 index 02d0bc50fe0..00000000000 --- a/server/src/__tests__/commentary-permission-migration.test.ts +++ /dev/null @@ -1,53 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import { eq, sql } from "drizzle-orm"; -import { afterAll, beforeAll, describe, expect, it } from "vitest"; -import { companies, companyMemberships, createDb, principalPermissionGrants } from "@paperclipai/db"; -import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; - -describe("commentary permission upgrade", () => { - let temporary: Awaited>; - let db: ReturnType; - - beforeAll(async () => { - temporary = await startEmbeddedPostgresTestDatabase("paperclip-commentary-permission-"); - db = createDb(temporary.connectionString); - }, 90_000); - - afterAll(async () => { await temporary?.cleanup(); }); - - it("grants existing active humans commentary access once without widening audit or existing scopes", async () => { - const companyId = randomUUID(), otherCompanyId = randomUUID(); - await db.insert(companies).values([ - { id: companyId, name: "Commentary upgrade", issuePrefix: "UPG" }, - { id: otherCompanyId, name: "Other company", issuePrefix: "OTH" }, - ]); - const activeHumans = ["owner", "admin", "operator", "viewer", "member", null].map((membershipRole) => ({ - companyId, principalType: "user", principalId: randomUUID(), membershipRole, status: "active", - })); - const excluded = [ - { companyId, principalType: "user", principalId: randomUUID(), membershipRole: "viewer", status: "inactive" }, - { companyId, principalType: "agent", principalId: randomUUID(), membershipRole: "member", status: "active" }, - { companyId: otherCompanyId, principalType: "user", principalId: activeHumans[0].principalId, membershipRole: "owner", status: "inactive" }, - ]; - await db.insert(companyMemberships).values([...activeHumans, ...excluded]); - const [existing] = await db.insert(principalPermissionGrants).values({ - companyId, principalType: "user", principalId: activeHumans[0].principalId, - permissionKey: "commentary:view", scope: { agentIds: [randomUUID()] }, grantedByUserId: "custom-author", - }).returning(); - const migration = await readFile(new URL( - "../../../packages/db/src/migrations/0359_commentary_view_human_defaults.sql", import.meta.url, - ), "utf8"); - await db.execute(sql.raw(migration)); - const first = await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); - expect(first).toHaveLength(activeHumans.length); - expect(first.every((grant) => grant.permissionKey === "commentary:view")).toBe(true); - expect(first.map((grant) => grant.principalId).sort()).toEqual(activeHumans.map((member) => member.principalId).sort()); - expect(first.find((grant) => grant.id === existing.id)).toEqual(existing); - expect(await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, otherCompanyId))).toEqual([]); - - await db.execute(sql.raw(migration)); - const second = await db.select().from(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId)); - expect(second.sort((a, b) => a.id.localeCompare(b.id))).toEqual(first.sort((a, b) => a.id.localeCompare(b.id))); - }); -}); diff --git a/server/src/__tests__/company-model-service-settings-guidance.test.ts b/server/src/__tests__/company-model-service-settings-guidance.test.ts deleted file mode 100644 index ae66a624877..00000000000 --- a/server/src/__tests__/company-model-service-settings-guidance.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { readFileSync } from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { expect, it } from "vitest"; -import { runnerApiCatalog, searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; - -const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); - -// An agent asked to turn on a company model service cannot do it and must link the page that holds the control. -// The general /company/settings page has none of these sections, so the catalog names the Connections page. -it.each([ - ["fast response feature", "/api/companies/{companyId}/fast-response", "Fast response"], - ["company settings page fast responses web UI", "/api/companies/{companyId}/fast-response", "Fast response"], - ["decision model settings", "/api/companies/{companyId}/decision-model", "Decision model"], - ["prompt injection prevention settings", "/api/companies/{companyId}/prompt-injection-prevention", "Prompt Injection Prevention"], -])("search %j returns the settings page that holds the %s control", (query, path, section) => { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.path === path && row.method === "PUT"); - expect(operation, query).toBeDefined(); - expect(operation!.description).toContain(`${section} section of the company-prefixed /company/settings/connections page`); - expect(operation!.description).toContain("//company/settings/connections"); -}); - -it("names the experiment that hides the Fast response section", () => { - const operation = searchRunnerApi({ query: "fast response", limit: 10 }).results.find(row => row.operationId === "GET /api/companies/{companyId}/fast-response"); - expect(operation?.description).toContain("//company/settings/instance/experimental"); -}); - -// The catalog text is the only place these page paths live on the server, so a renamed UI route -// would leave agents linking a page that no longer exists. Every page the guidance names must be -// a route the board UI mounts under the company prefix. -it("names only pages that the board UI mounts", () => { - const appRoutes = readFileSync(path.join(repoRoot, "ui/src/App.tsx"), "utf8"); - const pages = new Set( - runnerApiCatalog() - .filter(row => /^\/api\/companies\/\{companyId\}\/(fast-response|decision-model|prompt-injection-prevention)/.test(row.path)) - .flatMap(row => [...(row.description ?? "").matchAll(/\/\/([a-z0-9/-]+)/g)].map(match => match[1]!)), - ); - expect([...pages].sort()).toEqual(["company/settings/connections", "company/settings/instance/experimental"]); - for (const page of pages) expect(appRoutes, page).toContain(` { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.operationId === "POST /api/instance/database-backups"); - expect(operation, query).toBeDefined(); - const description = operation!.description; - expect(description).toContain("agent credentials receive 403"); - expect(description).toContain("The web UI has no control that creates or restores a backup"); - expect(description).toContain("Backup retention section of the company-prefixed /company/settings page"); - expect(description).toContain("paperclipai db:backup"); - expect(description).toContain("separate, empty PostgreSQL database, never over the live one"); -}); - -// The route answers a successful manual backup with 201. This guards the published document, which agents and -// clients read; the registration and the CREATED_OPERATIONS fixup in openapi.ts both supply that 201. -it("publishes the status the backup route returns on success", () => { - const responses = buildOpenApiDocument().paths["/api/instance/database-backups"].post.responses; - expect(Object.keys(responses)).toContain("201"); - expect(Object.keys(responses)).not.toContain("200"); -}); diff --git a/server/src/__tests__/hiring-operational-examples.test.ts b/server/src/__tests__/hiring-operational-examples.test.ts deleted file mode 100644 index 8b0510b3d92..00000000000 --- a/server/src/__tests__/hiring-operational-examples.test.ts +++ /dev/null @@ -1,62 +0,0 @@ -import { readFileSync } from "node:fs"; -import { describe, expect, it } from "vitest"; -import { createAgentHireSchema, createIssueThreadInteractionSchema, updateIssueSchema } from "@paperclipai/shared"; -import { runnerApiReference } from "../services/native-runtime/runner-api-reference.js"; - -const reference = readFileSync(new URL("../../../skills/paperclip/references/api-reference.md", import.meta.url), "utf8"); -const uuid = "11111111-1111-4111-8111-111111111111"; -const examples = [...reference.matchAll(/^(POST|PATCH) (\/api\/[^\s]+)\n(\{[^\n]*\}|\{\n[\s\S]*?\n\})/gm)] - .flatMap((match) => { - try { return [{ method: match[1], path: match[2], body: JSON.parse(match[3]) }]; } - catch { return []; } - }); -const substituteIds = (body: unknown) => JSON.parse(JSON.stringify(body).replace(/\{[\w-]+\}/g, uuid)); - -describe("published hiring and human-input examples", () => { - const questions = examples.filter(({ body }) => body.kind === "ask_user_questions"); - const hires = examples.filter(({ path }) => path.endsWith("/agent-hires")); - const waits = examples.filter(({ method, body }) => method === "PATCH" && (body.unblockDescriptor || body.comment === "Waiting for your answer in the saved responsibility question card.")); - - it("publishes valid structured and free-text questions, managed hires, and waiting states", () => { - expect(questions).toHaveLength(2); - expect(hires.length).toBeGreaterThan(0); - expect(waits).toHaveLength(2); - for (const { body } of questions) expect(createIssueThreadInteractionSchema.safeParse(substituteIds(body))).toMatchObject({ success: true }); - for (const { body } of hires) { - expect(createAgentHireSchema.safeParse(substituteIds(body))).toMatchObject({ success: true }); - expect(body.instructionsBundle.files["AGENTS.md"]).toEqual(expect.any(String)); - } - for (const { body } of waits) expect(updateIssueSchema.safeParse(substituteIds(body))).toMatchObject({ success: true }); - }); - - it("includes a complete valid text-field recipe in the skill itself", () => { - const skill = readFileSync(new URL("../../../skills/paperclip/SKILL.md", import.meta.url), "utf8"); - const section = skill.split('')[1]!; - const body = JSON.parse(section.match(/```json\n([\s\S]*?)\n```/)![1]); - const normalized = createIssueThreadInteractionSchema.parse(substituteIds(body)); - expect(body).toMatchObject({ resolverPolicy: "human_only", continuationPolicy: "wake_assignee" }); - expect(body).not.toHaveProperty("addresseeUserId"); - expect(body.payload.questionSet.questions[0]).toMatchObject({ answerMode: "text" }); - expect(body.payload).not.toHaveProperty("questions"); - expect(normalized.kind).toBe("ask_user_questions"); - if (normalized.kind !== "ask_user_questions") throw new Error("expected questions"); - expect(normalized.payload.questions[0].id).toBe(body.payload.questionSet.questions[0].id); - }); - - it("keeps these examples in the generated runner reference without displacing confirmations", () => { - for (const example of [...questions, ...hires, ...waits]) { - const key = `${example.method} ${example.path.replace(/\{[^}]+\}/g, "{}")}`; - expect(runnerApiReference[key]?.examples).toContainEqual({ body: example.body }); - } - expect(runnerApiReference["POST /api/issues/{}/interactions"].examples) - .toEqual(expect.arrayContaining([expect.objectContaining({ body: expect.objectContaining({ kind: "request_confirmation" }) })])); - }); - - it("only enriches documented endpoint templates, not literal narrative URLs", () => { - const documentedOperations = new Set([...reference.matchAll(/^\|\s*(GET|POST|PATCH|PUT|DELETE)\s*\|\s*`([^`]+)`/gm)] - .map((match) => `${match[1]} ${match[2].replace(/:[A-Za-z][A-Za-z0-9_]*|\{[^}]+\}/g, "{}")}`)); - expect(Object.keys(runnerApiReference).filter((key) => !documentedOperations.has(key))).toEqual([]); - expect(runnerApiReference["PATCH /api/issues/issue-101"]).toBeUndefined(); - expect(runnerApiReference["POST /api/companies/company-1/imports/preview"]).toBeUndefined(); - }); -}); diff --git a/server/src/__tests__/native-finalization-migration.test.ts b/server/src/__tests__/native-finalization-migration.test.ts deleted file mode 100644 index 66cd295a8b9..00000000000 --- a/server/src/__tests__/native-finalization-migration.test.ts +++ /dev/null @@ -1,260 +0,0 @@ -import { createHash } from "node:crypto"; -import { readFile } from "node:fs/promises"; -import { describe, expect, it } from "vitest"; -import { eq, sql } from "drizzle-orm"; -import { - agents, - applyPendingMigrations, - companies, - createDb, - environmentLeases, - heartbeatRunEvents, - heartbeatRuns, - issues, - nativeRunFinalizations, -} from "@paperclipai/db"; -import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; -import { remoteTerminationReceipt } from "../services/remote-execution-termination.js"; - -describe("P6-18 / MIG-01..04 native finalization migration", () => { - it("repairs only later duplicates and preserves legacy event bytes and cursors", async () => { - const temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-migration-"); - const migration = await readFile( - new URL("../../../packages/db/src/migrations/0227_modern_pandemic.sql", import.meta.url), - "utf8", - ); - const migrationHash = createHash("sha256").update(migration).digest("hex"); - const sequenceMigration = await readFile( - new URL("../../../packages/db/src/migrations/0235_heartbeat_run_event_sequence_uniqueness.sql", import.meta.url), - "utf8", - ); - const sequenceMigrationHash = createHash("sha256") - .update(sequenceMigration) - .digest("hex"); - const rawDb = createDb(temporary.connectionString); - try { - const companyId = "10000000-0000-4000-8000-000000000001"; - const agentId = "10000000-0000-4000-8000-000000000002"; - const runId = "10000000-0000-4000-8000-000000000003"; - // Reconstruct the actual pre-0227 shape rather than extracting selected - // repair statements from the migration under test. - await rawDb.execute(sql.raw(` - DROP TABLE IF EXISTS status_decision_effects, status_decisions, work_assessments, - native_run_finalizations, native_run_results, completion_contracts CASCADE; - DROP TRIGGER IF EXISTS paperclip_issue_status_version_trigger ON issues; - DROP FUNCTION IF EXISTS paperclip_bump_issue_status_version(); - DROP INDEX IF EXISTS heartbeat_run_events_run_seq_uq; - CREATE INDEX IF NOT EXISTS heartbeat_run_events_run_seq_idx - ON heartbeat_run_events (run_id, seq); - DROP INDEX IF EXISTS heartbeat_run_events_run_source_event_uq; - DROP INDEX IF EXISTS heartbeat_run_events_run_source_seq_uq; - ALTER TABLE heartbeat_run_events - DROP COLUMN IF EXISTS source_instance_id, - DROP COLUMN IF EXISTS source_event_id, - DROP COLUMN IF EXISTS source_seq, - DROP COLUMN IF EXISTS source_payload_sha256, - DROP COLUMN IF EXISTS protocol_schema_version; - ALTER TABLE heartbeat_run_events ALTER COLUMN seq TYPE integer; - ALTER TABLE heartbeat_runs - DROP COLUMN IF EXISTS runtime_mode, - DROP COLUMN IF EXISTS runtime_mode_resolver_version, - DROP COLUMN IF EXISTS runtime_mode_reason, - DROP COLUMN IF EXISTS runtime_mode_resolved_at, - DROP COLUMN IF EXISTS runner_profile_json, - DROP COLUMN IF EXISTS runner_instance_id, - DROP COLUMN IF EXISTS native_session_id, - DROP COLUMN IF EXISTS driver_kind, - DROP COLUMN IF EXISTS driver_version, - DROP COLUMN IF EXISTS completion_contract_id, - DROP COLUMN IF EXISTS completion_contract_sha256, - DROP COLUMN IF EXISTS next_event_seq, - DROP COLUMN IF EXISTS native_phase, - DROP COLUMN IF EXISTS native_phase_updated_at; - ALTER TABLE issues - DROP COLUMN IF EXISTS status_version, - DROP COLUMN IF EXISTS last_status_decision_id; - `)); - await rawDb.execute(sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${migrationHash}`); - await rawDb.execute(sql`DELETE FROM "drizzle"."__drizzle_migrations" WHERE "hash" = ${sequenceMigrationHash}`); - await rawDb.execute(sql` - INSERT INTO companies (id, name, issue_prefix) - VALUES (${companyId}, 'Migration fixture', 'MIG') - `); - await rawDb.execute(sql` - INSERT INTO agents (id, company_id, name) - VALUES (${agentId}, ${companyId}, 'Migration agent') - `); - await rawDb.execute(sql` - INSERT INTO heartbeat_runs (id, company_id, agent_id, status) - VALUES (${runId}, ${companyId}, ${agentId}, 'succeeded') - `); - await rawDb.execute(sql` - INSERT INTO heartbeat_run_events - (company_id, run_id, agent_id, seq, event_type, stream, level, message, payload, created_at) - VALUES - (${companyId}, ${runId}, ${agentId}, 1, 'legacy.start', 'system', 'info', 'one', ${JSON.stringify({ bytes: "α-1" })}::jsonb, '2026-08-01T00:00:01.000Z'), - (${companyId}, ${runId}, ${agentId}, 5, 'legacy.log', 'stdout', 'info', 'first-five', ${JSON.stringify({ bytes: "β-5a" })}::jsonb, '2026-08-01T00:00:02.000Z'), - (${companyId}, ${runId}, ${agentId}, 5, 'legacy.log', 'stderr', 'warn', 'duplicate-five', ${JSON.stringify({ bytes: "γ-5b" })}::jsonb, '2026-08-01T00:00:03.000Z'), - (${companyId}, ${runId}, ${agentId}, 9, 'legacy.end', 'system', 'info', 'nine', ${JSON.stringify({ bytes: "δ-9" })}::jsonb, '2026-08-01T00:00:04.000Z') - `); - const beforeResult = await rawDb.execute(sql` - SELECT * FROM heartbeat_run_events WHERE run_id = ${runId} ORDER BY id - `); - const before = [...beforeResult] as unknown as Record[]; - - await applyPendingMigrations(temporary.connectionString); - const db = createDb(temporary.connectionString); - - const after = await db.select().from(heartbeatRunEvents) - .where(eq(heartbeatRunEvents.runId, runId)).orderBy(heartbeatRunEvents.id); - expect(after.map((row) => row.seq)).toEqual([1, 5, 10, 9]); - expect((await db.select({ nextEventSeq: heartbeatRuns.nextEventSeq }).from(heartbeatRuns) - .where(eq(heartbeatRuns.id, runId)))[0]?.nextEventSeq).toBe(11); - - // The repaired duplicate's cursor is the only changed byte-equivalent read field. - const legacyColumns = (row: Record) => ({ - id: String(row.id), - companyId: row.companyId ?? row.company_id, - runId: row.runId ?? row.run_id, - agentId: row.agentId ?? row.agent_id, - eventType: row.eventType ?? row.event_type, - stream: row.stream, - level: row.level, - message: row.message, - payload: row.payload, - createdAt: new Date(String(row.createdAt ?? row.created_at)).toISOString(), - }); - expect(after.map((row) => legacyColumns(row))).toEqual(before.map(legacyColumns)); - expect(after[0]?.seq).toBe(Number(before[0]?.seq)); - expect(after[1]?.seq).toBe(Number(before[1]?.seq)); - expect(after[3]?.seq).toBe(Number(before[3]?.seq)); - await expect(db.insert(heartbeatRunEvents).values({ - companyId, runId, agentId, seq: 5, eventType: "must-conflict", - })).rejects.toThrow(); - } finally { - await temporary.cleanup(); - } - }, 60_000); - - it("clears recovery state left on committed, unleased finalizations", async () => { - const temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-recovery-backfill-"); - const migration = await readFile( - new URL("../../../packages/db/src/migrations/0376_clear_committed_native_recovery_state.sql", import.meta.url), - "utf8", - ); - const db = createDb(temporary.connectionString); - try { - const [company] = await db.insert(companies).values({ name: "Backfill", issuePrefix: "BKF" }).returning(); - const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Backfill agent" }).returning(); - const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Backfill", status: "done" }).returning(); - const history = [{ disposition: "resume_dead_runner" }]; - const fixtures = [ - { key: "committed", phase: "committed", leaseOwner: null, recoveryState: "resuming_session" }, - { key: "leased", phase: "committed", leaseOwner: "native-finalizer:live", recoveryState: "resuming_session" }, - { key: "observed", phase: "observed", leaseOwner: null, recoveryState: "resuming_session" }, - { key: "terminal", phase: "terminal_failure", leaseOwner: null, recoveryState: "blocked" }, - ]; - const runIds = new Map(); - for (const fixture of fixtures) { - const [run] = await db.insert(heartbeatRuns).values({ - companyId: company!.id, agentId: agent!.id, status: "succeeded", runtimeMode: "native", nativeIssueId: issue!.id, - }).returning(); - runIds.set(fixture.key, run!.id); - await db.insert(nativeRunFinalizations).values({ - runId: run!.id, companyId: company!.id, issueId: issue!.id, phase: fixture.phase, leaseOwner: fixture.leaseOwner, - recoveryState: fixture.recoveryState, recoveryRequestId: "restart-request", recoveryHistory: history, - }); - } - for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement)); - const rows = new Map((await db.select().from(nativeRunFinalizations)).map((row) => [row.runId, row])); - expect(rows.get(runIds.get("committed")!)).toMatchObject({ recoveryState: null, recoveryRequestId: null, recoveryHistory: history }); - expect(rows.get(runIds.get("leased")!)).toMatchObject({ recoveryState: "resuming_session", recoveryRequestId: "restart-request" }); - expect(rows.get(runIds.get("observed")!)).toMatchObject({ recoveryState: "resuming_session", recoveryRequestId: "restart-request" }); - expect(rows.get(runIds.get("terminal")!)).toMatchObject({ recoveryState: "blocked", recoveryRequestId: "restart-request" }); - } finally { - await temporary.cleanup(); - } - }, 60_000); - it("clears process identity only on old settled native runs whose sandbox confirmed termination", async () => { - const temporary = await startEmbeddedPostgresTestDatabase("paperclip-native-process-backfill-"); - const migration = await readFile( - new URL("../../../packages/db/src/migrations/0377_clear_settled_native_run_process_identity.sql", import.meta.url), - "utf8", - ); - const db = createDb(temporary.connectionString); - try { - const [company] = await db.insert(companies).values({ name: "Process backfill", issuePrefix: "PBF" }).returning(); - const [agent] = await db.insert(agents).values({ companyId: company!.id, name: "Process backfill agent" }).returning(); - const [issue] = await db.insert(issues).values({ companyId: company!.id, title: "Process backfill", status: "in_progress" }).returning(); - const old = new Date(Date.now() - 2 * 24 * 60 * 60 * 1000); - const checkpoint = { sessionCheckpoint: { providerSessionId: "thread" } }; - type Fixture = { - key: string; status?: string; runtimeMode?: string; finishedAt?: Date; phase?: string | null; - profile?: Record; providerEvent?: boolean; - leases?: Array<"stopped" | "unconfirmed" | "local">; - }; - const fixtures: Fixture[] = [ - { key: "failed" }, - { key: "cancelled", status: "cancelled" }, - { key: "timed_out", status: "timed_out", phase: "terminal_failure" }, - { key: "interrupted", status: "interrupted", phase: null }, - { key: "provider_event", profile: {}, providerEvent: true }, - { key: "recent", finishedAt: new Date(Date.now() - 60 * 60 * 1000) }, - { key: "succeeded", status: "succeeded" }, - { key: "running", status: "running" }, - { key: "legacy", runtimeMode: "legacy" }, - { key: "retryable", phase: "retryable_failure" }, - { key: "finalizing", phase: "workspace_finalizing" }, - { key: "no_evidence", profile: {} }, - { key: "unconfirmed", leases: ["stopped", "unconfirmed"] }, - { key: "local", leases: ["local"] }, - { key: "no_lease", leases: [] }, - ]; - const runIds = new Map(); - for (const fixture of fixtures) { - const [run] = await db.insert(heartbeatRuns).values({ - companyId: company!.id, agentId: agent!.id, status: fixture.status ?? "failed", - runtimeMode: fixture.runtimeMode ?? "native", nativeIssueId: issue!.id, - finishedAt: fixture.finishedAt ?? old, runnerProfileJson: fixture.profile ?? checkpoint, - processPid: 4242, processGroupId: 4242, processStartedAt: old, - }).returning(); - runIds.set(fixture.key, run!.id); - if (fixture.phase !== null) { - await db.insert(nativeRunFinalizations).values({ - runId: run!.id, companyId: company!.id, issueId: issue!.id, phase: fixture.phase ?? "committed", - }); - } - if (fixture.providerEvent) { - await db.insert(heartbeatRunEvents).values({ - companyId: company!.id, runId: run!.id, agentId: agent!.id, seq: 1, eventType: "session.started", - }); - } - for (const kind of fixture.leases ?? ["stopped"]) { - const [lease] = await db.insert(environmentLeases).values({ - companyId: company!.id, issueId: issue!.id, heartbeatRunId: run!.id, - provider: kind === "local" ? "local" : "sandbox-fixture", - providerLeaseId: kind === "local" ? null : `${fixture.key}-${kind}`, - status: "released", releasedAt: old, cleanupStatus: "success", - }).returning(); - if (kind === "stopped") { - await db.update(environmentLeases).set({ metadata: { - remoteExecutionTermination: remoteTerminationReceipt(lease!, { providerLeaseId: lease!.providerLeaseId, state: "destroyed" }), - } }).where(eq(environmentLeases.id, lease!.id)); - } - } - } - for (const statement of migration.split("--> statement-breakpoint")) await db.execute(sql.raw(statement)); - const rows = new Map((await db.select().from(heartbeatRuns)).map((row) => [row.id, row])); - const cleared = new Set(["failed", "cancelled", "timed_out", "interrupted", "provider_event"]); - for (const fixture of fixtures) { - const row = rows.get(runIds.get(fixture.key)!)!; - expect({ key: fixture.key, processPid: row.processPid, processGroupId: row.processGroupId, startedAt: row.processStartedAt === null }) - .toEqual(cleared.has(fixture.key) - ? { key: fixture.key, processPid: null, processGroupId: null, startedAt: true } - : { key: fixture.key, processPid: 4242, processGroupId: 4242, startedAt: false }); - } - } finally { - await temporary.cleanup(); - } - }, 60_000); -}); diff --git a/server/src/__tests__/person-only-page-guidance.test.ts b/server/src/__tests__/person-only-page-guidance.test.ts deleted file mode 100644 index c02e6b586e6..00000000000 --- a/server/src/__tests__/person-only-page-guidance.test.ts +++ /dev/null @@ -1,84 +0,0 @@ -import { readFileSync } from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; -import { expect, it } from "vitest"; -import { runnerApiCatalog, searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; - -const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); - -it.each([ - ["connect my assistant mcp setup", "GET /api/mcp/setup"], - ["assistant connection consent approve access", "POST /api/mcp/requests/{id}/consent"], -])("search %j says only the person connects an assistant, and links the page", (query, operationId) => { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.operationId === operationId); - expect(operation, query).toBeDefined(); - expect(operation!.description).toContain("[Assistant connections](//apps/assistant-connection)"); - expect(operation!.description).toContain("a read-only member can grant read access but not writes"); - expect(operation!.description).toContain("Do not search for another route"); -}); - -it.each([ - ["tool connection catalog quarantined", "GET /api/tool-connections/{connectionId}/catalog"], - ["quarantined catalog entry counts review", "GET /api/tool-connections/{connectionId}/review-counts"], - ["tool apps needing attention", "GET /api/companies/{companyId}/tools/apps/attention"], -])("search %j says where a person reviews a quarantined action", (query, operationId) => { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.operationId === operationId); - expect(operation, query).toBeDefined(); - expect(operation!.description).toContain("[Permissions](//apps//permissions)"); - expect(operation!.description).toContain("No agent can call a quarantined action"); -}); - -it("says chat endpoint creation needs the experiment, and links where it is turned on", () => { - const create = searchRunnerApi({ query: "create chat endpoint imessage", limit: 10 }).results.find(row => row.operationId === "POST /api/companies/{companyId}/chat-endpoints"); - expect(create?.description).toContain("[Experimental settings](//company/settings/instance/experimental)"); -}); - -it.each([ - "complete connection request for someone else", - "connection intent resolve decline", -])("search %j says only the addressee can resolve a connection request card", (query) => { - const found = searchRunnerApi({ query, limit: 10 }).results.filter(row => row.path.startsWith("/api/connection-intents/")); - expect(found.length, query).toBeGreaterThan(0); - for (const operation of found) { - expect(operation.description).toContain("Only that person, signed in to their own browser"); - expect(operation.description).toContain("[](//issues/)"); - } -}); - -it("says on the interaction listing that only the addressee resolves a connection request card", () => { - const list = searchRunnerApi({ query: "GET /api/issues/{id}/interactions" }).results.find(row => row.operationId === "GET /api/issues/{id}/interactions"); - expect(list?.description).toContain("Only that person can connect or decline it"); -}); - -it("names only pages that the board UI mounts", () => { - const appRoutes = readFileSync(path.join(repoRoot, "ui/src/App.tsx"), "utf8"); - const pages = new Set( - runnerApiCatalog() - .filter(row => /^\/api\/(mcp\/(setup|requests\/\{id\}\/consent)$|connection-intents\/|tool-connections\/\{connectionId\}\/(catalog|review-counts)$|companies\/\{companyId\}\/(tools\/apps\/attention|tools\/apps\/connect|tools\/connections|chat-endpoints)$)/.test(row.path)) - .flatMap(row => [...(row.description ?? "").matchAll(/\/\/([a-z0-9/<>-]+)/gi)].map(match => match[1]!)), - ); - expect([...pages].sort()).toEqual(["apps//permissions", "apps/assistant-connection", "apps/byo", "company/settings/instance/experimental", "issues/"]); - const mounted = (page: string) => page - .replace("apps//permissions", "apps/:connectionId/:tab") - .replace("issues/", "issues/:issueId"); - for (const page of pages) expect(appRoutes, page).toContain(` { - const found = searchRunnerApi({ query, limit: 10 }).results.filter(row => ["POST /api/companies/{companyId}/tools/apps/connect", "POST /api/companies/{companyId}/tools/connections"].includes(row.operationId)); - expect(found.length, query).toBeGreaterThan(0); - for (const operation of found) expect(operation.description).toContain("[Connect your own MCP server](//apps/byo)"); -}); - -it("links only mounted pages from connections_search", () => { - const appRoutes = readFileSync(path.join(repoRoot, "ui/src/App.tsx"), "utf8"); - const search = readFileSync(path.join(repoRoot, "server/src/services/connection-intents.ts"), "utf8"); - for (const page of ["apps/byo", "company/settings/instance/experimental"]) { - expect(search, page).toContain(`}/${page})`); - expect(appRoutes, page).toContain(` { - const found = searchRunnerApi({ query, limit: 10 }).results - .filter(row => row.path === "/api/routines/{id}" && (row.method === "GET" || row.method === "PATCH")); - expect(found.length, query).toBeGreaterThan(0); - for (const operation of found) { - expect(operation.description).toContain("managedByPlugin"); - expect(operation.description).toContain(settingsLink); - expect(operation.description).toContain("Do not rewrite, detach or duplicate"); - } -}); - -it("links a plugin settings page the board UI mounts", () => { - const appRoutes = readFileSync(path.join(repoRoot, "ui/src/App.tsx"), "utf8"); - expect(appRoutes).toContain('path="company/settings/instance/plugins/:pluginId"'); -}); - -it.each(["GET /api/routines/{id}", "PATCH /api/routines/{id}"])("%s carries the full plugin-managed routine guidance", (operationId) => { - const description = runnerApiCatalog().find(row => row.operationId === operationId)?.description ?? ""; - expect(description).toContain("managedByPlugin"); - expect(description).toContain(settingsLink); - expect(description).toContain("Do not rewrite, detach or duplicate"); - expect(description).toContain("reply now with that link"); -}); - -it("names the hosting operator instead of linking plugin settings when the operator hides them", () => { - const document = applyPluginSettingsVisibility(buildOpenApiDocument(), new Set(["instance.plugins"])); - for (const operation of [document.paths["/api/routines/{id}"].get, document.paths["/api/routines/{id}"].patch]) { - expect(operation.description).not.toContain("/company/settings/instance/plugins"); - expect(operation.description).toContain("the hosting operator controls this plugin's settings"); - expect(operation.description).toContain("Do not rewrite, detach or duplicate"); - } - const visible = applyPluginSettingsVisibility(buildOpenApiDocument(), new Set()); - expect(visible.paths["/api/routines/{id}"].get.description).toContain(settingsLink); -}); diff --git a/server/src/__tests__/project-archive-restore-guidance.test.ts b/server/src/__tests__/project-archive-restore-guidance.test.ts deleted file mode 100644 index a060cff52a3..00000000000 --- a/server/src/__tests__/project-archive-restore-guidance.test.ts +++ /dev/null @@ -1,12 +0,0 @@ -import { expect, it } from "vitest"; -import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; - -it.each(["archive project update project", "unarchive restore project"])("search %j says where a person restores an archived project", query => { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.operationId === "PATCH /api/projects/{id}"); - expect(operation, query).toBeDefined(); - const description = operation!.description; - expect(description).toContain("keeps the project, its tasks and their history"); - expect(description).toContain("Restoring sets archivedAt to null"); - expect(description).toContain("//projects//configuration, with the Unarchive button"); - expect(description).toContain("not restored from the company Status page"); -}); diff --git a/server/src/__tests__/routine-webhook-secret-guidance.test.ts b/server/src/__tests__/routine-webhook-secret-guidance.test.ts deleted file mode 100644 index 8be05ec2c7c..00000000000 --- a/server/src/__tests__/routine-webhook-secret-guidance.test.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { expect, it } from "vitest"; -import { searchRunnerApi } from "../services/native-runtime/runner-api-catalog.js"; - -it.each([ - ["routine webhook trigger", "POST /api/routines/{id}/triggers"], - ["rotate routine trigger secret", "POST /api/routine-triggers/{id}/rotate-secret"], -])("search %j tells the agent to keep the webhook secret out of chat and where the person reveals it", (query, operationId) => { - const operation = searchRunnerApi({ query, limit: 10 }).results.find(row => row.operationId === operationId); - expect(operation, query).toBeDefined(); - const description = operation!.description; - expect(description).toContain("never write its value, or a header containing it, in a chat reply"); - expect(description).toContain("//routines//triggers, as a Markdown link"); - expect(description).toContain("//routines//triggers?triggerSetup= and tell them to choose Generate new key"); - expect(description).toContain("Edit webhook, then Replace key"); - expect(description).toContain("With signingMode none the URL alone starts the routine, so treat that URL as a credential too"); -}); diff --git a/server/src/__tests__/user-facing-wording-guidance.test.ts b/server/src/__tests__/user-facing-wording-guidance.test.ts deleted file mode 100644 index a7cce6debd7..00000000000 --- a/server/src/__tests__/user-facing-wording-guidance.test.ts +++ /dev/null @@ -1,59 +0,0 @@ -import { readFile } from "node:fs/promises"; -import { describe, expect, it } from "vitest"; - -/** - * Agents write task briefs and chat replies that people read. The Nov 2026 - * onboarding walk found raw task UUIDs in an agent-written brief ("on task - * BRA-2 (id 2b330993-…)") and a Codex chief of staff narrating receipts, - * execution policies and policy patches to a new user. These checks keep the - * instructions that shape that text explicit about both. - */ -const read = (relative: string) => readFile(new URL(relative, import.meta.url), "utf8"); - -function section(markdown: string, heading: string): string { - const start = markdown.indexOf(heading); - if (start < 0) throw new Error(`Missing section: ${heading}`); - const next = markdown.indexOf("\n## ", start + heading.length); - return markdown.slice(start, next < 0 ? undefined : next); -} - -describe("agent-written text names tasks by identifier, never by UUID", () => { - it("the paperclip skill's comment style forbids raw UUIDs in comments and descriptions", async () => { - const style = section(await read("../../../skills/paperclip/SKILL.md"), "## Comment Style (Required)"); - expect(style).toContain("**No raw IDs in prose (required):**"); - expect(style).toMatch(/never paste a raw UUID/i); - expect(style).toContain("[BRA-2](/BRA/issues/BRA-2#document-plan)"); - }); - - it("the first-task handoff references inputs by identifier link, not UUID", async () => { - const skill = await read("../onboarding-assets/first-task/skills/first-task/SKILL.md"); - const handoff = skill.slice(skill.indexOf("Copy required input payloads verbatim")); - expect(handoff).toMatch(/source reference as an identifier link[^.]*not a raw UUID/i); - }); - - it("plan-to-task conversion keeps UUIDs out of task descriptions", async () => { - const skill = await read("../../../skills/paperclip-converting-plans-to-tasks/SKILL.md"); - expect(skill).toMatch(/identifier links[^.]*never raw UUIDs/i); - }); -}); - -describe("chat agents describe outcomes, not internal mechanics", () => { - it("the first-task workflow forbids narrating control-plane mechanics to the user", async () => { - const skill = await read("../onboarding-assets/first-task/skills/first-task/SKILL.md"); - expect(skill).toContain("**Talk in outcomes.**"); - for (const term of ["receipts", "execution policies", "patches", "runs"]) expect(skill).toContain(term); - expect(skill).toMatch(/what happened, what it means for them, and the next step/); - }); - - it("the chief-of-staff persona carries the same plain-language rule into every chat", async () => { - const persona = await read("../onboarding-assets/first-task/chief-of-staff/AGENTS.md"); - expect(persona).toMatch(/plain language/i); - expect(persona).toMatch(/never narrate internal mechanics/i); - expect(persona).toMatch(/raw IDs/); - }); - - it("the paperclip skill applies the rule to every user-facing comment", async () => { - const style = section(await read("../../../skills/paperclip/SKILL.md"), "## Comment Style (Required)"); - expect(style).toContain("**Describe outcomes, not mechanics (required):**"); - }); -}); diff --git a/tests/e2e/acp-stop-continuation.spec.ts b/tests/e2e/acp-stop-continuation.spec.ts index 9b9037d027c..3681ebadc4f 100644 --- a/tests/e2e/acp-stop-continuation.spec.ts +++ b/tests/e2e/acp-stop-continuation.spec.ts @@ -20,8 +20,10 @@ for (const { unfinishedWrite, stopResponse, sendSavedQueue = false } of [ const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-stop-browser-")); const company = await json(await request.post("/api/companies", { data: { name: `ACP Stop ${Date.now()}` } })); const originalSettings = await json(await request.get("/api/instance/settings/experimental")); + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...originalSettings, enableClassicTaskInterface: false, + } })); try { - await json(await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: false } })); const owner = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { name: "ACP Stop fixture", role: "engineer", adapterType: "claude_local", runner: "legacy", adapterConfig: { engine: "acp", cwd: root, stateDir: path.join(root, "state"), @@ -92,7 +94,6 @@ for (const { unfinishedWrite, stopResponse, sendSavedQueue = false } of [ await expect(page.getByRole("dialog")).toHaveCount(0); } finally { await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); - await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: originalSettings.enableClassicTaskInterface } }); await rm(root, { recursive: true, force: true }); } }); diff --git a/tests/e2e/agent-chat-projects.spec.ts b/tests/e2e/agent-chat-projects.spec.ts index 6d1c03a1919..64923178d93 100644 --- a/tests/e2e/agent-chat-projects.spec.ts +++ b/tests/e2e/agent-chat-projects.spec.ts @@ -36,10 +36,16 @@ test("cleanup restores agent chat experiments when cancellation fails", async ({ enableClassicTaskInterface: original.enableClassicTaskInterface, }); } finally { - await json(await request.patch("/api/instance/settings/experimental", { data: { - enableAgentChat: original.enableAgentChat, - enableClassicTaskInterface: original.enableClassicTaskInterface, - } })); + const current = await json(await request.get("/api/instance/settings/experimental")); + if ( + current.enableAgentChat !== original.enableAgentChat || + current.enableClassicTaskInterface !== original.enableClassicTaskInterface + ) { + await json(await request.patch("/api/instance/settings/experimental", { data: { + enableAgentChat: original.enableAgentChat, + enableClassicTaskInterface: original.enableClassicTaskInterface, + } })); + } } }); diff --git a/tests/e2e/agent-chat-sessions.spec.ts b/tests/e2e/agent-chat-sessions.spec.ts index 2c4ea106f65..a66da6c7ae0 100644 --- a/tests/e2e/agent-chat-sessions.spec.ts +++ b/tests/e2e/agent-chat-sessions.spec.ts @@ -297,12 +297,17 @@ test("secondary chat navigation preserves layout, unique conversations, history, const originalExperimental = await json(await request.get("/api/instance/settings/experimental")); const f = await setup(request); const originalWorkspace = await json(await request.get("/api/workspace-preferences/me")); - const workspacePath = `/api/companies/${f.company.id}/workspace-preferences/me`; try { - await json(await request.put(workspacePath, { data: { coordinatorWorkspaceEnabled: false } })); - await json(await request.patch("/api/instance/settings/experimental", { - data: { enableStreamlinedUi: true }, - })); + await page.route("**/api/workspace-preferences/me", (route) => + route.fulfill({ + json: { ...originalWorkspace, coordinatorWorkspaceEnabled: false }, + }), + ); + await page.route("**/api/instance/settings/experimental", (route) => + route.fulfill({ + json: { ...originalExperimental, enableStreamlinedUi: true }, + }), + ); await page.goto(`/${f.company.issuePrefix}/dashboard`); await page.getByRole("link", { name: /^Chat(?:\s|$)/ }).click(); // With no recent conversation, Chat opens the first human-created primary. @@ -390,10 +395,6 @@ test("secondary chat navigation preserves layout, unique conversations, history, await page.reload(); await expect(page.getByText("Background activity", { exact: true })).toBeVisible(); } finally { - await json(await request.put(workspacePath, { data: { coordinatorWorkspaceEnabled: originalWorkspace.coordinatorWorkspaceEnabled } })); await f.restore(); - await json(await request.patch("/api/instance/settings/experimental", { - data: { enableStreamlinedUi: originalExperimental.enableStreamlinedUi }, - })); } }); diff --git a/tests/e2e/agent-chat.shared.ts b/tests/e2e/agent-chat.shared.ts index 592af7641de..bb43d30c46f 100644 --- a/tests/e2e/agent-chat.shared.ts +++ b/tests/e2e/agent-chat.shared.ts @@ -25,11 +25,16 @@ export async function setup(request: APIRequestContext) { const original = await json( await request.get("/api/instance/settings/experimental"), ); - await json( - await request.patch("/api/instance/settings/experimental", { - data: { enableAgentChat: true, enableClassicTaskInterface: false }, - }), - ); + const needsExperimentalPatch = + original.enableAgentChat !== true || + original.enableClassicTaskInterface !== false; + if (needsExperimentalPatch) { + await json( + await request.patch("/api/instance/settings/experimental", { + data: { enableAgentChat: true, enableClassicTaskInterface: false }, + }), + ); + } const agents = []; for (const name of ["Alpha", "Beta", "Gamma", "Delta", "Epsilon", "Zeta"]) agents.push( @@ -122,14 +127,16 @@ export async function setup(request: APIRequestContext) { await request.post(`/api/heartbeat-runs/${run.id}/cancel`), ); } finally { - await json( - await request.patch("/api/instance/settings/experimental", { - data: { - enableAgentChat: original.enableAgentChat, - enableClassicTaskInterface: original.enableClassicTaskInterface, - }, - }), - ); + if (needsExperimentalPatch) { + await json( + await request.patch("/api/instance/settings/experimental", { + data: { + enableAgentChat: original.enableAgentChat, + enableClassicTaskInterface: original.enableClassicTaskInterface, + }, + }), + ); + } } } }, diff --git a/tests/e2e/agentmail.spec.ts b/tests/e2e/agentmail.spec.ts index 43373e99847..4d1bbd1b522 100644 --- a/tests/e2e/agentmail.spec.ts +++ b/tests/e2e/agentmail.spec.ts @@ -13,10 +13,6 @@ test("AgentMail setup and email work through the normal task conversation", asyn request, }) => { await page.setViewportSize({ width: 1440, height: 1080 }); - const settings = await request.patch("/api/instance/settings/experimental", { - data: { enableChatConnectors: false }, - }); - expect(settings.ok()).toBeTruthy(); const created = await request.post("/api/companies", { data: { name: `AgentMail browser ${Date.now()}` }, }); diff --git a/tests/e2e/ai-personal-connection-recovery.spec.ts b/tests/e2e/ai-personal-connection-recovery.spec.ts index 22f9cacd427..474b76131d9 100644 --- a/tests/e2e/ai-personal-connection-recovery.spec.ts +++ b/tests/e2e/ai-personal-connection-recovery.spec.ts @@ -9,8 +9,14 @@ test("a ready agent with a missing personal key offers Claude setup in chat and const root = await mkdtemp(path.join(os.tmpdir(), "personal-ai-recovery-")); const original = await json(await request.get("/api/instance/settings/experimental")); const company = await json(await request.post("/api/companies", { data: { name: `Personal AI recovery ${Date.now()}` } })); + const needsSettingsPatch = original.enableAgentChat !== true || original.enableClassicTaskInterface !== false; try { - await json(await request.patch("/api/instance/settings/experimental", { data: { enableAgentChat: true, enableClassicTaskInterface: false } })); + if (needsSettingsPatch) { + await json(await request.patch("/api/instance/settings/experimental", { data: { enableAgentChat: true, enableClassicTaskInterface: false } })); + } + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...original, enableAgentChat: true, enableClassicTaskInterface: false, + } })); const definition = await json(await request.post(`/api/companies/${company.id}/user-secret-definitions`, { data: { key: "ANTHROPIC_API_KEY", name: "ANTHROPIC_API_KEY for onboarding" }, })); @@ -74,7 +80,7 @@ test("a ready agent with a missing personal key offers Claude setup in chat and } finally { await Promise.allSettled([ request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }), - request.patch("/api/instance/settings/experimental", { data: original }), + ...(needsSettingsPatch ? [request.patch("/api/instance/settings/experimental", { data: original })] : []), ]); await rm(root, { recursive: true, force: true }); } diff --git a/tests/e2e/application-delete-screenshot.spec.ts b/tests/e2e/application-delete-screenshot.spec.ts deleted file mode 100644 index 966037fc778..00000000000 --- a/tests/e2e/application-delete-screenshot.spec.ts +++ /dev/null @@ -1,33 +0,0 @@ -import { expect, test } from "@playwright/test"; - -// One-off visual capture for PAP-10817. Connection removal now lives on the -// Connectors page, rather than behind a per-connection setup surface. -test("captures the current app removal confirmations", async ({ page }) => { - const companyRes = await page.request.post("/api/companies", { - data: { name: `PAP-10817 remove app ${Date.now()}` }, - }); - expect(companyRes.ok(), `create company failed ${companyRes.status()}: ${await companyRes.text()}`).toBe(true); - const company = await companyRes.json(); - const companyId: string = company.id; - const prefix: string = company.issuePrefix ?? company.prefix ?? company.urlKey ?? "E2E"; - - const conn = await page.request.post(`/api/companies/${companyId}/tools/connections`, { - data: { - applicationName: "Guarded MCP", - name: "Primary connection", - transport: "mcp_remote", - config: { url: "http://127.0.0.1:65535/mcp" }, - }, - }); - expect(conn.ok(), `connection create failed ${conn.status()}: ${await conn.text()}`).toBe(true); - await conn.json(); - - await page.goto(`/${prefix}/apps`); - await expect(page.getByRole("heading", { name: "Connectors" })).toBeVisible({ timeout: 15_000 }); - await page.getByRole("button", { name: "Manage Primary connection connection" }).click(); - await page.getByRole("menuitem", { name: "Remove connection" }).click(); - await expect(page.getByRole("button", { name: "Remove connection" })).toBeVisible(); - await page.screenshot({ path: "test-results/pap-10817-delete-dialog-guarded.png", fullPage: true }); - - await page.request.delete(`/api/companies/${companyId}`).catch(() => undefined); -}); diff --git a/tests/e2e/apps-dark-mode-shots.spec.ts b/tests/e2e/apps-dark-mode-shots.spec.ts deleted file mode 100644 index c9ed810e112..00000000000 --- a/tests/e2e/apps-dark-mode-shots.spec.ts +++ /dev/null @@ -1,194 +0,0 @@ -import { expect, test, type APIRequestContext, type Page } from "@playwright/test"; -import { createServer, type Server } from "node:http"; -import { listenOnFetchAllowedPort } from "./fetch-allowed-port"; - -// Apps navigation — dark-mode + navigation QA for the prosumer Apps surfaces. -// Seeds a healthy app and a broken (needs-attention) app, forces dark theme, -// and screenshots /apps, the folded attention banner, and the Advanced/developer doors to -// prove the amber/emerald surfaces read correctly on dark. - -const SCREENSHOT_DIR = "test-results"; - -type Seed = { companyId: string; prefix: string }; - -async function newCompany(request: APIRequestContext, label: string): Promise { - const res = await request.post("/api/companies", { data: { name: `Apps navigation ${label} ${Date.now()}` } }); - expect(res.ok(), `create company failed ${res.status()}: ${await res.text()}`).toBe(true); - const company = await res.json(); - return { - companyId: company.id, - prefix: company.issuePrefix ?? company.prefix ?? company.urlKey ?? "E2E", - }; -} - -type MockMcpServer = { url: string; close: () => Promise }; - -async function startMockMcp(): Promise { - const server: Server = createServer(async (req, res) => { - const chunks: Buffer[] = []; - for await (const chunk of req) chunks.push(chunk as Buffer); - let payload: { id?: string | number; method?: string } = {}; - try { - payload = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); - } catch { - // fall through - } - if (payload.method === "tools/list") { - res.writeHead(200, { "Content-Type": "application/json" }); - res.end( - JSON.stringify({ - jsonrpc: "2.0", - id: payload.id ?? null, - result: { - tools: [ - { - name: "list_widgets", - title: "List widgets", - description: "Read-only listing of widgets.", - inputSchema: { type: "object", properties: {}, additionalProperties: false }, - }, - ], - }, - }), - ); - return; - } - res.writeHead(200, { "Content-Type": "application/json" }); - res.end(JSON.stringify({ jsonrpc: "2.0", id: payload.id ?? null, result: {} })); - }); - const port = await listenOnFetchAllowedPort(server); - return { - url: `http://127.0.0.1:${port}`, - close: () => new Promise((resolve) => server.close(() => resolve())), - }; -} - -async function connectApp(request: APIRequestContext, seed: Seed, url: string): Promise { - const connect = await request.post(`/api/companies/${seed.companyId}/tools/apps/connect`, { - data: { link: url, credentialValues: { "credentials.authorization": "qa-token" } }, - }); - expect(connect.ok(), `connect failed ${connect.status()}: ${await connect.text()}`).toBe(true); - const body = await connect.json(); - const enabledCatalogEntryIds = (body.actions?.readOnly ?? []).map( - (action: { catalogEntryId: string }) => action.catalogEntryId, - ); - const finish = await request.post(`/api/companies/${seed.companyId}/tools/apps/${body.connectionId}/finish`, { - data: { enabledCatalogEntryIds, askFirstCatalogEntryIds: [], access: "all_agents" }, - }); - expect(finish.ok(), `finish failed ${finish.status()}: ${await finish.text()}`).toBe(true); - return body.connectionId as string; -} - -async function forceDark(page: Page) { - await page.addInitScript(() => window.localStorage.setItem("paperclip.theme", "dark")); -} - -test.describe.serial("dark-mode Apps surfaces", () => { - test.setTimeout(240_000); - - let healthy: MockMcpServer; - let seed: Seed; - let brokenId: string; - - test.beforeAll(async ({ request }) => { - healthy = await startMockMcp(); - seed = await newCompany(request, "dark"); - - // Healthy app. - await connectApp(request, seed, healthy.url); - - // Broken app → needs attention. Use a `localhost` URL so the derived - // connection name differs from the healthy `127.0.0.1` app. - const ephemeral = await startMockMcp(); - brokenId = await connectApp(request, seed, ephemeral.url.replace("127.0.0.1", "localhost")); - const brokenUrl = "http://localhost:65535/"; - const patch = await request.patch(`/api/tool-connections/${brokenId}`, { - data: { config: { url: brokenUrl } }, - }); - expect(patch.ok(), `patch broken url failed ${patch.status()}: ${await patch.text()}`).toBe(true); - await ephemeral.close(); - const health = await request.post(`/api/tool-connections/${brokenId}/health-check`); - expect(health.status()).toBe(502); - }); - - test.afterAll(async () => { - await healthy?.close(); - }); - - test("sidebar says Connectors and links to /apps", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/issues`); - await page.getByRole("button", { name: "More workspace pages", exact: true }).click(); - const connectorsLink = page.getByRole("link", { name: "Connectors", exact: true }); - await expect(connectorsLink).toBeVisible({ timeout: 30_000 }); - await expect(connectorsLink).toHaveAttribute("href", new RegExp(`/${seed.prefix}/apps$`)); - }); - - test("apps list dark mode with attention banner", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/apps/connections`); - await expect(page.getByRole("heading", { name: "Connectors" })).toBeVisible({ timeout: 30_000 }); - await expect(page.getByText(/needs attention/i).first()).toBeVisible({ timeout: 30_000 }); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-01-apps-dark.png`, fullPage: true }); - }); - - test("attention details dark mode", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/apps/connections`); - await expect(page.getByRole("heading", { name: "Connectors" })).toBeVisible({ timeout: 30_000 }); - await expect(page.getByText(/connect ECONNREFUSED/i).first()).toBeVisible({ timeout: 30_000 }); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-02-attention-dark.png`, fullPage: true }); - }); - - test("advanced door shows paste config with the merged Apps sidebar", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/apps/advanced`); - await expect(page.getByRole("heading", { name: "Advanced setup" })).toBeVisible({ timeout: 30_000 }); - await expect(page.getByText(/Paste the MCP config snippet/i).first()).toBeVisible({ timeout: 20_000 }); - await expect(page.getByRole("link", { name: "Connectors" })).toBeVisible(); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-03-advanced-run-dark.png`, fullPage: true }); - - // Sidebar and tab switcher both link Paste a config — either lands on /paste-config. - await page.getByRole("link", { name: "Paste a config" }).first().click(); - await expect(page).toHaveURL(/\/apps\/advanced\/paste-config$/); - await expect(page.getByText(/Paste the MCP config snippet/i).first()).toBeVisible({ timeout: 20_000 }); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-04-advanced-paste-dark.png`, fullPage: true }); - }); - - test("developer routes share the merged Apps sidebar without hidden tabs", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/apps/advanced/profiles`); - await expect(page.getByRole("heading", { name: "Access profiles" })).toBeVisible({ timeout: 30_000 }); - await expect(page.locator('a[href$="/apps/advanced/gateways"]', { hasText: "Gateways" })).toHaveCount(0); - await expect(page.locator('a[href$="/apps/advanced/profiles"]', { hasText: "Profiles" })).toHaveCount(0); - await expect(page.locator('a[href$="/apps/advanced/audit"]', { hasText: "Activity" })).toHaveCount(0); - await page.getByRole("button", { name: "More workspace pages", exact: true }).click(); - await expect(page.locator('a[href$="/activity"]', { hasText: "Audit" })).toBeVisible(); - await expect(page.getByRole("link", { name: "Applications", exact: true })).toHaveCount(0); - // Apps section lives in the same sidebar now. - await expect(page.locator('a[href$="/apps"]', { hasText: "Connectors" })).toBeVisible(); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-05-developer-overview-dark.png`, fullPage: true }); - }); - - test("app detail rename and connector-list removal", async ({ page }) => { - await forceDark(page); - await page.goto(`/${seed.prefix}/apps/${brokenId}/permissions`); - await expect(page.getByRole("heading").first()).toBeVisible({ timeout: 30_000 }); - - // Rename from the header pencil. - await page.getByRole("button", { name: "Rename app" }).click(); - await page.getByLabel("App name").fill("QA Renamed App"); - await page.getByRole("button", { name: "Save", exact: true }).click(); - await expect(page.getByRole("heading", { name: "QA Renamed App" })).toBeVisible({ timeout: 20_000 }); - - await page.goto(`/${seed.prefix}/apps`); - await page.getByRole("button", { name: "Manage QA Renamed App connection" }).click(); - await page.getByRole("menuitem", { name: "Remove connection" }).click(); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-06-danger-zone-dark.png`, fullPage: true }); - await page.getByRole("button", { name: "Remove connection" }).click(); - await expect(page).toHaveURL(new RegExp(`/${seed.prefix}/apps$`), { timeout: 20_000 }); - await expect(page.getByText("Connection removed").first()).toBeVisible({ timeout: 20_000 }); - await expect(page.getByRole("heading", { name: "Connectors" })).toBeVisible(); - await page.screenshot({ path: `${SCREENSHOT_DIR}/apps-nav-07-after-remove-dark.png`, fullPage: true }); - }); -}); diff --git a/tests/e2e/chat-adapters-ui-providers.spec.ts b/tests/e2e/chat-adapters-ui-providers.spec.ts index d03bf4c9486..3ea87a5ab35 100644 --- a/tests/e2e/chat-adapters-ui-providers.spec.ts +++ b/tests/e2e/chat-adapters-ui-providers.spec.ts @@ -177,7 +177,7 @@ test("Slack OAuth continuation reloads once from the callback origin without ech } finally { await new Promise((resolve, reject) => server.close(error => error ? reject(error) : resolve())); } }); -test.describe.serial("native chat adapter UI", () => { +test.describe("native chat adapter UI", () => { test.setTimeout(180_000); let seed: Seed; @@ -283,7 +283,10 @@ test.describe.serial("native chat adapter UI", () => { }); await page.goto(`/${seed.prefix}/apps/chat/connect?provider=slack&purpose=chat&resume=endpoint-slack`); await expect(page.getByText("Managed Slack setup is unavailable. Try again later.")).toBeVisible(); - available = true; await page.getByRole("button", { name: "Retry", exact: true }).click(); + const retryButton = page.getByRole("button", { name: "Retry", exact: true }); + await expect(retryButton).toBeEnabled(); + available = true; + await retryButton.click(); await expect(page.getByRole("heading", { name: "Send a message to your agent", exact: true })).toBeVisible(); }); test("Slack: own-app selection persists before provisioning", async ({ page }) => { diff --git a/tests/e2e/completed-task-paused-assignee.spec.ts b/tests/e2e/completed-task-paused-assignee.spec.ts index 13aee62864f..26d69d42fb5 100644 --- a/tests/e2e/completed-task-paused-assignee.spec.ts +++ b/tests/e2e/completed-task-paused-assignee.spec.ts @@ -6,33 +6,6 @@ async function json>(response: APIResponse): Promise return response.json(); } -let cleanup: { companyId: string; enableClassicTaskInterface: boolean; coordinatorWorkspaceEnabled: boolean } | undefined; - -test.afterEach(async ({ request }, testInfo) => { - const state = cleanup; - cleanup = undefined; - if (!state) return; - testInfo.setTimeout(15_000); - const workspaceResult = await request.put(`/api/companies/${state.companyId}/workspace-preferences/me`, { - data: { coordinatorWorkspaceEnabled: state.coordinatorWorkspaceEnabled }, timeout: 5_000, - }); - expect(workspaceResult.ok()).toBe(true); - const results = await Promise.allSettled([ - request.patch("/api/instance/settings/experimental", { - data: { enableClassicTaskInterface: state.enableClassicTaskInterface }, timeout: 5_000, - }), - request.patch(`/api/companies/${state.companyId}`, { data: { status: "archived" }, timeout: 5_000 }), - ]); - const failures = results.flatMap((result, index) => result.status === "rejected" - ? [`Cleanup ${index}: ${String(result.reason)}`] - : result.value.ok() ? [] : [`Cleanup ${index}: HTTP ${result.value.status()}`]); - if (!failures.length) return; - await testInfo.attach("cleanup-failure", { - body: Buffer.from(JSON.stringify({ companyId: state.companyId, failures })), contentType: "application/json", - }); - if (testInfo.status === "passed") throw new Error(failures.join("\n")); -}); - for (const classic of [false, true]) { test(`${classic ? "classic" : "task chat"}: paused assignee warnings follow the task's current status without resuming the agent`, async ({ page, request }, testInfo) => { page.setDefaultTimeout(10_000); @@ -41,14 +14,13 @@ for (const classic of [false, true]) { data: { name: `Completed task status ${randomUUID()}` }, })); const workspace = await json(await request.get("/api/workspace-preferences/me")); - cleanup = { companyId: company.id, enableClassicTaskInterface: settings.enableClassicTaskInterface, - coordinatorWorkspaceEnabled: workspace.coordinatorWorkspaceEnabled }; - await json(await request.put(`/api/companies/${company.id}/workspace-preferences/me`, { - data: { coordinatorWorkspaceEnabled: !classic }, - })); - await json(await request.patch("/api/instance/settings/experimental", { - data: { enableClassicTaskInterface: classic }, - })); + await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: { + ...workspace, coordinatorWorkspaceEnabled: !classic, + } })); + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...settings, enableClassicTaskInterface: classic, + } })); + try { // This command is deliberately not a model adapter. Heartbeats are disabled // and the agent is paused before assignment, so the journey starts no work. const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { @@ -145,5 +117,8 @@ for (const classic of [false, true]) { }, null, 2)), contentType: "application/json", }); + } finally { + await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" }, timeout: 5_000 }).catch(() => {}); + } }); } diff --git a/tests/e2e/composer-stop.spec.ts b/tests/e2e/composer-stop.spec.ts index 30c31a33a8b..7f8edb0ee4c 100644 --- a/tests/e2e/composer-stop.spec.ts +++ b/tests/e2e/composer-stop.spec.ts @@ -185,11 +185,24 @@ for (const adapter of ["process", "paperclip_runner"] as const) { }); }); try { - await json( - await request.patch("/api/instance/settings/experimental", { - data: { enableClassicTaskInterface: false, enableNativeRunner: true }, - }), - ); + const needsSettingsPatch = + originalSettings.enableClassicTaskInterface !== false || + originalSettings.enableNativeRunner !== true; + if (needsSettingsPatch) { + await json( + await request.patch("/api/instance/settings/experimental", { + data: { enableClassicTaskInterface: false, enableNativeRunner: true }, + }), + ); + } + await page.route("**/api/instance/settings/experimental", async (route) => { + const response = await route.fetch(); + const settings = await response.json(); + await route.fulfill({ + response, + json: { ...settings, enableClassicTaskInterface: false, enableNativeRunner: true }, + }); + }); async function agent(name: string) { return json( await request.post(`/api/companies/${company.id}/agents`, { @@ -369,18 +382,35 @@ for (const adapter of ["process", "paperclip_runner"] as const) { await expect( page.getByText("Subtree is paused.", { exact: true }), ).toBeVisible(); - // Cross the isolated server's ten-second scheduler interval repeatedly. - for (let i = 0; i < 3; i++) { - await new Promise((resolve) => setTimeout(resolve, 10_000)); - expect( - await json(await request.get(`/api/issues/${parent.id}/live-runs`)), - ).toEqual([]); - expect( - await json(await request.get(`/api/issues/${child.id}/live-runs`)), - ).toEqual([]); + // Cross the isolated server's ten-second scheduler interval and verify + // no paused subtree task resumes on the tick. + await new Promise((resolve) => setTimeout(resolve, 11_000)); + expect( + await json(await request.get(`/api/issues/${parent.id}/live-runs`)), + ).toEqual([]); + expect( + await json(await request.get(`/api/issues/${child.id}/live-runs`)), + ).toEqual([]); + if (adapter === "process") { + // Stopped legacy runs settle asynchronously into the reconciliation gate + // (status "blocked"). Wait for both tasks to settle so Resume preview + // sees 0 wakeable agents instead of racing mid-transition. + await expect.poll(async () => { + const [parentIssue, childIssue] = await Promise.all([ + json(await request.get(`/api/issues/${parent.id}`)), + json(await request.get(`/api/issues/${child.id}`)), + ]); + return [parentIssue.status, childIssue.status]; + }, { timeout: 30_000 }).toEqual(["blocked", "blocked"]); } await menu(page, "Resume subtree"); - const resumeWake = page.getByRole("dialog").getByRole("checkbox"); + const resumeDialog = page.getByRole("dialog"); + const resumeApply = resumeDialog.getByRole("button", { + name: "Resume subtree", + exact: true, + }); + await expect(resumeApply).toBeEnabled(); + const resumeWake = resumeDialog.getByRole("checkbox"); if (adapter === "process") { // Stopped legacy work is blocked pending reconciliation. Removing the // pause must not promise or request a wake through that recovery gate. @@ -390,11 +420,8 @@ for (const adapter of ["process", "paperclip_runner"] as const) { } else { await resumeWake.check(); } - await page - .getByRole("dialog") - .getByRole("button", { name: "Resume subtree", exact: true }) - .click(); - await expect(page.getByRole("dialog")).toHaveCount(0); + await resumeApply.click(); + await expect(resumeDialog).toHaveCount(0); if (adapter === "process") { // Legacy processes lack runner stop/action proof, so releasing the hold // preserves their recovery gate until the fixture reconciles them. @@ -486,13 +513,18 @@ for (const adapter of ["process", "paperclip_runner"] as const) { await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" }, }); - await request.patch("/api/instance/settings/experimental", { - data: { - enableClassicTaskInterface: - originalSettings.enableClassicTaskInterface, - enableNativeRunner: originalSettings.enableNativeRunner, - }, - }); + if ( + originalSettings.enableClassicTaskInterface !== false || + originalSettings.enableNativeRunner !== true + ) { + await request.patch("/api/instance/settings/experimental", { + data: { + enableClassicTaskInterface: + originalSettings.enableClassicTaskInterface, + enableNativeRunner: originalSettings.enableNativeRunner, + }, + }); + } await testInfo.attach("owned-company-status-metadata", { body: statusEvidence, contentType: "application/json", diff --git a/tests/e2e/connection-reviews.spec.ts b/tests/e2e/connection-reviews.spec.ts index b5f678f63a8..753ac9e4814 100644 --- a/tests/e2e/connection-reviews.spec.ts +++ b/tests/e2e/connection-reviews.spec.ts @@ -134,46 +134,68 @@ for (const journey of [ }); }); } + const fullUiSetup = journey === "approve" || journey === "decline" || journey === "restart"; const provider = await startReviewProvider(); try { const seed = await newCompany(request); const agent = await createAgent(request, seed.companyId, "Page reader"); - await page.goto(`/${seed.prefix}/apps`); - const connector = page - .getByRole("list", { name: "Connector list" }) - .getByRole("listitem") - .filter({ hasText: "Connect your own tool" }); - await connector - .getByRole("button", { name: "Connect", exact: true }) - .click(); - await connector - .getByRole("button", { name: "Connect your own MCP server" }) - .click(); - await page - .getByPlaceholder("https://example.com/actions") - .fill(provider.url); - await page.getByRole("button", { name: "Continue", exact: true }).click(); - await page.getByRole("button", { name: /Check link/i }).click(); - await expect( - page.getByRole("heading", { name: /is ready/i }), - ).toBeVisible({ timeout: 30_000 }); - const { - connections: [connection], - } = await json<{ connections: Array<{ id: string }> }>( - await request.get(`/api/companies/${seed.companyId}/tools/connections`), - ); - await json( - await request.put(`/api/tool-connections/${connection.id}/installs`, { - data: { installs: [{ targetType: "agent", targetId: agent.id }] }, - }), - ); - await page.goto(`/${seed.prefix}/apps/${connection.id}/permissions`); - const [permissionSave] = await Promise.all([ - page.waitForResponse(response => response.request().method() === "POST" && - new URL(response.url()).pathname === `/api/companies/${seed.companyId}/tools/apps/${connection.id}/finish`), - page.getByRole("radio", { name: "List fixture pages: Ask first" }).click(), - ]); - expect(permissionSave.ok()).toBe(true); + let connectionId: string; + if (fullUiSetup) { + await page.goto(`/${seed.prefix}/apps`); + const connector = page + .getByRole("list", { name: "Connector list" }) + .getByRole("listitem") + .filter({ hasText: "Connect your own tool" }); + await connector + .getByRole("button", { name: "Connect", exact: true }) + .click(); + await connector + .getByRole("button", { name: "Connect your own MCP server" }) + .click(); + await page + .getByPlaceholder("https://example.com/actions") + .fill(provider.url); + await page.getByRole("button", { name: "Continue", exact: true }).click(); + await page.getByRole("button", { name: /Check link/i }).click(); + await expect( + page.getByRole("heading", { name: /is ready/i }), + ).toBeVisible({ timeout: 30_000 }); + const { + connections: [connection], + } = await json<{ connections: Array<{ id: string }> }>( + await request.get(`/api/companies/${seed.companyId}/tools/connections`), + ); + connectionId = connection.id; + await json( + await request.put(`/api/tool-connections/${connectionId}/installs`, { + data: { installs: [{ targetType: "agent", targetId: agent.id }] }, + }), + ); + await page.goto(`/${seed.prefix}/apps/${connectionId}/permissions`); + const [permissionSave] = await Promise.all([ + page.waitForResponse(response => response.request().method() === "POST" && + new URL(response.url()).pathname === `/api/companies/${seed.companyId}/tools/apps/${connectionId}/finish`), + page.getByRole("radio", { name: "List fixture pages: Ask first" }).click(), + ]); + expect(permissionSave.ok()).toBe(true); + } else { + const connected = await json<{ connectionId: string; catalog: Array<{ id: string }> }>( + await request.post(`/api/companies/${seed.companyId}/tools/apps/connect`, { + data: { link: provider.url }, + }), + ); + connectionId = connected.connectionId; + const catalogIds = connected.catalog.map((entry) => entry.id); + await json( + await request.post(`/api/companies/${seed.companyId}/tools/apps/${connectionId}/finish`, { + data: { + enabledCatalogEntryIds: catalogIds, + askFirstCatalogEntryIds: catalogIds, + access: { agentIds: [agent.id] }, + }, + }), + ); + } const configureAgent = async (query: string) => json( await request.patch(`/api/agents/${agent.id}`, { @@ -183,7 +205,7 @@ for (const journey of [ args: [ "--input-type=module", "-e", - reviewAgentScript(connection.id, query), + reviewAgentScript(connectionId, query), ], }, replaceAdapterConfig: true, @@ -210,36 +232,39 @@ for (const journey of [ const calls = () => provider.captures.filter((c) => c.method === "tools/call").length; expect(calls()).toBe(0); - await page.screenshot({ - path: testInfo.outputPath("pending-review.png"), - }); - await page - .getByRole("button", { name: "Dismiss Approve tool action" }) - .click(); - await expect( - page.getByRole("button", { name: "Approve & run", exact: true }), - ).not.toBeVisible(); - await page.reload(); - await expect(page.getByRole("button", { name: "Review request", exact: true })).toBeVisible({ timeout: 30_000 }); - await expect( - page.getByRole("button", { name: "Approve & run", exact: true }), - ).not.toBeVisible(); - await json( - await request.post(`/api/issues/${issue.id}/comments`, { - data: { body: "Keeping this review pending while I check." }, - }), - ); - await page - .getByRole("button", { name: "Review request", exact: true }) - .click(); - await expect( - page.getByRole("button", { name: "Approve & run", exact: true }), - ).toBeVisible(); - const queue = await context.newPage(); - await queue.goto(`/${seed.prefix}/apps/review`); - await expect( - queue.getByRole("button", { name: "Decline", exact: true }), - ).toBeVisible({ timeout: 20_000 }); + let queue: Awaited> | null = null; + if (fullUiSetup) { + await page.screenshot({ + path: testInfo.outputPath("pending-review.png"), + }); + await page + .getByRole("button", { name: "Dismiss Approve tool action" }) + .click(); + await expect( + page.getByRole("button", { name: "Approve & run", exact: true }), + ).not.toBeVisible(); + await page.reload(); + await expect(page.getByRole("button", { name: "Review request", exact: true })).toBeVisible({ timeout: 30_000 }); + await expect( + page.getByRole("button", { name: "Approve & run", exact: true }), + ).not.toBeVisible(); + await json( + await request.post(`/api/issues/${issue.id}/comments`, { + data: { body: "Keeping this review pending while I check." }, + }), + ); + await page + .getByRole("button", { name: "Review request", exact: true }) + .click(); + await expect( + page.getByRole("button", { name: "Approve & run", exact: true }), + ).toBeVisible(); + queue = await context.newPage(); + await queue.goto(`/${seed.prefix}/apps/review`); + await expect( + queue.getByRole("button", { name: "Decline", exact: true }), + ).toBeVisible({ timeout: 20_000 }); + } if (journey === "restart") { const control = process.env.PAPERCLIP_REVIEW_RESTART_FILE!; const token = String(Date.now()); @@ -260,7 +285,7 @@ for (const journey of [ ) .toBe(true); await page.reload(); - await queue.reload(); + await queue!.reload(); await expect( page.getByRole("button", { name: "Approve & run", exact: true }), ).not.toBeVisible(); @@ -272,7 +297,7 @@ for (const journey of [ } if (journey === "decline") { // Resolve from Connections and observe the still-open task tab update. - await queue + await queue! .getByRole("button", { name: "Decline", exact: true }) .click(); @@ -320,9 +345,11 @@ for (const journey of [ await expect( page.getByRole("button", { name: "Approve & run", exact: true }), ).not.toBeVisible(); - await expect( - queue.getByRole("button", { name: "Decline", exact: true }), - ).not.toBeVisible({ timeout: 20_000 }); + if (queue) { + await expect( + queue.getByRole("button", { name: "Decline", exact: true }), + ).not.toBeVisible({ timeout: 20_000 }); + } await page.bringToFront(); expect(await page.evaluate(() => document.visibilityState)).toBe("visible"); await page.reload(); @@ -390,7 +417,7 @@ for (const journey of [ ), contentType: "application/json", }); - await queue.close(); + await queue?.close(); } finally { await provider.close(); } diff --git a/tests/e2e/coordinator-inbox-views.spec.ts b/tests/e2e/coordinator-inbox-views.spec.ts index 5a148fbaf84..d4405ddccf5 100644 --- a/tests/e2e/coordinator-inbox-views.spec.ts +++ b/tests/e2e/coordinator-inbox-views.spec.ts @@ -15,9 +15,10 @@ for (const mobile of [false, true]) test(`Mine retains Inbox behavior inside Tas }); const company = await json(await request.post("/api/companies", { data: { name: "Personal Tasks verification" } })); const preferences = await json(await request.get("/api/workspace-preferences/me")); - const preferencePath = `/api/companies/${company.id}/workspace-preferences/me`; + await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: { + ...preferences, coordinatorWorkspaceEnabled: true, + } })); try { - await json(await request.put(preferencePath, { data: { coordinatorWorkspaceEnabled: true } })); const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { name: "Inbox activity fixture", adapterType: "process", adapterConfig: { command: process.execPath, args: [path.resolve("tests/e2e/fixtures/inbox-activity.mjs")], @@ -101,7 +102,6 @@ for (const mobile of [false, true]) test(`Mine retains Inbox behavior inside Tas expect(firstFilter!.x).toBeCloseTo(search!.x, 0); } } finally { - await request.put(preferencePath, { data: { coordinatorWorkspaceEnabled: preferences.coordinatorWorkspaceEnabled } }); await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); } }); diff --git a/tests/e2e/disconnect-resilience.spec.ts b/tests/e2e/disconnect-resilience.spec.ts index 99324869f0f..758d34a2821 100644 --- a/tests/e2e/disconnect-resilience.spec.ts +++ b/tests/e2e/disconnect-resilience.spec.ts @@ -52,7 +52,7 @@ async function fixture(request: APIRequestContext) { } async function outage(page: Page) { - const until = Date.now() + 20_000; + let until = Date.now() + 20_000; let failures = 0; const control = realtime.get(page); if (!control) throw new Error("Realtime interception must be installed before navigation"); @@ -63,7 +63,14 @@ async function outage(page: Page) { await route.fulfill({ status: 503, json: { error: "tenant_app_unavailable" } }); }); await closeSockets(control); - return { until, failures: () => failures }; + return { + get until() { return until; }, + end() { + until = Date.now(); + control.until = 0; + }, + failures: () => failures, + }; } test("an outage closes the first realtime socket before it can report a late recovery", async ({ page, request }) => { @@ -139,6 +146,7 @@ test("a comment typed during a 20-second outage posts once and loaded task conte await expect(header.getByRole("heading", { name: data.issue.title, exact: true })).toBeVisible(); await expect(page.getByText(body, { exact: true }).first()).toBeVisible(); expect((await json(await request.get(`/api/issues/${data.issue.id}/comments`))).filter((comment: { body: string }) => comment.body === body)).toHaveLength(0); + interruption.end(); await expect(page.locator('[data-connection-status="back_online"]')).toBeVisible({ timeout: 35_000 }); expect(Date.now()).toBeGreaterThanOrEqual(interruption.until); await expect.poll(async () => (await json(await request.get(`/api/issues/${data.issue.id}/comments`))) @@ -180,6 +188,7 @@ test("a queued comment survives an outage reload and sends once after session ve await expect(page.getByTestId("issue-detail-header").getByRole("heading", { name: data.issue.title, exact: true })).toBeVisible(); await expectReconnecting(page); expect((await json(await request.get(`/api/issues/${data.issue.id}/comments`))).filter((comment: { body: string }) => comment.body === body)).toHaveLength(0); + interruption.end(); await expect(page.locator('[data-connection-status="back_online"]')).toBeVisible({ timeout: 35_000 }); await expect.poll(() => sessionHeld).toBe(true); expect(await page.evaluate(async () => (await fetch("/api/health")).ok)).toBe(true); @@ -215,11 +224,12 @@ test("a document edit stays visible and saves after a 20-second outage", async ( await expect(document.getByText(original, { exact: true })).toBeVisible(); await document.getByRole("button", { name: "Document actions", exact: true }).click(); await page.getByRole("menuitem", { name: "Edit document", exact: true }).click(); - await outage(page); + const interruption = await outage(page); await document.locator('[contenteditable="true"]').fill(edited); await expectReconnecting(page); await expect(document.locator('[contenteditable="true"]')).toContainText(edited); expect((await json(await request.get(`/api/issues/${data.issue.id}/documents/handoff`))).body).toBe(original); + interruption.end(); await expect(page.locator('[data-connection-status="back_online"]')).toBeVisible({ timeout: 35_000 }); await expect.poll(async () => (await json(await request.get(`/api/issues/${data.issue.id}/documents/handoff`))).body).toBe(edited); await page.reload(); @@ -241,7 +251,7 @@ test("a reload during a 20-second outage restores settings, sidebar and a recent await expect(page.getByRole("heading", { name: "General", exact: true })).toBeVisible(); await expect(page.locator('input[type="text"]').first()).toHaveValue(data.company.name); await expect.poll(() => page.evaluate(() => Object.keys(localStorage).some(key => key.startsWith("paperclip:query-cache:v1:") && key.endsWith(":root")))).toBe(true); - await outage(page); + const interruption = await outage(page); await page.reload(); await expect(page.getByRole("heading", { name: "General", exact: true })).toBeVisible(); await expect(page.locator('input[type="text"]').first()).toHaveValue(data.company.name); @@ -251,6 +261,7 @@ test("a reload during a 20-second outage restores settings, sidebar and a recent await expect(page.getByTestId("issue-detail-header").getByRole("heading", { name: data.issue.title, exact: true })).toBeVisible(); await expectReconnecting(page); await expect(page.getByText(data.issue.description, { exact: true }).first()).toBeVisible(); + interruption.end(); await expect(page.locator('[data-connection-status="back_online"]')).toBeVisible({ timeout: 35_000 }); } finally { await request.patch(`/api/companies/${data.company.id}`, { data: { status: "archived" } }); @@ -284,11 +295,12 @@ test("a legacy Inbox reload retains its saved task rows during a 20-second outag query.queryKey.includes("compact") && Array.isArray(query.state.data) && query.state.data.some(task => task.id === id)) ?? false; } catch { return false; } }), data.issue.id)).toBe(true); - await outage(page); + const interruption = await outage(page); await page.reload(); await expectReconnecting(page); await expect(row).toBeVisible(); await expect(page.getByRole("status", { name: "Loading tasks" })).toHaveCount(0); + interruption.end(); await expect(page.locator('[data-connection-status="back_online"]')).toBeVisible({ timeout: 35_000 }); await expect(row).toBeVisible(); } finally { diff --git a/tests/e2e/document-image-gallery.spec.ts b/tests/e2e/document-image-gallery.spec.ts index 178efa02293..7d657f6d59c 100644 --- a/tests/e2e/document-image-gallery.spec.ts +++ b/tests/e2e/document-image-gallery.spec.ts @@ -14,9 +14,11 @@ for (const mode of ["desktop", "mobile", "classic"] as const) { await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: { userId: "local-board", coordinatorWorkspaceEnabled: mode !== "classic", updatedAt: null, } })); + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...settings, enableClassicTaskInterface: mode === "classic", + } })); + const company = await json(await request.post("/api/companies", { data: { name: `Document gallery ${randomUUID()}` } })); try { - await json(await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: mode === "classic" } })); - const company = await json(await request.post("/api/companies", { data: { name: `Document gallery ${randomUUID()}` } })); const issue = await json(await request.post(`/api/companies/${company.id}/issues`, { data: { title: "Review the design document", status: "backlog" }, })); @@ -140,7 +142,7 @@ for (const mode of ["desktop", "mobile", "classic"] as const) { await expect(gallery).toContainText("1 / 3"); } } finally { - await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: settings.enableClassicTaskInterface } }); + await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); } }); } diff --git a/tests/e2e/legacy-failure-continuation.spec.ts b/tests/e2e/legacy-failure-continuation.spec.ts deleted file mode 100644 index 426ff9073a5..00000000000 --- a/tests/e2e/legacy-failure-continuation.spec.ts +++ /dev/null @@ -1,189 +0,0 @@ -import { randomUUID } from "node:crypto"; -import { mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; -import os from "node:os"; -import path from "node:path"; -import { test, expect, type APIResponse } from "@playwright/test"; -import { and, eq } from "../../server/node_modules/drizzle-orm/index.js"; -import { createDb, closeRegisteredClients, heartbeatRuns, issueRecoveryActions, issues, issueComments, agentWakeupRequests, authUsers, companyMemberships } from "../../packages/db/src/index.ts"; - -async function json(response: APIResponse) { - expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true); - return response.json(); -} - -for (const action of ["task_retry", "retry_after_reload", "inbox_retry", "message", "queued_retry", "automatic_message_on_reactivation"] as const) { - test(`legacy startup hold: ${action} reaches a new agent response`, async ({ page, request }) => { - test.setTimeout(120_000); - const root = await mkdtemp(path.join(os.tmpdir(), "legacy-recovery-browser-")); - const config = JSON.parse(await readFile(process.env.PAPERCLIP_E2E_SERVER_CONFIG!, "utf8")); - // Use the running test server's actual port, including fallback allocation. - const url = config.database.mode === "postgres" ? config.database.connectionString - : `postgres://paperclip:paperclip@127.0.0.1:${(await readFile( - path.join(config.database.embeddedPostgresDataDir, "postmaster.pid"), "utf8")).split("\n")[3]}/paperclip`; - const db = createDb(url); - const company = await json(await request.post("/api/companies", { data: { name: `Legacy recovery ${action} ${Date.now()}` } })); - try { - await writeFile(path.join(root, "continued"), "ready"); - const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { - name: "Recovery fixture", role: "engineer", adapterType: "claude_local", runner: "legacy", - adapterConfig: { engine: "acp", cwd: root, stateDir: path.join(root, "state"), - agentCommand: `${JSON.stringify(process.execPath)} ${JSON.stringify(path.resolve("scripts/mcp-fixtures/servers/acp-stop-agent.mjs"))}`, - // The ACP fixture has no provider login. Use a fixture key to keep setup offline. - env: { ANTHROPIC_API_KEY: "acp-stop-fixture-key", PAPERCLIP_STOP_FIXTURE_ROOT: root, PAPERCLIP_STOP_FIXTURE_FINISH_TASK: "1" } }, - runtimeConfig: { heartbeat: { enabled: false, wakeOnDemand: true } }, - } })); - await expect.poll(async () => (await json(await request.get(`/api/agents/${agent.id}`))).lifecycleState, - { timeout: 45_000 }).toBe("ready"); - const issue = await json(await request.post(`/api/companies/${company.id}/issues`, { data: { - title: "Continue after startup failure", description: "Answer the pending follow-up once.", - status: "backlog", assigneeAgentId: agent.id, - } })); - if (action === "automatic_message_on_reactivation") { - await json(await request.patch(`/api/companies/${company.id}`, { data: { status: "paused" } })); - // Pause cleanup cancels pending wakeups. Finish that operation before - // seeding the historical saved input that reactivation must recover. - await expect.poll(async () => (await json(await request.get(`/api/agents/${agent.id}`))).lifecycleState, - { timeout: 45_000 }).toBe("paused"); - } - const sourceRunId = randomUUID(); - // Seed the historical incident, then exercise ordinary recovery entry points. - // No adapter.invoke or new dispatch identity exists on this pre-upgrade run. - await db.insert(heartbeatRuns).values({ id: sourceRunId, companyId: company.id, agentId: agent.id, - status: "failed", runtimeMode: "legacy", processPid: action === "queued_retry" ? process.pid : 999999999, - responsibleUserId: issue.responsibleUserId, errorCode: "process_lost", error: "Server restarted during startup", - startedAt: new Date(Date.now() - 10_000), finishedAt: new Date(Date.now() - 5_000), - contextSnapshot: { issueId: issue.id }, - }); - await db.insert(issueRecoveryActions).values({ companyId: company.id, sourceIssueId: issue.id, - kind: "active_run_watchdog", cause: "legacy_execution_requires_reconciliation", fingerprint: sourceRunId, - status: "resolved", outcome: "blocked", nextAction: "Automatic recovery stopped.", - evidence: { runId: sourceRunId, automaticRecovery: { replay: "blocked", actionOutcome: "unknown" } }, - }); - await db.update(issues).set({ status: "blocked" }).where(eq(issues.id, issue.id)); - if (action === "queued_retry") { - await db.insert(authUsers).values({ id: "original-board", name: "Original author", email: "original-author@example.test", - createdAt: new Date(), updatedAt: new Date() }).onConflictDoNothing(); - await db.insert(companyMemberships).values({ companyId: company.id, principalType: "user", - principalId: "original-board", membershipRole: "operator", status: "active" }); - } - if (action === "queued_retry" || action === "automatic_message_on_reactivation") { - const commentId = randomUUID(); - // Reproduce a real user comment saved while the failed run was active, - // including queues originally created by a system wake. - await db.insert(issueComments).values({ id: commentId, companyId: company.id, issueId: issue.id, - authorType: "user", authorUserId: action === "queued_retry" ? "original-board" : "local-board", body: "Approved", - createdAt: new Date(Date.now() - 8_000), - }); - await db.insert(agentWakeupRequests).values({ companyId: company.id, agentId: agent.id, - source: "automation", reason: "issue_commented", status: "deferred_issue_execution", - requestedByActorType: "system", payload: { issueId: issue.id, commentId, - _paperclipWakeContext: { issueId: issue.id, wakeCommentIds: [commentId], wakeCommentId: commentId } }, - }); - } - const taskUrl = `/${company.issuePrefix}/issues/${issue.identifier}`; - await page.goto(action === "inbox_retry" ? `/${company.issuePrefix}/inbox/all` : taskUrl); - if (action === "task_retry") { - const notice = page.getByRole("status", { name: "Task status" }); - await expect(notice).toContainText("Couldn’t finish this attempt. Your message is saved."); - await expect(page.getByText("Automatic recovery stopped.", { exact: true })).toHaveCount(0); - await expect(notice.getByRole("link", { name: "Inspect run" })).toHaveCount(0); - await expect(notice.getByRole("button", { name: "Retry", exact: true })).toBeEnabled(); - await test.info().attach("task-retry", { body: await notice.screenshot(), contentType: "image/png" }); - } - if (action === "retry_after_reload") { - await page.reload(); - await expect(page.getByRole("button", { name: "Try again", exact: true })).toHaveCount(0); - await expect(page.getByRole("button", { name: "Retry", exact: true })).toBeEnabled(); - } - if (action === "queued_retry") { - await expect(page.getByRole("button", { name: "Interrupt", exact: true })).toHaveCount(0); - await expect(page.getByRole("button", { name: "Steer", exact: true })).toHaveCount(0); - const retry = page.getByRole("button", { name: "Retry", exact: true }); - await expect(retry).toBeEnabled(); - await page.route((url) => url.pathname === `/api/issues/${issue.id}/retry`, async route => { - if (route.request().method() !== "POST") return route.continue(); - await db.update(heartbeatRuns).set({ processPid: 999999999 }).where(eq(heartbeatRuns.id, sourceRunId)); - await route.continue(); - }, { times: 1 }); - const [response] = await Promise.all([ - page.waitForResponse(response => response.request().method() === "POST" && - new URL(response.url()).pathname === `/api/issues/${issue.id}/retry` && - response.request().postDataJSON()?.observedRunId === sourceRunId), - retry.click(), - ]); - expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true); - } else if (action === "automatic_message_on_reactivation") { - // This fixture writes history through a separate SQL connection after boot. - // Reactivation is the supported producer that makes saved work eligible; - // startup reconstruction itself is covered before registration in the PG suite. - const pending = await db.select().from(agentWakeupRequests).where(and( - eq(agentWakeupRequests.companyId, company.id), eq(agentWakeupRequests.agentId, agent.id), - eq(agentWakeupRequests.status, "deferred_issue_execution"), - )); - expect(pending).toHaveLength(1); - const before = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, company.id)); - expect(before).toHaveLength(1); - await json(await request.patch(`/api/companies/${company.id}`, { data: { status: "active" } })); - // No Retry or duplicate message: the existing saved input runs once. - } else if (action === "message") { - await page.getByRole("textbox", { name: "editable markdown" }).fill("Please continue the pending follow-up."); - await page.getByRole("button", { name: "Send", exact: true }).click(); - } else if (action === "inbox_retry") { - // Navigation can cancel the mutation before its request is sent. - const [response] = await Promise.all([ - page.waitForResponse((response) => { - const request = response.request(); - return request.method() === "POST" - && new URL(response.url()).pathname.endsWith(`/issues/${issue.id}/retry`) - && request.postDataJSON()?.observedRunId === sourceRunId; - }), - page.getByRole("button", { name: "Retry", exact: true }).click(), - ]); - expect(response.ok(), `${response.status()} ${await response.text()}`).toBe(true); - await page.goto(taskUrl); - } else { - await page.getByRole("button", { name: "Retry", exact: true }).click(); - } - await expect(page.getByText("Answered the pending follow-up once.", { exact: false })).toBeVisible({ timeout: 45_000 }); - await expect(page.getByRole("status", { name: "Task recovery" })).toHaveCount(0); - const completed = await json(await request.get(`/api/issues/${issue.id}`)); - expect(completed).toMatchObject({ status: "done", executionBlocker: null }); - const runs = await db.select().from(heartbeatRuns).where(and(eq(heartbeatRuns.companyId, company.id), eq(heartbeatRuns.agentId, agent.id))); - expect(runs.filter(run => run.id !== sourceRunId)).toHaveLength(1); - const source = runs.find(run => run.id === sourceRunId)!; - expect(source).toMatchObject({ status: "failed", errorCode: "process_lost", error: "Server restarted during startup" }); - // Fresh continuation revokes the replaced run's write authority with this timestamp. - if (source.resultJson !== null) { - expect(source.resultJson).toEqual({ freshContinuationSupersededAt: expect.any(String) }); - const supersededAt = source.resultJson.freshContinuationSupersededAt as string; - expect(new Date(supersededAt).toISOString()).toBe(supersededAt); - } - const prompts = await readFile(path.join(root, "prompts"), "utf8"); - if (action === "queued_retry" || action === "automatic_message_on_reactivation") { - expect(prompts).toContain("Approved"); - await expect(page.getByRole("button", { name: "Interrupt", exact: true })).toHaveCount(0); - } - if (action === "message") expect(prompts).toContain("Please continue the pending follow-up."); - const resumedRunId = runs.find(run => run.id !== sourceRunId)!.id; - await expect.poll(async () => { - const replies = await db.select({ body: issueComments.body }).from(issueComments).where(and( - eq(issueComments.companyId, company.id), eq(issueComments.issueId, issue.id), - eq(issueComments.authorAgentId, agent.id), eq(issueComments.createdByRunId, resumedRunId), - )); - return replies.filter(reply => reply.body.includes("Answered the pending follow-up once.")).length; - }, { timeout: 45_000 }).toBe(1); - await page.reload(); - await expect(page.getByText("Answered the pending follow-up once.", { exact: false })).toBeVisible(); - } finally { - try { - await request.patch(`/api/companies/${company.id}`, { data: { status: "archived" } }); - } finally { - try { - await closeRegisteredClients(url); - } finally { - await rm(root, { recursive: true, force: true }); - } - } - } - }); -} diff --git a/tests/e2e/nux-phase4-screenshots.spec.ts b/tests/e2e/nux-phase4-screenshots.spec.ts deleted file mode 100644 index 1e8994508b3..00000000000 --- a/tests/e2e/nux-phase4-screenshots.spec.ts +++ /dev/null @@ -1,128 +0,0 @@ -import { test, expect } from "@playwright/test"; -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const __dirname = path.dirname(fileURLToPath(import.meta.url)); - -/** - * NUX Phase 4 — visual QA screenshot capture. - * - * Boots a throwaway local_trusted instance (see playwright.config.ts webServer) - * and captures screenshots of every surface integrated by NUX Phases 1–3: - * - "Build a new company" step 1 (company name) - * - Team-lead hire step (capsule wizard, PAP-125) - * - Conference Room (BoardChat) shell + composer + activity feed - * - Artifacts page - * - * The onboarding front door and the "Add agents to your org" growth intake - * were removed with the four-step wizard, so the shots that captured them - * are gone too. - * - * These are structural/rendering checks — LLM-dependent streaming (CEO chat - * responses, hiring-plan generation) is verified separately on an LLM-backed - * instance. Screenshots land in ./nux-phase4-shots for upload as evidence. - */ - -// Write under the gitignored test-results dir so re-runs leave no untracked -// noise; screenshots are uploaded to the issue as QA evidence, not committed. -const SHOT_DIR = path.join(__dirname, "test-results", "nux-phase4-shots"); - -function shot(name: string) { - fs.mkdirSync(SHOT_DIR, { recursive: true }); - return path.join(SHOT_DIR, name); -} - -async function openWizard(page: import("@playwright/test").Page) { - await page.goto("/onboarding"); - const startBtn = page.getByRole("button", { name: /Start Onboarding|New Organization|Add Agent/ }); - if (await startBtn.count()) { - await startBtn.first().click(); - } -} - -test.describe("NUX Phase 4 visual QA", () => { - test("captures every integrated surface", async ({ page }) => { - // New-NUX surfaces are flag-gated default-OFF (PAP-136/137/138): turn the - // experimental flag on for this throwaway instance before driving them. - const flagRes = await page.request.patch("/api/instance/settings/experimental", { - data: { enableConferenceRoomChat: true }, - }); - expect(flagRes.ok()).toBe(true); - - const consoleErrors: string[] = []; - page.on("console", (msg) => { - if (msg.type() === "error") consoleErrors.push(msg.text()); - }); - page.on("pageerror", (err) => consoleErrors.push("PAGEERROR: " + err.message)); - - const baseUrl = - "http://127.0.0.1:" + (process.env.PAPERCLIP_E2E_PORT ?? "3199"); - - // ── Section A: create-company path (name → hire) ────────────────────── - await openWizard(page); - await expect( - page.getByRole("heading", { name: "What is the name of your organization?" }), - ).toBeVisible({ timeout: 15_000 }); - await page.getByPlaceholder("e.g. Northwind Labs").fill("QA Robotics"); - await page.screenshot({ path: shot("02-create-name.png") }); - - await page.getByRole("button", { name: /^Continue/ }).click(); - // Step 1's "Next" creates the company and goes straight to the team lead. - // The mission screenshot that sat here is gone with the step it captured. - await page.waitForSelector("#onboarding-agent-name", { - timeout: 30_000, - }); - await page.screenshot({ path: shot("04-hire-team-lead.png") }); - - // The company just created anchors the route-scoped sections below. - const companiesRes = await page.request.get(`${baseUrl}/api/companies`); - expect(companiesRes.ok()).toBe(true); - const companies = await companiesRes.json(); - const qaCompany = (Array.isArray(companies) ? companies : []).find( - (c: { name: string }) => c.name === "QA Robotics", - ); - expect(qaCompany, "wizard should have created QA Robotics").toBeTruthy(); - const prefix: string = qaCompany.issuePrefix; - - // ── Section B: Conference Room (BoardChat) ──────────────────────────── - // Visit the company dashboard first so CompanyContext selects the company - // from the route before we land on the board-chat surface. - await page.evaluate(() => window.localStorage.clear()); - await page.goto(`/${prefix}/dashboard`); - await page.waitForLoadState("networkidle"); - await page.goto(`/${prefix}/board-chat`); - await expect(page).toHaveURL(new RegExp(`/${prefix}/board-chat`)); - // Composer renders once a company is selected. (Regression guard for the - // Rules-of-Hooks crash that previously blanked this page — see PAP-50.) - await expect( - page.getByPlaceholder("Ask anything about your organization..."), - ).toBeVisible({ timeout: 20_000 }); - await page.waitForTimeout(2_000); // let welcome bubble + suggestion chips stage in - await page.screenshot({ path: shot("06-board-chat.png") }); - - // ── Section C: Artifacts ────────────────────────────────────────────── - await page.goto(`/${prefix}/artifacts`); - await expect(page).toHaveURL(new RegExp(`/${prefix}/artifacts`)); - await page.waitForLoadState("networkidle"); - await page.waitForTimeout(1_000); - await page.screenshot({ path: shot("07-artifacts.png") }); - - for (const f of [ - "02-create-name.png", - "04-hire-team-lead.png", - "06-board-chat.png", - "07-artifacts.png", - ]) { - const p = shot(f); - expect(fs.existsSync(p), `missing ${f}`).toBe(true); - expect(fs.statSync(p).size, `empty ${f}`).toBeGreaterThan(1_000); - } - - // No React Rules-of-Hooks / render crashes on any surface we visited. - const hookErrors = consoleErrors.filter( - (e) => /Rendered more hooks|change in the order of Hooks/i.test(e), - ); - expect(hookErrors, hookErrors.join("\n")).toHaveLength(0); - }); -}); diff --git a/tests/e2e/onboarding.spec.ts b/tests/e2e/onboarding.spec.ts index 33fba2c7f37..20fdd493802 100644 --- a/tests/e2e/onboarding.spec.ts +++ b/tests/e2e/onboarding.spec.ts @@ -17,8 +17,7 @@ import { mockOnboardingLocalAiConnection } from "./helpers/onboarding-ai-connect * * The tail (CEO chat at step 4, hiring-plan generation at step 5, final * landing) depends on a live LLM and is verified separately during manual / - * LLM-backed QA — see PAP-50. Surface-level rendering of every step is - * snapshotted by nux-phase4-screenshots.spec.ts. + * LLM-backed QA — see PAP-50. */ const COMPANY_NAME = `E2E-Test-${Date.now()}`; diff --git a/tests/e2e/paused-composer.spec.ts b/tests/e2e/paused-composer.spec.ts index 6bab5f45f43..5ef7d8d3db1 100644 --- a/tests/e2e/paused-composer.spec.ts +++ b/tests/e2e/paused-composer.spec.ts @@ -25,10 +25,9 @@ async function pauseTask(page: Page) { await page.getByRole("button", { name: "Pause work", exact: true }).click({ timeout: 10_000 }); } -async function cleanupFixture(request: APIRequestContext, companyId: string, classic: boolean, primaryFailed: boolean) { +async function cleanupFixture(request: APIRequestContext, companyId: string, primaryFailed: boolean) { const operations = [ { name: "archive fixture company", run: () => request.patch(`/api/companies/${companyId}`, { data: { status: "archived" } }) }, - { name: "restore task interface", run: () => request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: classic } }) }, ]; const outcomes = await Promise.allSettled(operations.map(async operation => { const response = await operation.run(); @@ -39,7 +38,7 @@ async function cleanupFixture(request: APIRequestContext, companyId: string, cla if (!failures.length) return; if (!primaryFailed) throw new AggregateError(failures.map(failure => new Error(`${failure.operation}: ${failure.error}`)), "Paused composer fixture cleanup failed"); // A timeout may have disposed the request fixture. Keep that original - // failure while retaining both cleanup outcomes for diagnosis. + // failure while retaining cleanup outcomes for diagnosis. console.warn("Paused composer fixture cleanup failed after the primary failure", failures); await test.info().attach("paused-composer-cleanup-errors", { body: Buffer.from(JSON.stringify(failures, null, 2)), contentType: "application/json", @@ -54,9 +53,11 @@ for (const classic of [false, true]) { await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: { userId: "local-board", coordinatorWorkspaceEnabled: !classic, updatedAt: null, } })); + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...settings, enableClassicTaskInterface: classic, + } })); let primaryFailed = false; try { - await json(await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: classic } })); const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { name: "Resume preview fixture", role: "engineer", adapterType: "process", adapterConfig: { command: "/usr/bin/true" }, @@ -93,7 +94,7 @@ for (const classic of [false, true]) { primaryFailed = true; throw error; } finally { - await cleanupFixture(request, company.id, settings.enableClassicTaskInterface, primaryFailed); + await cleanupFixture(request, company.id, primaryFailed); } }); @@ -104,9 +105,11 @@ for (const classic of [false, true]) { await page.route("**/api/workspace-preferences/me", route => route.fulfill({ json: { userId: "local-board", coordinatorWorkspaceEnabled: !classic, updatedAt: null, } })); + await page.route("**/api/instance/settings/experimental", route => route.fulfill({ json: { + ...settings, enableClassicTaskInterface: classic, + } })); let primaryFailed = false; try { - await json(await request.patch("/api/instance/settings/experimental", { data: { enableClassicTaskInterface: classic } })); const agent = await json(await request.post(`/api/companies/${company.id}/agents`, { data: { name: "Paused composer fixture", role: "engineer", adapterType: "process", adapterConfig: { command: "/usr/bin/true" }, @@ -173,7 +176,7 @@ for (const classic of [false, true]) { primaryFailed = true; throw error; } finally { - await cleanupFixture(request, company.id, settings.enableClassicTaskInterface, primaryFailed); + await cleanupFixture(request, company.id, primaryFailed); } }); } diff --git a/tests/e2e/planning-mode-visual-verification.spec.ts b/tests/e2e/planning-mode-visual-verification.spec.ts deleted file mode 100644 index 309ee89b457..00000000000 --- a/tests/e2e/planning-mode-visual-verification.spec.ts +++ /dev/null @@ -1,199 +0,0 @@ -import { expect, test } from "@playwright/test"; -import { mockOnboardingLocalAiConnection } from "./helpers/onboarding-ai-connection"; -import { - expectLandsOnChatWithoutDashboardBounce, - instrumentNavLog, -} from "./helpers/onboarding-landing"; - -/** The name the CEO role fills in — see AGENT_ROLE_LABELS. */ -const AGENT_NAME = "CEO"; -const TASK_TITLE = "Paperclip onboarding"; - -/** Wait for the saved question before checking its dismissed presentation. */ -async function expectOpeningQuestionDismissed(page: import("@playwright/test").Page) { - await expect(page.getByTestId("task-chat-unanswered-question")).toBeVisible({ timeout: 30_000 }); - await expect(page.getByTestId("task-chat-composer-takeover")).toHaveCount(0); - await expect(page.getByTestId("task-chat-pending-input-indicator")).toHaveCount(0); - await expect(page.getByTestId("task-chat-composer-mode")).toBeVisible({ timeout: 30_000 }); -} - -/** The opening question arrives after the interactions fetch. Dismiss it once. */ -async function dismissOpeningCard(page: import("@playwright/test").Page) { - const takeover = page.getByTestId("task-chat-composer-takeover"); - await expect(takeover).toBeVisible({ timeout: 30_000 }); - await takeover.getByRole("button", { name: "Cancel", exact: true }).click(); - await expectOpeningQuestionDismissed(page); -} - -test("captures planning mode UI for desktop and mobile", async ({ page }) => { - const timestamp = Date.now(); - const companyName = `PAP-3413-${timestamp}`; - const screenshotDir = "test-results/planning-mode"; - - await instrumentNavLog(page); - await mockOnboardingLocalAiConnection(page); - await page.route("**/onboarding/greeting", route => route.fulfill({ json: { started: false } })); - - await page.route("**/test-environment", (route) => - route.fulfill({ - contentType: "application/json", - body: JSON.stringify({ status: "pass", checks: [] }), - }), - ); - - await page.route("**/agent-hires", async (route) => { - const req = route.request(); - const body = JSON.parse(req.postData() || "{}"); - const auth = req.headers().authorization; - const real = await fetch(new URL(req.url()).toString(), { - method: "POST", - headers: { - "Content-Type": "application/json", - ...(auth ? { Authorization: auth } : {}), - }, - body: JSON.stringify({ - name: body.name, - role: body.role, - adapterType: "http", - adapterConfig: { url: "http://127.0.0.1:1/dead" }, - runtimeConfig: { heartbeat: { enabled: false } }, - }), - }); - await route.fulfill({ - status: real.status, - contentType: "application/json", - body: await real.text(), - }); - }); - - await page.goto("/onboarding"); - const startBtn = page.getByRole("button", { name: /Start Onboarding|New Organization|Add Agent/ }); - if (await startBtn.count()) await startBtn.first().click(); - - const createCard = page.getByRole("button", { name: /Build a new organization/ }); - if (await createCard.count()) await createCard.first().click(); - - await expect(page.getByRole("heading", { name: "What is the name of your organization?" })).toBeVisible({ timeout: 15_000 }); - - await page.locator('input[placeholder="e.g. Northwind Labs"]').fill(companyName); - await page.getByRole("button", { name: /^Continue/ }).click(); - - // Naming the company creates it and goes straight to the agent step. - - // The agent step asks for a name and nothing else; the name is what gates - // "Next", and the hire is filed under the neutral `general` role. - await page.waitForSelector("#onboarding-agent-name", { timeout: 30_000 }); - await page.locator("#onboarding-agent-name").fill(AGENT_NAME); - - await page.getByRole("button", { name: /^Next$/ }).click(); - - // The connect step arrives with no source selected — the tile row is a - // question, not a confirmation — so its CTA stays disabled until one is - // pressed. The simulated verified account then advances automatically. - const source = page.getByRole("radio").first(); - await source.waitFor({ timeout: 30_000 }); - await source.click(); - - // The review step names the agent rather than the step. - await expect( - page.getByRole("heading", { name: "Let's get started..." }), - ).toBeVisible({ timeout: 30_000 }); - await page.getByRole("button", { name: /Get started/ }).click(); - // The wizard opens the standing chat, - // and must not bounce through the dashboard (PAP-404). - await expectLandsOnChatWithoutDashboardBounce(page); - - const baseOrigin = new URL(page.url()).origin; - const companyRes = await page.request.get(`${baseOrigin}/api/companies`); - expect(companyRes.ok()).toBe(true); - const companies = await companyRes.json(); - const company = companies.find((c: { name: string }) => c.name === companyName); - expect(company).toBeTruthy(); - const issueRes = await page.request.get(`${baseOrigin}/api/companies/${company.id}/issues`); - expect(issueRes.ok()).toBe(true); - const issues = await issueRes.json(); - expect(issues).toEqual([]); - const agentsRes = await page.request.get(`${baseOrigin}/api/companies/${company.id}/agents`); - const [agent] = await agentsRes.json(); - // This suite explicitly creates its legacy planning/question fixture; the - // onboarding wizard itself must leave execution work empty. - const created = await page.request.post(`${baseOrigin}/api/companies/${company.id}/issues`, { - data: { title: TASK_TITLE, assigneeAgentId: agent.id, onboardingFirstTask: true, status: "todo" }, - }); - expect(created.ok()).toBe(true); - const issue = await created.json(); - const issueIdentifier = issue.identifier ?? issue.id; - const issuePath = `/${company.issuePrefix ?? company.id}/issues/${issueIdentifier}`; - const companyPrefix = company.issuePrefix ?? company.id; - const issueRow = page.locator(`[data-issue-row-details="${issue.id}"]`); - - const setMode = async (mode: "standard" | "planning") => { - const patchRes = await page.request.patch(`${baseOrigin}/api/issues/${issue.id}`, { - data: { workMode: mode }, - }); - expect(patchRes.ok()).toBe(true); - await expect - .poll(async () => { - const currentRes = await page.request.get(`${baseOrigin}/api/issues/${issue.id}`); - expect(currentRes.ok()).toBe(true); - const current = await currentRes.json(); - return current.workMode; - }, { timeout: 10_000 }) - .toBe(mode); - }; - - await setMode("planning"); - - await page.goto(issuePath); - await dismissOpeningCard(page); - await page.reload(); - await expectOpeningQuestionDismissed(page); - await expect(page.getByText("Plan mode").first()).toBeVisible(); - const desktopPlanningToggle = page.getByTestId("task-chat-composer-mode"); - await expect(desktopPlanningToggle).toBeVisible(); - await expect(desktopPlanningToggle).toHaveAttribute("data-pending-work-mode", "planning"); - - await page.screenshot({ - path: `${screenshotDir}/desktop-planning-detail-${timestamp}.png`, - fullPage: true, - }); - - await page.goto(`/${companyPrefix}/issues`); - await expect(issueRow).toBeVisible(); - await expect(issueRow).not.toContainText("Plan mode"); - await page.screenshot({ - path: `${screenshotDir}/desktop-planning-row-${timestamp}.png`, - fullPage: true, - }); - - await page.goto(issuePath); - await expectOpeningQuestionDismissed(page); - await page.getByTestId("task-chat-composer-mode").click(); - await expect(page.getByTestId("task-chat-composer-mode")).toHaveCount(0); - await expect(page.getByTestId("task-chat-composer-add")).toBeVisible(); - await page.screenshot({ - path: `${screenshotDir}/desktop-standard-toggle-${timestamp}.png`, - fullPage: true, - }); - - await setMode("planning"); - await page.setViewportSize({ width: 390, height: 844 }); - await page.goto(issuePath); - await expectOpeningQuestionDismissed(page); - await expect(page.getByText("Plan mode").first()).toBeVisible(); - const mobilePlanningToggle = page.getByTestId("task-chat-composer-mode"); - await expect(mobilePlanningToggle).toBeVisible(); - await expect(mobilePlanningToggle).toHaveAttribute("data-pending-work-mode", "planning"); - await page.screenshot({ - path: `${screenshotDir}/mobile-planning-detail-${timestamp}.png`, - fullPage: true, - }); - - await page.goto(`/${companyPrefix}/issues`); - await expect(issueRow).toBeVisible(); - await expect(issueRow).not.toContainText("Plan mode"); - await page.screenshot({ - path: `${screenshotDir}/mobile-planning-row-${timestamp}.png`, - fullPage: true, - }); -}); diff --git a/tests/e2e/playwright.config.ts b/tests/e2e/playwright.config.ts index 3b99ee9dd79..a8674ce101c 100644 --- a/tests/e2e/playwright.config.ts +++ b/tests/e2e/playwright.config.ts @@ -30,6 +30,100 @@ process.env.PAPERCLIP_AGENT_JWT_SECRET = PAPERCLIP_AGENT_JWT_SECRET; process.env.PAPERCLIP_DECISION_SIGNING_SECRET = PAPERCLIP_DECISION_SIGNING_SECRET; process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET = PAPERCLIP_TOOL_ACTION_SIGNING_SECRET; +const REPO_ROOT = path.resolve(import.meta.dirname, "../.."); +const UI_DIST_INDEX = path.join(REPO_ROOT, "server", "ui-dist", "index.html"); +const SKIP_UI_BUILD = ["1", "true"].includes( + (process.env.PAPERCLIP_E2E_SKIP_UI_BUILD ?? "").trim().toLowerCase(), +); +if (SKIP_UI_BUILD && !fs.existsSync(UI_DIST_INDEX)) { + throw new Error( + `PAPERCLIP_E2E_SKIP_UI_BUILD is enabled, but prebuilt UI assets are missing at ${UI_DIST_INDEX}. ` + + "Build @paperclipai/ui into server/ui-dist first or unset PAPERCLIP_E2E_SKIP_UI_BUILD.", + ); +} + +// Specs that mutate instance-wide state on the shared throwaway server +// (server-read experimental flags or server-persisted workspace preferences) +// or assert strict real-time latency / focus restoration sensitive to +// multi-worker Chromium CPU contention. Keep in sync with `SERIAL_SPECS` in +// `scripts/e2e-shard.mjs` — `scripts/__tests__/e2e-shard.test.mjs` fails if +// the two ever drift. +export const SERIAL_SPECS = [ + "agent-configuration.spec.ts", + "cases-read-only.spec.ts", + "classic-workspace.spec.ts", + "composer-stop.spec.ts", + "connection-intents.spec.ts", + "document-image-gallery.spec.ts", + "onboarding.spec.ts", + "smoke-lab-p1-p4.spec.ts", + "smoke-lab-p5-p7.spec.ts", +]; + +function extractCliSpecBasenames(argv: string[]): string[] { + const specs: string[] = []; + for (let index = 2; index < argv.length; index += 1) { + const arg = argv[index]!; + if (arg === "--config" || arg === "-c" || arg === "--project" || arg === "--grep" || arg === "-g") { + index += 1; + continue; + } + if (arg.startsWith("-")) continue; + if (arg.endsWith(".spec.ts")) { + specs.push(path.basename(arg)); + } + } + return specs; +} + +function resolveExecutionMode(): { workers: number; fullyParallel: boolean } { + // Worker processes reload this config without the parent CLI spec filters. + // Cache the parent process's decision in env so workers agree with the runner. + if ( + process.env.PAPERCLIP_E2E_RESOLVED_WORKERS && + process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL + ) { + return { + workers: Number(process.env.PAPERCLIP_E2E_RESOLVED_WORKERS), + fullyParallel: process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL === "true", + }; + } + + const cliSpecs = extractCliSpecBasenames(process.argv); + const serialSet = new Set(SERIAL_SPECS); + const includesSerial = cliSpecs.some((spec) => serialSet.has(spec)); + const strictlyParallelSafe = cliSpecs.length > 0 && !includesSerial; + + const explicitWorkers = Number.parseInt(process.env.PAPERCLIP_E2E_WORKERS ?? "", 10); + let workers: number; + let fullyParallel: boolean; + if (Number.isInteger(explicitWorkers) && explicitWorkers >= 1) { + workers = explicitWorkers; + fullyParallel = workers > 1 && !includesSerial; + } else if (strictlyParallelSafe) { + // 2 Chromium workers + Node server + embedded Postgres fits cleanly on + // 4-vCPU CI runners without CPU over-subscription thrashing. + workers = process.env.CI + ? 2 + : Math.min(2, Math.max(1, Math.floor(os.cpus().length / 2))); + fullyParallel = true; + } else { + workers = 1; + fullyParallel = false; + } + + process.env.PAPERCLIP_E2E_RESOLVED_WORKERS = String(workers); + process.env.PAPERCLIP_E2E_RESOLVED_FULLY_PARALLEL = String(fullyParallel); + return { workers, fullyParallel }; +} + +const EXECUTION_MODE = resolveExecutionMode(); +const SERVER_START_COMMAND = + "node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts onboard --yes --run"; +const WEB_SERVER_COMMAND = SKIP_UI_BUILD + ? SERVER_START_COMMAND + : `pnpm --filter @paperclipai/ui build --outDir ../server/ui-dist --emptyOutDir && ${SERVER_START_COMMAND}`; + export default defineConfig({ testDir: ".", testMatch: "**/*.spec.ts", @@ -38,11 +132,11 @@ export default defineConfig({ testIgnore: ["in-feed-native/**", "multi-user.spec.ts", "multi-user-authenticated.spec.ts"], timeout: 60_000, retries: 0, - // All specs share one throwaway server, and several toggle instance-level - // state (the `enableConferenceRoomChat` experimental flag) that changes - // which UI variant renders. Run files serially so a flag flip in one spec - // can't change the wizard/thread under another spec mid-flight. - workers: 1, + // Parallel-safe shards run concurrently across multiple workers; shards or + // runs that include any spec in SERIAL_SPECS (or unfiltered full runs) fall + // back to 1 worker so server-level experimental flags cannot race mid-flight. + workers: EXECUTION_MODE.workers, + fullyParallel: EXECUTION_MODE.fullyParallel, use: { baseURL: BASE_URL, headless: true, @@ -61,13 +155,13 @@ export default defineConfig({ // The webServer directive bootstraps a throwaway instance and then starts it. // `onboard --yes --run` works in a non-interactive temp PAPERCLIP_HOME. webServer: { - cwd: path.resolve(import.meta.dirname, "../.."), + cwd: REPO_ROOT, // Exercise the shipped UI. Source-checkout onboarding otherwise enables // Vite middleware: every reload traverses thousands of modules, including // service-worker-intercepted requests, before React can even start. - // Build the server's first-choice static directory so a prior package build - // cannot shadow the UI under test with stale server/ui-dist assets. - command: "pnpm --filter @paperclipai/ui build --outDir ../server/ui-dist --emptyOutDir && node cli/node_modules/tsx/dist/cli.mjs cli/src/index.ts onboard --yes --run", + // Build the server's first-choice static directory unless CI/caller already + // prebuilt server/ui-dist and opted in via PAPERCLIP_E2E_SKIP_UI_BUILD=1. + command: WEB_SERVER_COMMAND, url: `${BASE_URL}/api/health`, // Always boot a dedicated throwaway instance for e2e so browser tests // never attach to the developer's active Paperclip home/server. @@ -79,6 +173,7 @@ export default defineConfig({ ...process.env, NODE_ENV: "test", PAPERCLIP_UI_DEV_MIDDLEWARE: "false", + HEARTBEAT_SCHEDULER_INTERVAL_MS: process.env.HEARTBEAT_SCHEDULER_INTERVAL_MS ?? "10000", NODE_OPTIONS: `${process.env.NODE_OPTIONS ?? ""} --import=${path.resolve(import.meta.dirname, "fixtures/agent-chat-github.mjs")} --import=${path.resolve(import.meta.dirname, "fixtures/ai-connection-provider.mjs")}`, PORT: String(PORT), PAPERCLIP_OPEN_ON_LISTEN: "false", diff --git a/turbo.json b/turbo.json index e8a3ccdc3f0..0295f677a3a 100644 --- a/turbo.json +++ b/turbo.json @@ -15,7 +15,11 @@ "scripts/**", ".github/**", "patches/**", - "tests/**", + "tests/fixtures/**", + "tests/helpers/**", + "tests/runner-e2e/fixtures/**", + "tests/tsconfig.playwright.json", + "tests/acpx-qualification-models.ts", "doc/**", "docs/**", "skills/**", @@ -92,10 +96,16 @@ }, "//#ci:workspaces-a": { "inputs": [ - "server/**", + "ui/**", "cli/**", - "packages/**", - "ui/**" + "packages/db/**", + "packages/shared/**", + "packages/adapter-utils/**", + "packages/adapters/**", + "packages/paperclip-runner/**", + "packages/plugins/**", + "server/src/services/agent-conversations.ts", + "announcements/examples/animated/**" ], "outputs": [], "cache": true @@ -113,7 +123,8 @@ }, "//#ci:db": { "inputs": [ - "packages/**" + "packages/db/**", + "packages/shared/**" ], "outputs": [], "cache": true @@ -138,8 +149,8 @@ "//#ci:runner-static": { "inputs": [ "server/**", - "cli/**", "packages/**", + "tests/runner-e2e/**", "ui/src/lib/**", "ui/src/api/**", "ui/src/types/**", @@ -159,10 +170,20 @@ "outputs": [], "cache": true }, + "//#ci:runner-package": { + "inputs": [ + "packages/paperclip-runner/**", + "packages/paperclip-eval-kernel/**", + "packages/adapters/codex-local/**", + "packages/adapter-utils/**", + "tests/runner-e2e/**" + ], + "outputs": [], + "cache": false + }, "//#ci:runner-vitest": { "inputs": [ "server/**", - "cli/**", "packages/**", "ui/src/lib/**", "ui/src/api/**", @@ -181,7 +202,9 @@ "server/**", "cli/**", "packages/**", - "ui/**" + "ui/**", + "tests/e2e/**", + "tests/runner-e2e/**" ], "outputs": [], "cache": false @@ -207,20 +230,18 @@ }, "//#ci:docker": { "inputs": [ - "server/**", - "cli/**", - "packages/**", - "ui/**" + "packages/paperclip-runner/**" ], "outputs": [], "cache": false }, "//#ci:canary": { "inputs": [ - "server/**", - "cli/**", - "packages/**", - "ui/**" + "scripts/**", + "cli/esbuild.config.mjs", + "server/scripts/**", + "packages/paperclip-runner/scripts/**", + "packages/paperclip-runner/release-runner-targets.json" ], "outputs": [], "cache": false @@ -230,17 +251,76 @@ "server/**", "cli/**", "packages/**", - "ui/**" + "ui/**", + "tests/e2e/**" ], "outputs": [], "cache": false }, "//#ci:runner-e2e-support": { "inputs": [ - "server/**", - "cli/**", - "packages/**", - "ui/**" + "tests/runner-e2e/**", + "tests/e2e/fetch-allowed-port.ts", + "packages/paperclip-runner/**", + "packages/plugins/sdk/**", + "packages/adapter-utils/**", + "packages/adapters/**", + "packages/shared/**", + "packages/teams-catalog/**", + "packages/db/src/client.ts", + "packages/db/src/index.ts", + "packages/db/src/test-embedded-postgres.ts", + "packages/db/src/schema/cases.ts", + "packages/db/src/schema/execution_workspace_repositories.ts", + "packages/db/src/schema/heartbeat_runs.ts", + "cli/src/checks/database-check.ts", + "cli/src/client/context.ts", + "cli/src/index.ts", + "server/src/__tests__/helpers/embedded-postgres.ts", + "server/src/__tests__/helpers/isolated-test-home.ts", + "server/src/__tests__/helpers/recovery-postgres.ts", + "server/src/adapters/**", + "server/src/agent-auth-jwt.ts", + "server/src/attachment-types.ts", + "server/src/home-paths.ts", + "server/src/index.ts", + "server/src/lib/agent-records.ts", + "server/src/middleware/board-mutation-guard.ts", + "server/src/modules/agent-lifecycle/**", + "server/src/onboarding-assets/**", + "server/src/redaction.ts", + "server/src/routes/activity.ts", + "server/src/routes/native-run-mcp.ts", + "server/src/secrets/local-encrypted-provider.ts", + "server/src/services/accounting-integrity.ts", + "server/src/services/activity.ts", + "server/src/services/agent-ai-connection-default.ts", + "server/src/services/agentmail-api.ts", + "server/src/services/ai-api-key-failures.ts", + "server/src/services/company-member-roles.ts", + "server/src/services/company-portability.ts", + "server/src/services/cost-data-quality.ts", + "server/src/services/cron.ts", + "server/src/services/default-agent-instructions.ts", + "server/src/services/heartbeat/task-markdown.ts", + "server/src/services/hot-restart.ts", + "server/src/services/issue-comment-wakeup.ts", + "server/src/services/issues.ts", + "server/src/services/native-runtime/**", + "server/src/services/plugin-tool-dispatcher.ts", + "server/src/services/run-cost-accounting.ts", + "server/src/services/tool-content-guards.ts", + "server/src/vendor/paperclip-runner/**", + "ui/public/favicon-32x32.png", + "ui/public/fonts/InterVariable.woff2", + "ui/src/api/activity.ts", + "ui/src/features/connections/ConnectionSetupFlow.tsx", + "ui/src/lib/company-routes.ts", + "ui/src/lib/company-skill-routes.ts", + "ui/src/lib/grok-bot-setup-prompt.ts", + "ui/src/lib/issue-reference.ts", + "ui/src/lib/markdown-reply-content.ts", + "ui/src/lib/onboarding-route.ts" ], "outputs": [], "cache": false diff --git a/ui/src/App.activity-routing.test.tsx b/ui/src/App.activity-routing.test.tsx deleted file mode 100644 index 1a6120e53bf..00000000000 --- a/ui/src/App.activity-routing.test.tsx +++ /dev/null @@ -1,313 +0,0 @@ -// @vitest-environment jsdom - -// Regression guard for the Audit hub: Activity remains the canonical root, -// while Runs, Costs, and Budgets live beneath it. Company-prefixed and bare -// legacy routes must keep resolving with their query filters intact; `/audit` -// specifically retains the historical Agent Actions preset. This drives the -// real route table so removing either registration fails loudly. - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { MemoryRouter, useLocation } from "react-router-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { App } from "./App"; - -const streamlinedUiState = vi.hoisted(() => ({ enabled: true, loaded: true })); - -vi.mock("./hooks/useStreamlinedUiEnabled", () => ({ - useStreamlinedUiEnabled: () => streamlinedUiState, -})); - -// jsdom's CSS parser rejects the custom-property marker rule stitches inserts -// (`--sxs{--sxs:N}`), pulled into 's eager import graph transitively via -// @codesandbox/sandpack-react. Substitute a benign, valid rule on parse failure -// so stitches' index bookkeeping stays intact and the module graph evaluates. -vi.hoisted(() => { - const sheetProto = window.CSSStyleSheet.prototype as unknown as { - insertRule: (rule: string, index?: number) => number; - __papActivityRoutingPatched?: boolean; - }; - if (!sheetProto.__papActivityRoutingPatched) { - const original = sheetProto.insertRule; - sheetProto.insertRule = function patched(this: CSSStyleSheet, rule: string, index?: number) { - try { - return original.call(this, rule, index); - } catch { - try { - return original.call(this, ".pap16302-noop{}", index); - } catch { - return this.cssRules?.length ?? 0; - } - } - }; - sheetProto.__papActivityRoutingPatched = true; - } -}); - -// Real Layout renders the full authenticated shell (sidebar, data queries) and -// owns the "No company matches prefix" NotFound. For routing we only need it to -// resolve the :companyPrefix segment and render its nested routes. -vi.mock("./components/Layout", async () => { - const { Outlet } = await import("react-router-dom"); - return { Layout: () => }; -}); - -vi.mock("./components/Layout.production", async () => { - const { Outlet } = await import("react-router-dom"); - return { Layout: () => }; -}); - -// Rendered by outside and needs DialogProvider; irrelevant here. -// These routing tests render App without a QueryClientProvider. -vi.mock("./components/PageLoadTracker", () => ({ PageLoadTracker: () => null })); - -vi.mock("./components/OnboardingWizardVariant", () => ({ - OnboardingWizardVariant: () => null, -})); - -// Cloud access is unrelated to the route-table regression. Let it fall through -// synchronously so this test does not poll its query transitions. -vi.mock("./components/CloudAccessGate", async () => { - const { Outlet } = await import("react-router-dom"); - return { CloudAccessGate: () => }; -}); - -// Sentinel page that also reports the resolved path + query, so we can assert -// the merged route *and* the preset mode a redirect carried into it. -vi.mock("./pages/audit/CompanyActivity", () => ({ - CompanyActivity: () => { - const location = useLocation(); - return
{`ACTIVITY_PAGE@${location.pathname}${location.search}`}
; - }, -})); - -vi.mock("./pages/audit/AuditHub", () => ({ - AuditHub: ({ section }: { section: string }) => { - const location = useLocation(); - return
{`AUDIT_${section.toUpperCase()}@${location.pathname}${location.search}`}
; - }, -})); - -vi.mock("./pages/Issues", () => ({ - Issues: () => { - const location = useLocation(); - return
{`TASKS_PAGE@${location.pathname}`}
; - }, -})); - -vi.mock("./pages/audit/CompanyActivity.production", () => ({ - CompanyActivity: () => { - const location = useLocation(); - return
{`PRODUCTION_ACTIVITY@${location.pathname}${location.search}`}
; - }, -})); - -vi.mock("./pages/Costs", () => ({ - Costs: () => { - const location = useLocation(); - return
{`SHARED_COSTS@${location.pathname}${location.search}`}
; - }, -})); - -vi.mock("./pages/NotFound", () => ({ - NotFoundPage: ({ scope }: { scope: string }) =>
{`NOT_FOUND:${scope}`}
, -})); - -vi.mock("./pages/PluginPage", () => ({ - PluginPage: () =>
PRODUCTION_PLUGIN_FALLBACK
, -})); - -const PAP_COMPANY = { - id: "company-1", - name: "Paperclip", - issuePrefix: "PAP", - status: "active", -}; -const ACME_COMPANY = { - id: "company-2", - name: "Acme", - issuePrefix: "ACME", - status: "active", -}; - -// Mutable so a test can put the *selected* company out of step with the company -// in the URL — that mismatch is what catches a redirect that re-resolves the -// company from context instead of keeping the one the deep link named. -let companyState = { - companies: [PAP_COMPANY] as Array, - selected: PAP_COMPANY as typeof PAP_COMPANY | null, -}; -vi.mock("./context/CompanyContext", () => ({ - useCompany: () => ({ - companies: companyState.companies, - selectedCompanyId: companyState.selected?.id ?? null, - selectedCompany: companyState.selected, - loading: false, - }), - CompanyProvider: ({ children }: { children: ReactNode }) => <>{children}, -})); - -function renderAppAt(container: HTMLElement, path: string) { - const root = createRoot(container); - flushSync(() => { - root.render( - - - , - ); - }); - return root; -} - -/** - * Waits on the condition, not on a fixed number of turns. The previous version - * yielded at most five macrotasks before asserting, which is ample on an idle - * machine and not when the suite is running many workers in parallel — the - * container was still empty and the assertion failed on a route that resolves - * perfectly well. `vi.waitFor` retries against a time budget instead, so a - * loaded worker gets more turns rather than a failure. - */ -async function waitForRoute(container: HTMLElement, text: string) { - await vi.waitFor(() => expect(container.textContent).toContain(text)); -} - -describe("App Activity routing (PAP-16302)", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - companyState = { companies: [PAP_COMPANY], selected: PAP_COMPANY }; - streamlinedUiState.enabled = true; - streamlinedUiState.loaded = true; - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - it("serves the merged Activity page at /:company/activity", async () => { - const root = renderAppAt(container, "/PAP/activity"); - await waitForRoute(container, "ACTIVITY_PAGE@/PAP/activity"); - expect(container.textContent).not.toContain("No organization matches prefix"); - flushSync(() => root.unmount()); - }); - - it("serves organization and entity-scoped run history beneath Activity", async () => { - const root = renderAppAt( - container, - "/PAP/activity/runs?entityType=routine&entityId=routine-1", - ); - await waitForRoute( - container, - "AUDIT_RUNS@/PAP/activity/runs?entityType=routine&entityId=routine-1", - ); - flushSync(() => root.unmount()); - }); - - it("redirects /:company/audit to Activity with the agent-actions mode preset", async () => { - const root = renderAppAt(container, "/PAP/audit"); - await waitForRoute(container, "ACTIVITY_PAGE@/PAP/activity?mode=agents"); - flushSync(() => root.unmount()); - }); - - it("serves each canonical Audit section under Activity", async () => { - const root = renderAppAt(container, "/PAP/activity/runs?agentId=agent-1"); - await waitForRoute(container, "AUDIT_RUNS@/PAP/activity/runs?agentId=agent-1"); - flushSync(() => root.unmount()); - }); - - it("redirects legacy costs and preserves its deep-link filters", async () => { - const root = renderAppAt(container, "/PAP/costs?range=30d#usage"); - await waitForRoute(container, "AUDIT_COSTS@/PAP/activity/costs?range=30d"); - flushSync(() => root.unmount()); - }); - - it("redirects legacy Audit sections to their canonical destination", async () => { - const root = renderAppAt(container, "/PAP/audit/budgets?projectId=project-1"); - await waitForRoute( - container, - "AUDIT_BUDGETS@/PAP/activity/budgets?projectId=project-1", - ); - flushSync(() => root.unmount()); - }); - - it("keeps the company from the URL when /:company/audit is not the selected company", async () => { - // A shared /ACME/audit link opened by someone whose selected company is PAP - // must still show ACME's activity. The redirect target is written absolute - // (`/activity?mode=agents`) and relies on `@/lib/router`'s prefix-aware - // , which resolves the company from the route param ahead of the - // selected company. Importing from `react-router-dom` instead — - // the import most files use — would send this deep link to the *viewer's* - // company, so pin the behaviour here. - companyState = { companies: [PAP_COMPANY, ACME_COMPANY], selected: PAP_COMPANY }; - const root = renderAppAt(container, "/ACME/audit"); - await waitForRoute(container, "ACTIVITY_PAGE@/ACME/activity?mode=agents"); - expect(container.textContent).not.toContain("ACTIVITY_PAGE@/PAP/activity"); - flushSync(() => root.unmount()); - }); - - it("redirects the bare /audit deep link through to the prefixed Activity page", async () => { - const root = renderAppAt(container, "/audit"); - await waitForRoute(container, "ACTIVITY_PAGE@/PAP/activity?mode=agents"); - expect(container.textContent).not.toContain("No organization matches prefix"); - flushSync(() => root.unmount()); - }); - - it("redirects the bare /tasks post-login target to the real task list", async () => { - const root = renderAppAt(container, "/tasks"); - await waitForRoute(container, "TASKS_PAGE@/PAP/issues"); - expect(container.textContent).not.toContain("/tasks/dashboard"); - flushSync(() => root.unmount()); - }); - - it("redirects a bare legacy section through to the prefixed Audit hub", async () => { - const root = renderAppAt(container, "/runs?runStatus=succeeded"); - await waitForRoute(container, "AUDIT_RUNS@/PAP/activity/runs?runStatus=succeeded"); - flushSync(() => root.unmount()); - }); - - it("uses legacy Activity and the shared standalone Costs page when Streamlined UI is disabled", async () => { - streamlinedUiState.enabled = false; - const activityRoot = renderAppAt(container, "/PAP/activity"); - await waitForRoute(container, "PRODUCTION_ACTIVITY@/PAP/activity"); - flushSync(() => activityRoot.unmount()); - - const costsRoot = renderAppAt(container, "/PAP/costs?range=30d"); - await waitForRoute(container, "SHARED_COSTS@/PAP/costs?range=30d"); - flushSync(() => costsRoot.unmount()); - }); - - it.each([true, false])("serves all Audit tab destinations with Streamlined UI set to %s", async (enabled) => { - streamlinedUiState.enabled = enabled; - for (const section of ["runs", "costs", "budgets", "timeline", "commentary"]) { - const path = `/PAP/activity/${section}?agentId=agent-1`; - const root = renderAppAt(container, path); - await waitForRoute(container, `AUDIT_${section.toUpperCase()}@${path}`); - expect(container.textContent).not.toContain("NOT_FOUND"); - flushSync(() => root.unmount()); - } - }); - - it("does not mount streamlined routes before the experiment setting loads", async () => { - streamlinedUiState.loaded = false; - const root = renderAppAt(container, "/PAP/activity"); - expect(container.textContent).not.toContain("ACTIVITY_PAGE"); - expect(container.textContent).not.toContain("PRODUCTION_ACTIVITY"); - - streamlinedUiState.enabled = false; - streamlinedUiState.loaded = true; - flushSync(() => { - root.render( - - - , - ); - }); - await waitForRoute(container, "PRODUCTION_ACTIVITY@/PAP/activity"); - flushSync(() => root.unmount()); - }); -}); diff --git a/ui/src/App.cases-routing.test.tsx b/ui/src/App.cases-routing.test.tsx deleted file mode 100644 index 86bf3b2be38..00000000000 --- a/ui/src/App.cases-routing.test.tsx +++ /dev/null @@ -1,148 +0,0 @@ -// @vitest-environment jsdom - -// Regression guard for PAP-13002: the experimental Cases UI emits *unprefixed* -// links (`/cases`, `/cases/:id`) — the same global-unprefixed pattern Routines -// uses. Those only resolve if `cases` and `cases/:caseIdentifier` are registered -// as reserved unprefixed redirect routes in ; otherwise the first path -// segment is parsed as a company prefix ("CASES") and the page 404s with -// "No company matches prefix". This drives the real route table so a -// future removal of those redirect routes fails loudly. - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { MemoryRouter } from "react-router-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { App } from "./App"; - -// jsdom's CSS parser rejects the custom-property marker rule stitches inserts -// (`--sxs{--sxs:N}`), pulled into 's eager import graph transitively via -// @codesandbox/sandpack-react. Substitute a benign, valid rule on parse failure -// so stitches' index bookkeeping stays intact and the module graph evaluates. -// (sandpack itself is never exercised by the routing under test.) -vi.hoisted(() => { - const sheetProto = window.CSSStyleSheet.prototype as unknown as { - insertRule: (rule: string, index?: number) => number; - __pap13002Patched?: boolean; - }; - if (!sheetProto.__pap13002Patched) { - const original = sheetProto.insertRule; - sheetProto.insertRule = function patched(this: CSSStyleSheet, rule: string, index?: number) { - try { - return original.call(this, rule, index); - } catch { - try { - return original.call(this, ".pap13002-noop{}", index); - } catch { - return this.cssRules?.length ?? 0; - } - } - }; - sheetProto.__pap13002Patched = true; - } -}); - -// Real Layout renders the full authenticated shell (sidebar, data queries) and -// owns the "No company matches prefix" NotFound. For routing we only need it to -// resolve the :companyPrefix segment and render its nested routes. -vi.mock("./components/Layout", async () => { - const { Outlet } = await import("react-router-dom"); - return { Layout: () => }; -}); - -// The experimental gate would otherwise hide the page behind a feature flag. -vi.mock("./components/CasesExperimentalGate", () => ({ - CasesExperimentalGate: ({ children }: { children: ReactNode }) => <>{children}, -})); - -// Rendered by outside and needs DialogProvider; irrelevant here. -// These routing tests render App without a QueryClientProvider. -vi.mock("./components/PageLoadTracker", () => ({ PageLoadTracker: () => null })); - -vi.mock("./components/OnboardingWizardVariant", () => ({ - OnboardingWizardVariant: () => null, -})); - -// Sentinel pages so we can assert *which* route resolved. -vi.mock("./pages/Cases", () => ({ Cases: () =>
CASES_LIST_PAGE
})); -vi.mock("./pages/CaseDetail", () => ({ CaseDetail: () =>
CASE_DETAIL_PAGE
})); - -// Cloud access is unrelated to the route-table regression. Let it fall through -// synchronously so this test does not poll its three query transitions. -vi.mock("./components/CloudAccessGate", async () => { - const { Outlet } = await import("react-router-dom"); - return { CloudAccessGate: () => }; -}); - -// The prefix resolver + redirect logic both read the active company. -const PAP_COMPANY = { - id: "company-1", - name: "Paperclip", - issuePrefix: "PAP", - status: "active", -}; -vi.mock("./context/CompanyContext", () => ({ - useCompany: () => ({ - companies: [PAP_COMPANY], - selectedCompanyId: PAP_COMPANY.id, - selectedCompany: PAP_COMPANY, - loading: false, - }), - CompanyProvider: ({ children }: { children: ReactNode }) => <>{children}, -})); - -async function renderAppAt(container: HTMLElement, path: string) { - const root = createRoot(container); - flushSync(() => { - root.render( - - - , - ); - }); - return root; -} - -/** - * Waits on the condition, not on a fixed number of turns. The previous version - * yielded at most three macrotasks before asserting, which is ample on an idle - * machine and not when the suite is running many workers in parallel — the - * container was still empty and the assertion failed on a route that resolves - * perfectly well. `vi.waitFor` retries against a time budget instead, so a - * loaded worker gets more turns rather than a failure. - * - * The same fix #11499 applied to the sibling `App.activity-routing.test.tsx`, - * which had the identical loop with five turns instead of three. - */ -async function waitForRoute(container: HTMLElement, text: string) { - await vi.waitFor(() => expect(container.textContent).toContain(text)); -} - -describe("App Cases routing (PAP-13002)", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - it("redirects unprefixed /cases to the company-prefixed list page", async () => { - const root = await renderAppAt(container, "/cases"); - await waitForRoute(container, "CASES_LIST_PAGE"); - expect(container.textContent).not.toContain("No organization matches prefix"); - flushSync(() => root.unmount()); - }); - - it("redirects unprefixed /cases/:id to the company-prefixed detail page", async () => { - const root = await renderAppAt(container, "/cases/PAP-C5"); - await waitForRoute(container, "CASE_DETAIL_PAGE"); - expect(container.textContent).not.toContain("No organization matches prefix"); - flushSync(() => root.unmount()); - }); -}); diff --git a/ui/src/App.home-routing.test.tsx b/ui/src/App.home-routing.test.tsx deleted file mode 100644 index d58d31557a3..00000000000 --- a/ui/src/App.home-routing.test.tsx +++ /dev/null @@ -1,119 +0,0 @@ -// @vitest-environment jsdom - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { MemoryRouter } from "react-router-dom"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { App } from "./App"; - -const streamlinedUiState = vi.hoisted(() => ({ enabled: true, loaded: true })); - -vi.mock("./hooks/useStreamlinedUiEnabled", () => ({ - useStreamlinedUiEnabled: () => streamlinedUiState, -})); - -// jsdom's CSS parser rejects the custom-property marker rule stitches inserts -// (`--sxs{--sxs:N}`), pulled into 's eager import graph transitively via -// @codesandbox/sandpack-react. Substitute a benign, valid rule on parse failure -// so stitches' index bookkeeping stays intact and the module graph evaluates. -vi.hoisted(() => { - const sheetProto = window.CSSStyleSheet.prototype as unknown as { - insertRule: (rule: string, index?: number) => number; - __papHomeRoutingPatched?: boolean; - }; - if (!sheetProto.__papHomeRoutingPatched) { - const original = sheetProto.insertRule; - sheetProto.insertRule = function patched(this: CSSStyleSheet, rule: string, index?: number) { - try { - return original.call(this, rule, index); - } catch { - try { - return original.call(this, ".pap16302-noop{}", index); - } catch { - return this.cssRules?.length ?? 0; - } - } - }; - sheetProto.__papHomeRoutingPatched = true; - } -}); - -// Real Layout renders the full authenticated shell (sidebar, data queries) and -// owns the "No company matches prefix" NotFound. For routing we only need it to -// resolve the :companyPrefix segment and render its nested routes. -vi.mock("./components/Layout", async () => { - const { Outlet } = await import("react-router-dom"); - return { Layout: () => }; -}); - -vi.mock("./components/Layout.production", async () => { - const { Outlet } = await import("react-router-dom"); - return { Layout: () => }; -}); - -// Rendered by outside and needs DialogProvider; irrelevant here. -// These routing tests render App without a QueryClientProvider. -vi.mock("./components/PageLoadTracker", () => ({ PageLoadTracker: () => null })); - -vi.mock("./components/OnboardingWizardVariant", () => ({ - OnboardingWizardVariant: () => null, -})); - -// Cloud access is unrelated to the route-table regression. Let it fall through -// synchronously so this test does not poll its query transitions. -vi.mock("./components/CloudAccessGate", async () => { - const { Outlet } = await import("react-router-dom"); - return { CloudAccessGate: () => }; -}); - -const homeState = vi.hoisted(() => ({ - value: { path: "/dashboard", loaded: true, error: null as unknown, retry: () => {} }, -})); -vi.mock("./hooks/useCompanyHomePath", () => ({ useCompanyHomePath: () => homeState.value })); - -vi.mock("./pages/Dashboard", () => ({ Dashboard: () =>
CLASSIC_DASHBOARD
})); - -const COMPANY = { id: "company-1", name: "Paperclip", issuePrefix: "PAP", status: "active" }; -vi.mock("./context/CompanyContext", () => ({ - useCompany: () => ({ companies: [COMPANY], selectedCompanyId: COMPANY.id, selectedCompany: COMPANY, loading: false }), - CompanyProvider: ({ children }: { children: ReactNode }) => <>{children}, -})); - -describe("App root redirect", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - it("shows a settings read failure with Retry instead of loading forever", async () => { - const retry = vi.fn(); - homeState.value = { path: "/dashboard", loaded: false, error: new Error("Server error"), retry }; - const root = createRoot(container); - flushSync(() => { - root.render( - - - , - ); - }); - const button = await vi.waitFor(() => { - const found = [...container.querySelectorAll("button")].find((node) => node.textContent?.includes("Retry")); - expect(found).toBeTruthy(); - return found!; - }); - expect(container.querySelector('[data-query-view="error"]')).not.toBeNull(); - expect(container.textContent).not.toContain("CLASSIC_DASHBOARD"); - flushSync(() => button.click()); - expect(retry).toHaveBeenCalledOnce(); - flushSync(() => root.unmount()); - }); -}); diff --git a/ui/src/App.onboarding-launcher.test.tsx b/ui/src/App.onboarding-launcher.test.tsx deleted file mode 100644 index 7e9153f6d9f..00000000000 --- a/ui/src/App.onboarding-launcher.test.tsx +++ /dev/null @@ -1,209 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { - ONBOARDING_AGENT_STEP, -} from "./lib/onboarding-route"; - -/** - * The third way into onboarding for a company that already exists: the "Add - * Agent" card on `/{prefix}/onboarding`, shown once the wizard is dismissed. - * - * The route resolver and the dashboard both choose the step from whether the - * company already has its mission. This button hardcoded the mission step, so - * the one entry point whose own copy says "add another agent" was the one that - * stopped to ask for the mission again. - */ - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -// jsdom's CSS parser rejects the custom-property marker rule stitches inserts -// (`--sxs{--sxs:N}`), pulled into 's eager import graph transitively via -// @codesandbox/sandpack-react. Substitute a benign, valid rule on parse failure -// so stitches' index bookkeeping stays intact and the module graph evaluates. -vi.hoisted(() => { - const sheetProto = window.CSSStyleSheet.prototype as unknown as { - insertRule: (rule: string, index?: number) => number; - __papLauncherPatched?: boolean; - }; - if (!sheetProto.__papLauncherPatched) { - const original = sheetProto.insertRule; - sheetProto.insertRule = function patched(this: CSSStyleSheet, rule: string, index?: number) { - try { - return original.call(this, rule, index); - } catch { - try { - return original.call(this, ".pap-launcher-noop{}", index); - } catch { - return this.cssRules?.length ?? 0; - } - } - }; - sheetProto.__papLauncherPatched = true; - } -}); - -const routeState = vi.hoisted(() => ({ companyPrefix: "PC1" as string | undefined })); -const dialogState = vi.hoisted(() => ({ - onboardingOpen: false, - onboardingRouteDismissed: true, - openOnboarding: vi.fn(), -})); -const mockGoalsApi = vi.hoisted(() => ({ list: vi.fn() })); - -vi.mock("@/lib/router", async () => { - const actual = await vi.importActual("react-router-dom"); - return { - ...actual, - useParams: () => ({ companyPrefix: routeState.companyPrefix }), - useActiveCompanyPrefix: () => routeState.companyPrefix ?? null, - }; -}); - -vi.mock("./context/CompanyContext", () => ({ - useCompany: () => ({ - companies: [{ id: "company-1", name: "Acme", issuePrefix: "PC1" }], - selectedCompanyId: "company-1", - loading: false, - error: null, - }), -})); - -vi.mock("./context/DialogContext", () => ({ - useDialogActions: () => ({ openOnboarding: dialogState.openOnboarding }), - useDialogState: () => ({ - onboardingOpen: dialogState.onboardingOpen, - onboardingRouteDismissed: dialogState.onboardingRouteDismissed, - }), -})); - -vi.mock("./api/goals", () => ({ goalsApi: mockGoalsApi })); - -const { OnboardingRoutePage } = await import("./App"); - -const COMPANY_GOAL = { - id: "goal-1", - companyId: "company-1", - title: "Scale the marketplace", - description: null, - level: "company", - status: "active", - parentId: null, - ownerAgentId: null, - createdAt: new Date("2026-03-02T00:00:00Z"), - updatedAt: new Date("2026-03-02T00:00:00Z"), -}; - -describe("the onboarding launcher's Add Agent button", () => { - let container: HTMLDivElement; - let queryClient: QueryClient; - let root: Root | null = null; - - async function render() { - root = createRoot(container); - await act(async () => { - root!.render( - - - , - ); - }); - } - - async function settle(ticks = 12) { - for (let i = 0; i < ticks; i++) { - await act(async () => { - await new Promise((resolve) => setTimeout(resolve, 0)); - }); - } - } - - function addAgentButton(): HTMLButtonElement { - const button = [...container.querySelectorAll("button")].find((b) => - b.textContent?.includes("Add Agent"), - ); - // Asserted rather than optional-chained: a lookup that silently matches - // nothing turns the click below into a no-op and the test into decoration. - expect(button).toBeDefined(); - return button!; - } - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } }); - routeState.companyPrefix = "PC1"; - dialogState.onboardingOpen = false; - dialogState.onboardingRouteDismissed = true; - mockGoalsApi.list.mockResolvedValue([]); - }); - - afterEach(async () => { - await act(async () => root?.unmount()); - root = null; - queryClient.clear(); - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - it("opens on the agent step for a company that already has its mission", async () => { - mockGoalsApi.list.mockResolvedValue([COMPANY_GOAL]); - await render(); - await settle(); - - await act(async () => { - addAgentButton().dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(dialogState.openOnboarding).toHaveBeenCalledWith({ - initialStep: ONBOARDING_AGENT_STEP, - companyId: "company-1", - }); - }); - - it("goes to the agent step whatever the goals lookup says", async () => { - // Two tests lived here — company with no mission, and a lookup that failed — - // and both sent "Add Agent" to the mission step first. Onboarding no longer - // asks for the mission, so neither goal state can divert a button whose - // whole purpose is adding an agent. - for (const goals of [ - () => mockGoalsApi.list.mockResolvedValue([]), - () => mockGoalsApi.list.mockRejectedValue(new Error("goals unavailable")), - ]) { - dialogState.openOnboarding.mockClear(); - goals(); - await render(); - await settle(); - - await act(async () => { - addAgentButton().dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(dialogState.openOnboarding).toHaveBeenCalledWith({ - initialStep: ONBOARDING_AGENT_STEP, - companyId: "company-1", - }); - } - }); - - it("opens with no company when the prefix matches none", async () => { - routeState.companyPrefix = "NOPE"; - await render(); - await settle(); - - const start = [...container.querySelectorAll("button")].find((b) => - b.textContent?.includes("Start Onboarding"), - ); - expect(start).toBeDefined(); - await act(async () => { - start!.dispatchEvent(new MouseEvent("click", { bubbles: true })); - }); - - expect(dialogState.openOnboarding).toHaveBeenCalledWith(); - }); -}); diff --git a/ui/src/artifact-directions/api-stub.test.ts b/ui/src/artifact-directions/api-stub.test.ts deleted file mode 100644 index c909a3a2988..00000000000 --- a/ui/src/artifact-directions/api-stub.test.ts +++ /dev/null @@ -1,45 +0,0 @@ -// @vitest-environment jsdom - -import { afterEach, describe, expect, it } from "vitest"; -import { installApiStub, registerApiRoute } from "./api-stub"; -import { COMPANY } from "./fixtures"; - -describe("installApiStub", () => { - const original = window.fetch; - const restores: Array<() => void> = []; - - afterEach(() => { - while (restores.length) restores.pop()?.(); - window.fetch = original; - }); - - it("answers /api/ from the fixtures and puts fetch back when restored", async () => { - restores.push(installApiStub()); - expect(window.fetch).not.toBe(original); - const companies = await (await window.fetch("/api/companies")).json(); - expect(companies).toEqual([COMPANY]); - restores.pop()?.(); - expect(window.fetch).toBe(original); - }); - - it("serves a registered route and answers anything else under /api/ with an empty object", async () => { - registerApiRoute((pathname) => (pathname === "/api/lab/ping" ? { pong: true } : undefined)); - restores.push(installApiStub()); - expect(await (await window.fetch("/api/lab/ping")).json()).toEqual({ pong: true }); - expect(await (await window.fetch("/api/lab/nothing", { method: "POST" })).json()).toEqual({}); - }); - - it("keeps one stub across nested installs and restores on the last release", () => { - const first = installApiStub(); - const stub = window.fetch; - const second = installApiStub(); - restores.push(first, second); - expect(window.fetch).toBe(stub); - first(); - expect(window.fetch).toBe(stub); - first(); // a second call of the same restore is a no-op - expect(window.fetch).toBe(stub); - second(); - expect(window.fetch).toBe(original); - }); -}); diff --git a/ui/src/artifact-directions/directions/d5-v1-mvp/MediaPrint.test.ts b/ui/src/artifact-directions/directions/d5-v1-mvp/MediaPrint.test.ts deleted file mode 100644 index 469c44ab724..00000000000 --- a/ui/src/artifact-directions/directions/d5-v1-mvp/MediaPrint.test.ts +++ /dev/null @@ -1,23 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { fitPrint, SINGLE_BOX, STACK_BOX } from "./MediaPrint"; - -describe("fitPrint", () => { - it("fits a landscape print to the stack box by width and a portrait one by height", () => { - expect(fitPrint({ aspect: 4 / 3 }, STACK_BOX)).toEqual({ width: 245, height: 183.75, border: 3.3 }); - expect(fitPrint({ aspect: 3 / 4 }, STACK_BOX)).toEqual({ width: 165, height: 220, border: 3.3 }); - }); - - it("never lets a print grow past the box", () => { - for (const aspect of [0.5, 1, 2, 16 / 9]) { - const print = fitPrint({ aspect }, STACK_BOX); - expect(print.width).toBeLessThanOrEqual(STACK_BOX.maxWidth); - expect(print.height).toBeLessThanOrEqual(STACK_BOX.maxHeight); - expect(print.width / print.height).toBeCloseTo(aspect, 2); - } - }); - - it("assumes 4:3 when the picture's ratio is unknown", () => { - expect(fitPrint({}, SINGLE_BOX)).toEqual({ width: 240, height: 180, border: 4 }); - expect(fitPrint({ aspect: 0 }, SINGLE_BOX)).toEqual(fitPrint({}, SINGLE_BOX)); - }); -}); diff --git a/ui/src/artifact-directions/directions/d5-v1-mvp/Thread.test.tsx b/ui/src/artifact-directions/directions/d5-v1-mvp/Thread.test.tsx deleted file mode 100644 index efb7d09288f..00000000000 --- a/ui/src/artifact-directions/directions/d5-v1-mvp/Thread.test.tsx +++ /dev/null @@ -1,59 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot, type Root } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { ThreadAttachments, ThreadWorkProduct } from "./Thread"; -import { testArtifact } from "./test-artifact"; - -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -const files = (count: number) => - Array.from({ length: count }, (_, i) => testArtifact({ kind: "pdf", id: `pdf-${i}`, filename: `deck-${i}.pdf`, sizeLabel: "57.7 KB" })); - -describe("the thread's artifact rows", () => { - let container: HTMLDivElement; - let root: Root; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); - }); - - afterEach(() => { - act(() => root.unmount()); - container.remove(); - }); - - it("renders a work product as one full-width row named after its file", () => { - act(() => root.render()); - const button = container.querySelector("button"); - expect(button?.getAttribute("aria-label")).toBe("Open deck-0.pdf"); - expect(container.querySelector('[data-surface="thread"]')).toBeNull(); - expect(button?.textContent).toContain("57.7 KB"); - }); - - it("renders one attachment as a single row, with no group around it", () => { - act(() => root.render()); - expect(container.querySelectorAll("button")).toHaveLength(1); - expect(container.querySelector('[data-surface="thread"]')).toBeNull(); - }); - - it("groups several attachments inline at equal widths that wrap past 280px each", () => { - act(() => root.render()); - const group = container.querySelector('[data-surface="thread"]'); - expect(group?.className).toContain("flex-wrap"); - const rows = Array.from(group?.querySelectorAll("button") ?? []); - expect(rows).toHaveLength(5); - for (const row of rows) { - expect(row.style.flex).toBe("1 0 280px"); - expect(row.className).toContain("min-w-px"); - } - }); - - it("renders nothing for an empty attachments block", () => { - act(() => root.render()); - expect(container.innerHTML).toBe(""); - }); -}); diff --git a/ui/src/artifact-directions/directions/d5-v1-mvp/kinds.test.ts b/ui/src/artifact-directions/directions/d5-v1-mvp/kinds.test.ts deleted file mode 100644 index 5c44ca4e8a2..00000000000 --- a/ui/src/artifact-directions/directions/d5-v1-mvp/kinds.test.ts +++ /dev/null @@ -1,67 +0,0 @@ -import { Music } from "lucide-react"; -import { describe, expect, it } from "vitest"; -import { glyphOf, isPortrait, labelOf, mediaKindOf, treatmentOf } from "./kinds"; -import { testArtifact } from "./test-artifact"; - -describe("treatmentOf", () => { - it("prints media that has a preview and falls back when it has none", () => { - expect(treatmentOf(testArtifact({ kind: "image", thumbnailUrl: "/cap.svg" }))).toBe("media"); - expect(treatmentOf(testArtifact({ kind: "video" }))).toBe("media-fallback"); - expect(treatmentOf(testArtifact({ kind: "file", ext: "mp3" }))).toBe("media-fallback"); - }); - - it("previews a document whose text is known and shows the sheet otherwise", () => { - expect(treatmentOf(testArtifact({ kind: "document", body: "# Plan" }))).toBe("preview"); - expect(treatmentOf(testArtifact({ kind: "document", excerpt: "Plan" }))).toBe("preview"); - expect(treatmentOf(testArtifact({ kind: "document" }))).toBe("icon"); - expect(treatmentOf(testArtifact({ kind: "pdf" }))).toBe("icon"); - }); -}); - -describe("labelOf", () => { - it("takes the type from the extension and keeps links as URL", () => { - expect(labelOf(testArtifact({ kind: "slides", filename: "deck.pptx" }))).toBe("PPTX"); - expect(labelOf(testArtifact({ kind: "file", ext: "otf", filename: "Font.otf" }))).toBe("OTF"); - expect(labelOf(testArtifact({ kind: "link", url: "https://example.com" }))).toBe("URL"); - expect(labelOf(testArtifact({ kind: "document" }))).toBe("MD"); - }); -}); - -describe("isPortrait", () => { - it("stands only prints that are taller than wide; a square lies", () => { - expect(isPortrait(testArtifact({ kind: "image", aspect: 4 / 5 }))).toBe(true); - expect(isPortrait(testArtifact({ kind: "image", aspect: 1 }))).toBe(false); - expect(isPortrait(testArtifact({ kind: "image" }))).toBe(false); - }); -}); - -describe("glyphOf", () => { - it("draws PDF as bars and audio with the music glyph", () => { - expect(glyphOf(testArtifact({ kind: "pdf" }))).toBe("bars"); - expect(glyphOf(testArtifact({ kind: "file", ext: "wav" }))).toBe(Music); - }); -}); - -describe("mediaKindOf", () => { - it("sorts a task document under Documents and an attached Markdown file under Text, as the product does", () => { - expect(mediaKindOf(testArtifact({ kind: "document", revision: 1, contentType: "text/markdown" }))).toBe("document"); - expect(mediaKindOf(testArtifact({ kind: "document", filename: "deck-guide.md", contentType: "text/markdown" }))).toBe("text"); - }); - - it("goes by content type for files: text, JSON and XML are Text, office files and archives are Files", () => { - expect(mediaKindOf(testArtifact({ kind: "sheet", contentType: "text/csv" }))).toBe("text"); - expect(mediaKindOf(testArtifact({ kind: "code", contentType: "application/json" }))).toBe("text"); - expect(mediaKindOf(testArtifact({ kind: "code", contentType: "image/svg+xml" }))).toBe("image"); - expect(mediaKindOf(testArtifact({ kind: "code", contentType: "application/ld+json" }))).toBe("text"); - expect(mediaKindOf(testArtifact({ kind: "sheet", contentType: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" }))).toBe("file"); - expect(mediaKindOf(testArtifact({ kind: "pdf", contentType: "application/pdf" }))).toBe("file"); - expect(mediaKindOf(testArtifact({ kind: "archive", contentType: "application/zip" }))).toBe("file"); - expect(mediaKindOf(testArtifact({ kind: "link" }))).toBe("file"); - }); - - it("keeps images and video by their types, and by kind when a fixture has no type", () => { - expect(mediaKindOf(testArtifact({ kind: "image", contentType: "image/png" }))).toBe("image"); - expect(mediaKindOf(testArtifact({ kind: "video", contentType: "video/webm" }))).toBe("video"); - expect(mediaKindOf(testArtifact({ kind: "video" }))).toBe("video"); - }); -}); diff --git a/ui/src/artifact-directions/directions/d5-v1-mvp/when.test.ts b/ui/src/artifact-directions/directions/d5-v1-mvp/when.test.ts deleted file mode 100644 index ad53b3026b3..00000000000 --- a/ui/src/artifact-directions/directions/d5-v1-mvp/when.test.ts +++ /dev/null @@ -1,28 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { countLabel, LAB_NOW, panelDateLabel, updatedLabel } from "./when"; - -// LAB_NOW is Monday 2026-09-28, 6:00 PM local time. -describe("updatedLabel", () => { - it("gives the time today, Yesterday, the weekday within a week, then the date", () => { - expect(updatedLabel("2026-09-28T16:05:00", LAB_NOW)).toBe("4:05 PM"); - expect(updatedLabel("2026-09-27T23:30:00", LAB_NOW)).toBe("Yesterday"); - expect(updatedLabel("2026-09-23T09:00:00", LAB_NOW)).toBe("Wednesday"); - expect(updatedLabel("2026-09-12T09:00:00", LAB_NOW)).toBe("Sep 12"); - }); -}); - -describe("panelDateLabel", () => { - it("gives Today, Yesterday, a day count within a week, then the long date", () => { - expect(panelDateLabel("2026-09-28T08:00:00", LAB_NOW)).toBe("Today"); - expect(panelDateLabel("2026-09-27T08:00:00", LAB_NOW)).toBe("Yesterday"); - expect(panelDateLabel("2026-09-25T08:00:00", LAB_NOW)).toBe("3D ago"); - expect(panelDateLabel("2026-07-23T08:00:00", LAB_NOW)).toBe("July 23"); - }); -}); - -describe("countLabel", () => { - it("pluralises", () => { - expect(countLabel(1)).toBe("1 Artifact"); - expect(countLabel(21)).toBe("21 Artifacts"); - }); -}); diff --git a/ui/src/artifact-directions/lab-state.test.ts b/ui/src/artifact-directions/lab-state.test.ts deleted file mode 100644 index ef2419c5a62..00000000000 --- a/ui/src/artifact-directions/lab-state.test.ts +++ /dev/null @@ -1,54 +0,0 @@ -import { describe, expect, it } from "vitest"; -import { kitIdOf, labSearch, readLabState } from "./lab-state"; - -describe("readLabState", () => { - it("lands a bare URL on MVP V1's overview, dark, with animation on", () => { - expect(readLabState("")).toEqual({ direction: "d5-v1-mvp", view: "board", theme: "dark", chrome: true, anim: true }); - }); - - it("reads a kit with no surface as its thread", () => { - expect(readLabState("?d=d1-solid")).toMatchObject({ direction: "d1-solid", view: "thread" }); - }); - - it("reads a surface with no kit as Today's", () => { - expect(readLabState("?s=panel")).toMatchObject({ direction: "today", view: "panel" }); - }); - - it("keeps the every-kit contact sheet and the kinds sheet reachable by URL", () => { - expect(readLabState("?d=all")).toMatchObject({ direction: "all", view: "board" }); - expect(readLabState("?d=today&s=kinds")).toMatchObject({ direction: "today", view: "kinds" }); - }); - - it("ignores an unknown kit or surface", () => { - expect(readLabState("?d=nope&s=thread")).toMatchObject({ direction: "today", view: "thread" }); - expect(readLabState("?d=d2-tint&s=nope")).toMatchObject({ direction: "d2-tint", view: "thread" }); - }); - - it("turns the light theme, the bare frame and animation off only on request", () => { - expect(readLabState("?theme=light&chrome=0&anim=0")).toMatchObject({ theme: "light", chrome: false, anim: false }); - expect(readLabState("?theme=dusk&chrome=1&anim=1")).toMatchObject({ theme: "dark", chrome: true, anim: true }); - }); -}); - -describe("labSearch", () => { - it("writes the defaults as the short form", () => { - expect(labSearch(readLabState(""))).toBe("?d=d5-v1-mvp&s=board&theme=dark"); - }); - - it("carries chrome and animation only when they are off", () => { - expect(labSearch({ direction: "today", view: "gallery", theme: "light", chrome: false, anim: false })).toBe("?d=today&s=gallery&theme=light&chrome=0&anim=0"); - }); - - it("round-trips through readLabState", () => { - for (const search of ["?d=d3-tactile&s=stack&theme=light", "?d=all&s=board&theme=dark&anim=0", "?d=today&s=kinds&theme=dark&chrome=0"]) { - expect(labSearch(readLabState(search))).toBe(search); - } - }); -}); - -describe("kitIdOf", () => { - it("renders the every-kit board's single views with Today", () => { - expect(kitIdOf(readLabState("?d=all&s=thread"))).toBe("today"); - expect(kitIdOf(readLabState("?d=d4-hybrid"))).toBe("d4-hybrid"); - }); -}); diff --git a/ui/src/components/ActiveAgentsPanel.test.tsx b/ui/src/components/ActiveAgentsPanel.test.tsx deleted file mode 100644 index 532785a228c..00000000000 --- a/ui/src/components/ActiveAgentsPanel.test.tsx +++ /dev/null @@ -1,358 +0,0 @@ -// @vitest-environment jsdom - -import { act, type ReactNode } from "react"; -import { createRoot } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { ActiveAgentsPanel, AgentRunCard } from "./ActiveAgentsPanel"; - -const mockHeartbeatsApi = vi.hoisted(() => ({ - liveRunsForCompany: vi.fn(), -})); - -const mockIssuesApi = vi.hoisted(() => ({ - get: vi.fn(), -})); - -vi.mock("@/lib/router", () => ({ - Link: ({ to, children, ...props }: { to: string; children: ReactNode }) => ( - - {children} - - ), -})); - -vi.mock("../api/heartbeats", () => ({ - heartbeatsApi: mockHeartbeatsApi, -})); - -vi.mock("../api/issues", () => ({ - issuesApi: mockIssuesApi, -})); - -vi.mock("./RunChatSurface", () => ({ - RunChatSurface: () =>
Run output
, -})); - -vi.mock("./transcript/useLiveRunTranscripts", () => ({ - useLiveRunTranscripts: () => ({ - transcriptByRun: new Map(), - hasOutputForRun: () => false, - }), -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function flushReact() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -async function waitForMicrotaskAssertion(assertion: () => void, attempts = 20) { - let lastError: unknown; - for (let index = 0; index < attempts; index += 1) { - await flushReact(); - try { - assertion(); - return; - } catch (error) { - lastError = error; - } - } - throw lastError; -} - -function createRun(index: number) { - return { - id: `run-${index}`, - status: "running", - invocationSource: "assignment", - triggerDetail: null, - startedAt: "2026-04-24T12:00:00.000Z", - finishedAt: null, - createdAt: `2026-04-24T12:00:0${index}.000Z`, - agentId: `agent-${index}`, - agentName: `Agent ${index}`, - adapterType: "codex_local", - issueId: null, - }; -} - -function createIssueRun(index: number, issueId: string) { - return { - ...createRun(index), - issueId, - }; -} - -function createIssue(id: string, identifier: string, title: string) { - return { - id, - companyId: "company-1", - identifier, - title, - description: null, - status: "in_progress", - priority: "medium", - assigneeAgentId: null, - assigneeUserId: null, - parentId: null, - projectId: null, - projectWorkspaceId: null, - executionWorkspaceId: null, - goalId: null, - labels: [], - blockedByIssueIds: [], - blocksIssueIds: [], - createdAt: "2026-04-24T12:00:00.000Z", - updatedAt: "2026-04-24T12:00:00.000Z", - }; -} - -describe("ActiveAgentsPanel", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([1, 2, 3, 4, 5].map(createRun)); - mockIssuesApi.get.mockRejectedValue(new Error("Issue not found")); - }); - - afterEach(() => { - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - it("links hidden active/recent runs to the full live dashboard", async () => { - const root = createRoot(container); - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - - await act(async () => { - root.render( - - - , - ); - }); - await flushReact(); - - expect(mockHeartbeatsApi.liveRunsForCompany).toHaveBeenCalledWith("company-1", { - minCount: 4, - limit: undefined, - distinctTasks: false, - }); - - const moreLink = [...container.querySelectorAll("a")].find((anchor) => - anchor.textContent?.includes("more active/recent"), - ); - expect(moreLink?.getAttribute("href")).toBe("/dashboard/live"); - expect(container.textContent).not.toContain("Run output"); - - await act(async () => { - root.unmount(); - }); - }); - - it("shows each linked task once on the dashboard while keeping distinct taskless runs", async () => { - const repeatedIssueId = "issue-repeated"; - mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([ - createIssueRun(1, repeatedIssueId), - { ...createIssueRun(2, repeatedIssueId), status: "succeeded", finishedAt: "2026-04-24T11:00:00.000Z" }, - createIssueRun(3, "issue-other"), - createRun(4), - createRun(5), - createRun(6), - ]); - - const root = createRoot(container); - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - - await act(async () => { - root.render( - - - , - ); - }); - await flushReact(); - - expect(mockHeartbeatsApi.liveRunsForCompany).toHaveBeenCalledWith("company-1", { - minCount: 4, - limit: undefined, - distinctTasks: true, - }); - expect([...container.querySelectorAll(".dashboard-agent-card")].map((card) => - card.querySelector('a[aria-label$=". View run"]')?.getAttribute("href"), - )).toEqual([ - "/agents/agent-1/runs/run-1", - "/agents/agent-3/runs/run-3", - "/agents/agent-4/runs/run-4", - "/agents/agent-5/runs/run-5", - ]); - expect(container.textContent).toContain("1 more active/recent run"); - - await act(async () => root.unmount()); - }); - - it("can request the full live dashboard page limit without a hidden-runs link", async () => { - mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([ - createIssueRun(1, "issue-repeated"), - { ...createIssueRun(2, "issue-repeated"), status: "succeeded" }, - ]); - const root = createRoot(container); - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - - await act(async () => { - root.render( - - - , - ); - }); - await flushReact(); - - expect(mockHeartbeatsApi.liveRunsForCompany).toHaveBeenCalledWith("company-1", { - minCount: 50, - limit: 50, - distinctTasks: false, - }); - expect(container.textContent).not.toContain("more active/recent"); - expect(container.textContent).not.toContain("Run output"); - expect(container.querySelectorAll(".dashboard-agent-card")).toHaveLength(2); - - await act(async () => { - root.unmount(); - }); - }); - - it("loads exact visible run issues so task names render even when the issue list page would miss them", async () => { - mockHeartbeatsApi.liveRunsForCompany.mockResolvedValue([ - createIssueRun(1, "65274215-0000-4000-8000-000000000000"), - ]); - mockIssuesApi.get.mockResolvedValue(createIssue( - "65274215-0000-4000-8000-000000000000", - "PAP-3562", - "Phase 4B: Implement LLM Wiki distillation UI", - )); - - const root = createRoot(container); - const queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - - await act(async () => { - root.render( - - - , - ); - }); - await flushReact(); - - await waitForMicrotaskAssertion(() => { - expect(mockIssuesApi.get).toHaveBeenCalledWith("65274215-0000-4000-8000-000000000000"); - const issueLink = [...container.querySelectorAll("a")].find((anchor) => - anchor.textContent?.includes("Phase 4B"), - ); - expect(issueLink?.textContent).toContain("Phase 4B: Implement LLM Wiki distillation UI"); - expect(issueLink?.textContent).toContain("PAP-3562"); - expect(issueLink?.getAttribute("href")).toBe("/issues/PAP-3562"); - }); - - await act(async () => { - root.unmount(); - }); - }); - - it("keeps run outcomes distinct from the linked task status", async () => { - const root = createRoot(container); - const statuses = ["running", "queued", "succeeded", "failed", "timed_out", "cancelled", "interrupted"]; - await act(async () => { - root.render(<>{statuses.map((status, index) => ( - - ))}); - }); - const headers = [...container.querySelectorAll('a[aria-label$=". View run"]')]; - expect(headers.map((header) => header.getAttribute("aria-label"))).toEqual([ - "Agent 0 — Running. View run", "Agent 1 — Queued. View run", - "Agent 2 — Succeeded. View run", "Agent 3 — Failed. View run", - "Agent 4 — Timed out. View run", "Agent 5 — Cancelled. View run", - "Agent 6 — Interrupted. View run", - ]); - expect(headers.every((header) => header.querySelector("svg") === null)).toBe(true); - expect(container.querySelector(".status-chip")).toBeNull(); - expect(container.querySelectorAll('[aria-label="Task in review"]')).toHaveLength(7); - expect(container.querySelectorAll(".motion-safe\\:animate-spin")).toHaveLength(0); - expect(container.querySelector('a[aria-label="Agent 0 — Running. View run"]')?.getAttribute("href")) - .toBe("/agents/agent-0/runs/run-0"); - await act(async () => root.unmount()); - }); - - it("shows an answered Slack task as idle without changing the run outcome", async () => { - const root = createRoot(container); - await act(async () => { - root.render(); - }); - expect(container.querySelector('[aria-label="Agent 0 — Succeeded. View run"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Task idle"]')).not.toBeNull(); - expect(container.querySelector('[aria-label="Task in review"]')).toBeNull(); - await act(async () => root.unmount()); - }); - - it("keeps a failed task lookup navigable and shows a clear error", async () => { - const root = createRoot(container); - await act(async () => { - root.render(); - }); - expect(container.textContent).toContain("Task unavailable"); - expect(container.querySelector('a[href="/issues/issue-missing"]')).not.toBeNull(); - await act(async () => root.unmount()); - }); - - it("does not animate running records while execution is reconnecting", async () => { - const root = createRoot(container); - await act(async () => { - root.render(); - }); - expect(container.querySelector('a[aria-label="Agent 0 — Running. View run"]')).not.toBeNull(); - expect(container.querySelector(".status-chip")).toBeNull(); - expect(container.querySelectorAll(".motion-safe\\:animate-spin")).toHaveLength(0); - await act(async () => root.unmount()); - }); -}); diff --git a/ui/src/components/ActivityCharts.test.tsx b/ui/src/components/ActivityCharts.test.tsx deleted file mode 100644 index 9fe6b2f59c0..00000000000 --- a/ui/src/components/ActivityCharts.test.tsx +++ /dev/null @@ -1,137 +0,0 @@ -// @vitest-environment jsdom - -import type { ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot, type Root } from "react-dom/client"; -import type { HeartbeatRun } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { RunActivityChart, SuccessRateChart } from "./ActivityCharts"; - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -let container: HTMLDivElement; -let root: Root; - -beforeEach(() => { - vi.useFakeTimers(); - vi.setSystemTime(new Date("2026-04-20T12:00:00.000Z")); - container = document.createElement("div"); - document.body.appendChild(container); - root = createRoot(container); -}); - -afterEach(() => { - flushSync(() => root.unmount()); - container.remove(); - vi.useRealTimers(); -}); - -function render(ui: ReactNode) { - flushSync(() => { - root.render(ui); - }); -} - -function createRun(overrides: Partial = {}): HeartbeatRun { - return { - id: "run-1", - companyId: "company-1", - agentId: "agent-1", - issueId: null, - responsibleUserId: null, - invocationSource: "on_demand", - triggerDetail: "manual", - status: "succeeded", - startedAt: new Date("2026-04-20T11:58:00.000Z"), - finishedAt: new Date("2026-04-20T11:59:00.000Z"), - error: null, - wakeupRequestId: null, - exitCode: 0, - signal: null, - usageJson: null, - resultJson: null, - sessionIdBefore: null, - sessionIdAfter: null, - logStore: null, - logRef: null, - logBytes: null, - logSha256: null, - logCompressed: false, - lastOutputAt: null, - lastOutputSeq: 0, - lastOutputStream: null, - lastOutputBytes: null, - stdoutExcerpt: null, - stderrExcerpt: null, - errorCode: null, - externalRunId: null, - processPid: null, - processGroupId: null, - processStartedAt: null, - retryOfRunId: null, - processLossRetryCount: 0, - scheduledRetryAt: null, - scheduledRetryAttempt: 0, - scheduledRetryReason: null, - livenessState: null, - livenessReason: null, - continuationAttempt: 0, - lastUsefulActionAt: null, - nextAction: null, - contextSnapshot: null, - createdAt: new Date("2026-04-20T11:58:00.000Z"), - updatedAt: new Date("2026-04-20T11:59:00.000Z"), - ...overrides, - scopeKind: overrides.scopeKind ?? "company", - }; -} - -describe("ActivityCharts", () => { - it("renders empty run charts when dashboard aggregate data is temporarily missing", () => { - render(); - expect(container.textContent).toContain("No runs yet"); - - render(); - expect(container.textContent).toContain("No runs yet"); - }); - - it("still aggregates raw agent runs for detail charts", () => { - render( - , - ); - - expect(container.textContent).not.toContain("No runs yet"); - // Tooltip now carries the per-day breakdown (incl. failure error codes). - const dayCell = container.querySelector("[title^='2026-04-20: 2 runs']"); - expect(dayCell).not.toBeNull(); - expect(dayCell?.getAttribute("title")).toContain("provider_quota: 1"); - }); - - it("renders a distinct recovered segment and legend for recovered restart kills", () => { - render( - , - ); - - expect(container.textContent).toContain("Recovered"); - const dayCell = container.querySelector("[title*='recovered: 4']"); - expect(dayCell).not.toBeNull(); - }); -}); diff --git a/ui/src/components/AgentActionButtons.test.tsx b/ui/src/components/AgentActionButtons.test.tsx deleted file mode 100644 index e5d9b89f352..00000000000 --- a/ui/src/components/AgentActionButtons.test.tsx +++ /dev/null @@ -1,505 +0,0 @@ -// @vitest-environment jsdom - -import type { ComponentProps, ReactNode } from "react"; -import { flushSync } from "react-dom"; -import { createRoot } from "react-dom/client"; -import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; -import type { Agent } from "@paperclipai/shared"; -import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import { History } from "lucide-react"; -import { AgentActionButtons } from "./AgentActionButtons"; -import { useAgentLifecycleStatus } from "./AgentLifecycleStatus"; -import { queryKeys } from "../lib/queryKeys"; - -const mockNavigate = vi.hoisted(() => vi.fn()); -const mockOpenNewIssue = vi.hoisted(() => vi.fn()); -const mockPushToast = vi.hoisted(() => vi.fn()); -const mockAgentsApi = vi.hoisted(() => ({ - get: vi.fn(), - invoke: vi.fn(), - pause: vi.fn(), - resume: vi.fn(), - clearError: vi.fn(), - approve: vi.fn(), - terminate: vi.fn(), - resetSession: vi.fn(), - instructionsBundle: vi.fn(), - instructionsFile: vi.fn(), - create: vi.fn(), - hire: vi.fn(), -})); - -vi.mock("@/lib/router", () => ({ - Link: ({ children, to, ...props }: { children: ReactNode; to: string }) => ( - {children} - ), - useNavigate: () => mockNavigate, -})); - -vi.mock("../context/DialogContext", () => ({ - useDialogActions: () => ({ openNewIssue: mockOpenNewIssue }), -})); - -vi.mock("../context/ToastContext", () => ({ - useToastActions: () => ({ pushToast: mockPushToast }), -})); - -vi.mock("../api/agents", () => ({ - agentsApi: mockAgentsApi, -})); - -// eslint-disable-next-line @typescript-eslint/no-explicit-any -(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true; - -async function act(callback: () => void | Promise) { - let result: void | Promise = undefined; - flushSync(() => { - result = callback(); - }); - await result; -} - -async function flushReact() { - await act(async () => { - await Promise.resolve(); - await new Promise((resolve) => window.setTimeout(resolve, 0)); - }); -} - -function makeAgent(overrides: Partial = {}): Agent { - return { - id: "agent-1", - companyId: "company-1", - name: "Alpha Agent", - urlKey: "alpha", - role: "engineer", - title: null, - icon: null, - status: "active", - reportsTo: null, - capabilities: null, - adapterType: "codex_local", - adapterConfig: {}, - runtimeConfig: {}, - budgetMonthlyCents: 0, - spentMonthlyCents: 0, - pauseReason: null, - pausedAt: null, - permissions: { canCreateAgents: false }, - lastHeartbeatAt: null, - metadata: null, - createdAt: new Date("2026-01-01T00:00:00Z"), - updatedAt: new Date("2026-01-01T00:00:00Z"), - ...overrides, - }; -} - -describe("AgentActionButtons", () => { - let container: HTMLDivElement; - let root: ReturnType | null; - let queryClient: QueryClient; - let invalidateQueries: ReturnType; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - root = null; - queryClient = new QueryClient({ - defaultOptions: { queries: { retry: false } }, - }); - invalidateQueries = vi.spyOn(queryClient, "invalidateQueries") as unknown as ReturnType; - mockAgentsApi.clearError.mockResolvedValue(makeAgent({ status: "idle" })); - mockAgentsApi.pause.mockResolvedValue(makeAgent({ status: "paused" })); - mockAgentsApi.resume.mockResolvedValue(makeAgent({ status: "idle" })); - mockAgentsApi.terminate.mockResolvedValue(makeAgent({ status: "terminated" })); - mockAgentsApi.invoke.mockResolvedValue({ id: "run-1" }); - mockAgentsApi.resetSession.mockResolvedValue(undefined); - }); - - afterEach(async () => { - const currentRoot = root; - if (currentRoot) { - await act(async () => { - currentRoot.unmount(); - }); - } - queryClient.clear(); - container.remove(); - document.body.innerHTML = ""; - vi.clearAllMocks(); - }); - - function render(agent: Agent, props: Partial> = {}) { - root ??= createRoot(container); - root.render( - - - , - ); - } - - it.each(["codex_local", "claude_local", "opencode_local", "pi_local", "paperclip_runner"])("returns unfinished %s agents to their saved runner", async adapterType => { - render(makeAgent({ adapterType, status: "paused", lifecycleState: "paused", pauseReason: "setup" })); - await flushReact(); - const finish = [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup"); - expect(finish).toBeTruthy(); - expect([...container.querySelectorAll("button")].some(button => button.textContent === "Resume")).toBe(false); - await act(() => finish!.click()); - expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining("setupAgentId=agent-1")); - expect(mockNavigate).toHaveBeenCalledWith(expect.stringContaining(`runner=${adapterType === "paperclip_runner" ? "paperclip" : "legacy"}`)); - expect(mockAgentsApi.resume).not.toHaveBeenCalled(); - }); - it("reopens the saved pending Antigravity choice while its execution adapter remains held", async () => { - render(makeAgent({ adapterType: "process", adapterConfig: {}, status: "paused", lifecycleState: "paused", pauseReason: "setup", - metadata: { setupAdapterPending: true, setupAdapterChoice: { adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto" } } })); - await flushReact(); - const finish = [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup"); - await act(() => finish!.click()); - const params = new URL(mockNavigate.mock.calls[0][0], "http://local").searchParams; - expect(Object.fromEntries(params)).toMatchObject({ adapterType: "paperclip_runner", runnerProvider: "antigravity", runner: "auto", setupAgentId: "agent-1" }); - expect(mockAgentsApi.resume).not.toHaveBeenCalled(); - expect(mockAgentsApi.invoke).not.toHaveBeenCalled(); - }); - - it.each(["paused", "preparing", "verifying", "pausing", undefined] as const)("replaces run controls with one setup action when lifecycle is %s", async lifecycleState => { - render(makeAgent({ adapterType: "paperclip_runner", adapterConfig: { provider: "acpx", acpxAgent: "claude" }, status: "paused", lifecycleState, pauseReason: "setup" })); - await flushReact(); - const buttons = [...container.querySelectorAll("button")]; - const finish = buttons.filter(button => button.textContent === "Finish setup"); - expect(finish).toHaveLength(1); - expect(buttons.some(button => /Run Heartbeat|^Resume$|^Pause$/.test(button.textContent ?? ""))).toBe(false); - await act(() => finish[0].click()); - const target = new URL(mockNavigate.mock.calls[0][0], "https://example.test"); - expect(target.pathname).toBe("/agents/new"); - expect(Object.fromEntries(target.searchParams)).toMatchObject({ setupAgentId: "agent-1", adapterType: "paperclip_runner", runnerProvider: "claude", runner: "paperclip" }); - expect(mockAgentsApi.invoke).not.toHaveBeenCalled(); - expect(mockAgentsApi.resume).not.toHaveBeenCalled(); - }); - - it.each(["terminating", "cleaning_up", "terminated", "rejected"] as const)("does not reopen setup during %s", async lifecycleState => { - render(makeAgent({ status: "terminated", lifecycleState, pauseReason: "setup" })); - await flushReact(); - expect(container.textContent).not.toContain("Finish setup"); - }); - - it("restores Run after lifecycle refresh completes setup without replacing the editable record", async () => { - const draft = makeAgent({ status: "paused", lifecycleState: "paused", lifecycleVersion: 1, pauseReason: "setup", pausedAt: new Date("2026-01-01T00:00:00Z"), adapterConfig: { model: "saved-model" } }); - queryClient.setQueryData(queryKeys.agents.detail("alpha"), draft); - mockAgentsApi.get.mockResolvedValueOnce(draft); - function LiveActions() { - const lifecycle = useAgentLifecycleStatus(draft); - return ; - } - root = createRoot(container); - root.render(); - await flushReact(); - expect(container.textContent).toContain("Finish setup"); - mockAgentsApi.get.mockResolvedValue({ ...draft, status: "idle", lifecycleState: "ready", lifecycleVersion: 2, pauseReason: null, pausedAt: null, adapterConfig: { model: "updated-on-server" } }); - await act(async () => { await queryClient.invalidateQueries({ queryKey: [...queryKeys.agents.detail(draft.id), "lifecycle", draft.companyId] }); }); - await flushReact(); - expect(container.textContent).not.toContain("Finish setup"); - const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat"); - expect(run?.disabled).toBe(false); - expect(queryClient.getQueryData(queryKeys.agents.detail("alpha"))?.adapterConfig).toEqual({ model: "saved-model" }); - expect(mockAgentsApi.get).toHaveBeenLastCalledWith("agent-1", "company-1"); - await act(() => run!.click()); - await flushReact(); - expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1"); - }); - - it("checks unsaved changes before leaving to finish setup", async () => { - const onBeforeNavigate = vi.fn(() => false); - render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { hasPendingNavigationChanges: true, onBeforeNavigate }); - await flushReact(); - await act(() => [...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.click()); - expect(onBeforeNavigate).toHaveBeenCalledOnce(); - expect(mockNavigate).not.toHaveBeenCalled(); - expect(mockAgentsApi.invoke).not.toHaveBeenCalled(); - }); - - it("keeps setup available when the caller hides Run or blocks work", async () => { - render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { showRun: false, workActionsDisabled: true }); - await flushReact(); - expect([...container.querySelectorAll("button")].find(button => button.textContent === "Finish setup")!.disabled).toBe(false); - }); - - it("offers Run after setup completes without turning a manual pause into setup", async () => { - render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" })); - await flushReact(); - render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "manual" })); - await flushReact(); - expect(container.textContent).toContain("Resume"); - expect(container.textContent).not.toContain("Finish setup"); - render(makeAgent({ status: "idle", lifecycleState: "ready", pauseReason: null })); - await flushReact(); - const run = [...container.querySelectorAll("button")].find(button => button.textContent === "Run Heartbeat"); - expect(run?.disabled).toBe(false); - await act(() => run!.click()); - await flushReact(); - expect(mockAgentsApi.invoke).toHaveBeenCalledWith("agent-1", "company-1"); - }); - - it.each(["preparing", "verifying", "resuming"] as const)("offers pause rather than resume during %s", async lifecycleState => { - render(makeAgent({ status: "paused", lifecycleState })); - await flushReact(); - const buttons = Array.from(container.querySelectorAll("button")); - expect(buttons.some(button => button.textContent === "Resume")).toBe(false); - const pause = buttons.find(button => button.textContent === "Pause")!; - expect(pause.disabled).toBe(false); - await act(async () => pause.click()); - await flushReact(); - expect(mockAgentsApi.pause).toHaveBeenCalledWith("agent-1", "company-1"); - }); - - it.each(["pausing", "terminating", "cleaning_up", "terminated", "rejected"] as const)("disables pause and resume during %s", async lifecycleState => { - render(makeAgent({ status: lifecycleState === "pausing" ? "paused" : "terminated", lifecycleState })); - await flushReact(); - const buttons = Array.from(container.querySelectorAll("button")); - expect(buttons.find(button => button.textContent === "Pause")!.disabled).toBe(true); - if (lifecycleState !== "pausing") { - expect(buttons.find(button => button.textContent === "Run Heartbeat")!.disabled).toBe(true); - expect(buttons.find(button => button.textContent === "Assign Task")!.disabled).toBe(true); - } - }); - - it("replaces the pause slot with Clear error for error agents", async () => { - render(makeAgent({ status: "error" })); - await flushReact(); - - expect(container.textContent).toContain("Clear error"); - expect(container.textContent).not.toContain("Pause"); - expect(container.textContent).toContain("Run Heartbeat"); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - - expect(document.body.textContent).toContain("Reset Sessions"); - }); - - it("moves work actions into the menu, leaving Assign task as the one button", async () => { - const openHistory = vi.fn(); - render(makeAgent({ status: "error" }), { - assignLabel: "Assign task", - workActionsInMenu: true, - menuItems: [{ label: "Agent history", icon: History, onSelect: openHistory }], - }); - await flushReact(); - - expect([...container.querySelectorAll("button")].map((button) => button.textContent?.trim()).filter(Boolean)).toEqual(["Assign task"]); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - const items = [...document.body.querySelectorAll("[data-slot='popover-content'] button, [data-radix-popper-content-wrapper] button")].map((button) => button.textContent?.trim()); - expect(items).toEqual(["Run Heartbeat", "Clear error", "Agent history", "Duplicate agent", "Copy agent ID", "Reset sessions", "Terminate"]); - - await act(async () => { - [...document.body.querySelectorAll("button")].find((button) => button.textContent?.trim() === "Agent history")?.click(); - }); - expect(openHistory).toHaveBeenCalledTimes(1); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - await act(async () => { - document.body.querySelector('[aria-label="Clear error and return agent to idle"]')?.click(); - }); - await flushReact(); - expect(mockAgentsApi.clearError).toHaveBeenCalledWith("agent-1", "company-1"); - }); - - it("keeps Finish setup as the one button while setup is pending in menu mode", async () => { - render(makeAgent({ status: "paused", lifecycleState: "paused", pauseReason: "setup" }), { - assignLabel: "Assign task", - workActionsInMenu: true, - }); - await flushReact(); - - expect([...container.querySelectorAll("button")].map((button) => button.textContent?.trim()).filter(Boolean)).toEqual(["Finish setup"]); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - const items = [...document.body.querySelectorAll("[data-slot='popover-content'] button, [data-radix-popper-content-wrapper] button")].map((button) => button.textContent?.trim()); - expect(items).toEqual(["Assign task", "Duplicate agent", "Copy agent ID", "Reset sessions", "Terminate"]); - }); - - it("calls clearError and refreshes agent-related queries", async () => { - render(makeAgent({ status: "error" })); - await flushReact(); - - await act(async () => { - container.querySelector('[aria-label="Clear error and return agent to idle"]')?.click(); - }); - await flushReact(); - - expect(mockAgentsApi.clearError).toHaveBeenCalledWith("agent-1", "company-1"); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "alpha"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "runtime-state", "agent-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "task-sessions", "agent-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "company-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["live-runs", "company-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["heartbeats", "company-1", "agent-1"] }); - }); - - it("keeps the normal pause action for non-error agents", async () => { - render(makeAgent({ status: "active" })); - await flushReact(); - - expect(container.textContent).toContain("Pause"); - expect(container.textContent).not.toContain("Clear error"); - }); - - it.each([false, true])("keeps the normal run action when persistent tracing is %s", async tracingEnabled => { - render(makeAgent({ runtimeConfig: tracingEnabled ? { debug: { providerTrace: "raw" } } : {} })); - await flushReact(); - - const buttons = Array.from(container.querySelectorAll("button")); - expect(buttons.some(button => button.textContent?.includes("Run with provider trace"))).toBe(false); - expect(container.textContent?.includes("Raw tracing on")).toBe(tracingEnabled); - - await act(async () => { - buttons.find(button => button.textContent === "Run Heartbeat")!.click(); - }); - await flushReact(); - - expect(mockAgentsApi.invoke).toHaveBeenCalledExactlyOnceWith("agent-1", "company-1"); - expect(mockNavigate).toHaveBeenCalledWith("/agents/alpha/runs/run-1"); - }); - - it.each([ - ["terminating", false], - ["cleaning_up", false], - ["terminating", true], - ["cleaning_up", true], - ] as const)("leaves the detail page after termination is accepted during %s (work actions in menu: %s)", async (lifecycleState, workActionsInMenu) => { - mockAgentsApi.terminate.mockResolvedValue(makeAgent({ status: "terminated", lifecycleState })); - const onTerminateSuccess = vi.fn(); - render(makeAgent(), { onTerminateSuccess, workActionsInMenu }); - await flushReact(); - await act(async () => { container.querySelector('[aria-label="Open actions for Alpha Agent"]')!.click(); }); - await flushReact(); - await act(async () => { Array.from(document.body.querySelectorAll("button")).find(button => button.textContent?.includes("Terminate"))!.click(); }); - await flushReact(); - expect(mockAgentsApi.terminate).toHaveBeenCalledWith("agent-1", "company-1"); - expect(onTerminateSuccess).toHaveBeenCalledWith(expect.objectContaining({ - id: "agent-1", - lifecycleState, - })); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "company-1"] }); - }); - - it("keeps the detail page open and reports a failed termination", async () => { - mockAgentsApi.terminate.mockRejectedValue(new Error("Termination failed")); - const onTerminateSuccess = vi.fn(); - render(makeAgent(), { onTerminateSuccess }); - await flushReact(); - await act(async () => { container.querySelector('[aria-label="Open actions for Alpha Agent"]')!.click(); }); - await flushReact(); - await act(async () => { Array.from(document.body.querySelectorAll("button")).find(button => button.textContent?.includes("Terminate"))!.click(); }); - await flushReact(); - - expect(onTerminateSuccess).not.toHaveBeenCalled(); - expect(invalidateQueries).not.toHaveBeenCalled(); - expect(mockPushToast).toHaveBeenCalledWith(expect.objectContaining({ - body: "Termination failed", - tone: "error", - })); - }); - - it("calls the terminate success handler after terminating an agent", async () => { - const onTerminateSuccess = vi.fn(); - render(makeAgent(), { onTerminateSuccess }); - await flushReact(); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - - const terminateButton = Array.from(document.body.querySelectorAll("button")) - .find((button) => button.textContent?.includes("Terminate")); - expect(terminateButton).toBeTruthy(); - - await act(async () => { - terminateButton?.click(); - }); - await flushReact(); - - expect(mockAgentsApi.terminate).toHaveBeenCalledWith("agent-1", "company-1"); - expect(onTerminateSuccess).toHaveBeenCalledWith(expect.objectContaining({ - id: "agent-1", - status: "terminated", - })); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "agent-1"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "detail", "alpha"] }); - expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: ["agents", "company-1"] }); - }); - - it("does not terminate when navigation away from a dirty detail page is rejected", async () => { - const onBeforeNavigate = vi.fn().mockReturnValue(false); - render(makeAgent(), { onBeforeNavigate, onTerminateSuccess: vi.fn() }); - await flushReact(); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - - const terminateButton = Array.from(document.body.querySelectorAll("button")) - .find((button) => button.textContent?.includes("Terminate")); - await act(async () => { - terminateButton?.click(); - }); - await flushReact(); - - expect(onBeforeNavigate).toHaveBeenCalledOnce(); - expect(mockAgentsApi.terminate).not.toHaveBeenCalled(); - }); - - it.each([undefined, "terminating", "cleaning_up"] as const)("rechecks unsaved changes before leaving after termination returns %s", async lifecycleState => { - let resolveTermination!: (agent: Agent) => void; - mockAgentsApi.terminate.mockReturnValue(new Promise((resolve) => { - resolveTermination = resolve; - })); - const onBeforeNavigate = vi.fn().mockReturnValueOnce(true).mockReturnValue(false); - const onTerminateSuccess = vi.fn(); - const agent = makeAgent(); - render(agent, { - hasPendingNavigationChanges: false, - onBeforeNavigate, - onTerminateSuccess, - }); - await flushReact(); - - await act(async () => { - container.querySelector('[aria-label="Open actions for Alpha Agent"]')?.click(); - }); - await flushReact(); - const terminateButton = Array.from(document.body.querySelectorAll("button")) - .find((button) => button.textContent?.includes("Terminate")); - await act(async () => { - terminateButton?.click(); - }); - await flushReact(); - - render(agent, { - hasPendingNavigationChanges: true, - onBeforeNavigate, - onTerminateSuccess, - }); - await flushReact(); - resolveTermination(makeAgent({ status: "terminated", lifecycleState })); - await flushReact(); - - expect(onBeforeNavigate).toHaveBeenCalledTimes(2); - expect(onTerminateSuccess).not.toHaveBeenCalled(); - }); -}); diff --git a/ui/src/components/AgentAvatar.test.tsx b/ui/src/components/AgentAvatar.test.tsx deleted file mode 100644 index 596e158fa1b..00000000000 --- a/ui/src/components/AgentAvatar.test.tsx +++ /dev/null @@ -1,27 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { expect, it } from "vitest"; -import { appearanceForPalette } from "@paperclipai/shared"; -import { AgentAvatar } from "./AgentAvatar"; -import { AgentCharacter } from "./AgentCharacter"; - -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); -it("shows the uploaded image in small and animated-character surfaces, then returns to the palette on reset", async () => { - const base = appearanceForPalette("deep-tide"); - const appearance = { ...base, customAvatarAssetId: "22222222-2222-4222-8222-222222222222" }; - const container = document.createElement("div"); - const root = createRoot(container); - try { - await act(async () => root.render(<>)); - for (const image of container.querySelectorAll("img")) { - expect(image.getAttribute("src")).toBe("/api/assets/22222222-2222-4222-8222-222222222222/content"); - expect(image.hasAttribute("srcset")).toBe(false); - expect(image.parentElement?.classList.contains("invisible")).toBe(false); - } - expect(container.querySelectorAll("img")).toHaveLength(2); - expect(container.querySelector("canvas")).toBeNull(); - await act(async () => root.render()); - expect(container.querySelector("img")?.getAttribute("src")).toContain("/api/agent-avatars/cap-v1/deep-tide/"); - } finally { await act(async () => root.unmount()); } -}); diff --git a/ui/src/components/AgentCapsule.test.tsx b/ui/src/components/AgentCapsule.test.tsx deleted file mode 100644 index 87285eb0323..00000000000 --- a/ui/src/components/AgentCapsule.test.tsx +++ /dev/null @@ -1,117 +0,0 @@ -// @vitest-environment jsdom - -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, describe, expect, it } from "vitest"; -import { AgentCapsule } from "./AgentCapsule"; - -(globalThis as unknown as { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT = true; - -describe("AgentCapsule", () => { - let container: HTMLDivElement; - - beforeEach(() => { - container = document.createElement("div"); - document.body.appendChild(container); - }); - - afterEach(() => { - container.remove(); - }); - - function render(node: React.ReactElement) { - const root = createRoot(container); - act(() => { - root.render(node); - }); - return container.querySelector('[role="img"]') as HTMLElement; - } - - it("renders a dashed pulsing outline with no liquid in the slot state", () => { - const cap = render(); - expect(cap.dataset.state).toBe("slot"); - const dash = cap.querySelector(".agent-cap-dash") as HTMLElement; - expect(dash).not.toBeNull(); - expect(dash.className).toContain("border-dashed"); - expect(dash.className).toContain("agent-cap-slot"); - expect(dash.className).toContain("opacity-100"); - // Solid stroke layer is present but faded out. - expect((cap.querySelector(".agent-cap-stroke") as HTMLElement).className).toContain("opacity-0"); - expect(cap.querySelector(".agent-cap-liquid")).toBeNull(); - expect(cap.getAttribute("aria-label")).toBe("empty agent slot"); - }); - - it("renders a solid stroke with no liquid in the configured state", () => { - const cap = render(); - expect(cap.dataset.state).toBe("configured"); - const stroke = cap.querySelector(".agent-cap-stroke") as HTMLElement; - expect(stroke.className).toContain("border-solid"); - expect(stroke.className).toContain("opacity-100"); - // Dashed layer is present but faded out (no pulse). - const dash = cap.querySelector(".agent-cap-dash") as HTMLElement; - expect(dash.className).toContain("opacity-0"); - expect(dash.className).not.toContain("agent-cap-slot"); - expect(cap.querySelector(".agent-cap-liquid")).toBeNull(); - }); - - it("renders the rising gradient liquid + green online pulse by default", () => { - const cap = render(); - expect(cap.className).toContain("agent-cap-online"); - expect(cap.className).not.toContain("agent-cap-online-blue"); - expect(cap.dataset.glow).toBe("green"); - const liquid = cap.querySelector(".agent-cap-liquid") as HTMLElement; - expect(liquid).not.toBeNull(); - expect(liquid.style.background).toContain("--agent-5a"); - expect(liquid.style.background).toContain("--agent-5b"); - expect(cap.dataset.gradient).toBe("5"); - }); - - it("uses the blue online glow when glow='blue'", () => { - const cap = render(); - expect(cap.className).toContain("agent-cap-online-blue"); - expect(cap.dataset.glow).toBe("blue"); - expect(cap.querySelector(".agent-cap-liquid")).not.toBeNull(); - }); - - it("maps preset sizes to pixel dimensions (proportion 1:>=2)", () => { - const cap = render(); - expect(cap.style.width).toBe("34px"); - expect(cap.style.height).toBe("84px"); - }); - - it("accepts an explicit pixel size", () => { - const cap = render(); - expect(cap.style.width).toBe("28px"); - expect(cap.style.height).toBe("96px"); - }); - - it("wraps out-of-range gradient indices into 1..10", () => { - expect(render().dataset.gradient).toBe("1"); - expect(render().dataset.gradient).toBe("10"); - expect(render().dataset.gradient).toBe("9"); - }); - - it("traces the outline instead of cross-fading it when strokeDraw is set", () => { - // The cross-fade renders a bordered ; the trace renders an SVG rect - // animated from pathLength 0 to 1. - const cap = render(); - expect(cap.querySelector("svg rect")).not.toBeNull(); - expect(cap.querySelector(".agent-cap-stroke")).toBeNull(); - }); - - it("keeps the cross-fade when strokeDraw is not asked for", () => { - // Everywhere outside the onboarding arc the quieter default applies. - const cap = render(); - expect(cap.querySelector(".agent-cap-stroke")).not.toBeNull(); - expect(cap.querySelector("svg rect")).toBeNull(); - }); - - it("holds the dashed outline until the trace finishes", () => { - // Fading the dashed layer on the usual schedule would leave the capsule - // briefly outline-less in the middle of its own birth. - const cap = render(); - const dashed = cap.querySelector(".agent-cap-dash") as HTMLElement; - expect(dashed).not.toBeNull(); - expect(dashed.style.transitionDelay).not.toBe(""); - }); -}); diff --git a/ui/src/components/AgentCharacter.test.tsx b/ui/src/components/AgentCharacter.test.tsx deleted file mode 100644 index 8418931daed..00000000000 --- a/ui/src/components/AgentCharacter.test.tsx +++ /dev/null @@ -1,54 +0,0 @@ -// @vitest-environment jsdom -import { act } from "react"; -import { createRoot } from "react-dom/client"; -import { afterEach, beforeEach, expect, it, vi } from "vitest"; -import { AgentCharacter } from "./AgentCharacter"; - -const createMock = vi.hoisted(() => vi.fn()); -vi.mock("@paperclipai/shared/cliplab/runtime", () => ({ createCharacter: createMock })); -vi.mock("@paperclipai/shared/cliplab/definition", () => ({ characterDefinition: vi.fn(), animationId: (state: string) => state })); -Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true }); -let container: HTMLDivElement; -let root: ReturnType; -let media: MediaQueryList; -let observers: Array<(visible: boolean) => void>; -beforeEach(() => { - observers = []; - media = Object.assign(new EventTarget(), { matches: false }) as unknown as MediaQueryList; - vi.stubGlobal("matchMedia", () => media); - vi.stubGlobal("IntersectionObserver", class { - constructor(callback: (entries: Array<{ isIntersecting: boolean }>) => void) { observers.push(visible => callback([{ isIntersecting: visible }])); } - observe() {} disconnect() {} - }); - createMock.mockReset().mockImplementation((host: HTMLElement) => { - const canvas = document.createElement("canvas"); host.appendChild(canvas); - return { destroy: vi.fn(() => canvas.remove()), setDefinition: vi.fn(), setAnimation: vi.fn() }; - }); - container = document.createElement("div"); document.body.appendChild(container); root = createRoot(container); -}); -afterEach(async () => { await act(async () => root.unmount()); container.remove(); vi.unstubAllGlobals(); }); -async function settle() { await act(async () => { await vi.dynamicImportSettled(); }); } -async function reveal() { await act(async () => observers.forEach(notify => notify(true))); await settle(); } - -it("animates visible org leaders together, bounds GPU contexts, and hands off offscreen slots", async () => { - await act(async () => root.render(<>{Array.from({ length: 12 }, (_, index) => )})); - await reveal(); - expect(container.querySelectorAll("canvas")).toHaveLength(8); - expect(createMock).toHaveBeenCalledTimes(8); - for (const call of createMock.mock.calls) expect(call[2]).toMatchObject({ trackingScope: "page", followCursor: true }); - await act(async () => observers[0](false)); await settle(); - expect(container.querySelectorAll("canvas")).toHaveLength(8); - expect(createMock).toHaveBeenCalledTimes(9); - // Reduced motion disposes every live renderer and reveals the static images. - await act(async () => { Object.assign(media, { matches: true }); media.dispatchEvent(new Event("change")); }); - expect(container.querySelectorAll("canvas")).toHaveLength(0); - expect(container.querySelectorAll(".invisible")).toHaveLength(0); -}); - -it("retains one hero outside the org chart and ignores custom avatars", async () => { - await act(async () => root.render(<>)); - await reveal(); - expect(container.querySelectorAll("canvas")).toHaveLength(1); - expect(createMock).toHaveBeenCalledTimes(1); - expect(container.querySelector('img[src="/api/assets/22222222-2222-4222-8222-222222222222/content"]')).not.toBeNull(); -}); diff --git a/ui/src/components/AgentConfigForm.render.test.tsx b/ui/src/components/AgentConfigForm.render.test.tsx index e944adc16c8..6766e864144 100644 --- a/ui/src/components/AgentConfigForm.render.test.tsx +++ b/ui/src/components/AgentConfigForm.render.test.tsx @@ -1,31 +1,17 @@ // @vitest-environment jsdom -import { sampleHarnesses } from "@/test-support/harness-availability"; - -import { useState } from "react"; -import { MemoryRouter } from "react-router-dom"; import { createRoot, type Root } from "react-dom/client"; import { flushSync } from "react-dom"; import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -import type { Agent, Environment, UserSecretDefinition } from "@paperclipai/shared"; +import type { Agent, Environment } from "@paperclipai/shared"; import { getEnvironmentCapabilities } from "@paperclipai/shared"; import { TooltipProvider } from "@/components/ui/tooltip"; import { ToastProvider } from "../context/ToastContext"; -import { AgentConfigForm, AdapterLoginPanel, ModelDropdown, subtractPersistedOverlay, type AdapterLoginDescriptor } from "./AgentConfigForm"; -import { AgentLifecycleStatus, useAgentLifecycleStatus } from "./AgentLifecycleStatus"; -import { queryKeys } from "../lib/queryKeys"; +import { AgentConfigForm } from "./AgentConfigForm"; import { isBlockedFromReplay } from "@/lib/analytics/replay-recording.test-utils"; -import { defaultCreateValues } from "./agent-config-defaults"; -import { buildNewAgentHirePayload } from "../lib/new-agent-hire-payload"; import { ApiError } from "../api/client"; -import { aiConnectionsApi } from "../api/ai-connections"; -import * as ConnectionField from "./ai-connections/AiConnectionField"; import { CodexLocalConfigFields } from "../adapters/codex-local/config-fields"; import type { AdapterConfigFieldsProps } from "../adapters/types"; -import { buildClaudeLocalConfig } from "@paperclipai/adapter-claude-local/ui"; -import { DEFAULT_CODEX_LOCAL_MODEL } from "@paperclipai/adapter-codex-local"; -import { ConfigurationTab } from "../pages/AgentDetail"; -import { ConfigurationTab as ClassicConfigurationTab } from "../pages/AgentDetail.production"; const mockAgentsApi = vi.hoisted(() => ({ get: vi.fn(), @@ -48,18 +34,6 @@ const mockAgentsApi = vi.hoisted(() => ({ getClaudeOAuthTokenStatus: vi.fn(), })); -// The default resume read for a test that does not exercise resume: no active -// session for the caller. -function noActiveSession() { - return Promise.reject( - new ApiError("Adapter login session not found", 404, { error: "Adapter login session not found" }), - ); -} - -const mockClipboard = vi.hoisted(() => ({ - copyTextToClipboard: vi.fn(), -})); - const mockEnvironmentsApi = vi.hoisted(() => ({ list: vi.fn(), capabilities: vi.fn(), @@ -78,35 +52,19 @@ const mockSecretsApi = vi.hoisted(() => ({ listUserSecretDefinitions: vi.fn(async () => [] as unknown[]), })); -vi.mock("../api/agents", () => ({ - agentsApi: mockAgentsApi, +const mockAdaptersApi = vi.hoisted(() => ({ + list: vi.fn(async () => [{ type: "codex_local", supportedRunners: ["legacy", "paperclip"], defaultRunner: "legacy" }]), })); +vi.mock("../api/agents", () => ({ agentsApi: mockAgentsApi })); vi.mock("../api/grokBot", () => ({ - grokBotApi: { - connection: async () => ({ enabled: true, canConfigureConnection: true, binding: null }), - }, + grokBotApi: { connection: async () => ({ enabled: true, canConfigureConnection: true, binding: null }) }, })); - -const mockAdaptersApi = vi.hoisted(() => ({ list: vi.fn(async () => [{ type: "codex_local", supportedRunners: ["legacy", "paperclip"], defaultRunner: "legacy" }]) })); vi.mock("../api/adapters", () => ({ adaptersApi: mockAdaptersApi })); - -vi.mock("../api/environments", () => ({ - environmentsApi: mockEnvironmentsApi, -})); - -vi.mock("../api/instanceSettings", () => ({ - instanceSettingsApi: mockInstanceSettingsApi, -})); - -vi.mock("../api/secrets", () => ({ - secretsApi: mockSecretsApi, -})); - -vi.mock("../lib/clipboard", () => ({ - copyTextToClipboard: mockClipboard.copyTextToClipboard, -})); - +vi.mock("../api/environments", () => ({ environmentsApi: mockEnvironmentsApi })); +vi.mock("../api/instanceSettings", () => ({ instanceSettingsApi: mockInstanceSettingsApi })); +vi.mock("../api/secrets", () => ({ secretsApi: mockSecretsApi })); +vi.mock("../lib/clipboard", () => ({ copyTextToClipboard: vi.fn() })); vi.mock("../context/CompanyContext", () => ({ useCompany: () => ({ companies: [{ id: "company-1", name: "Paperclip", issuePrefix: "CO" }], @@ -120,100 +78,33 @@ vi.mock("../context/CompanyContext", () => ({ createCompany: vi.fn(), }), })); - vi.mock("../adapters", () => ({ getUIAdapter: (type: string) => ({ type, - label: type === "hermes_gateway" ? "Hermes Gateway" : "Codex", - // The stand-in also records the two gates the form resolves for every - // adapter, so a test can assert the plumbing without rendering a real - // adapter's fields. - ConfigFields: (props: AdapterConfigFieldsProps) => { - if (type === "paperclip_runner") return ; - const { adapterType, hideInstructionsFile, managedSandboxOnly } = props; - return adapterType === "hermes_gateway" - ?
Hermes Gateway fields
- : ( -
- ); - }, - buildAdapterConfig: (values: { model?: string }) => ({ - model: values.model || undefined, - }), + label: "Codex", + ConfigFields: (props: AdapterConfigFieldsProps) => + type === "paperclip_runner" ? :
, + buildAdapterConfig: (values: { model?: string }) => ({ model: values.model || undefined }), parseStdoutLine: () => [], }), })); - -// The projected login capability per adapter type. The server projects these -// safe scalar fields. `codex_local` drives the displayed-code panel; `claude_local` -// drives the submitted-browser-code panel. A test overrides this map to add a -// third adapter with a projected login capability. -const mockLoginProjections = vi.hoisted( - () => - new Map([ - ["codex_local", { panelMode: "displayed_code", timeoutPolicy: "caller_bounded" }], - ["grok_local", { panelMode: "displayed_code", timeoutPolicy: "caller_bounded" }], - ["claude_local", { panelMode: "submitted_browser_code", timeoutPolicy: "fixed" }], - // A third adapter, not a built-in, with a projected displayed-code login. - ["vendor_local", { panelMode: "displayed_code", timeoutPolicy: "caller_bounded" }], - // A non-built-in adapter with a submitted-browser-code login. Every login - // runs on a real pseudo-terminal, so the gate requires the provider pty - // capability from the login capability, not the adapter name. - ["pty_vendor_local", { panelMode: "submitted_browser_code", timeoutPolicy: "fixed" }], - ]), -); - vi.mock("../adapters/use-adapter-capabilities", () => ({ - useAdapterCapabilities: () => (adapterType: string) => { - const login = mockLoginProjections.get(adapterType); - return adapterType === "hermes_gateway" - ? { - supportsInstructionsBundle: false, - supportsSkills: false, - supportsLocalAgentJwt: false, - requiresMaterializedRuntimeSkills: false, - supportsAcp: false, - } - : { - supportsInstructionsBundle: true, - supportsSkills: true, - supportsLocalAgentJwt: true, - requiresMaterializedRuntimeSkills: false, - supportsAcp: true, - ...(login ? { login } : {}), - }; - }, + useAdapterCapabilities: () => () => ({ + supportsInstructionsBundle: true, + supportsSkills: true, + supportsLocalAgentJwt: true, + requiresMaterializedRuntimeSkills: false, + supportsAcp: true, + login: { panelMode: "displayed_code", timeoutPolicy: "caller_bounded" }, + }), })); - -vi.mock("../adapters/use-disabled-adapters", () => ({ - useDisabledAdaptersSync: () => [], -})); - +vi.mock("../adapters/use-disabled-adapters", () => ({ useDisabledAdaptersSync: () => [] })); vi.mock("./MarkdownEditor", () => ({ - MarkdownEditor: ({ - value, - onChange, - placeholder, - }: { - value: string; - onChange: (value: string) => void; - placeholder?: string; - }) => ( -