Merge remote-tracking branch 'origin/master' into swarm-fin-tmp

* origin/master:
  perf(test): split chat-channels monolith into 16 suites and shrink PR chat shards 5 -> 2 (#22838)
  fix: Restore icon and appearance when rolling back an agent config revision (#19244)
  fix: Match originKindPrefix as a literal prefix by escaping LIKE wildcards (#19197)
This commit is contained in:
Dotta committed 2026-11-24 17:47:35 -06:00
commit a2decc65f3
46 files changed
+50785 -87946

No files matched your search

+4 -25
View File
@@ -147,37 +147,16 @@
}, },
{ {
"group": "general-chat", "group": "general-chat",
"group_label": "chat (1/5)", "group_label": "chat (1/2)",
"shard_index": 0, "shard_index": 0,
"shard_count": 5, "shard_count": 2,
"task": "ci:chat" "task": "ci:chat"
}, },
{ {
"group": "general-chat", "group": "general-chat",
"group_label": "chat (2/5)", "group_label": "chat (2/2)",
"shard_index": 1, "shard_index": 1,
"shard_count": 5, "shard_count": 2,
"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" "task": "ci:chat"
}, },
{ {
+1 -1
View File
@@ -426,7 +426,7 @@ else process.exit(3);
else { else {
assert.notEqual(value, "plan=", `${JSON.stringify(overrides)}: ${result.stderr}`); assert.notEqual(value, "plan=", `${JSON.stringify(overrides)}: ${result.stderr}`);
const resultPlan = JSON.parse(value.slice("plan=".length)); const resultPlan = JSON.parse(value.slice("plan=".length));
assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 30 : 2); assert.equal(resultPlan.jobs.general_tests.selected, overrides.PROFILE_CI || overrides.STACK_JSON ? 27 : 2);
assert.equal(resultPlan.diff.base, base); assert.equal(resultPlan.diff.base, base);
assert.deepEqual(resultPlan.changed, ["ui/src/components/Sidebar.tsx"]); assert.deepEqual(resultPlan.changed, ["ui/src/components/Sidebar.tsx"]);
} }
+1 -1
View File
@@ -562,7 +562,7 @@ jobs:
strategy: strategy:
fail-fast: false fail-fast: false
max-parallel: ${{ needs.gate.outputs.runner == 'ubuntu-latest' && 4 || 256 }} 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/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 (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-b","group_label":"workspaces-b (2/2)","shard_index":1,"shard_count":2,"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/2)","shard_index":0,"shard_count":2,"task":"ci:chat"},{"group":"general-chat","group_label":"chat (2/2)","shard_index":1,"shard_count":2,"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 (1/2)","shard_index":0,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-b","group_label":"workspaces-b (2/2)","shard_index":1,"shard_count":2,"task":"ci:workspaces-b"},{"group":"general-workspaces-c","group_label":"workspaces-c","task":"ci:db"}]}') }}
env: env:
PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }} PAPERCLIP_CI_FULL: ${{ (contains(github.event.pull_request.labels.*.name, 'full-ci') || vars.CI_INCREMENTAL_MODE == 'full') && '1' || '' }}
+2 -1
View File
@@ -691,7 +691,8 @@ Endpoint settings, linked identity, tool profiles, and invocation policy still
apply on each call. The native tool contract rotates older provider sessions so apply on each call. The native tool contract rotates older provider sessions so
an empty retained catalog is not reused. PostgreSQL fixtures cover discovery, an empty retained catalog is not reused. PostgreSQL fixtures cover discovery,
review publication, Slack reads, and revocation in review publication, Slack reads, and revocation in
[channel integration](../../server/src/__tests__/chat-channels.integration.test.ts). [GitHub review workflow](../../server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts)
and [Slack interactions and files](../../server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts).
The [voice gateway fixture](../../server/src/__tests__/voice-session-store.integration.test.ts) The [voice gateway fixture](../../server/src/__tests__/voice-session-store.integration.test.ts)
also verifies durable task binding for a later personal callback invocation. also verifies durable task binding for a later personal callback invocation.
Failure replies cannot replace final answers inherited from an earlier run. Failure replies cannot replace final answers inherited from an earlier run.
+4 -4
View File
@@ -49,9 +49,9 @@ Setup is covered in [connection setup](./connection-setup.md).
### `external-thread` ### `external-thread`
Automated: [channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) uses provider fixtures; it does not prove a live Slack, Discord, Teams, Telegram, GitHub, email, or Photon delivery. Automated: the chat channel integration suites ([Slack](../../server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts), [Discord](../../server/src/__tests__/chat-channels/discord-setup-and-commands.integration.test.ts), [Teams](../../server/src/__tests__/chat-channels/teams-ingress-and-media.integration.test.ts), [Telegram](../../server/src/__tests__/chat-channels/telegram-ingress-and-callbacks.integration.test.ts), [GitHub](../../server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts), and [shared core](../../server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts)) use provider fixtures; they do not prove a live Slack, Discord, Teams, Telegram, GitHub, email, or Photon delivery.
Monitor continuation coverage lives in [channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) Monitor continuation coverage lives in [GitHub review workflow](../../server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts), [Slack interactions and files](../../server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts),
and [external chat wait](../../server/src/services/native-runtime/external-chat-wait.integration.test.ts). In a disposable live thread, request work that needs deferred repository and [external chat wait](../../server/src/services/native-runtime/external-chat-wait.integration.test.ts). In a disposable live thread, request work that needs deferred repository
preparation. Verify a useful continuation explanation, automatic resumption, and preparation. Verify a useful continuation explanation, automatic resumption, and
the final result in that same thread. A successful provider turn alone is insufficient. the final result in that same thread. A successful provider turn alone is insufficient.
@@ -159,7 +159,7 @@ write safety; record hosted destination acceptance separately.
### `endpoint-management` ### `endpoint-management`
Automated: [channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) covers shared endpoint/delivery behavior; live credential repair and provider ownership remain manual checks. Automated: [board and shared core integration](../../server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts) and the provider-scoped suites under `server/src/__tests__/chat-channels/` cover shared endpoint/delivery behavior; live credential repair and provider ownership remain manual checks.
Manual: Inspect the bound agent and identity, recent activity, and delivery failure details. Repair a disposable credential, retry a safe message when offered, and verify exactly one external reply. Disable the endpoint and confirm new traffic is not silently processed. Manual: Inspect the bound agent and identity, recent activity, and delivery failure details. Repair a disposable credential, retry a safe message when offered, and verify exactly one external reply. Disable the endpoint and confirm new traffic is not silently processed.
@@ -250,7 +250,7 @@ Capability ID: `chat-channels/attachments`.
Scope: ui 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. 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. 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: [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), [slack-interactions-and-files.integration.test.ts](../../server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts), [teams-authority-and-transfer.integration.test.ts](../../server/src/__tests__/chat-channels/teams-authority-and-transfer.integration.test.ts), [telegram-media-and-recovery.integration.test.ts](../../server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts), [issue-attachment-routes.test.ts](../../server/src/__tests__/issue-attachment-routes.test.ts)
### Documentation scope: Chat and email channel setup ### Documentation scope: Chat and email channel setup
+1 -1
View File
@@ -214,7 +214,7 @@ 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 [chat adapters E2E](../../tests/e2e/chat-adapters-ui-providers.spec.ts) and manual
checks). Provider-specific live setup is not implied. checks). Provider-specific live setup is not implied.
[Channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) [Telegram draft and progress integration](../../server/src/__tests__/chat-channels/telegram-drafts-and-progress.integration.test.ts)
also covers bounded Telegram subscription recovery at startup and after committed also covers bounded Telegram subscription recovery at startup and after committed
configuration changes, saved retry deadlines, rollback, and parking pending configuration changes, saved retry deadlines, rollback, and parking pending
repair while an endpoint or connection is inactive. The provider responses are repair while an endpoint or connection is inactive. The provider responses are
+5 -4
View File
@@ -104,7 +104,7 @@ stopped-run recovery checks.
### `operator-retry` ### `operator-retry`
The [connected-task regression](../../server/src/__tests__/chat-channels.integration.test.ts) The [connected-task regression](../../server/src/__tests__/chat-channels/github-retry-and-recovery.integration.test.ts)
uses HTTP Retry after an accepted board message fails before provider startup. uses HTTP Retry after an accepted board message fails before provider startup.
It checks the canonical intent, same-user identity and actual queue dispatch, It checks the canonical intent, same-user identity and actual queue dispatch,
then repeats Retry after another contained preparation failure with the same then repeats Retry after another contained preparation failure with the same
@@ -122,9 +122,10 @@ needs containment. Observe a saved wait with no new executor. After verified
containment, the same chat receipt must admit one successor with the original containment, the same chat receipt must admit one successor with the original
source batch. Reload and repeat reconciliation. Check that a paused endpoint, source batch. Reload and repeat reconciliation. Check that a paused endpoint,
changed source, superseded request or revoked access cannot start that work. changed source, superseded request or revoked access cannot start that work.
The connected-chat database regression in The connected-chat database regressions in
[chat channel integration](../../server/src/__tests__/chat-channels.integration.test.ts) [GitHub retry and recovery](../../server/src/__tests__/chat-channels/github-retry-and-recovery.integration.test.ts)
exercises admission and queue continuation. It does not establish hosted and [board and shared core](../../server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts)
exercise admission and queue continuation. They do not establish hosted
provider recovery or successful delivery. provider recovery or successful delivery.
For GitHub, save a follow-up behind a failed run, then reconnect the same App. For GitHub, save a follow-up behind a failed run, then reconnect the same App.
+7 -6
View File
@@ -199,13 +199,14 @@ test("repository skill directory links preserve reuse while target edits invalid
assert.notEqual(snapshot(f.root, f.env).hash, before.hash); assert.notEqual(snapshot(f.root, f.env).hash, before.hash);
}); });
test("local chat selection schedules exactly six single-worker partitions", { timeout: 120_000 }, async t => { test("local chat selection schedules affected split chat suites through general-chat", { timeout: 120_000 }, async t => {
const f = fixture(t); const f = fixture(t);
f.write("ui/src/leaf.ts", "export const value = 1;\n"); f.write("ui/src/leaf.ts", "export const value = 1;\n");
f.write("vitest.config.mjs", 'export default {test:{projects:["server"]}};'); f.write("vitest.config.mjs", 'export default {test:{projects:["server"]}};');
f.write("server/vitest.config.mjs", 'export default {test:{name:"@paperclipai/server",include:["src/**/*.test.ts"]}};'); f.write("server/vitest.config.mjs", 'export default {test:{name:"@paperclipai/server",include:["src/**/*.test.ts"]}};');
f.write("server/src/leaf.ts", "export const value = 1;\n"); f.write("server/src/leaf.ts", "export const value = 1;\n");
f.write("server/src/__tests__/chat-channels.integration.test.ts", 'import {test,expect} from "vitest"; import {value} from "../leaf"; test("chat selection",()=>expect(value).toBeGreaterThan(0));'); f.write("server/src/__tests__/chat-channels/sample.integration.test.ts", 'import {test,expect} from "vitest"; import {value} from "../../leaf"; test("chat selection",()=>expect(value).toBeGreaterThan(0));');
f.write("server/src/__tests__/chat-channels/unrelated.integration.test.ts", 'import {test,expect} from "vitest"; test("unrelated chat",()=>expect(1).toBe(1));');
f.write(".github/ci-task-matrix.json", JSON.stringify({ general_tests: [ f.write(".github/ci-task-matrix.json", JSON.stringify({ general_tests: [
{ task: "ci:server", group: "general-server-without-chat" }, { task: "ci:chat", group: "general-chat" }, { task: "ci:server", group: "general-server-without-chat" }, { task: "ci:chat", group: "general-chat" },
] })); ] }));
@@ -214,10 +215,10 @@ test("local chat selection schedules exactly six single-worker partitions", { ti
f.write("server/src/leaf.ts", "export const value = 2;\n"); f.write("server/src/leaf.ts", "export const value = 2;\n");
const plan = await planVerification({ root: f.root, env: f.env, diff: comparison(f.root, base) }); const plan = await planVerification({ root: f.root, env: f.env, diff: comparison(f.root, base) });
assert.equal(plan.kind, "selected", plan.reason); assert.equal(plan.kind, "selected", plan.reason);
const shards = plan.jobs.flatMap(job => JSON.parse(execFileSync(process.execPath, assert.deepEqual(plan.selectedFiles, ["server/src/__tests__/chat-channels/sample.integration.test.ts"]);
[path.join(f.root, "scripts/run-vitest-stable.mjs"), ...job.args, "--dry-run"], assert.deepEqual(plan.manifest.lanes["general-chat"].shards, [
{ cwd: f.root, env: f.env, encoding: "utf8" })).chatVitestShards); { "@paperclipai/server": ["server/src/__tests__/chat-channels/sample.integration.test.ts"] },
assert.deepEqual(shards, Array.from({ length: 6 }, (_, index) => ({ index, count: 6 }))); ]);
}); });
for (const [group, task, primary, directory] of [ for (const [group, task, primary, directory] of [
@@ -14,7 +14,7 @@ import {
import { assertManifestSource } from "../ci/pr-run-durations.mjs"; import { assertManifestSource } from "../ci/pr-run-durations.mjs";
import { assertSelectedTests, partitionTestLines } from "../test-line-shard.mjs"; import { assertSelectedTests, partitionTestLines } from "../test-line-shard.mjs";
import { chatManifestData, entryDurations } from "../ci/refresh-chat-shard-durations.mjs"; import { chatManifestData } from "../ci/refresh-chat-shard-durations.mjs";
import { defaultServerParallelWorkers } from "../ci/vitest-workers.mjs"; import { defaultServerParallelWorkers } from "../ci/vitest-workers.mjs";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
@@ -285,17 +285,21 @@ test("the checked-in manifest loads and covers most of the current suite set", (
); );
}); });
test("the chat integration suite keeps a measured duration for duration-aware fallbacks", () => { test("the split chat integration suites keep measured durations for duration-aware sharding", () => {
// The PR and release matrices both run the chat suite in dedicated const chat = dryRunJson(["--mode", "general", "--group", "general-chat"]);
// line-sharded lanes, but the plain general-server group (local full runs) assert.ok(chat.selectedChatSuites.length > 1, "expected multiple split chat integration suites");
// still weighs it into the LPT partition; a median-fallback weight there const generalDurations = loadShardDurations(durationsManifest);
// would silently overload whichever shard receives it. const chatDurations = loadShardDurations(path.join(repoRoot, "scripts", "chat-shard-durations.json"));
const chatSuite = "server/src/__tests__/chat-channels.integration.test.ts"; for (const suite of chat.selectedChatSuites) {
const durations = loadShardDurations(durationsManifest); assert.ok(
assert.ok( Number.isFinite(chatDurations[suite]),
Number.isFinite(durations[chatSuite]), `missing chat-shard-durations entry for ${suite}`,
"the full chat cohort must have a measured duration, not the median fallback", );
); assert.ok(
Number.isFinite(generalDurations[suite]),
`missing general-server-shard-durations entry for ${suite}`,
);
}
}); });
test("the checked-in serialized manifest loads and covers most of the current suite set", () => { test("the checked-in serialized manifest loads and covers most of the current suite set", () => {
@@ -336,7 +340,8 @@ test("the real serialized shard partition is complete, non-overlapping and durat
); );
}); });
const chatSuitePath = "server/src/__tests__/chat-channels.integration.test.ts"; const allChatSuites = dryRunJson(["--mode", "general", "--group", "general-chat"]).selectedChatSuites;
const chatSuiteSet = new Set(allChatSuites);
const nativeRunnerSuitePath = const nativeRunnerSuitePath =
"server/src/services/native-runtime/native-codex-runner.integration.test.ts"; "server/src/services/native-runtime/native-codex-runner.integration.test.ts";
const ingressRetrySuitePath = "server/src/services/native-runtime/native-ingress-bootstrap-retry.integration.test.ts"; const ingressRetrySuitePath = "server/src/services/native-runtime/native-ingress-bootstrap-retry.integration.test.ts";
@@ -374,12 +379,11 @@ test("12 PR without-chat shards plus the dedicated chat and native-runner lanes
// LPT keeps the spread within the heaviest single suite; use that as the // LPT keeps the spread within the heaviest single suite; use that as the
// bound. The chat and native-runner suites run in their own lanes, so // bound. The chat and native-runner suites run in their own lanes, so
// exclude them here. // exclude them here.
const chat = "server/src/__tests__/chat-channels.integration.test.ts";
const nativeRunner = const nativeRunner =
"server/src/services/native-runtime/native-codex-runner.integration.test.ts"; "server/src/services/native-runtime/native-codex-runner.integration.test.ts";
const heaviest = Math.max( const heaviest = Math.max(
...Object.entries(durations) ...Object.entries(durations)
.filter(([file]) => file !== chat && file !== nativeRunner) .filter(([file]) => !chatSuiteSet.has(file) && file !== nativeRunner)
.map(([, ms]) => ms), .map(([, ms]) => ms),
); );
assert.ok( assert.ok(
@@ -388,7 +392,9 @@ test("12 PR without-chat shards plus the dedicated chat and native-runner lanes
); );
const files = shards.flatMap((shard) => shard.selectedGeneralServerSuites); const files = shards.flatMap((shard) => shard.selectedGeneralServerSuites);
assert.ok(!files.includes(chatSuitePath)); for (const chatFile of allChatSuites) {
assert.ok(!files.includes(chatFile), `chat suite must stay in general-chat: ${chatFile}`);
}
assert.ok(!files.includes(nativeRunnerSuitePath)); assert.ok(!files.includes(nativeRunnerSuitePath));
assert.ok(!files.includes(ingressRetrySuitePath)); assert.ok(!files.includes(ingressRetrySuitePath));
assert.ok(!files.includes(dotRunnerSuitePath)); assert.ok(!files.includes(dotRunnerSuitePath));
@@ -404,7 +410,7 @@ test("12 PR without-chat shards plus the dedicated chat and native-runner lanes
for (const shard of shards) { for (const shard of shards) {
assert.deepEqual(shard.excludedNightlySuites ?? [], excludedNightly, "nightly exclusions must agree across 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.deepEqual([...files, ...excludedNightly, ...allChatSuites, 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); assert.equal(new Set(files).size, files.length);
const defaultRun = dryRunJson([], prEnv); const defaultRun = dryRunJson([], prEnv);
assert.ok(defaultRun.generalServerSuiteCount === full.generalServerSuiteCount); assert.ok(defaultRun.generalServerSuiteCount === full.generalServerSuiteCount);
@@ -420,7 +426,9 @@ for (const [caller, envOverrides] of [["Release", { GITHUB_WORKFLOW: "Release" }
"--shard-index", String(index), "--shard-count", "10", "--shard-index", String(index), "--shard-count", "10",
], envOverrides)); ], envOverrides));
const files = shards.flatMap((shard) => shard.selectedGeneralServerSuites); const files = shards.flatMap((shard) => shard.selectedGeneralServerSuites);
assert.ok(!files.includes(chatSuitePath)); for (const chatFile of allChatSuites) {
assert.ok(!files.includes(chatFile));
}
assert.ok(files.includes(nativeRunnerSuitePath)); assert.ok(files.includes(nativeRunnerSuitePath));
assert.ok(files.includes(dotRunnerSuitePath)); assert.ok(files.includes(dotRunnerSuitePath));
assert.ok(files.includes(restartRecoverySuitePath)); assert.ok(files.includes(restartRecoverySuitePath));
@@ -429,7 +437,7 @@ for (const [caller, envOverrides] of [["Release", { GITHUB_WORKFLOW: "Release" }
assert.ok(files.includes(pluginWarmOwnerSuitePath)); assert.ok(files.includes(pluginWarmOwnerSuitePath));
assert.ok(files.includes(pluginReleaseResumeSuitePath)); assert.ok(files.includes(pluginReleaseResumeSuitePath));
assert.ok(files.includes(pluginEvictionSuitePath)); assert.ok(files.includes(pluginEvictionSuitePath));
assert.deepEqual([...files, chatSuitePath].sort(), full.selectedGeneralServerSuites.sort()); assert.deepEqual([...files, ...allChatSuites].sort(), full.selectedGeneralServerSuites.sort());
assert.equal(new Set(files).size, files.length); assert.equal(new Set(files).size, files.length);
}); });
} }
@@ -445,7 +453,7 @@ for (const caller of ["Release", "Cloud readiness", "another caller"]) {
"--shard-index", String(index), "--shard-count", "10", "--shard-index", String(index), "--shard-count", "10",
], env)).flatMap((shard) => shard.selectedGeneralServerSuites); ], env)).flatMap((shard) => shard.selectedGeneralServerSuites);
const native = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], env); const native = dryRunJson(["--mode", "general", "--group", "general-server-native-runner"], env);
const combined = [...files, chatSuitePath, ...native.selectedGeneralServerSuites]; const combined = [...files, ...allChatSuites, ...native.selectedGeneralServerSuites];
assert.equal(new Set(combined).size, combined.length, "lanes must not overlap"); assert.equal(new Set(combined).size, combined.length, "lanes must not overlap");
assert.deepEqual(combined.sort(), full.selectedGeneralServerSuites.sort()); assert.deepEqual(combined.sort(), full.selectedGeneralServerSuites.sort());
}); });
@@ -649,32 +657,34 @@ test("recorded durations balance chat line shards by time without splitting a so
assert.deepEqual(partitionTestLines(cases, 2, lineShardFile).map((shard) => shard.tests.length), [4, 3]); assert.deepEqual(partitionTestLines(cases, 2, lineShardFile).map((shard) => shard.tests.length), [4, 3]);
}); });
test("chat durations attribute every executed case to the collected entry that registers it", () => { test("chat durations compute per-file medians across profile runs", () => {
const entries = ["sends %s", "suite > sends %s twice", "plain", "keyed $provider ($mode)"]; const inventory = [
const { totals, unmatched } = entryDurations(entries, [ "server/src/__tests__/chat-channels/a.integration.test.ts",
{ name: "chat channel control-plane integration > sends a", duration: 5 }, "server/src/__tests__/chat-channels/b.integration.test.ts",
{ name: "chat channel control-plane integration > suite > sends b twice", duration: 7 }, ];
{ name: "chat channel control-plane integration > plain", duration: 11 }, const data = chatManifestData(
{ name: "chat channel control-plane integration > keyed slack (fast)", duration: 13 }, inventory,
{ name: "chat channel control-plane integration > keyed github (slow)", duration: 17 }, [
{ name: "chat channel control-plane integration > unknown", duration: 19 }, new Map([[inventory[0], 4000]]),
]); new Map([[inventory[0], 9000], ["server/src/__tests__/unrelated.test.ts", 100]]),
assert.deepEqual(Object.fromEntries(totals), { "sends %s": 5, "suite > sends %s twice": 7, plain: 11, "keyed $provider ($mode)": 30 }); new Map([[inventory[0], 6000]]),
assert.deepEqual(unmatched, ["chat channel control-plane integration > unknown"]); ],
const data = chatManifestData(["plain", "other"], [[{ name: "x > plain", duration: 4 }], [{ name: "x > plain", duration: 9 }], ["run-1"],
[{ name: "x > plain", duration: 6 }]], []); );
assert.deepEqual(data.durations, { plain: 6 }); assert.deepEqual(data.durations, { [inventory[0]]: 6000 });
assert.deepEqual(data.coverage, { measured: 1, entries: 2 }); assert.deepEqual(data.coverage, { measured: 1, inventory: 2 });
assert.throws(() => chatManifestData(["plain"], [[{ name: "x > missing", duration: 1 }]], []));
}); });
test("the checked-in chat duration manifest is well formed", () => { test("the checked-in chat duration manifest is well formed and covers all chat suites", () => {
const manifest = JSON.parse(readFileSync(path.join(repoRoot, "scripts", "chat-shard-durations.json"), "utf8")); const manifest = JSON.parse(readFileSync(path.join(repoRoot, "scripts", "chat-shard-durations.json"), "utf8"));
assert.equal(manifest.unit, "ms"); assert.equal(manifest.unit, "ms");
const entries = Object.entries(manifest.durations); const entries = Object.entries(manifest.durations);
assert.ok(entries.length > 0); assert.ok(entries.length > 0);
assert.ok(entries.every(([name, ms]) => name.length > 0 && Number.isSafeInteger(ms) && ms > 0)); assert.ok(entries.every(([name, ms]) => name.length > 0 && Number.isSafeInteger(ms) && ms > 0));
assert.deepEqual(loadShardDurations(path.join(repoRoot, "scripts", "chat-shard-durations.json")), manifest.durations); assert.deepEqual(loadShardDurations(path.join(repoRoot, "scripts", "chat-shard-durations.json")), manifest.durations);
for (const suite of allChatSuites) {
assert.ok(manifest.durations[suite] > 0, `chat manifest missing ${suite}`);
}
}); });
test("line-shard collection rejects empty, foreign, or unlocated tests and invalid shard counts", () => { test("line-shard collection rejects empty, foreign, or unlocated tests and invalid shard counts", () => {
@@ -696,41 +706,43 @@ test("filtered collection must match the exact assigned case identities, includi
} }
}); });
test("chat file shards form a complete, non-overlapping, duration-balanced partition", () => {
test("parallel chat jobs form a complete disjoint partition", () => { const durations = loadShardDurations(path.join(repoRoot, "scripts", "chat-shard-durations.json"));
for (const count of [2, 3, 4]) { const heaviest = Math.max(...Object.values(durations));
for (const count of [2, 3, 5]) {
const shards = Array.from({ length: count }, (_, index) => const shards = Array.from({ length: count }, (_, index) =>
dryRunJson(["--mode", "general", "--group", "general-chat", "--shard-index", String(index), "--shard-count", String(count)], dryRunJson(["--mode", "general", "--group", "general-chat", "--shard-index", String(index), "--shard-count", String(count)],
{ PAPERCLIP_TEST_DATABASE_URL: "" }).chatVitestShards, { PAPERCLIP_TEST_DATABASE_URL: "" }),
); );
assert.ok(shards.every((workers) => workers.length === 3)); const assigned = shards.flatMap((shard) => shard.selectedChatSuites);
assert.deepEqual(shards.flat().map(({ index }) => index).sort((a, b) => a - b), assert.equal(new Set(assigned).size, assigned.length, `chat shards (${count}) must not overlap`);
Array.from({ length: count * 3 }, (_, index) => index)); assert.deepEqual([...assigned].sort(), [...allChatSuites].sort(), `chat shards (${count}) must cover all chat suites`);
assert.ok(shards.flat().every((shard) => shard.count === count * 3)); const totals = shards.map((shard) => shard.selectedChatSuites.reduce((sum, file) => sum + (durations[file] ?? 0), 0));
assert.ok(Math.max(...totals) - Math.min(...totals) <= heaviest, `chat shard spread exceeded heaviest suite for count=${count}`);
} }
assert.deepEqual(
dryRunJson(["--mode", "general", "--group", "general-chat"], { PAPERCLIP_TEST_DATABASE_URL: "" }).selectedChatSuites,
allChatSuites,
);
const trailing = dryRunJson(
["--mode", "general", "--group", "general-chat", "--shard-index", String(allChatSuites.length), "--shard-count", String(allChatSuites.length + 2)],
{ PAPERCLIP_TEST_DATABASE_URL: "" },
);
assert.deepEqual(trailing.selectedChatSuites, []);
}); });
test("shared-database and unsharded chat runs retain one serial partition", () => { test("default ungrouped runs isolate chat suites in parallel before general-server without dropping native suites", () => {
for (let index = 0; index < 3; index++) {
const result = dryRunJson(["--mode", "general", "--group", "general-chat", "--shard-index", String(index), "--shard-count", "3"],
{ PAPERCLIP_TEST_DATABASE_URL: "postgresql://shared/test" });
assert.deepEqual(result.chatVitestShards, [{ index, count: 3 }]);
}
assert.deepEqual(dryRunJson(["--mode", "general", "--group", "general-chat"],
{ PAPERCLIP_TEST_DATABASE_URL: "" }).chatVitestShards, [{ index: 0, count: 1 }]);
});
test("default chat isolation covers six partitions without dropping native suites", () => {
for (const args of [[], ["--mode", "general"]]) { for (const args of [[], ["--mode", "general"]]) {
for (const workflow of ["PR", "Release", ""]) { for (const workflow of ["PR", "Release", ""]) {
const env = { GITHUB_WORKFLOW: workflow, PAPERCLIP_TEST_DATABASE_URL: "" }; const env = { GITHUB_WORKFLOW: workflow, PAPERCLIP_TEST_DATABASE_URL: "" };
const plan = dryRunJson(args, env); const plan = dryRunJson(args, env);
const full = dryRunJson(["--mode", "general", "--group", "general-server", const full = dryRunJson(["--mode", "general", "--group", "general-server",
"--shard-index", "0", "--shard-count", "1"], env); "--shard-index", "0", "--shard-count", "1"], env);
assert.deepEqual(plan.chatVitestShards, Array.from({ length: 6 }, (_, index) => ({ index, count: 6 }))); assert.deepEqual(plan.selectedChatSuites, allChatSuites);
assert.ok(!plan.selectedGeneralServerSuites.includes(chatSuitePath)); for (const chatFile of allChatSuites) {
assert.equal(new Set(plan.selectedGeneralServerSuites).size, plan.selectedGeneralServerSuites.length); assert.ok(!plan.selectedGeneralServerSuites.includes(chatFile));
assert.deepEqual([...plan.selectedGeneralServerSuites, chatSuitePath].sort(), full.selectedGeneralServerSuites.sort()); }
assert.deepEqual([...plan.selectedGeneralServerSuites, ...allChatSuites].sort(), full.selectedGeneralServerSuites.sort());
} }
} }
}); });
@@ -738,164 +750,23 @@ test("default chat isolation covers six partitions without dropping native suite
test("default chat isolation leaves explicit groups and shared databases unchanged", () => { test("default chat isolation leaves explicit groups and shared databases unchanged", () => {
for (const args of [[], ["--mode", "general"]]) { for (const args of [[], ["--mode", "general"]]) {
const shared = dryRunJson(args, { PAPERCLIP_TEST_DATABASE_URL: "postgresql://shared/test", GITHUB_WORKFLOW: "PR" }); const shared = dryRunJson(args, { PAPERCLIP_TEST_DATABASE_URL: "postgresql://shared/test", GITHUB_WORKFLOW: "PR" });
assert.equal(shared.chatVitestShards, null); assert.equal(shared.selectedChatSuites, null);
assert.equal(shared.selectedGeneralServerSuites, null); assert.equal(shared.selectedGeneralServerSuites, null);
} }
const full = dryRunJson(["--mode", "general", "--group", "general-server", const full = dryRunJson(["--mode", "general", "--group", "general-server",
"--shard-index", "0", "--shard-count", "1"], { PAPERCLIP_TEST_DATABASE_URL: "", GITHUB_WORKFLOW: "PR" }); "--shard-index", "0", "--shard-count", "1"], { PAPERCLIP_TEST_DATABASE_URL: "", GITHUB_WORKFLOW: "PR" });
assert.equal(full.chatVitestShards, null); assert.equal(full.selectedChatSuites, null);
assert.ok(full.selectedGeneralServerSuites.includes(chatSuitePath)); for (const chatFile of allChatSuites) {
assert.ok(full.selectedGeneralServerSuites.includes(chatFile));
}
assert.ok(full.selectedGeneralServerSuites.includes(nativeRunnerSuitePath)); assert.ok(full.selectedGeneralServerSuites.includes(nativeRunnerSuitePath));
assert.deepEqual(dryRunJson(["--mode", "general", "--group", "general-chat"], assert.equal(dryRunJson(["--mode", "serialized"], { PAPERCLIP_TEST_DATABASE_URL: "" }).selectedChatSuites, null);
{ PAPERCLIP_TEST_DATABASE_URL: "" }).chatVitestShards, [{ index: 0, count: 1 }]);
assert.equal(dryRunJson(["--mode", "serialized"], { PAPERCLIP_TEST_DATABASE_URL: "" }).chatVitestShards, null);
});
function defaultLauncher({ shared = false, failureIndex = null } = {}) {
const directory = mkdtempSync(path.join(os.tmpdir(), "default-chat-launch-"));
const file = path.join(repoRoot, chatSuitePath);
const lines = readFileSync(file, "utf8").split("\n")
.flatMap((line, index) => /^\s*it\(/.test(line) ? [index + 1] : []).slice(0, 6);
assert.equal(lines.length, 6);
const cases = lines.map(line => ({ file, projectName: "@paperclipai/server",
name: `default launcher fixture ${line}`, location: { line } }));
const receipt = path.join(directory, "events.ndjson");
const active = path.join(directory, "active");
const fakePnpm = path.join(directory, "pnpm");
try {
writeFileSync(fakePnpm, `#!${process.execPath}
const fs = require('node:fs');
const args = process.argv.slice(2);
const tests = ${JSON.stringify(cases)};
const selected = args.flatMap(arg => {
const match = arg.match(/chat-channels\\.integration\\.test\\.ts:(\\d+)$/);
return match ? [Number(match[1])] : [];
});
if (args.includes('list')) {
const output = args.find(arg => arg.startsWith('--json=')).slice(7);
fs.writeFileSync(output, JSON.stringify(selected.length
? tests.filter(test => selected.includes(test.location.line)) : tests));
} else {
const entry = { args, selected, home: process.env.PAPERCLIP_HOME,
config: process.env.PAPERCLIP_CONFIG, instance: process.env.PAPERCLIP_INSTANCE_ID,
tmpdir: process.env.TMPDIR };
const record = edge => fs.appendFileSync(${JSON.stringify(receipt)}, JSON.stringify({ ...entry, edge }) + '\\n');
record('begin');
if (fs.existsSync(${JSON.stringify(active)})) process.exit(91);
fs.writeFileSync(${JSON.stringify(active)}, 'running');
setTimeout(() => {
record('end');
fs.unlinkSync(${JSON.stringify(active)});
process.exit(selected.includes(${JSON.stringify(failureIndex === null ? null : lines[failureIndex])}) ? 7 : 0);
}, selected.length ? 200 : 0);
}
`);
chmodSync(fakePnpm, 0o755);
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_POSTGRES_SHARED: "0" }),
});
const events = existsSync(receipt) ? readFileSync(receipt, "utf8").trim().split("\n").map(line => JSON.parse(line)) : [];
return { result, events, lines };
} finally {
rmSync(directory, { recursive: true, force: true });
}
}
test("default chat isolation executes every partition sequentially before other groups", { skip: process.platform === "win32" }, () => {
const { result, events, lines } = defaultLauncher();
assert.equal(result.status, 0, result.stdout + result.stderr);
const chat = events.filter(event => event.selected.length > 0);
assert.deepEqual(chat.map(event => event.edge), Array.from({ length: 6 }, () => ["begin", "end"]).flat());
const starts = chat.filter(event => event.edge === "begin");
assert.deepEqual(starts.flatMap(event => event.selected).sort((a, b) => a - b), lines);
for (const event of starts) {
assert.ok(event.args.includes("--no-file-parallelism"));
assert.deepEqual(event.args.filter(arg => arg.startsWith("--maxWorkers")), ["--maxWorkers=1"]);
}
for (const field of ["home", "config", "instance", "tmpdir"]) {
assert.equal(new Set(starts.map(event => event[field])).size, 6, `${field} must be isolated per child`);
}
assert.equal(events.findIndex(event => event.selected.length === 0), 12);
const server = events[12];
assert.ok(server.args.includes("@paperclipai/server"));
const excluded = server.args.flatMap((arg, index) => arg === "--exclude" ? [server.args[index + 1]] : []);
assert.equal(excluded.filter(file => file === chatSuitePath.replace(/^server\//, "")).length, 1);
for (const file of [nativeRunnerSuitePath, ingressRetrySuitePath, usageDeliverySuitePath, dotRunnerSuitePath, restartRecoverySuitePath,
"server/src/services/native-runtime/plugin-runner-probe.test.ts"]) {
assert.ok(!excluded.includes(file.replace(/^server\//, "")), `default must retain ${file}`);
}
});
test("default chat isolation propagates failure without starting another partition or group", { skip: process.platform === "win32" }, () => {
const { result, events } = defaultLauncher({ failureIndex: 2 });
assert.equal(result.status, 1, result.stdout + result.stderr);
assert.match(result.stderr, /failed \(7\)/);
assert.equal(events.length, 6);
assert.ok(events.every(event => event.selected.length === 1));
assert.deepEqual(events.map(event => event.edge), ["begin", "end", "begin", "end", "begin", "end"]);
});
test("default chat isolation keeps shared-database execution monolithic and serial", { skip: process.platform === "win32" }, () => {
const { result, events } = defaultLauncher({ shared: true });
assert.equal(result.status, 0, result.stdout + result.stderr);
assert.ok(events.every(event => event.selected.length === 0));
assert.ok(events[0].args.includes("@paperclipai/server"));
assert.ok(events[0].args.includes("--no-file-parallelism"));
assert.deepEqual(events[0].args.filter(arg => arg.startsWith("--maxWorkers")), ["--maxWorkers=1"]);
const excluded = events[0].args.flatMap((arg, index) => arg === "--exclude" ? [events[0].args[index + 1]] : []);
assert.ok(!excluded.includes(chatSuitePath.replace(/^server\//, "")));
assert.ok(!excluded.includes(nativeRunnerSuitePath.replace(/^server\//, "")));
assert.deepEqual(events.map(event => event.edge), Array.from({ length: events.length / 2 }, () => ["begin", "end"]).flat());
});
test("a failed chat child fails the job after its sibling finishes", { skip: process.platform === "win32" }, () => {
const directory = mkdtempSync(path.join(os.tmpdir(), "chat-launch-proof-"));
const file = path.join(repoRoot, "server/src/__tests__/chat-channels.integration.test.ts");
const lines = readFileSync(file, "utf8").split("\n")
.flatMap((line, index) => /^\s*it\(/.test(line) ? [index + 1] : []).slice(0, 9);
assert.equal(lines.length, 9);
const tests = lines.map((line) => ({ file, projectName: "@paperclipai/server",
name: `launcher fixture ${line}`, location: { line } }));
const receipt = path.join(directory, "sibling-finished");
const fakePnpm = path.join(directory, "pnpm");
try {
writeFileSync(fakePnpm, `#!${process.execPath}
const fs = require('node:fs');
const args = process.argv.slice(2);
const tests = ${JSON.stringify(tests)};
const selected = args.flatMap(arg => {
const match = arg.match(/chat-channels\\.integration\\.test\\.ts:(\\d+)$/);
return match ? [Number(match[1])] : [];
});
if (args.includes('list')) {
const output = args.find(arg => arg.startsWith('--json=')).slice(7);
fs.writeFileSync(output, JSON.stringify(selected.length
? tests.filter(test => selected.includes(test.location.line)) : tests));
} else if (selected.includes(${lines[0]})) process.exit(7);
else setTimeout(() => fs.writeFileSync(${JSON.stringify(receipt)}, 'finished'), 200);
`);
chmodSync(fakePnpm, 0o755);
const result = spawnSync(process.execPath, [script, "--mode", "general", "--group", "general-chat",
"--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_POSTGRES_SHARED: "0" },
});
assert.equal(result.status, 1, result.stdout + result.stderr);
assert.match(result.stderr, /failed \(7\)/);
assert.equal(readFileSync(receipt, "utf8"), "finished", "a failed worker must not abandon its sibling");
} finally {
rmSync(directory, { recursive: true, force: true });
}
}); });
for (const [label, modeArgs, lane] of [ for (const [label, modeArgs, lane] of [
["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], "general"], ["general-server-native-runner", ["--mode", "general", "--group", "general-server-native-runner"], "general"],
["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], "general"], ["general-server-without-chat-or-native-runner", ["--mode", "general", "--group", "general-server-without-chat-or-native-runner", "--shard-index", "0", "--shard-count", "12"], "general"],
["general-chat", ["--mode", "general", "--group", "general-chat", "--shard-index", "0", "--shard-count", "2"], "general"],
["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], "serialized"], ["serialized", ["--mode", "serialized", "--shard-index", "4", "--shard-count", "9"], "serialized"],
]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => { ]) test(`${label} files overlap only when their database fixtures are isolated`, { skip: process.platform === "win32" }, () => {
const parallelWorkers = defaultServerParallelWorkers(lane); const parallelWorkers = defaultServerParallelWorkers(lane);
+20 -939
View File
@@ -1,948 +1,29 @@
{ {
"$comment": "Generated by node scripts/ci/refresh-chat-shard-durations.mjs from the CI profile test records of the PR chat jobs (profile-ci label). Per collected test entry, keyed by the name that vitest list reports: the summed duration of every case that entry runs, so an it.each line carries all its cases. Median across the given runs. scripts/test-line-shard.mjs uses these weights only to place source lines on chat partitions; they never change which tests run. Missing entries take the median weight.", "$comment": "Per-file Vitest durations (ms) for server/src/__tests__/chat-channels/*.integration.test.ts used by scripts/run-vitest-stable.mjs (--group general-chat) to balance file-level shards via LPT. Missing files take the partitioner's median weight. Timing changes only partition work; they never skip a test.",
"unit": "ms", "unit": "ms",
"sources": [ "sources": [
"https://github.com/paperclipai/paperclip/actions/runs/45324415100" "local-shared-pg-benchmark:refactor/split-optimize-chat-channel-tests@b9618367ff"
], ],
"coverage": { "coverage": {
"measured": 935, "measured": 16,
"entries": 937 "inventory": 16
}, },
"durations": { "durations": {
"$label": 2223, "server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts": 45011,
"accepts a manually created GitHub App when /app lists only selectable webhook events": 330, "server/src/__tests__/chat-channels/discord-modals-and-publications.integration.test.ts": 6507,
"accepts only signed GitHub setup pings before App credentials exist": 125, "server/src/__tests__/chat-channels/discord-setup-and-commands.integration.test.ts": 54809,
"accepts the Slack invitation mention exactly once (%s)": 755, "server/src/__tests__/chat-channels/github-retry-and-recovery.integration.test.ts": 41634,
"acknowledges a denied Slack action before its durable notice completes and deduplicates redelivery": 615, "server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts": 171270,
"acknowledges a provider question when the board resolves after callback validation": 650, "server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts": 20202,
"acknowledges a signed URL mention through the real Slack SDK without waiting for an unfurl": 309, "server/src/__tests__/chat-channels/github-webhook-recovery.integration.test.ts": 20859,
"acknowledges a Slack mention while %s is blocked": 1124, "server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts": 9836,
"acknowledges a Slack retry while one durable worker owns the unrecorded command root": 350, "server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts": 28768,
"acknowledges denied Telegram actions after one durable, payload-free notice": 181, "server/src/__tests__/chat-channels/slack-protocol.integration.test.ts": 8705,
"acknowledges durable Slack ingress promptly and never replays paused traffic on resume": 898, "server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts": 42468,
"acknowledges GitHub lifecycle callbacks without changing a paused endpoint": 287, "server/src/__tests__/chat-channels/teams-authority-and-transfer.integration.test.ts": 12088,
"acknowledges Telegram control $command without a processing receipt (bound=$bound denied=$denied)": 1819, "server/src/__tests__/chat-channels/teams-ingress-and-media.integration.test.ts": 15672,
"acknowledges Telegram edits while verifying and when processing is suspended": 259, "server/src/__tests__/chat-channels/telegram-drafts-and-progress.integration.test.ts": 30015,
"activates Slack only after provider verification and a real test message": 550, "server/src/__tests__/chat-channels/telegram-ingress-and-callbacks.integration.test.ts": 10615,
"admits a separate connected-conversation Retry only after committed original-controller containment: %s": 7148, "server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts": 9966
"admits concurrent and retried Slack slash commands only once": 435,
"admits current GitHub task Retry without replaying obsolete input: %s": 4150,
"admits only an addressed raw GitHub comment as the first setup repository": 484,
"admits ordinary chat task Retry with a missing checkpoint only after containment: %s": 2025,
"admits the exact chat source for ordinary %s failure": 1205,
"advances failed retry notices past denied history with microsecond timestamps (%s)": 1387,
"advances native progress past suppressed candidates with microsecond timestamps": 712,
"advances pre-run FIFO selection past a suppressed page with microsecond timestamps (%s)": 2143,
"allows a new exact failed chat retry after an ordinary retry fails, without rearming its ancestors": 401,
"allows only one concurrent live endpoint to claim a Discord bot across guilds": 158,
"allows Slack thread replies without mentions while exempting DMs (DM=%s)": 1499,
"applies Teams installation and Telegram membership resource lifecycle": 689,
"applies the direct-message toggle to Slack slash commands": 211,
"applies the Slack Board resume once during %s dispatch": 1137,
"applies the Teams direct-message reach toggle and starts a new generation after task completion": 414,
"atomically admits only one first GitHub repository under concurrent root mentions": 407,
"atomically rejects a Slack DM when reach is revoked after initial admission": 240,
"atomically rejects a sponsored Telegram guest after the sponsor is suspended": 192,
"atomically rejects a Telegram DM when reach is revoked at the final task-mutation boundary": 155,
"atomically rejects Slack task mutation after a linked identity is revoked or loses write membership": 497,
"atomically rejects Teams messages when DM, group, or channel reach is revoked at the task-mutation boundary": 590,
"audits Microsoft Teams reactions idempotently without treating them as task instructions": 475,
"audits reactions on linked messages without treating them as task instructions": 500,
"audits repeated Discord reaction cycles while deduplicating an exact Gateway replay": 569,
"audits Telegram reactions on completed DM generations idempotently without comments or runs": 660,
"authorizes protected channel workspace defaults for the endpoint's assigned agent": 414,
"automatic Slack registration > acknowledges verification before sending one DM across concurrent callbacks and restart recovery": 529,
"automatic Slack registration > adds events only after saving signing credentials and answers Slack's update-time challenge before OAuth": 625,
"automatic Slack registration > claims callbacks once, keeps denied installation resumable, and does not replay ambiguous exchange": 604,
"automatic Slack registration > creates once under concurrent submissions and resumes after restart without exposing credentials": 192,
"automatic Slack registration > does not advance avatar state after management access is revoked during upload": 139,
"automatic Slack registration > does not bind runtime credentials when management access is revoked during provider checks": 259,
"automatic Slack registration > does not complete setup from %s event evidence": 5369,
"automatic Slack registration > does not link or welcome an installer after company membership is revoked during lookup": 395,
"automatic Slack registration > does not repeat uncertain creation until the operator explicitly confirms no app exists": 175,
"automatic Slack registration > does not replay a verification DM after %s": 1116,
"automatic Slack registration > does not replay a welcome dispatch interrupted by restart": 390,
"automatic Slack registration > does not send a pending verification DM after %s": 2234,
"automatic Slack registration > does not send a pending welcome to a subsequently revoked account link": 546,
"automatic Slack registration > does not verify or notify for a %s challenge": 1760,
"automatic Slack registration > keeps installation usable after %s without leaking provider echoes or creating another app": 1154,
"automatic Slack registration > keeps setup connected after %s and never retries an optional DM": 1206,
"automatic Slack registration > keeps the saved app installable after local avatar rendering fails": 147,
"automatic Slack registration > links the OAuth installer, sends one welcome DM, and still requires signed URL verification": 874,
"automatic Slack registration > managed Slack > atomically consumes manager state and rejects wrong actors and expired attempts": 138,
"automatic Slack registration > managed Slack > claims concurrent manager callbacks once": 234,
"automatic Slack registration > managed Slack > clears a manager reconnect error after renewing the bound grant": 898,
"automatic Slack registration > managed Slack > creates and installs once, uploads the avatar and links only the manager grant owner": 1039,
"automatic Slack registration > managed Slack > does not accept another company's grant or keep authorizations after removal": 167,
"automatic Slack registration > managed Slack > does not activate a bot when the manager grant is revoked during child OAuth": 515,
"automatic Slack registration > managed Slack > does not restore a revoked grant when an in-flight refresh returns": 143,
"automatic Slack registration > managed Slack > installs a second bot using the same grant without new manager consent": 1150,
"automatic Slack registration > managed Slack > keeps configured Cloud drafts managed when the broker profile disappears": 131,
"automatic Slack registration > managed Slack > keeps open-source setup independent of the broker": 152,
"automatic Slack registration > managed Slack > never recreates an uncertain app": 268,
"automatic Slack registration > managed Slack > preserves configured-app reconnect intent when managed installation fails": 961,
"automatic Slack registration > managed Slack > preserves declined manager authorization as a safe recoverable outcome": 209,
"automatic Slack registration > managed Slack > preserves provider rate-limit backoff across subsequent attempts": 535,
"automatic Slack registration > managed Slack > reconnects a rejected manager token without losing pending manifest configuration": 813,
"automatic Slack registration > managed Slack > reinstalls the configured app on an explicit %s reconnect": 2529,
"automatic Slack registration > managed Slack > reinstalls the saved app after missing bot scopes without creating another app": 660,
"automatic Slack registration > managed Slack > rejects a bot token belonging to a different Slack app before activation": 351,
"automatic Slack registration > managed Slack > rejects manager identity changes and both callback-origin and ingress-origin drift": 184,
"automatic Slack registration > managed Slack > rejects missing tool scopes before activating a managed bot": 534,
"automatic Slack registration > managed Slack > rejects missing, malformed, foreign and other-user manager grants before provisioning": 252,
"automatic Slack registration > managed Slack > resumes saved installation credentials after inventory failure without creating or reinstalling": 784,
"automatic Slack registration > managed Slack > retains reinstall intent after a provider failure instead of retrying rejected credentials": 787,
"automatic Slack registration > managed Slack > reuses the same personal workspace grant for another draft without another authorization": 117,
"automatic Slack registration > managed Slack > revocation invalidates pending authorization and prevents future provisioning": 188,
"automatic Slack registration > managed Slack > routes the broker claim_id callback back to the saved wizard without exposing the handoff": 217,
"automatic Slack registration > managed Slack > serializes refreshes across endpoints and never replays an ambiguous refresh": 201,
"automatic Slack registration > managed Slack > uses bound OAuth for approval fallback and rejects a different installer": 475,
"automatic Slack registration > managed Slack > uses the held transaction for grant queries without acquiring another pool connection": 183,
"automatic Slack registration > maps invalid token and validation echoes without persisting or exposing the supplied token": 339,
"automatic Slack registration > preserves a saved app when its creation activity fails without exposing the failure": 96,
"automatic Slack registration > preserves an existing %s account link without a welcome DM": 563,
"automatic Slack registration > recovers %s on the same saved app after restart without exposing provider echoes": 3277,
"automatic Slack registration > reinstalls a revoked bot using the same app and preserves the linked account": 767,
"automatic Slack registration > rejects a missing or invalid OAuth installer (%s)": 291,
"automatic Slack registration > rejects an authorization started before the bot was revoked": 734,
"automatic Slack registration > rejects an installer lookup %s mismatch without linking": 1503,
"automatic Slack registration > rejects an OAuth %s mismatch without binding runtime credentials": 826,
"automatic Slack registration > rejects changing an established %s during reauthorization": 766,
"automatic Slack registration > rejects expiry, wrong actor/session/company, permission revocation, and origin drift before exchange": 187,
"automatic Slack registration > removes registration secrets and prevents late callbacks after %s removal": 322,
"automatic Slack registration > respects disabled direct messages when provisioning the welcome": 296,
"automatic Slack registration > resumes an interrupted avatar upload without repeating creation or requesting another token": 165,
"automatic Slack registration > retains the token and installer after lookup failure and resumes without exchanging a code": 493,
"automatic Slack registration > returns expired authorization to the saved wizard without exchanging its code": 185,
"automatic Slack registration > reuses the saved installer and sends no further DM on reauthorization or restart": 785,
"automatic Slack registration > saves advanced app details with the initial draft and rejects them for other providers": 85,
"automatic Slack registration > shows interrupted creation as uncertain after restart and supports manual recovery on the same draft": 93,
"automatic Slack registration > Slack test messages > does not downgrade confirmed delivery when activity logging fails": 665,
"automatic Slack registration > Slack test messages > does not restore revoked access or take another user's identity": 531,
"automatic Slack registration > Slack test messages > loads another workspace page instead of truncating account discovery": 806,
"automatic Slack registration > Slack test messages > redacts provider failures and never retries an ambiguous send": 739,
"automatic Slack registration > Slack test messages > rejects wrong-workspace users, disabled DMs, and membership revocation": 639,
"automatic Slack registration > Slack test messages > requires a private Slack challenge for an unknown account before linking and sending the test": 813,
"automatic Slack registration > Slack test messages > sends to the current linked user and reuses a durable result on duplicate requests": 783,
"automatic Slack registration > Slack test messages > settles a failed Slack account-link intent without committing identity or sending a test message": 722,
"automatic Slack registration > Slack test messages > signals milestone eligibility around the real Slack account link and stays quiet on reconfirmation": 807,
"automatic Slack registration > uploads a real 512-pixel PNG from the production renderer": 2609,
"automatic Slack registration > uploads preset bytes after credentials are durable, even with private avatar %s": 309,
"automatic Slack registration > uses an authenticated message event to complete automatic setup without a URL challenge and notifies once": 491,
"automatic Slack registration > vaults the bot token before %s and resumes without code exchange": 1183,
"automatic Slack registration > wakes verification from a signed callback with no maintenance polling": 686,
"automatically enables native modals for an existing Discord endpoint after %s runtime qualification": 915,
"automatically recovers a pre-ingress GitHub failure only through a genuine callback and normal durable workers": 620,
"binds Slack DM slash controls to the latest task ($control, $status, $state)": 4312,
"binds Slack tools to the admitted linked request, recovers its provenance and revokes retained access": 4258,
"blocks a committed native review response and selected files at transport after %s": 1981,
"Board send terminal attachment rejection > commits one content-free scoped receipt for concurrent rejection and allows only a separately keyed corrected send": 843,
"Board send terminal attachment rejection > does not classify missing attachments as a safe terminal rejection": 877,
"Board send terminal attachment rejection > keeps the exact rejected key terminal after normal owner-comment deletion and service reconstruction": 554,
"Board send terminal attachment rejection > returns the exact HTTP rejection with only the bound subset and replays that receipt unchanged": 742,
"bounds a held Slack receipt before delivering an already-ready same-endpoint final": 2418,
"bounds company fixture prefix collision retries without creating a partial fixture": 70,
"bounds failed retry notice scope discovery with retained candidates (%s)": 2564,
"bounds inbound notice scope discovery with denied history (%s)": 2051,
"bounds interaction continuation recovery reads with completed history": 2304,
"bounds terminal confirmation recovery reads with completed history": 2314,
"cancels a queued Slack slash start when channel reach is revoked before transport": 213,
"cancels and redacts GitHub ingress when rotation wins before replay authentication": 636,
"cancels staged GitHub ingress when a minimal recovery tombstone arrives before processing": 412,
"cancels staged GitHub ingress when same-secret pause and resume wins at the replay barrier": 401,
"cannot publish a runtime whose initialization is overtaken by pause": 241,
"canonicalizes prefixed Chat SDK channel ids onto provider inventory resources": 264,
"captures initial Slack communication guidance once per task, ignoring forged message configuration": 531,
"captures signed Slack forwarding protocol with registered owners (%s)": 1138,
"checks both linked sender and agent assignment grants for protected organizational defaults": 562,
"checks protected organizational defaults against the assignee locked at creation": 430,
"classifies publication $label": 3848,
"cleans only the GitHub final run's receipt and never re-adds it on replay": 656,
"clears an older multi-line Slack receipt diagnostic on terminal removal with attachment warning %s": 718,
"coalesces closed native progress on %s fixture %s (%s) without projecting event content": 4087,
"coalesces concurrent automatic pre-ingress GitHub scans into one provider redelivery": 281,
"coalesces one Microsoft Teams run into one provider reply": 516,
"coalesces one Telegram run into one provider message": 904,
"coalesces Telegram status and final output into one run-scoped provider message": 570,
"composes a parsed Discord question answer with one same-thread continuation publication": 1294,
"configures a customer-owned GitHub App and only auto-enables the first addressed setup repository": 651,
"configures a customer-owned Microsoft Teams bot with the entered credentials": 101,
"configures a Discord bot only after identity, intent, server, and channel permissions verify": 907,
"configures Telegram and preserves queued updates with webhook origin %s": 881,
"consumes Telegram forum-topic controls without remapping or waking the topic task": 420,
"continues a legacy Teams binding across a regional route change without forking its task": 499,
"continues an accepted GitHub task Retry from recovered saved work when its chat replay is refused after the click: %s": 59477,
"continues an inherited GitHub task from its recorded result instead of replaying the committed provider failure": 602,
"corrects Telegram DM conversation links without rewriting retained provider receipts": 355,
"creates a channel-purpose connection and rejects attempts to change its assigned agent": 199,
"deduplicates inbound events, keeps one task per thread, and enables newly discovered Slack channels": 661,
"deduplicates Slack file-only revisions by consumed metadata without retaining private locators": 289,
"defers a rate-limited Telegram receipt reaction for the full provider interval without blocking the inbound turn": 291,
"defers continuation dispatch until the outer response transaction commits": 1430,
"defers scheduled accepted-response recovery behind %s status effects": 960,
"defers scheduled accepted-response recovery until the persisted retry is due": 548,
"defers Slack file receipt recovery while the original post owns the same attempt": 584,
"delivers a recovered %s answer without editing another run's failure notice": 1184,
"delivers and replaces a Slack %s card through the publication service": 4848,
"delivers oversized Discord Markdown losslessly as one retryable attachment": 1241,
"delivers queued provider notices from commit wakes without the deferred fast path": 271,
"denies a pre-provider reviewed retry with %s": 6262,
"denies a staged failed chat retry after its original lifecycle epoch changes": 258,
"denies a stale automatic GitHub callback after pause and reconnect even with the still-current HMAC secret": 577,
"denies guest Slack stops, fences delayed events from newer runs, and cancels queued wakes": 1115,
"Discord automatic command registration > does not rediscover a receiver stopped by a company removal refresh": 287,
"Discord automatic command registration > drives receiver discovery through real configure, rotation, pause, and resume producers": 897,
"Discord automatic command registration > fences receiver construction across renewal: %s": 5137,
"Discord automatic command registration > keeps mention setup usable on registration failure and upgrades automatically when due": 415,
"Discord automatic command registration > learns the first configured command and cancels its deadline when the endpoint is removed": 490,
"Discord automatic command registration > preserves a healthy Discord Gateway when a due command refresh returns 503": 516,
"Discord automatic command registration > rechecks durable ownership after an earlier renewal finishes before listener start": 384,
"Discord automatic command registration > reconstructs an uncertain registration by GET without repeating the provider write": 391,
"Discord automatic command registration > restarts a receiver after token loss only after the old listener has stopped": 2357,
"Discord automatic command registration > retains the Gateway after an external command namespace conflict without overwriting it": 364,
"Discord automatic command registration > takes over a persisted foreign receiver lease at its deadline through the worker": 1365,
"Discord automatic command registration > updates scheduled registration after real %s": 1041,
"Discord native commands with durable service authority > acknowledges privately before a blocked DB wait but denies %s before commit": 1354,
"Discord native commands with durable service authority > answers a cold unavailable Discord command privately without leaving the interaction thinking": 632,
"Discord native commands with durable service authority > denies a previously accepted command after %s without another action or public receipt": 4532,
"Discord native commands with durable service authority > fresh-after-close publication bindings > allows a complete freshly admitted coalesced batch": 1349,
"Discord native commands with durable service authority > fresh-after-close publication bindings > allows an admitted source sent after close command but before close confirmation to present": 1086,
"Discord native commands with durable service authority > fresh-after-close publication bindings > does not cross a historical close after current %s authority changes": 12159,
"Discord native commands with durable service authority > fresh-after-close publication bindings > does not drop an older coalesced source while selecting the fresh batch": 988,
"Discord native commands with durable service authority > fresh-after-close publication bindings > does not grant presentation across a published control with %s proof": 4360,
"Discord native commands with durable service authority > fresh-after-close publication bindings > does not let an automatic child copy %s presentation authority": 1820,
"Discord native commands with durable service authority > fresh-after-close publication bindings > does not let an unseen stale native Discord %s act on reopened work": 1691,
"Discord native commands with durable service authority > fresh-after-close publication bindings > keeps a newly closed source internal after a still newer source reopens the thread": 972,
"Discord native commands with durable service authority > fresh-after-close publication bindings > keeps a source admitted before close confirmation internal after a fresh source reopens": 1323,
"Discord native commands with durable service authority > fresh-after-close publication bindings > orders same-millisecond Discord sources only within the same worker and process": 1014,
"Discord native commands with durable service authority > fresh-after-close publication bindings > publishes working and the exact fresh final after pinned close without resurrecting the old source": 1716,
"Discord native commands with durable service authority > fresh-after-close publication bindings > refuses %s provider chronology at intake when first ingested after close": 1957,
"Discord native commands with durable service authority > fresh-after-close publication bindings > wakes a post-close milestone when %s authority is restored": 20614,
"Discord native commands with durable service authority > fresh-after-close publication bindings > wakes a post-close milestone when interrupted inbound acceptance settles its %s receipt": 4457,
"Discord native commands with durable service authority > fresh-after-close publication bindings > wakes saved post-close native progress when %s authority returns": 10286,
"Discord native commands with durable service authority > qualifies pinned Discord close-owned progress retirement (%s)": 3200,
"Discord native commands with durable service authority > records DM new once and never applies its old replay to a replacement conversation": 1195,
"Discord native commands with durable service authority > returns private status, keeps guild new as guidance, and closes only after a real public control receipt": 953,
"Discord native commands with durable service authority > rolls back staged public control when the durable command receipt fails": 654,
"Discord native commands with durable service authority > serializes simultaneous exact close deliveries and denies a changed command or registered ID": 470,
"Discord native commands with durable service authority > upgrades a retained prior-copy registration after service restart before admitting close": 836,
"discovers a Slack connect identity without starting work or granting access": 445,
"dispatches and publishes a queued Slack Board send with a one-connection database pool": 504,
"dispatches saved input through the task Retry HTTP endpoint and survives a repeated click": 899,
"does not accept a contradictory HTTP%s Slack duplicate receipt": 670,
"does not acknowledge lifecycle callbacks whose durable write fails": 207,
"does not adopt historical pre-ingress GitHub failures when initializing a recovery epoch": 360,
"does not adopt input or deliver a pending identity-contended Retry after %s": 4614,
"does not bypass %s task guards from the Slack Board composer or its outbox": 1718,
"does not bypass %s through an exact chat retry": 1748,
"does not cancel an ambiguous Slack task start after credential-lease ownership is lost": 29,
"does not commit a Telegram close control when its provider reply is definitively rejected": 461,
"does not commit endpoint reach changes after credential-lease ownership is lost": 25,
"does not commit stale Slack task-start recovery after credential-lease ownership is lost": 67,
"does not complete GitHub webhook repair or overwrite a new credential lease owner after remote success": 336,
"does not create SDK eyes reactions for accepted GitHub requests": 418,
"does not deadlock reaction replay against publication link settlement": 645,
"does not dispatch an accepted inbound wake after destination access is revoked": 340,
"does not duplicate an inbound file when delivery recovery resumes after the task mutation": 660,
"does not enable Discord modals after a connection-lock wait with %s": 419,
"does not hide another endpoint behind a page of busy-bot conversation heads": 2328,
"does not hold another endpoint's final publication behind Slack session status transport": 885,
"does not lend a consumed failure lane to a recovered answer with %s": 1863,
"does not let a late %s milestone replace authoritative ownership attention or final status": 2607,
"does not let an obsolete GitHub webhook secret reopen a repository during rotation": 508,
"does not let an obsolete Slack signing secret verify a reconnected configuration": 364,
"does not let an obsolete Slack task-start failure quarantine successor credentials or reach": 272,
"does not let GitHub lifecycle recovery undo a webhook-secret rotation": 543,
"does not let ineligible pre-ingress GitHub candidates exhaust every future recovery scan": 370,
"does not let one blocked Slack conversation starve another outbox head": 442,
"does not let pause overtake a credential-fenced Discord root thread creation": 211,
"does not let pause return while a Slack publication is still in provider transport": 568,
"does not let rejected callbacks or malformed proxy hints establish healthy Slack callbacks": 283,
"does not let Slack reach disables return ahead of in-flight provider sends": 816,
"does not let stale GitHub setup-secret rotation overwrite successor credentials": 80,
"does not let stale Telegram removal clear successor credentials after lease reclamation": 145,
"does not let two live agent connections claim the same native bot or spoof its verified identity": 107,
"does not lock durably ineligible %s history on repeated issue milestones": 16881,
"does not normalize a stale Slack retry-anyway action after credential-lease ownership is lost": 144,
"does not recover a committed answer after %s": 5862,
"does not reload dormant accepted-response history for an unrelated %s wake": 2888,
"does not repeat a failed chat run with %s": 798,
"does not replace a failure while another exact-run authored publication is %s": 1018,
"does not replay stale native progress after a paused endpoint restarts behind an exact final": 870,
"does not request automatic pre-ingress GitHub recovery while the latest provider attempt is %s": 1359,
"does not resurrect publication ownership after waiting beyond expiry on a real lease row lock": 402,
"does not retain signed GitHub events outside the configured App event set": 233,
"does not retry a chat comment edited on the Board during the failed execution": 344,
"does not retry a provider-accepted publication after its exact attempt lease is lost": 316,
"does not retry automatic pre-ingress GitHub redelivery without a distinct failed provider attempt": 367,
"does not retry unrelated company fixture database errors": 12,
"does not rotate a GitHub webhook secret when stored credentials cannot be resolved": 219,
"does not treat an accepted-response endpoint scheduling hint as current authority": 381,
"does not wake twice when an operator replays an already admitted failed delivery": 422,
"drains accepted GitHub webhooks from commit wakes and durable retry deadlines": 1652,
"drains bounded Slack chat-origin milestones without admitting an internal issue run (%s)": 2259,
"drains failed chat retries from durable work and becomes idle: %s": 9549,
"durably admits a Telegram edit that races deferred original-message processing": 1084,
"durably audits a rejected Discord Gateway action before surfacing transport rejection": 136,
"durably deduplicates Telegram guidance webhook retries and filters disabled DMs": 252,
"durably recovers rate-limited Telegram menu registration and removal cleanup": 431,
"durably replays a reaction that arrives before its outbound link without waking the task": 1033,
"durably retries a signed Slack session stop and cancels its exact linked run once": 813,
"durably stages GitHub webhooks while credential mutation owns the processing lease": 478,
"durably stages GitHub webhooks within budget before cold runtime initialization": 438,
"edits a Slack working reply into one terminal failure reply": 389,
"edits Slack public progress and posts the final as a fresh reply, cancelling an older queued edit": 887,
"enforces Telegram group reach and privacy-mode addressing before retaining message content": 570,
"enforces the native progress cadence boundary and one publication per phase": 617,
"exhausts the existing delivery Retry budget after identity authorization without background renewal": 8200,
"expires Teams consent from the committed Board transfer without periodic maintenance": 1816,
"expires the saved identity wait without renewal when the lock is released before expiry processing: %s": 1688,
"fails closed for unbound rich callbacks and unknown slash commands": 207,
"fails closed on automatic pre-ingress GitHub recovery with %s": 734,
"fails closed when GitHub App permissions drift before installation recovery": 837,
"fails closed when the GitHub installation has not approved the App permissions": 747,
"fences a reclaimed Slack task admission from the obsolete worker's settlement": 362,
"fences message and reaction callbacks that resume after Discord Gateway takeover": 864,
"filters a claimed message lifecycle delivery after pause and reconnect supersede its runtime": 614,
"filters a durable orphan Telegram edit after the bounded reorder window": 404,
"filters a durably admitted GitHub callback when rotation and reconnect supersede its runtime before deferred processing": 743,
"filters a late duplicate instead of bypassing the bounded reaction-link lifetime": 687,
"filters a staged reaction when destination reach is revoked before replay": 788,
"filters a standalone unaddressed GitHub comment after bounded orphan retention": 568,
"filters an unlinked guest when the endpoint sponsor is suspended and exposes the reason and duplicate count": 204,
"filters unlinked people when configured, then honors a confirmed active-member identity link": 690,
"first-seen messages behind completed chat controls > accepts delayed %s backlog without an explicit control": 1037,
"first-seen messages behind completed chat controls > continues to accept authenticated Slack slash close/new on a genuinely new generation": 1485,
"first-seen messages behind completed chat controls > does not infer a stop from bare completed state with %s": 2160,
"first-seen messages behind completed chat controls > does not let an unseen old Telegram /%s close a newer generation": 1801,
"first-seen messages behind completed chat controls > does not lower a newer provider boundary when an older close is confirmed later": 1131,
"first-seen messages behind completed chat controls > does not promote metadata-only %s timestamps after a completed control": 1394,
"first-seen messages behind completed chat controls > does not recreate or filter a previously committed inbound link when its delivery retries after close": 821,
"first-seen messages behind completed chat controls > honors operator-confirmed close without inventing an outbound message receipt": 777,
"first-seen messages behind completed chat controls > keeps controls scoped to their endpoint, immutable thread, and company": 2023,
"first-seen messages behind completed chat controls > preserves a Teams close across regional routes (close after route change: %s)": 1409,
"first-seen messages behind completed chat controls > rechecks a close committed while old input waits before the endpoint transaction": 747,
"first-seen messages behind completed chat controls > refuses unseen %s input before %s (same second: %s) without creating work": 5905,
"first-seen messages behind completed chat controls > retains a committed control boundary through pause, redacted duplicate, and resume": 2215,
"first-seen messages behind completed chat controls > retains a completed trailing-newline control as a first-seen source boundary": 777,
"GitHub agent review workflow > acknowledges a GitHub request after a durable scheduler retry succeeds": 563,
"GitHub agent review workflow > adds the progress tool to an existing enabled bot without restoring disabled tools": 717,
"GitHub agent review workflow > admits a GitHub request explicitly addressed to both connected bots": 1632,
"GitHub agent review workflow > admits a newly mentioned %s edit while preserving its lifecycle record": 2519,
"GitHub agent review workflow > admits opt-in signed issue events without PR checks, deduplicates them and rechecks revoked policy": 1436,
"GitHub agent review workflow > admits signed %s mentions with automation off, deduplicates and retains manual task authority": 32572,
"GitHub agent review workflow > admits signed PR events into an ordinary assigned task and deduplicates delivery": 4668,
"GitHub agent review workflow > adopts an existing GitHub PR placeholder and retires earlier duplicate placeholders": 1431,
"GitHub agent review workflow > authorizes description edits as the editor, never inheriting the original author's access": 2115,
"GitHub agent review workflow > automatically retries a transient GitHub review publication (HTTP %s)": 8356,
"GitHub agent review workflow > backs off remote head polls while an unresolved GitHub review check cannot change": 1261,
"GitHub agent review workflow > bounds GitHub response authorization reads with large saved chat content": 1285,
"GitHub agent review workflow > checks live repository permission and reports a revoked installation selection": 482,
"GitHub agent review workflow > classifies recovered GitHub receipts without republishing or overwriting historical success": 1569,
"GitHub agent review workflow > closes a GitHub placeholder after a formal review (legacy receipt: %s)": 2088,
"GitHub agent review workflow > closes an inline-only GitHub review when an earlier working comment was deleted: %s": 2641,
"GitHub agent review workflow > coordinates GitHub working feedback with a %s fast response": 3090,
"GitHub agent review workflow > defers GitHub review check enqueue until outer commit and discards rollback": 1855,
"GitHub agent review workflow > does not admit an unlinked issue author through the linked webhook sender": 406,
"GitHub agent review workflow > does not edit a %s replacement of the bound GitHub comment": 1500,
"GitHub agent review workflow > does not handle a blocked new GitHub request with an older run's final reply": 1711,
"GitHub agent review workflow > does not invent a GitHub completion response when the agent sends no tool reply": 1196,
"GitHub agent review workflow > does not let a progress edit overwrite a final GitHub answer": 1182,
"GitHub agent review workflow > does not let an unsettled GitHub fallback block a later board message": 966,
"GitHub agent review workflow > does not post a GitHub working comment when the scheduler declines the request": 349,
"GitHub agent review workflow > does not resubmit a permanent GitHub publication rejection (HTTP %s)": 2232,
"GitHub agent review workflow > does not route GitHub mentions using %s identities": 2984,
"GitHub agent review workflow > drains more than one page of stale GitHub review projections without touching manual history": 1734,
"GitHub agent review workflow > finalizes every working comment in a coalesced GitHub run": 1320,
"GitHub agent review workflow > finds a GitHub review check after a full page of revoked work and ignores settled history": 5882,
"GitHub agent review workflow > finds owed terminal GitHub work beyond a full page of unrelated request history": 2087,
"GitHub agent review workflow > finds terminal GitHub responses by native issue binding before legacy run context": 1590,
"GitHub agent review workflow > finishes the same GitHub working comment after an authorized same-App reconnect (legacy: %s)": 1503,
"GitHub agent review workflow > GitHub failure fallback respects exact tool delivery state: %s": 9519,
"GitHub agent review workflow > holds stale GitHub review projection receipt repair until the outer commit and discards rollback": 2435,
"GitHub agent review workflow > ignores a review request addressed to an external GitHub bot": 934,
"GitHub agent review workflow > imports initial GitHub access for a %s App without a second picker and leaves later additions disabled": 759,
"GitHub agent review workflow > keeps a newer GitHub request open when its acknowledgement follows older progress": 1949,
"GitHub agent review workflow > keeps a report-only GitHub check neutral after a %s run without an assessment": 1792,
"GitHub agent review workflow > keeps an acknowledged paused GitHub request quiet until its new run finishes": 2106,
"GitHub agent review workflow > keeps GitHub publication I/O outside transactions and fences an expired owner's receipt": 299,
"GitHub agent review workflow > keeps GitHub response maintenance truthful for a new request: $scenario ($reason)": 37299,
"GitHub agent review workflow > keeps GitHub response ownership checks independent of large run payloads": 1244,
"GitHub agent review workflow > keeps GitHub review check history quiet and wakes from the real enqueue producer": 2504,
"GitHub agent review workflow > keeps GitHub review tools callable through a later native task gateway (board follow-up: $boardFollowUp, legacy origin: $legacyOrigin)": 5744,
"GitHub agent review workflow > keeps native presentation idle until its committed GitHub outcome: %s": 5610,
"GitHub agent review workflow > keeps partial review delivery authoritative when the head changes %s": 2115,
"GitHub agent review workflow > keeps per-request fallback outside the main GitHub PR review wait": 986,
"GitHub agent review workflow > keeps terminal GitHub responses waiting while a natively bound newer run is active": 881,
"GitHub agent review workflow > keeps the published review in the main GitHub PR comment when a later request has only a status: %s": 2471,
"GitHub agent review workflow > legacy name-only registration preserves an explicit empty repository selection": 40,
"GitHub agent review workflow > links a gated GitHub check to the current vanity review page before a task exists": 420,
"GitHub agent review workflow > lists each GitHub bot tool once when an inline thread shares the task": 617,
"GitHub agent review workflow > loads an old GitHub review directly without crossing endpoint or company boundaries": 1100,
"GitHub agent review workflow > loads only the current configured instruction skills, never provider links or another company": 2046,
"GitHub agent review workflow > manual App credential retry imports repositories after an interrupted vault write": 788,
"GitHub agent review workflow > manual App setup preserves explicitly disabled repositories and tools": 530,
"GitHub agent review workflow > manual App setup resumes tool initialization after an interrupted repository import": 476,
"GitHub agent review workflow > offers Retry for a saved automatic PR event after a successful older review": 2034,
"GitHub agent review workflow > parks a GitHub acknowledgement until native presentation commits": 1056,
"GitHub agent review workflow > parks terminal GitHub responses behind the publication owner (uncertain: %s)": 6260,
"GitHub agent review workflow > preserves %s policy context while omitting body content": 2076,
"GitHub agent review workflow > preserves a final GitHub assessment while settling an incomplete request receipt": 1678,
"GitHub agent review workflow > preserves an earlier final GitHub answer when a later continuation fails": 866,
"GitHub agent review workflow > preserves GitHub connection intent after publication HTTP %s": 2399,
"GitHub agent review workflow > preserves malformed GitHub authority input %j": 4427,
"GitHub agent review workflow > preserves newer GitHub PR progress when an older run fails": 1728,
"GitHub agent review workflow > preserves the %s GitHub receipt lifecycle during acknowledgement recovery": 1409,
"GitHub agent review workflow > preserves the published GitHub assessment during passive-response maintenance: %s": 2348,
"GitHub agent review workflow > publishes a local change at once and still recovers a missed head after backing off": 1243,
"GitHub agent review workflow > publishes a run change for a GitHub review check at once from its issue milestone": 1167,
"GitHub agent review workflow > publishes one score heading when a newly configured bot submits a formatted summary": 1134,
"GitHub agent review workflow > reactivates terminal GitHub response recovery from committed native identity": 2016,
"GitHub agent review workflow > reads no GitHub review check status for company-wide hints and still reads it for the check's task": 851,
"GitHub agent review workflow > reads pending GitHub receipts without dispatch and refuses a missing publication": 2593,
"GitHub agent review workflow > rechecks a GitHub fallback after waiting for the credential lane": 880,
"GitHub agent review workflow > rechecks another GitHub bot's mention when recovering a durable subscribed delivery": 1133,
"GitHub agent review workflow > rechecks assessment ownership after stale GitHub review projection selection waits for a row lock (shutdown: %s)": 3174,
"GitHub agent review workflow > reconciles a GitHub working comment when execution stops without a publication": 991,
"GitHub agent review workflow > reconciles stopped GitHub work from native identity without legacy wake fields": 776,
"GitHub agent review workflow > reconsiders the same GitHub reply after stopped native workspace cleanup (%s)": 27754,
"GitHub agent review workflow > records automatic policy skips without retaining provider content, and refuses mentions in disabled repositories": 541,
"GitHub agent review workflow > recovers %s after a timeout before publication staging": 2302,
"GitHub agent review workflow > recovers a delayed GitHub acknowledgement after a successful run without leaving it working": 829,
"GitHub agent review workflow > recovers a durable GitHub publication receipt ($label)": 14526,
"GitHub agent review workflow > recovers a missed GitHub head webhook only while a review check remains unresolved": 606,
"GitHub agent review workflow > recovers an acknowledgement whose local receipt was lost without posting another comment": 1269,
"GitHub agent review workflow > recovers an approved queued GitHub review without another approval (revoked: %s)": 3892,
"GitHub agent review workflow > recovers long %s requests without accepting changes hidden by the audit preview": 4406,
"GitHub agent review workflow > recovers lost inline and check responses without duplicate GitHub publications": 7936,
"GitHub agent review workflow > recovers stale GitHub review projection through %s": 3271,
"GitHub agent review workflow > rejects arbitrary comment IDs and edits after the initiating person is revoked": 567,
"GitHub agent review workflow > rejects changed requests and revoked access before repeating an unstaged review": 7429,
"GitHub agent review workflow > releases a GitHub acknowledgement after fast response %s without maintenance polling": 9033,
"GitHub agent review workflow > replies in review finding threads behind an active run > answers each finding thread in its own run instead of one unattestable batch": 3506,
"GitHub agent review workflow > replies in review finding threads behind an active run > still batches several replies in one finding thread into one attested run": 3755,
"GitHub agent review workflow > replies in review finding threads behind an active run > still denies each separated finding-thread run after the linked identity is revoked": 1638,
"GitHub agent review workflow > requires every essential GitHub tool and rejects Contents write during verification": 508,
"GitHub agent review workflow > resolves only the secrets a %s signed GitHub webhook delivery uses": 599,
"GitHub agent review workflow > restores terminal GitHub responses and leaves finalized history quiet": 1469,
"GitHub agent review workflow > resumes a delayed GitHub publication after coordinator restart without another inbound event": 3373,
"GitHub agent review workflow > resumes a paused GitHub request and reconciles stopped execution (prior run: %s, progress: %s)": 4580,
"GitHub agent review workflow > retains a provider-verified GitHub mention when its plain text uses an alias": 1168,
"GitHub agent review workflow > retains attachment provenance in a signed GitHub mention %s": 2294,
"GitHub agent review workflow > retains failed stale GitHub review projection repair across drain without passive SQL": 1638,
"GitHub agent review workflow > retains GitHub review check work across %s": 5816,
"GitHub agent review workflow > retains subscribed GitHub follow-ups with incidental human or unknown mentions: %s": 6044,
"GitHub agent review workflow > retains terminal GitHub response work across %s": 5540,
"GitHub agent review workflow > retains the saved GitHub review check retry through restart without an early provider call": 607,
"GitHub agent review workflow > retires a legacy coalesced GitHub placeholder before replacing its receipt": 2076,
"GitHub agent review workflow > retires a legacy GitHub placeholder when its acknowledgement is superseded": 2043,
"GitHub agent review workflow > retries a failed GitHub acknowledgement at its saved deadline": 1064,
"GitHub agent review workflow > retries an ambiguous GitHub edit without creating another comment": 7896,
"GitHub agent review workflow > returns snapshot finding categories and publishes only accepted categories": 2110,
"GitHub agent review workflow > reuses one main GitHub PR comment across review requests: %s": 5300,
"GitHub agent review workflow > scopes guest tasks and rechecks their sponsor before every bot tool": 556,
"GitHub agent review workflow > settles a deleted Board-origin request without starving unrelated terminal GitHub replies": 2719,
"GitHub agent review workflow > settles a deleted coalesced working comment without blocking the current GitHub response": 1076,
"GitHub agent review workflow > settles a GitHub working comment whose run finished just before another request's run started": 2007,
"GitHub agent review workflow > settles an older request's status without replacing a newer main GitHub PR placeholder": 1243,
"GitHub agent review workflow > stack exchanges a callback code only once when vault storage is interrupted": 33,
"GitHub agent review workflow > stack rejects forged raw gateway deliveries without changing verification or waking an agent": 865,
"GitHub agent review workflow > stages one assessment when the timed-out metadata read completes alongside its retry": 1768,
"GitHub agent review workflow > still fences a GitHub publication when reconnect races the provider read": 990,
"GitHub agent review workflow > stops a queued GitHub publication after %s": 3349,
"GitHub agent review workflow > stops GitHub acknowledgement sends at %s between provider requests": 5753,
"GitHub agent review workflow > stops GitHub review check HTTP after shutdown admission and recovers its durable action": 7005,
"GitHub agent review workflow > supersedes a late review projection after its check already rejected the old head": 1360,
"GitHub agent review workflow > suppresses subscribed GitHub comments for another connected bot in %s": 2892,
"GitHub agent review workflow > updates one GitHub acknowledgement through progress and final answer in %s": 3652,
"GitHub agent review workflow > uses task-bound bot tools and deterministic checks, then denies revoked people": 2500,
"GitHub agent review workflow > uses the manifest state parameter and rejects expired, reused, and wrong-origin registrations": 29,
"GitHub agent review workflow > verifies %i enabled repositories in bounded token batches": 1010,
"GitHub agent review workflow > verifies a repaired GitHub webhook in %s only from a %s installation delivery with %s repository": 4124,
"GitHub agent review workflow > waits for and wakes from the actual GitHub review check publication lease": 1696,
"GitHub agent review workflow > waits for the existing GitHub publication lease before a terminal response": 1722,
"GitHub agent review workflow > wakes a GitHub acknowledgement only after the outer fast-response transaction commits": 1718,
"GitHub agent review workflow > wakes a GitHub review check from committed run identity before its future head deadline": 1639,
"GitHub agent review workflow > wakes a paused GitHub response from %s": 9412,
"GitHub agent review workflow > wakes GitHub acknowledgements from a real publication lease %s": 5660,
"GitHub agent review workflow > wakes GitHub milestone identity restoration only after outer commit and stays quiet on reconfirmation": 439,
"GitHub agent review workflow > wakes milestone authority only when GitHub guest settings change, after outer commit": 477,
"GitHub agent review workflow > wakes stale GitHub review projection repair from real admission and leaves settled history quiet": 1438,
"GitHub agent review workflow > wakes stale GitHub review projection repair when cancellation commits after the review is admitted": 1457,
"GitHub agent review workflow > wakes terminal GitHub responses after the outer issue transaction commits": 1652,
"GitHub agent review workflow > wizard completes a verified connection automatically without claiming runtime execution": 587,
"GitHub agent review workflow > wizard configures Cloud webhook delivery without a public instance URL": 344,
"GitHub agent review workflow > wizard keeps localhost draft choices while waiting for Cloud enrollment": 52,
"GitHub agent review workflow > wizard persists a %s owner and resumes the same bound registration after a lost Cloud response and enrolled origin change": 148,
"GitHub agent review workflow > wizard preserves an explicit empty repository selection at revision zero": 336,
"GitHub agent review workflow > wizard preserves explicit review behavior and repository restrictions on existing drafts": 644,
"GitHub agent review workflow > wizard recovers a renamed enrolled origin only after checking bound state and Cloud authority": 31,
"GitHub agent review workflow > wizard repairs Cloud after manual credential recovery and secret rotation without changing App identity": 550,
"GitHub agent review workflow > wizard restarts only an expired unconsumed registration: %s": 302,
"GitHub agent review workflow > wizard resumes a %s installation callback after its signed ping": 1267,
"GitHub agent review workflow > wizard retains partial manifest recovery until explicit existing-App recovery succeeds": 816,
"GitHub agent review workflow > wizard serializes identity starts and callbacks without overwriting PKCE or handoff state": 309,
"GitHub repository pagination and bulk access > pages and searches 1000 repositories while toggle all changes unloaded rows atomically": 525,
"GitHub terminal receipt composes pinned HTTP and durable source authority (%s)": 11177,
"GitHub webhook recovery scheduling > joins held GitHub history at shutdown without starting another HTTP request": 395,
"GitHub webhook recovery scheduling > leaves %s recovery quiet": 563,
"GitHub webhook recovery scheduling > preempts a future GitHub recovery window when only credential references change": 1270,
"GitHub webhook recovery scheduling > preserves a GitHub redelivery stopped before transport (%s, prior receipt: %s, superseded: %s)": 2457,
"GitHub webhook recovery scheduling > reactivates recovery from real resume and cancels its deadline on pause": 3400,
"GitHub webhook recovery scheduling > reconstructs due GitHub recovery through %s": 1155,
"GitHub webhook recovery scheduling > reconstructs more than one page of GitHub recovery deadlines and dispatches fair batches of five": 1988,
"GitHub webhook recovery scheduling > recovers a failed GitHub deadline reconstruction after drain without passive SQL": 329,
"GitHub webhook recovery scheduling > rejects a %s assigned agent before GitHub recovery can become orphaned": 4131,
"GitHub webhook recovery scheduling > retains GitHub recovery configuration intent through nested commit and rollback": 2314,
"GitHub webhook recovery scheduling > waits for the saved recovery deadline and requests a genuine GitHub redelivery": 360,
"globally fences GitHub App identity across owner transfers without leaking another company": 398,
"globally fences one Microsoft Bot application across tenants": 123,
"hands an explicitly bound same-run image to Discord's final native file response": 1008,
"holds a delayed first Teams setup reply until its older root mention enables the channel": 468,
"holds a delayed Slack thread reply until its older root mention arrives": 414,
"holds a GitHub follow-up that arrives after the reorder window until its older root mention arrives": 723,
"holds ambiguous provider sends for an audited duplicate-risk resolution without reordering": 1100,
"holds an ordinary $provider Retry behind its exact remote recovery: $gate": 22963,
"honors a prepared Retry identity wait after %s": 9624,
"honors Slack slash-start rate-limit backoff without hammering transport": 345,
"honors Telegram flood-control timing and publishes one final message after retry": 866,
"ignores a signed GitHub installation before App credentials exist": 117,
"ignores repeated unscoped routine %s hints without rebuilding dormant accepted-response history": 788,
"ignores signed Slack callbacks from a different workspace before SDK dispatch": 211,
"immediately initializes a new GitHub recovery generation despite the previous epoch's 24-hour backoff": 545,
"imports every Discord upload when text files include MIME parameters": 334,
"ingests a pinned Telegram video-note without optional MIME metadata (%s)": 1343,
"ingests bounded Telegram photo, audio, video, and document attachments without stranding text": 305,
"ingests only admitted public GitHub attachments after restart (HTTP $status, $count files, expired batch $expireBatch)": 3661,
"ingests Teams files only from personal chats and keeps non-DM references link-only": 391,
"invalidates only an exact provider-verified GitHub source edit independently of editor admission: %s": 3110,
"isolates malformed publication preparation so later messages still deliver": 979,
"isolates pre-run FIFO reconciliation scopes and exhausts published history": 529,
"joins in-flight recovery before rethrowing an ordinary drain failure (%s)": 1582,
"keeps a %s retry's queue and working progress on its own provider identity and delivers its selected final": 2184,
"keeps a board message queued separately when saved GitHub Retry resumes after cleanup": 793,
"keeps a chat-origin run presentation internal when its external question owns the reply": 1078,
"keeps a claimed $provider identity immutable when first setup resumes from attention": 51,
"keeps a first-channel Teams orphan payload-free during grace and filters it without a live retry": 178,
"keeps a refused GitHub task Retry continued when reconciliation read it before the refusal settled": 526,
"keeps a saved HTTP Retry alive through a healthy nine-second identity transaction": 10314,
"keeps a separate FIFO answer visible while removed-input cleanup edits its queued notice": 1060,
"keeps a successful GitHub link-question continuation final internal": 769,
"keeps a verified Slack $kind authoritative for $contentType read and reuse after reach or identity returns": 7239,
"keeps accepted-response work behind the outer %s boundary": 3751,
"keeps an aged live publication owned across standby sweeps but quarantines only exact-lease orphans": 697,
"keeps an internal Telegram run summary private and completes its progress message": 711,
"keeps an omitted-file warning after an early Slack receipt failure and %s retry": 763,
"keeps bare Slack mentions subject to %s access restrictions": 326,
"keeps case-variant Teams Entra object ids on one external principal": 345,
"keeps current GitHub task Retry authority gated: %s": 8183,
"keeps disabled-channel Slack %s scoped to its exact source without admitting content": 1819,
"keeps external-continuation lifecycle comments internal and publishes only the selected final": 476,
"keeps GitHub issues, PR conversations, and inline review threads on distinct tasks": 853,
"keeps intermediate %s agent comments internal and publishes only the selected final": 1318,
"keeps lifecycle and native progress projection independent with %s": 1577,
"keeps medium Telegram $label in one native publication": 1109,
"keeps missing attachment storage retryable but fails invalid metadata before provider transport": 820,
"keeps native progress behind question, final, and current reach authority on %s fixture %s (%s)": 4897,
"keeps one durable pre-run FIFO notice across coalescing and restart, then reuses only its successor lane": 2176,
"keeps one Paperclip account mapping for the same provider principal across endpoints": 371,
"keeps one Slack progress message and a separate final response despite an interleaved task control": 662,
"keeps processing audit truth and rejects stale Slack runtime callbacks across resume": 362,
"keeps provider startup diagnostics private on %s fixture %s (%s)": 3392,
"keeps recovered GitHub final prose and attachment navigation internal (omission: %s)": 1148,
"keeps root-chat bookkeeping comments internal and publishes only the selected final": 362,
"keeps saved-input Retry behind current admission gates: %s": 3282,
"keeps separate Slack DM thread roots on separate tasks": 430,
"keeps Slack tools callable after a native task continuation without wake JSON": 517,
"keeps successive Telegram DM messages on one active Paperclip task": 586,
"keeps task-bound /close active after an ambiguous publication commit until explicit confirmation": 671,
"keeps Teams group chat closed by default without consuming first-channel setup enablement": 280,
"keeps Telegram start and unknown commands as terse guidance without creating work": 157,
"keeps the admitted chat Retry queued until its source lease cleanup settles: %s": 25477,
"keeps the pre-run FIFO sweep running when a valid owner's action has comment ids that are not uuids": 410,
"leaves a contended accepted response retryable without reclassifying or partially publishing it (%s)": 934,
"leaves accepted-response presentation to its worker during periodic %s replay": 945,
"leaves Cloud-managed GitHub webhook recovery to the relay": 333,
"leaves fresh-commit accepted-response presentation to the worker when periodic replay skips it": 446,
"leaves GitHub reconnect unqualified after a %s webhook repair failure": 1574,
"leaves saved GitHub input pending when a persisted Retry wait loses board authority": 849,
"links outbound Teams files instead of attempting an unsupported native upload": 616,
"Lossless long Board publications > keeps an ambiguous %s text part blocked across restart and retries only that part and its tail": 3766,
"Lossless long Board publications > preserves %s code, Unicode and sanitization expansion through actual durable parts": 4766,
"Lossless long Board publications > preserves all 100000 characters for %s %s-comment publication": 8009,
"Lossless long Board publications > preserves an accepted native Slack response whose rendered mentions exceed the Markdown cap": 581,
"Lossless long Board publications > refuses malformed persisted wrappers before provider I/O %#": 1238,
"Lossless long Board publications > retains a complete 100000-character %s response in the existing Markdown document transport": 1242,
"maps a timestamp-bearing Slack DM reaction to the completed generation that owns its linked message": 828,
"maps Telegram image, audio, and video output onto native media lanes": 652,
"marks provider setup as needing attention when Telegram webhook registration fails": 67,
"materializes direct external-chat finals once and accepts the next turn without agent bookkeeping writes": 3577,
"migrates Telegram basic-group reach, topic tasks and $defaultsMode defaults (existing destination: $existingDestination)": 5150,
"mirrors Paperclip messages with user attribution and returns only the selected Slack reply": 1081,
"never promises a queued follow-up before durable admission succeeds": 424,
"never re-arms a failed local GitHub receipt when an automatic redelivery races the original callback": 385,
"never replaces or resurrects an already selected answer (deleted=%s)": 964,
"never stores a GitHub webhook body before its signature is authenticated": 367,
"opens and corrects an actual Discord modal through current service authority exactly once (%s concurrent answers)": 1649,
"orders a Telegram authentication failure before concurrent reconnect": 527,
"orders a Telegram destination failure before concurrent membership recovery": 536,
"orders a Telegram new command before the next message from the same provider second": 1086,
"orders rapid Discord replies by provider time before waking one task": 484,
"orders rapid Teams follow-ups by provider time when callbacks arrive reversed": 518,
"orders reversed GitHub edit and delete callbacks behind their durable root (root processed before replay: %s)": 5757,
"orders Slack private-channel archive, unarchive, and rename lifecycle": 237,
"paginates mixed activity beyond 100 rows without losing timestamp ties": 79,
"parks pending confirmation history, passes malformed prefixes, and wakes on the outer interaction commit": 8904,
"parks provider-confirmed Slack admissions on paused endpoints without starving active work": 415,
"passes historical continuation prefixes and retains a response committed during dispatch": 3786,
"persists Slack manifest draft details and the registered command, then locks them once connected": 160,
"persists Slack membership, uninstall, and same-bot reinstall lifecycle before acknowledging": 703,
"persists the first identity wait deadline for an older pending action": 741,
"presents a fresh Teams personal generation after close and a regional route change": 822,
"preserves a published %s file prefix across restart and retries only an explicitly resolved ambiguous upload": 1989,
"preserves a recorded %s presentation instead of recovering an unsolicited answer": 668,
"preserves a Teams personal %s attachment omission after losing its live download closure": 574,
"preserves an early Slack receipt failure after %s acceptance": 679,
"preserves an explicitly disabled Slack channel after invitation and mentions (%s)": 541,
"preserves an interrupted run's selected final when its publication is %s": 867,
"preserves automatic final replies for legacy GitHub connections without saved review configuration": 622,
"preserves delivery quarantine when a slow Slack post finishes after stale recovery": 602,
"preserves exact Discord source authority through registered Gateway %s updates": 1567,
"preserves GitHub webhook verification through setup completion and reconnect": 962,
"preserves one current GitHub Retry across %s": 26093,
"preserves ordinary legacy task Retry success without replaying its canonical request": 1954,
"preserves running Slack tool authority after Require at-mention is enabled": 411,
"preserves selected answer and failure lanes after deferred admission (%s)": 1363,
"preserves selected answer and failure lanes on $provider after $status ($order)": 11962,
"preserves Slack thread history across completion ($isDM, $threaded, $status, $state)": 1988,
"preserves stored Telegram credentials and lifecycle when reconnect uses an unsupported webhook port": 161,
"preserves the complete failed coalesced chat batch and rejects a dropped sibling": 545,
"preserves the GitHub resource, task, and conversation across repository rename and transfer": 672,
"preserves the public inventory error response for %s": 814,
"preserves the raw webhook request and returns the provider adapter response": 178,
"preserves unavailable Teams $surface file references through $mode admission": 3429,
"projects prepared but unsettled task Retry using its actual stale-claim deadline": 1211,
"provider timestamp provenance after closed conversations > retains only raw Telegram date through the pinned parser or runtime slash path (%s)": 3508,
"provider timestamp provenance after closed conversations > retains only the actual Teams activity clock, not SDK display fallback (%s)": 3324,
"provides assigned Slack tools to routine tasks and can DM only their linked responsible user": 1666,
"publishes a closed-choice question, settles its Slack card, and delivers its exact continuation response": 1917,
"publishes a serialized Telegram run response after the preceding run completes the conversation": 1176,
"publishes a Telegram failure for an exact confirmation continuation that stops before commenting": 964,
"publishes an agent's explicitly selected same-run Slack attachment after its response": 940,
"publishes an explicitly selected board attachment through Telegram's native file lane": 557,
"publishes complex question sets as non-executable Paperclip fallbacks": 651,
"publishes equal-time Slack outbox rows once in stable order across concurrent drains": 431,
"publishes explicit Board GitHub attachment fallbacks without provider file bytes": 1779,
"publishes fast responses to the accepted %s thread without completing its work": 1732,
"publishes GitHub questions as link-only cards with no executable callback": 546,
"publishes long structured Telegram Markdown as one durable lossless document": 850,
"publishes native progress with a typed issue binding present: %s": 860,
"publishes one truthful notice when a selected PNG receives a definite provider rejection": 1130,
"publishes only a resolver-selected Telegram reply for $authorizationReason": 2015,
"publishes only explicitly selected board attachments and stays idempotent across retries": 827,
"publishes only the safe projection once and locks reassignment of a bound task": 848,
"publishes the old final before /new and suppresses later output from the completed generation": 1071,
"quarantines a Telegram control when the reply lands but its state commit crashes": 729,
"quarantines an active GitHub endpoint when its dedicated App drifts to multiple installations": 520,
"quarantines an ambiguous automatic pre-ingress GitHub redelivery without blindly repeating the POST": 354,
"quarantines Telegram maintenance success when credential-lease ownership is reclaimed": 510,
"queues Telegram guidance on the durable publication FIFO when a task is active": 360,
"reactivates denied retry notices when authority is restored during %s": 6377,
"reactivates dormant accepted-response work when the live chat authority registers": 2389,
"reactivates failed retry notices from real admission after idle through %s": 3676,
"reactivates restored ordinary input after an earlier Retry notice wake is consumed": 406,
"reads the entire publication batch without side effects and rejects foreign bindings": 347,
"reauthorizes a failed chat retry against a %s provider correction before lifecycle projection": 2885,
"reauthorizes a failed chat retry and denies %s before scheduling": 2983,
"reauthorizes skipped native progress after %s wins before retry": 1556,
"rechecks %s authority before queued Slack Board messages and replies": 2445,
"rechecks a recovered response at provider dispatch after %s": 2594,
"rechecks a Slack file receipt after a competing worker changes its retry deadline": 694,
"rechecks canonical content before processing an automatically recovered GitHub callback": 406,
"rechecks linked authority and channel reach before admitting a provider-confirmed Slack task (%s)": 512,
"rechecks pre-provider retry evidence after staging and refuses a late execution event": 594,
"rechecks queued Slack channel roots but exempts replies and DMs (DM=$isDM, reply=$isReply)": 970,
"rechecks source retirement after a queued notice's late provider receipt commits": 772,
"rechecks the outbound link when publication commits between reaction preflight reads": 874,
"rechecks the recovered failure link after waiting for the provider mutation lane": 544,
"recognizes Slack callbacks behind TLS termination without trusting forwarded headers": 168,
"reconciled chat retry delivery ownership > does not resolve or mint a substitute owner for %s": 1062,
"reconciled chat retry delivery ownership > keeps one exact chat delivery owner through %s reconciliation": 1325,
"reconciled chat retry delivery ownership > retains the sole owner but refuses its deferred dispatch after %s": 1095,
"reconciles a foreign GitHub installation lifecycle event against canonical App inventory": 425,
"reconciles a provider-confirmed Slack starter into one task without replaying Slack": 975,
"reconciles concurrent opposite GitHub lifecycle callbacks from canonical App state": 667,
"reconciles Slack membership during configure, resume, and reconnect": 399,
"reconciles Slack session status without replaying messages after rate limits or restart": 968,
"reconstructs a future accepted-response deadline without early publication": 434,
"reconstructs inbound admission committed after the notice worker stops": 495,
"records message edits and deletes durably and deduplicates lifecycle callbacks": 557,
"records one content-free GitHub receipt for a disabled repository without admitting work": 393,
"records the public Cloud proxy host for authenticated Slack callback health": 199,
"records verified Telegram edited_message updates against the existing DM task": 738,
"recovers a committed %s answer once without rerunning or changing review/quarantine evidence": 1266,
"recovers a genuine unanswered %s presentation": 1374,
"recovers a provider-confirmed Slack starter after restart but rechecks revoked reach": 201,
"recovers accepted-response work on startup and leaves selected history quiet": 1473,
"recovers action rows on startup, wakes after outer commit, and leaves empty queues quiet": 1499,
"recovers an accepted Slack file receipt without uploading twice or exposing provider identifiers": 992,
"recovers an ambiguous Slack slash-task start only after an audited explicit retry": 457,
"recovers an authenticated GitHub webhook after shutdown before deferred work starts": 431,
"recovers buffered Discord messages and reactions after an unreclaimed host-pause lease expiry": 1235,
"recovers committed terminal confirmations without polling through %s": 4461,
"recovers stale provider sends on startup without replaying uncertain effects": 214,
"recovers the committed authorization phase after %s without renewing its deadline": 17664,
"recovers the exact port-bound canonical response before skipping a superseded native decision": 570,
"recovers the same Telegram bot and historical task after token rotation": 1234,
"recovers the visible receipt exactly once after wake acceptance contention": 7621,
"redacts lifecycle edits and ignores reactions after channel reach is revoked": 647,
"redacts Telegram bot tokens from provider setup errors and endpoint health": 82,
"refills four tracked publication endpoint lanes after a scheduled budget and joins shutdown": 1787,
"refreshes Slack tool guidance without restoring disabled catalog policies": 255,
"refuses an otherwise eligible exact Slack retry after %s without admitting source changes": 897,
"refuses to create a chat endpoint while its provider experiment is off": 104,
"refuses to enable a destination the provider no longer exposes": 137,
"registers ordinary-notice intent before a retry-owned receipt is retired": 575,
"registers ordinary-notice work through the retry admission transaction": 489,
"registers provider callbacks after a live Cloud claim (ingress: %s)": 982,
"rehydrates a durable attachment descriptor after restart and stores the file on the issue": 448,
"rehydrates exact chat retry authority and verifies its persisted projection after service restart": 514,
"rehydrates one Discord Gateway owner on startup and hands off cleanly across replicas": 188,
"rejects a recovered Slack file identity when destination reach changes during lookup": 533,
"rejects a signed automatic GitHub callback whose original %s identity changed": 1470,
"rejects automatic pre-ingress GitHub recovery after %s": 948,
"rejects caller-controlled GitHub setup secrets and arbitrary credential fields": 379,
"rejects chat endpoints for non-invokable agents": 46,
"rejects over-scoped GitHub Apps while tolerating unavoidable lifecycle events": 98,
"rejects reconnect credentials for a different Slack bot without rotating secrets": 119,
"rejects under-scoped Slack and GitHub apps before saving provider credentials": 182,
"rejects unsupported Telegram webhook ports before provider access or secret persistence": 24,
"releases authorization row locks before a Slack slash starter waits on provider I/O": 278,
"releases Discord ownership when runtime construction fails": 178,
"releases task-control authorization locks before provider I/O and quarantines stale claims": 777,
"removes a $label endpoint without deleting its task or audit history": 1108,
"renders safe Telegram confirmations as opaque one-use buttons and wakes the resolved task": 1274,
"reorders rapid Slack callbacks by provider time before one conversation drain": 1767,
"reorders reverse-arrival Telegram webhooks by provider sequence before waking the agent": 1099,
"reorders same-second GitHub callbacks by comment id before starting the task": 1357,
"repairs a committed reply and its recovery notice without reversing row locks": 482,
"repairs the same GitHub App webhook on reconnect without claiming a fresh signed ping or chat round trip": 475,
"replaces a pre-connect GitHub webhook secret without inventing a broken existing App": 166,
"replaces Telegram queued progress with its native confirmation and rejects late working progress": 777,
"replaces working with one safe ownership-attention message without terminalizing the run": 899,
"replays a pre-link reaction into the completed DM generation that sent the message": 911,
"replays one pre-link Discord reaction after service reconstruction without waking the task": 765,
"requires a successful final response for setup qualification": 777,
"requires at-mentions by default only in Slack channels (DM=%s)": 1111,
"requires connection-manager authority for chat connector administration": 238,
"requires terminal-safe native ownership for an exact chat retry: %s": 7495,
"requires the successful setup final to consume the qualifying follow-up": 747,
"resamples reaction expiry after replay waits on authorization locks": 698,
"resolves ambiguous provider effects explicitly and never lets terminal failures starve reconciliation": 758,
"resolves an admitted GitHub private image after restart with current reach at %s": 3803,
"resource change audit atomicity > joins concurrent identical and opposite changes into actual before/after history": 107,
"resource change audit atomicity > keeps duplicate last-write semantics but audits only net changes": 37,
"resource change audit atomicity > keeps the audit aligned with commit on lease loss %s": 75,
"resource change audit atomicity > reads the actual resource state after the row lock, not a pre-lock snapshot": 100,
"resource change audit atomicity > rolls back resource writes and suppresses events on %s failure": 63,
"resource change audit atomicity > rolls back the entire %s resource batch without audit or events": 96,
"resource change auditing > records exact actual changes and authenticated route actor, without resource content": 135,
"restarts an inbound notice cursor when privacy is restored during a bounded pass": 2409,
"restores action retry and stale-claim deadlines and parks paused or uncertain work": 363,
"restores changed native review metadata once and signals only its committed change": 817,
"restores chat queue deadlines without polling blocked followers or receipt owners": 257,
"restores inbound retry and abandoned wake deadlines and excludes paused queues": 216,
"resumes saved GitHub input after a successful board turn: %s": 1481,
"retains a confirmation committed while another settlement is in flight": 1699,
"retains a contended pre-run FIFO projection and settles cancelled input without a visible notice": 347,
"retains a failed accepted-response attempt across drain and retries after resume": 445,
"retains a retry final when its source authorization read fails transiently": 534,
"retains a standalone unaddressed Slack thread reply for the bounded reorder window": 489,
"retains admission committed while an empty inbound-notice selection is returning": 449,
"retains an accepted-response deadline that elapses during the locked recovery check": 402,
"retains an exact chat retry through a transient scheduling failure and a lost committed receipt acknowledgement": 350,
"retains content-free GitHub source invalidation after actor revocation and denies stale retry after regrant": 958,
"retains HTTP Retry under the endpoint authorization row lock: %s": 3713,
"retains inbound notices through %s during drain without passive SQL": 1315,
"retains one HTTP task Retry intent while saved chat identity authorization is busy": 1296,
"retains only a source invalidation for a Telegram edit when the original actor's link is revoked": 602,
"retains the first accepted-response wake through idle drain without passive SQL": 465,
"retains the service idle probe after failed $name retirement and shutdown until owner retry": 956,
"retires a Discord receipt after terminal failure without letting an add retry resurrect it": 527,
"retires a pre-run FIFO notice with the exact promoted %s run even before a working update": 1306,
"retires a stale verifying receipt before another fixture runs recovery": 690,
"retires an already-visible pre-run FIFO notice once without publishing scheduler failures": 503,
"retires only the exact Slack final's receipt (%s)": 2187,
"retires only the exact Telegram final receipt through the pinned adapter (%s)": 2684,
"retires only the removed source's pre-run FIFO notice after its surviving batch promotes": 676,
"retires superseded credentials and clears endpoint-owned secrets on removal": 289,
"retries a colliding company fixture prefix and creates a distinct complete fixture": 72,
"retries a contended committed review response before transport, then publishes it and its files once": 1547,
"retries a contended pre-run FIFO receipt before I/O and observes cancellation after the lock releases": 448,
"retries a durable lifecycle row without treating it as a message delivery": 175,
"retries a fully recorded never-dispatched $provider setup through HTTP: $mode": 13493,
"retries an accepted inbound wake outbox in FIFO order without blocking other conversations": 740,
"retries an authenticated GitHub request after isolated-directory validation failed before allocation: %s": 24684,
"retries an exact GitHub source denied by pre-provider reviewed attestation without rewriting its failure": 487,
"retries credential cleanup after archival made a remove partially complete": 333,
"retries failed chat execution authorization after actual %s lock contention": 17188,
"retries lifecycle mutation atomically and reclaims it after restart": 1040,
"retries only the original pre-provider Telegram request after exact cleanup: $mode ($errorMessage)": 11958,
"retries pre-transport attachment integrity failures without blocking another conversation": 1267,
"retries saved GitHub input after a successful run without replaying that run": 862,
"retries saved GitHub input after an endpoint admission lock collision": 31953,
"retries the exact failed %s chat input with a new idempotent admission": 789,
"retries the newer saved $provider request instead of the failed request after a budget hold: $mode": 91979,
"retries the saved board-message turn in a connected task after environment qualification failed before provider startup": 4463,
"retries transient GitHub endpoint lock contention before accepting a wake": 768,
"returns a committed one-time GitHub setup secret after final lease loss when its exact ref remains current": 63,
"returns a failed link-only interaction continuation to its GitHub thread": 841,
"returns a retryable webhook failure when the delivery insert fails before durable receipt": 1074,
"returns ephemeral guidance for exact Slack controls in channels without creating tasks or actions": 362,
"returns not found rather than revealing another company's chat endpoint": 47,
"returns two answered Slack turns to Idle in the same thread (DM=%s)": 1533,
"reuses a pre-run FIFO notice when the successor asks before its working milestone": 427,
"reveals a rotated GitHub secret despite a later completion-audit failure and makes retry a new rotation": 1088,
"revokes a deleted canonical GitHub installation and recovers the same endpoint after reinstall": 3212,
"rotates a live GitHub webhook secret fail-closed and reconnects with stored credentials": 551,
"rotates Microsoft Teams secrets without changing bot identity and preserves the last good credentials on rejection": 309,
"round-trips a $label question modal and durably acknowledges denied or replayed tokens": 2486,
"safely re-arms an exact terminal GitHub delivery after an operator redelivery": 358,
"saves Slack communication instructions with validation, company isolation, and audit attribution": 139,
"scopes board-send idempotency to one external conversation": 1082,
"scopes failed retry notices and retains receipt contention without retrying settled history": 831,
"scopes Slack setup %s detection to the linked user and current test": 520,
"scopes Telegram publication failure from $label correctly": 1293,
"segments long Telegram output into durable FIFO publications and resumes at the failed part": 833,
"selects the Telegram photo boundary before provider I/O (%s)": 10801,
"sends Telegram audio and video outside native format contracts as exact original documents": 787,
"separates verified webhook ingress from board identity links for every webhook provider": 213,
"serializes a GitHub secret rotation racing reconnect and preserves the rotated secret": 893,
"serializes and caps an agent run's selected Discord files before final handoff": 2174,
"serializes concurrent GitHub setup-secret requests without losing stored credentials": 1067,
"serializes Discord Gateway health events and recovers transient guild outages": 203,
"serializes duplicate Slack admission with an owned provider-reply settlement: %s": 871,
"serializes recovered Telegram maintenance behind credential rotation": 334,
"serializes setup activation ahead of a concurrent reconnect without overwriting the newer runtime": 728,
"settles a refused GitHub task Retry by its own gates: %s": 3796,
"settles a retried Slack receipt reaction when the provider reports already_reacted": 240,
"settles a shared-endpoint accepted-response backlog without retrying its own locks": 2694,
"settles an interrupted native run once without overwriting its successor": 675,
"settles GitHub self-update receipts without orphan retries for %s": 4030,
"settles rejected pre-acceptance intent and permits a later authorized external message": 463,
"settles responses on different endpoints for one principal without retrying its own identity lock: %s": 3964,
"singleflights concurrent cold GitHub runtime initialization": 473,
"skips a locked native progress %s while unrelated final and question publications deliver": 2910,
"skips a pre-run FIFO candidate with a noncanonical coalesced owner id (%s)": 850,
"skips paused outbox heads and resumes promptly without bypassing provider backoff": 602,
"sleeps behind an unresolved Slack tool send and wakes when its receipt settles": 380,
"snapshots channel workspace defaults on new tasks and preserves them on replies": 705,
"starts real Slack conversations from bare mentions and accepts same-thread follow-ups": 1221,
"stops a conversation drain after its lease renewal fails": 453,
"stops a Discord Gateway on lease loss and lets a standby take over": 542,
"stops automatic pre-ingress GitHub pagination at the epoch floor without adopting older failures": 324,
"stops starting continuation publications during %s": 3222,
"streams long output in bounded chunks after applying the safe external projection": 773,
"supplements Chat SDK with verified GitHub comment edit and delete lifecycle events": 1278,
"supplements verified Teams edit, soft-delete, and restore activities against the existing task": 1286,
"suppresses a pending pre-run FIFO notice after %s wins": 2789,
"suppresses a queued provider reply when destination reach is revoked before transport": 201,
"suppresses automatic pre-ingress GitHub redelivery for any existing local receipt (%s)": 1734,
"suppresses persisted GitHub queued, progress and completion comments on replay": 559,
"suppresses queued and working placeholders that terminalize while paused": 846,
"surfaces an attachment-only Telegram ingestion failure without waking the agent": 270,
"Teams authenticated inline-picture intake > ingests an actual pinned-parser %s picture into its exact admitted turn (%s)": 2783,
"Teams current file authority and composed Board transfer > deduplicates the same actual acceptance activity before and after file delivery": 788,
"Teams current file authority and composed Board transfer > durably accepts a callback inside the consent POST before the native receipt returns": 1102,
"Teams current file authority and composed Board transfer > freezes the original recipient at Board Send and publishes only after consent and exact-byte PUT": 1184,
"Teams current file authority and composed Board transfer > keeps the task-link fallback with no native file intent for %s": 2547,
"Teams current file authority and composed Board transfer > offers only exact conflict cancellation after valid Teams consent receipts disagree": 1166,
"Teams current file authority and composed Board transfer > rechecks revoked %s authority before acceptance and before PUT": 4582,
"Teams current file authority and composed Board transfer > rejects a retained old-runtime consent callback after normal pause and resume": 678,
"Teams current file authority and composed Board transfer > retries only fileInfo after a confirmed PUT and an explicitly resolved missing fileInfo receipt": 1189,
"Teams current file authority and composed Board transfer > stages native Board file consent on the first send from a cold reconstructed service": 844,
"Teams exact self-unknown source continuation > accepts the exact native file after a lost consent-card receipt without reposting": 1502,
"Teams exact self-unknown source continuation > does not exempt other unknown effects or changed native authority: %s": 4731,
"Teams exact self-unknown source continuation > retries only the confirmed native file-info stage with an exact audited phase/version, never its PUT": 2128,
"Teams file receipt API projection > does not consume a worker slot for a pending Teams transfer on a %s endpoint": 1542,
"Teams file receipt API projection > does not treat a caller-only transfer hint as ordinary delivery authority": 81,
"Teams file receipt API projection > generic publication worker ignores an existing %s Teams transfer on an active endpoint": 1024,
"Teams file receipt API projection > keeps a cancelled head locked while a consent-card receipt waits for the file tail": 82,
"Teams file receipt API projection > never projects a transfer from another conversation into Activity": 163,
"Teams file receipt API projection > offers only the exact %s stage actions": 253,
"Teams file receipt API projection > preserves all-published legacy batches without transfer metadata and excludes other comments": 69,
"Teams file receipt API projection > projects mixed delivered, declined, expired and cancelled file outcomes without making GET effects": 92,
"Teams file receipt API projection > refuses generic replay of a failed transfer without another provider attempt": 107,
"Teams file receipt API projection > refuses generic resolution with %s transfer preconditions without changing receipts": 527,
"Teams file receipt API projection > refuses terminal success or actions for %s": 389,
"Teams file receipt API projection > requires exact endpoint, conversation, publication and Board company scope": 132,
"Teams inline picture publication > keeps $surface picture delivery truthful for $outcome": 7050,
"Teams personal-recipient admission and durable restart > does not invent personal recipient proof when an AAD-only legacy delivery resumes without original runtime evidence": 233,
"Teams personal-recipient admission and durable restart > preserves actual-parser personal recipient proof across database admission and reconstructed restart": 239,
"Teams personal-recipient admission and durable restart > redacts a rejected personal destination instead of persisting its derived recipient proof": 143,
"Telegram callback-only native private responses > cancels a queued private callback notice after %s changes without public fallback": 772,
"Telegram callback-only native private responses > does not rebind a retained callback denial to another %s": 584,
"Telegram callback-only native private responses > does not refresh the callback deadline after service runtime-readiness waits": 127,
"Telegram callback-only native private responses > does not treat another actor's private chat as a reply destination": 125,
"Telegram callback-only native private responses > preserves an authenticated exact-actor DM denial without native ephemeral or public fallback": 170,
"Telegram callback-only native private responses > quarantines missing private acceptance receipts and never retries them publicly": 147,
"Telegram callback-only native private responses > records an authenticated denial before its recipient-bound send and deduplicates the exact callback": 215,
"Telegram callback-only native private responses > retains an exact-actor DM proof across restart (expired=%s)": 380,
"Telegram callback-only native private responses > retains the original private callback deadline across restart (expired=%s)": 370,
"Telegram close-owned progress retirement > does not borrow an unrelated run's interaction as progress-consumer evidence": 707,
"Telegram close-owned progress retirement > does not guess a close edit for %s": 4374,
"Telegram close-owned progress retirement > does not reclaim a progress lane consumed by a $state $kind prompt": 3239,
"Telegram close-owned progress retirement > keeps close uncommitted after %s of its retirement edit": 1432,
"Telegram close-owned progress retirement > preserves an attempted unknown %s after public operator cancellation": 1608,
"Telegram close-owned progress retirement > preserves an authored final that wins while close is admitted": 648,
"Telegram close-owned progress retirement > qualifies $provider close-owned progress retirement ($mode)": 7083,
"Telegram close-owned progress retirement > retires a status-interleaved working lane": 856,
"Telegram close-owned progress retirement > retires one working lane on close without cancelling the run or publishing its late final": 1054,
"Telegram close-owned progress retirement > treats a $state consumer with $attempts attempts conservatively": 1256,
"Telegram current rich inbound compatibility > keeps rich files and omissions scoped through lifecycle recovery (%s)": 1272,
"Telegram current rich inbound compatibility > retains current rich content through the pinned parser and service (%s)": 938,
"Telegram durable private draft Stop > automatically repairs an existing %s subscription after restart without dropping updates": 6559,
"Telegram durable private draft Stop > commits chat connection credentials atomically before waking maintenance": 612,
"Telegram durable private draft Stop > does not confirm a subscription from non-boolean ok=%s": 1288,
"Telegram durable private draft Stop > does not reuse an old draft ID after endpoint cascade deletion and same-bot re-binding": 1474,
"Telegram durable private draft Stop > does not withdraw an unowned or already-claimed final (%s)": 4326,
"Telegram durable private draft Stop > durably stops during the first draft RPC without cancelling a run, and never reuses its ID after restart": 894,
"Telegram durable private draft Stop > keeps ordinary output when automatic subscription repair is unsafe: %s": 6669,
"Telegram durable private draft Stop > parks pending Telegram subscription repair while its %s is inactive": 3861,
"Telegram durable private draft Stop > preserves an uncertain final after restart and a late Stop without automatic replay": 647,
"Telegram durable private draft Stop > recovers Telegram maintenance from committed work and becomes SQL quiet: %s": 10717,
"Telegram durable private draft Stop > refuses a retained Stop and later final after current %s authority changes": 2518,
"Telegram durable private draft Stop > retries an unknown subscription mutation after restart using freshly observed options, not a recovered confirmation flag": 1143,
"Telegram durable private draft Stop > returns 503 on failed Stop commit and accepts the exact verified retry before final send": 762,
"Telegram durable private draft Stop > sends ordinary complete output without Stop when subscription proof is %s": 4661,
"Telegram retained zero-message admission > recovers only ordinary source identity ($state / command=$command / $source)": 3408,
"Telegram source-bound optional media > imports exact permitted bytes or gives accurate recovery advice (%s)": 1872,
"Telegram source-bound optional media > retains exact durable media authority across restart (%s)": 842,
"tracks Slack callback surfaces independently and reports public URL drift": 261,
"tracks the actual Board Teams claim and retires recovery when its receipt commits": 1579,
"treats D-prefixed Slack status, new, and close callbacks as DM task controls even when the SDK flag is false": 877,
"turns a Slack slash command into a new native thread and one Paperclip task": 345,
"uses a live Cloud claim after chat service startup (ingress: %s)": 191,
"uses compact single-use Telegram action tokens and filters forged, expired, and oversized callbacks": 984,
"uses GitHub numeric user ids for linked authority and rechecks membership on every follow-up": 539,
"uses the Teams group-chat toggle without weakening channel resource gates": 498,
"wakes a failed retry notice only after %s cancellation commits": 1019,
"wakes a not-started retry notice after resumed admission is denied": 853,
"wakes a saved inbound notice when %s restores privacy access": 965,
"wakes a visible pre-run FIFO retirement only after %s commits": 4434,
"wakes accepted-response recovery from the real coordinator retry release": 559,
"wakes accepted-response recovery when its authenticated accepted-result journal arrives late": 2297,
"wakes an existing chat milestone when ordinary ingress reactivates its conversation": 1385,
"wakes chat dispatch after commit and refills free endpoint slots without the maintenance loop": 1416,
"wakes dormant accepted-response history from the real company membership restoration owner": 2388,
"wakes dormant accepted-response recovery after agent resume": 2343,
"wakes inbound notice retirement from a signed Slack Stop without a maintenance scan": 692,
"wakes interaction continuations from a committed response through %s": 10828,
"wakes parked Slack %s actions after board %s commits": 7018,
"wakes pre-run FIFO notices from real admission after quiet and becomes quiet again": 360,
"wakes saved native progress when %s restores eligibility": 5081,
"wakes Slack session sync from publication commit and leaves settled action queues quiet": 1543,
"withholds a committed one-time GitHub setup secret after final lease loss when its ref was superseded": 58,
"yields a %s inbound notice backlog between bounded passes without losing work": 6641
} }
} }
+29 -67
View File
@@ -1,54 +1,26 @@
import assert from "node:assert/strict"; import assert from "node:assert/strict";
import { spawnSync } from "node:child_process"; import { readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path"; import path from "node:path";
import { fileURLToPath } from "node:url"; import { fileURLToPath } from "node:url";
export const chatSuite = "server/src/__tests__/chat-channels.integration.test.ts"; export const chatSuitesPrefix = "server/src/__tests__/chat-channels/";
export const chatManifest = "scripts/chat-shard-durations.json"; export const chatManifest = "scripts/chat-shard-durations.json";
const comment = "Generated by node scripts/ci/refresh-chat-shard-durations.mjs from the CI profile test records of the PR chat jobs (profile-ci label). Per collected test entry, keyed by the name that vitest list reports: the summed duration of every case that entry runs, so an it.each line carries all its cases. Median across the given runs. scripts/test-line-shard.mjs uses these weights only to place source lines on chat partitions; they never change which tests run. Missing entries take the median weight."; const comment = "Per-file Vitest durations (ms) for server/src/__tests__/chat-channels/*.integration.test.ts used by scripts/run-vitest-stable.mjs (--group general-chat) to balance file-level shards via LPT. Missing files take the partitioner's median weight. Timing changes only partition work; they never skip a test.";
const placeholder = /%[sdifjo#%]|\$[A-Za-z_][\w.]*|\$\d+/;
function literalLength(name) { function isChatSuiteFile(file) {
return name.split(new RegExp(placeholder, "g")).join("").length; return typeof file === "string" && file.startsWith(chatSuitesPrefix) && file.endsWith(".test.ts");
} }
export function entryMatcher(entries) { function discoverChatSuites(repoRoot) {
const patterns = entries.map((name) => ({ const dir = path.join(repoRoot, chatSuitesPrefix);
name, return readdirSync(dir)
literal: literalLength(name), .filter((entry) => entry.endsWith(".test.ts"))
regex: new RegExp(`(?:^|> )${name.split(new RegExp(placeholder, "g")) .map((entry) => `${chatSuitesPrefix}${entry}`)
.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join(".*?")}$`, "s"), .sort((a, b) => a.localeCompare(b));
}));
return (caseName) => {
let best = null;
for (const pattern of patterns) {
if (!pattern.regex.test(caseName)) continue;
const exact = caseName === pattern.name || caseName.endsWith(` > ${pattern.name}`);
const score = [exact ? 1 : 0, pattern.literal];
if (!best || score[0] > best.score[0] || (score[0] === best.score[0] && score[1] > best.score[1])) {
best = { name: pattern.name, score };
}
}
return best?.name ?? null;
};
} }
export function entryDurations(entries, cases) { function profileFileDurations(directory) {
const match = entryMatcher(entries);
const totals = new Map(); const totals = new Map();
const unmatched = [];
for (const { name, duration } of cases) {
const entry = match(name);
if (entry === null) unmatched.push(name);
else totals.set(entry, (totals.get(entry) ?? 0) + duration);
}
return { totals, unmatched };
}
function profileCases(directory) {
const cases = [];
const walk = (dir) => { const walk = (dir) => {
for (const entry of readdirSync(dir)) { for (const entry of readdirSync(dir)) {
const file = path.join(dir, entry); const file = path.join(dir, entry);
@@ -57,45 +29,35 @@ function profileCases(directory) {
for (const line of readFileSync(file, "utf8").split("\n")) { for (const line of readFileSync(file, "utf8").split("\n")) {
if (!line.trim()) continue; if (!line.trim()) continue;
const record = JSON.parse(line); const record = JSON.parse(line);
if (record.kind !== "test" || record.file !== chatSuite) continue; if (record.kind !== "test" || !isChatSuiteFile(record.file)) continue;
assert.equal(typeof record.name, "string");
assert.ok(Number.isFinite(record.duration) && record.duration >= 0 && record.duration <= 3_600_000); assert.ok(Number.isFinite(record.duration) && record.duration >= 0 && record.duration <= 3_600_000);
if (record.status === "passed") cases.push({ name: record.name, duration: record.duration }); if (record.status === "passed") {
totals.set(record.file, (totals.get(record.file) ?? 0) + record.duration);
}
} }
} }
} }
}; };
walk(directory); walk(directory);
return cases; return totals;
} }
function collectedEntries(repoRoot) { export function chatManifestData(inventory, runs, sources) {
const directory = mkdtempSync(path.join(os.tmpdir(), "chat-durations-")); const known = new Set(inventory);
try {
const output = path.join(directory, "list.json");
const result = spawnSync("pnpm", ["exec", "vitest", "list", "--exclude", "**/dist/**", "--project", "@paperclipai/server",
chatSuite, "--allowOnly=false", "--includeTaskLocation", `--json=${output}`], { cwd: repoRoot, stdio: "inherit" });
assert.equal(result.status, 0, "vitest list failed");
return [...new Set(JSON.parse(readFileSync(output, "utf8")).map((test) => test.name))];
} finally {
rmSync(directory, { recursive: true, force: true });
}
}
export function chatManifestData(entries, runs, sources) {
const samples = new Map(); const samples = new Map();
for (const cases of runs) { for (const runTotals of runs) {
const { totals, unmatched } = entryDurations(entries, cases); for (const [file, ms] of runTotals) {
assert.equal(unmatched.length, 0, `Cases without a collected entry: ${unmatched.slice(0, 5).join(", ")}`); if (!known.has(file)) continue;
for (const [entry, ms] of totals) samples.set(entry, [...(samples.get(entry) ?? []), ms]); samples.set(file, [...(samples.get(file) ?? []), ms]);
}
} }
const durations = {}; const durations = {};
for (const [entry, values] of [...samples].sort(([a], [b]) => a.localeCompare(b))) { for (const [file, values] of [...samples].sort(([a], [b]) => a.localeCompare(b))) {
const sorted = values.sort((a, b) => a - b); const sorted = values.sort((a, b) => a - b);
const middle = Math.floor(sorted.length / 2); const middle = Math.floor(sorted.length / 2);
durations[entry] = Math.max(1, Math.round(sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2)); durations[file] = Math.max(1, Math.round(sorted.length % 2 ? sorted[middle] : (sorted[middle - 1] + sorted[middle]) / 2));
} }
return { $comment: comment, unit: "ms", sources, coverage: { measured: Object.keys(durations).length, entries: entries.length }, durations }; return { $comment: comment, unit: "ms", sources, coverage: { measured: Object.keys(durations).length, inventory: inventory.length }, durations };
} }
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
@@ -104,7 +66,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
const directories = args.filter((arg) => !arg.startsWith("--")); const directories = args.filter((arg) => !arg.startsWith("--"));
assert.ok(directories.length > 0, "Usage: refresh-chat-shard-durations.mjs [--source=<run url>] <profile artifact directory>..."); assert.ok(directories.length > 0, "Usage: refresh-chat-shard-durations.mjs [--source=<run url>] <profile artifact directory>...");
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", ".."); const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..");
const data = chatManifestData(collectedEntries(repoRoot), directories.map(profileCases), sources); const data = chatManifestData(discoverChatSuites(repoRoot), directories.map(profileFileDurations), sources);
writeFileSync(path.join(repoRoot, chatManifest), JSON.stringify(data, null, 2) + "\n"); writeFileSync(path.join(repoRoot, chatManifest), JSON.stringify(data, null, 2) + "\n");
console.log(`${chatManifest}: ${data.coverage.measured} of ${data.coverage.entries} entries measured`); console.log(`${chatManifest}: ${data.coverage.measured} of ${data.coverage.inventory} chat suites measured`);
} }
+7 -4
View File
@@ -44,7 +44,6 @@ export async function createTestSelection(plan, head) {
for (const job of ["general_tests", "verify_serialized_server"]) { for (const job of ["general_tests", "verify_serialized_server"]) {
if (plan.jobs[job].run) for (const entry of plan.jobs[job].matrix.include) groups.add(entry.group ?? "serialized"); if (plan.jobs[job].run) for (const entry of plan.jobs[job].matrix.include) groups.add(entry.group ?? "serialized");
} }
groups.delete("general-chat"); // Keep its line sharding and DB ownership intact.
const owners = {}, projects = new Set(), inventories = new Map(); const owners = {}, projects = new Set(), inventories = new Map();
const inventoryFor = group => { const inventoryFor = group => {
if (!inventories.has(group)) inventories.set(group, runnerInventory(group)); if (!inventories.has(group)) inventories.set(group, runnerInventory(group));
@@ -52,9 +51,12 @@ export async function createTestSelection(plan, head) {
}; };
for (const group of groups) { for (const group of groups) {
const inventory = inventoryFor(group); const inventory = inventoryFor(group);
if (group === "serialized" || group === "general-server-without-chat") { if (group === "serialized" || group === "general-server-without-chat" || group === "general-chat") {
owners[group] = { "@paperclipai/server": group === "serialized" owners[group] = { "@paperclipai/server": group === "serialized"
? inventory.selectedSerializedSuites : inventory.selectedGeneralServerSuites }; ? inventory.selectedSerializedSuites
: group === "general-chat"
? inventory.selectedChatSuites
: inventory.selectedGeneralServerSuites };
projects.add("@paperclipai/server"); projects.add("@paperclipai/server");
} else { } else {
owners[group] = Object.fromEntries(inventory.workspaceProjects.map((project) => [project, null])); owners[group] = Object.fromEntries(inventory.workspaceProjects.map((project) => [project, null]));
@@ -74,8 +76,9 @@ export async function createTestSelection(plan, head) {
if (server) { if (server) {
const general = inventoryFor("general-server-without-chat"); const general = inventoryFor("general-server-without-chat");
const native = inventoryFor("general-server-native-runner"); const native = inventoryFor("general-server-native-runner");
const chat = inventoryFor("general-chat");
assert.deepEqual([...general.selectedGeneralServerSuites, ...general.selectedSerializedSuites, assert.deepEqual([...general.selectedGeneralServerSuites, ...general.selectedSerializedSuites,
...native.selectedGeneralServerSuites, "server/src/__tests__/chat-channels.integration.test.ts"].sort(), ...native.selectedGeneralServerSuites, ...chat.selectedChatSuites].sort(),
server.inventory, "Server inventory must be completely covered by existing lane ownership"); server.inventory, "Server inventory must be completely covered by existing lane ownership");
} }
const excludedSuites = activeNightlySuitesForEnv(); const excludedSuites = activeNightlySuitesForEnv();
+2 -2
View File
@@ -3,8 +3,8 @@ import { createHash } from "node:crypto";
import { execFileSync } from "node:child_process"; import { execFileSync } from "node:child_process";
import { readFileSync, statSync } from "node:fs"; import { readFileSync, statSync } from "node:fs";
export const selectableGroups = ["general-server-without-chat", "general-workspaces-a", export const selectableGroups = ["general-server-without-chat", "general-chat",
"general-workspaces-b", "general-workspaces-c", "serialized"]; "general-workspaces-a", "general-workspaces-b", "general-workspaces-c", "serialized"];
export function selectionHash(manifest) { export function selectionHash(manifest) {
return createHash("sha256").update(JSON.stringify({ version: manifest.version, lanes: manifest.lanes })).digest("hex"); return createHash("sha256").update(JSON.stringify({ version: manifest.version, lanes: manifest.lanes })).digest("hex");
+1 -1
View File
@@ -24,7 +24,6 @@ export function refineTestPlan({ plan, head, owners, graphs, durations = {}, exc
const matrix = []; const matrix = [];
for (const group of groups) { for (const group of groups) {
const original = entries.filter((entry) => (entry.group ?? "serialized") === group); const original = entries.filter((entry) => (entry.group ?? "serialized") === group);
if (group === "general-chat") { matrix.push(...original); continue; }
const owned = owners[group]; const owned = owners[group];
assert.ok(owned, `Missing inventory owner: ${group}`); assert.ok(owned, `Missing inventory owner: ${group}`);
const projectByFile = new Map(); const projectByFile = new Map();
@@ -72,6 +71,7 @@ export function refineTestPlan({ plan, head, owners, graphs, durations = {}, exc
export function selectionDurations() { export function selectionDurations() {
return { return {
"general-server-without-chat": loadShardDurations("scripts/general-server-shard-durations.json"), "general-server-without-chat": loadShardDurations("scripts/general-server-shard-durations.json"),
"general-chat": loadShardDurations("scripts/chat-shard-durations.json"),
serialized: loadShardDurations("scripts/serialized-shard-durations.json"), serialized: loadShardDurations("scripts/serialized-shard-durations.json"),
}; };
} }
+18 -3
View File
@@ -10,9 +10,9 @@
} }
], ],
"coverage": { "coverage": {
"measured": 1573, "measured": 1588,
"withSetup": 1573, "withSetup": 1573,
"inventory": 1655 "inventory": 1670
}, },
"durations": { "durations": {
"server/scripts/build-config.test.mjs": 10828, "server/scripts/build-config.test.mjs": 10828,
@@ -183,7 +183,22 @@
"server/src/__tests__/case-history-api-discovery.test.ts": 5795, "server/src/__tests__/case-history-api-discovery.test.ts": 5795,
"server/src/__tests__/change-consent-gate.test.ts": 3035, "server/src/__tests__/change-consent-gate.test.ts": 3035,
"server/src/__tests__/chat-admission-condition.test.ts": 2827, "server/src/__tests__/chat-admission-condition.test.ts": 2827,
"server/src/__tests__/chat-channels.integration.test.ts": 428744, "server/src/__tests__/chat-channels/board-and-shared-core.integration.test.ts": 45011,
"server/src/__tests__/chat-channels/discord-modals-and-publications.integration.test.ts": 6507,
"server/src/__tests__/chat-channels/discord-setup-and-commands.integration.test.ts": 54809,
"server/src/__tests__/chat-channels/github-retry-and-recovery.integration.test.ts": 41634,
"server/src/__tests__/chat-channels/github-review-workflow.integration.test.ts": 171270,
"server/src/__tests__/chat-channels/github-setup-and-access.integration.test.ts": 20202,
"server/src/__tests__/chat-channels/github-webhook-recovery.integration.test.ts": 20859,
"server/src/__tests__/chat-channels/slack-ingress-and-threads.integration.test.ts": 9836,
"server/src/__tests__/chat-channels/slack-interactions-and-files.integration.test.ts": 28768,
"server/src/__tests__/chat-channels/slack-protocol.integration.test.ts": 8705,
"server/src/__tests__/chat-channels/slack-setup-and-registration.integration.test.ts": 42468,
"server/src/__tests__/chat-channels/teams-authority-and-transfer.integration.test.ts": 12088,
"server/src/__tests__/chat-channels/teams-ingress-and-media.integration.test.ts": 15672,
"server/src/__tests__/chat-channels/telegram-drafts-and-progress.integration.test.ts": 30015,
"server/src/__tests__/chat-channels/telegram-ingress-and-callbacks.integration.test.ts": 10615,
"server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts": 9966,
"server/src/__tests__/chat-completion-proof.test.ts": 3148, "server/src/__tests__/chat-completion-proof.test.ts": 3148,
"server/src/__tests__/chat-execution-defaults.test.ts": 6586, "server/src/__tests__/chat-execution-defaults.test.ts": 6586,
"server/src/__tests__/chat-failed-run-retry-boundary.test.ts": 9094, "server/src/__tests__/chat-failed-run-retry-boundary.test.ts": 9094,
+7 -19
View File
@@ -5,11 +5,9 @@ import { planTasks } from "../../.github/scripts/ci-plan.mjs";
import { productInputs } from "../../.github/scripts/ci-inputs.mjs"; import { productInputs } from "../../.github/scripts/ci-inputs.mjs";
import { selectionEligibility } from "../ci/select-tests.mjs"; import { selectionEligibility } from "../ci/select-tests.mjs";
const chatSuite = "server/src/__tests__/chat-channels.integration.test.ts";
function inventory(root, env, group) { function inventory(root, env, group) {
const args = group === "serialized" ? ["--mode", "serialized"] : ["--mode", "general", "--group", group]; const args = group === "serialized" ? ["--mode", "serialized"] : ["--mode", "general", "--group", group];
const shards = ["general-workspaces-b", "general-workspaces-c"].includes(group) ? [] const shards = ["general-workspaces-b", "general-workspaces-c", "general-chat"].includes(group) ? []
: ["--shard-index", "0", "--shard-count", "1"]; : ["--shard-index", "0", "--shard-count", "1"];
return JSON.parse(execFileSync(process.execPath, [path.join(root, "scripts/run-vitest-stable.mjs"), ...args, return JSON.parse(execFileSync(process.execPath, [path.join(root, "scripts/run-vitest-stable.mjs"), ...args,
...shards, "--dry-run"], { ...shards, "--dry-run"], {
@@ -29,7 +27,7 @@ export async function planVerification({ root, env, diff, full = false }) {
try { try {
const groups = [...new Set(["general_tests", "verify_serialized_server"].flatMap(job => const groups = [...new Set(["general_tests", "verify_serialized_server"].flatMap(job =>
coarse.jobs[job]?.run ? coarse.jobs[job].matrix.include.map(entry => entry.group ?? "serialized") : []))]; coarse.jobs[job]?.run ? coarse.jobs[job].matrix.include.map(entry => entry.group ?? "serialized") : []))];
const inventories = new Map(groups.filter(group => group !== "general-chat").map(group => [group, inventory(root, env, group)])); const inventories = new Map(groups.map(group => [group, inventory(root, env, group)]));
const projects = [...new Set([...inventories.values()].flatMap(value => value.workspaceProjects ?? ["@paperclipai/server"]))]; const projects = [...new Set([...inventories.values()].flatMap(value => value.workspaceProjects ?? ["@paperclipai/server"]))];
const { selectProjects } = await import("../ci/select-projects.mjs"); const { selectProjects } = await import("../ci/select-projects.mjs");
const graphs = await selectProjects({ root, projects, changed: productInputs(diff.changed), concurrency: 1, env }); const graphs = await selectProjects({ root, projects, changed: productInputs(diff.changed), concurrency: 1, env });
@@ -39,24 +37,15 @@ export async function planVerification({ root, env, diff, full = false }) {
if (uncovered.length) throw new Error(`Changes outside resolved test graphs: ${uncovered.join(", ")}`); if (uncovered.length) throw new Error(`Changes outside resolved test graphs: ${uncovered.join(", ")}`);
const byProject = new Map(graphs.map(graph => [graph.project, graph])); const byProject = new Map(graphs.map(graph => [graph.project, graph]));
const manifest = { version: 1, head: diff.head, lanes: {} }, jobs = [], selectedFiles = new Set(); 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) { for (const group of groups) {
if (group === "general-chat") {
scheduleChat();
continue;
}
const value = inventories.get(group); const value = inventories.get(group);
const owners = value.workspaceProjects const owners = value.workspaceProjects
? Object.fromEntries(value.workspaceProjects.map(project => [project, byProject.get(project).inventory])) ? Object.fromEntries(value.workspaceProjects.map(project => [project, byProject.get(project).inventory]))
: { "@paperclipai/server": group === "serialized" ? value.selectedSerializedSuites : value.selectedGeneralServerSuites }; : { "@paperclipai/server": group === "serialized"
? value.selectedSerializedSuites
: group === "general-chat"
? value.selectedChatSuites
: value.selectedGeneralServerSuites };
const reusable = {}, fresh = {}; const reusable = {}, fresh = {};
for (const [project, files] of Object.entries(owners)) { for (const [project, files] of Object.entries(owners)) {
const graph = byProject.get(project), all = new Set(graph.inventory), affected = new Set(graph.selected); const graph = byProject.get(project), all = new Set(graph.inventory), affected = new Set(graph.selected);
@@ -75,7 +64,6 @@ export async function planVerification({ root, env, diff, full = false }) {
cacheable: files === reusable, selected: true, args: ["--mode", group === "serialized" ? "serialized" : "general", cacheable: files === reusable, selected: true, args: ["--mode", group === "serialized" ? "serialized" : "general",
...(group === "serialized" ? [] : ["--group", group]), "--shard-index", String(index), "--shard-count", String(partitions.length)] }); ...(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)); const expected = new Set(graphs.flatMap(graph => graph.selected));
if (expected.size !== selectedFiles.size || [...expected].some(file => !selectedFiles.has(file))) { if (expected.size !== selectedFiles.size || [...expected].some(file => !selectedFiles.has(file))) {
throw new Error("Selected tests are not completely covered by local runner ownership"); throw new Error("Selected tests are not completely covered by local runner ownership");
+86 -123
View File
@@ -16,8 +16,6 @@ import {
import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs"; import { runUnderSharedPostgres, shouldWrapWithSharedPostgres } from "./ci/vitest-shared-postgres.mjs";
import { resolveServerParallelWorkers, resolveWorkspaceParallelWorkers } from "./ci/vitest-workers.mjs"; import { resolveServerParallelWorkers, resolveWorkspaceParallelWorkers } from "./ci/vitest-workers.mjs";
import { selectWorkspaceProjectsShard } from "./ci/workspaces-b-shard.mjs"; import { selectWorkspaceProjectsShard } from "./ci/workspaces-b-shard.mjs";
import { assertSelectedTests, partitionTestLines } from "./test-line-shard.mjs";
import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs"; import { loadSelection, selectedShard } from "./ci/test-selection-manifest.mjs";
const repoRoot = process.cwd(); const repoRoot = process.cwd();
@@ -97,7 +95,15 @@ const generalServerWithoutChatGroupName = "general-server-without-chat";
const generalServerWithoutChatOrNativeRunnerGroupName = "general-server-without-chat-or-native-runner"; const generalServerWithoutChatOrNativeRunnerGroupName = "general-server-without-chat-or-native-runner";
const generalChatGroupName = "general-chat"; const generalChatGroupName = "general-chat";
const generalServerNativeRunnerGroupName = "general-server-native-runner"; const generalServerNativeRunnerGroupName = "general-server-native-runner";
const chatSuite = "server/src/__tests__/chat-channels.integration.test.ts"; const chatSuitesPrefix = "server/src/__tests__/chat-channels/";
const legacyChatSuitePath = "server/src/__tests__/chat-channels.integration.test.ts";
function isChatChannelSuite(repoPath) {
return (
(repoPath.startsWith(chatSuitesPrefix) && repoPath.endsWith(".test.ts")) ||
repoPath === legacyChatSuitePath
);
}
// The first suite rebuilds the Runner release binaries with cargo in beforeAll. // The first suite rebuilds the Runner release binaries with cargo in beforeAll.
// Inside the PR workflow's plain server shards, which carry no Rust cache, // Inside the PR workflow's plain server shards, which carry no Rust cache,
// that build was a ~4m30s cold compile of every third-party crate on each run // that build was a ~4m30s cold compile of every third-party crate on each run
@@ -131,9 +137,6 @@ const nativeRunnerSuites = [
// than dropping the suite. // than dropping the suite.
const prWorkflowName = PR_WORKFLOW_NAME; const prWorkflowName = PR_WORKFLOW_NAME;
const nativeRunnerSuiteRunsInRustCachedLane = process.env.GITHUB_WORKFLOW === prWorkflowName; const nativeRunnerSuiteRunsInRustCachedLane = process.env.GITHUB_WORKFLOW === prWorkflowName;
const withoutChatExcludedSuites = nativeRunnerSuiteRunsInRustCachedLane
? [chatSuite, ...nativeRunnerSuites]
: [chatSuite];
const nightlyOnlySuitesPath = resolveNightlyOnlySuitesPath({ repoRoot }); const nightlyOnlySuitesPath = resolveNightlyOnlySuitesPath({ repoRoot });
const strictlySerialServerTests = new Set([]); const strictlySerialServerTests = new Set([]);
@@ -166,8 +169,14 @@ const generalServerGroups = [
generalServerWithoutChatOrNativeRunnerGroupName, generalServerWithoutChatOrNativeRunnerGroupName,
]; ];
function baseExcludedServerSuites(groupName) { function baseExcludedServerSuites(groupName) {
if (groupName === generalServerWithoutChatOrNativeRunnerGroupName) return [chatSuite, ...nativeRunnerSuites]; if (groupName === generalServerWithoutChatOrNativeRunnerGroupName) {
if (groupName === generalServerWithoutChatGroupName) return withoutChatExcludedSuites; return [...chatSuites, ...nativeRunnerSuites];
}
if (groupName === generalServerWithoutChatGroupName) {
return nativeRunnerSuiteRunsInRustCachedLane
? [...chatSuites, ...nativeRunnerSuites]
: [...chatSuites];
}
return []; return [];
} }
function excludedServerSuites(groupName) { function excludedServerSuites(groupName) {
@@ -236,38 +245,10 @@ function toServerPath(file) {
return path.relative(serverRoot, file).split(path.sep).join("/"); return path.relative(serverRoot, file).split(path.sep).join("/");
} }
// For a multi-line `it.each([...])("name", fn)` call, Vitest 5's `vitest
// list --includeTaskLocation` and `vitest run <file>:<line>` disagree about
// which line registers the test: `list` reports (and only matches) the line
// of the wrapped "name" argument, while `run` only matches the line above
// it, where Prettier's formatting puts that call's opening `(`. Separately,
// on this file `list` also occasionally invents an entry whose "location"
// sits on an ordinary body statement that merely ends in `)(` or starts a
// line with a quote, with no `it`/`test` call anywhere nearby — a bogus
// artifact of the same collector, not a real test. Both only showed up on
// server/src/__tests__/chat-channels.integration.test.ts, a 70,000+ line
// fixture; smaller files have not reproduced either issue.
//
// chatSuiteRunLine classifies a `list`-reported line against the actual
// source and returns the line `vitest run` accepts, or null if the line
// does not belong to any real `it`/`test` call (a bogus entry to drop).
const callAnywherePattern = /(?:^|[^\w$])(?:it|test)(?:\.(?:each|skip|only))?\(/;
const inlineCallPattern = /\)\(\s*["'`]/;
function chatSuiteRunLine(sourceLines, line) {
const text = (sourceLines[line - 1] ?? "").trim();
if (callAnywherePattern.test(text) || text.endsWith(")(") || inlineCallPattern.test(text)) {
return line;
}
const previous = (sourceLines[line - 2] ?? "").trim();
const isNameArgument = text.startsWith('"') || text.startsWith("'") || text.startsWith("`");
if (isNameArgument && previous.endsWith(")(")) {
return line - 1;
}
return null;
}
function isRouteOrAuthzTest(file) { function isRouteOrAuthzTest(file) {
if (isChatChannelSuite(file)) {
return false;
}
if (routeTestPattern.test(file)) { if (routeTestPattern.test(file)) {
return true; return true;
} }
@@ -479,56 +460,13 @@ function isolatedTestEnv() {
return { testRoot, env }; return { testRoot, env };
} }
async function collectVitestList(filters, { testRoot, env }, name) { async function runVitest(args, label, exactFiles = false) {
const output = path.join(testRoot, `${name}.json`);
await new Promise((resolve, reject) => {
const child = spawn("pnpm", ["exec", "vitest", "list", ...sourceOnlyVitestArgs,
...filters, "--allowOnly=false", "--includeTaskLocation", `--json=${output}`], {
cwd: repoRoot, env, stdio: "inherit",
});
child.once("error", (error) => reject(new Error(`Vitest collection failed: ${error.message}`)));
child.once("close", (code, signal) => {
if (code === 0) resolve();
else reject(new Error(`Vitest collection failed: ${signal ?? code}`));
});
});
return JSON.parse(readFileSync(output, "utf8"));
}
async function runVitest(args, label, testShard = null, exactFiles = false) {
console.log(`\n[test:run] ${label}`); console.log(`\n[test:run] ${label}`);
const isolated = isolatedTestEnv(); const isolated = isolatedTestEnv();
const { env } = isolated; const { env } = isolated;
if (testShard) {
const file = path.resolve(repoRoot, chatSuite);
const sourceLines = readFileSync(file, "utf8").split("\n");
const allCollected = testShard.collected ?? await collectVitestList(args, isolated, "all");
const collected = [];
const bogusCollected = [];
for (const test of allCollected) {
(chatSuiteRunLine(sourceLines, test.location.line) === null ? bogusCollected : collected).push(test);
}
if (bogusCollected.length > 0) {
console.warn(
`[test:run] dropping ${bogusCollected.length} bogus Vitest collection entr${bogusCollected.length === 1 ? "y" : "ies"} with no matching it()/test() call: ${bogusCollected.map((test) => `${test.location.line}:${JSON.stringify(test.name)}`).join(", ")}`,
);
}
const selected = partitionTestLines(collected, testShard.count, file, chatShardDurations)[testShard.index];
// Validate shard membership with the same `list`-reported lines that
// produced `selected`, then switch to the `run`-compatible lines only for
// the filters handed to the real `vitest run` below (see
// chatSuiteRunLine).
const validationFilters = selected.lines.map((line) => `${chatSuite}:${line}`);
const validationArgs = [...args.filter((arg) => arg !== chatSuite), ...validationFilters];
assertSelectedTests(selected.tests, await collectVitestList(validationArgs, isolated, "selected"), file);
console.log(`[test:run] chat shard ${testShard.index + 1}/${testShard.count}: ${selected.tests.length}/${collected.length} tests, ${selected.lines.length} source lines, ${Math.round(selected.weight / 1000)}s recorded; exact filter coverage verified`);
const runFilters = selected.lines.map((line) => `${chatSuite}:${chatSuiteRunLine(sourceLines, line)}`);
args = [...args.filter((arg) => arg !== chatSuite), ...runFilters, "--allowOnly=false"];
}
await new Promise((resolve, reject) => { await new Promise((resolve, reject) => {
const command = exactFiles ? process.execPath : "pnpm"; const command = exactFiles ? process.execPath : "pnpm";
const prefix = exactFiles ? [path.join(scriptsDir, "ci/run-selected-vitest.mjs")] : ["exec", "vitest", "run"]; const prefix = exactFiles ? [path.join(scriptsDir, "ci/run-selected-vitest.mjs")] : ["exec", "vitest", "run"];
// `vitest list` collection above never retries; only the run does.
const child = spawn(command, [...prefix, ...sourceOnlyVitestArgs, ...vitestRetryArgs(), ...args], { const child = spawn(command, [...prefix, ...sourceOnlyVitestArgs, ...vitestRetryArgs(), ...args], {
cwd: repoRoot, cwd: repoRoot,
env: invocationEnv("vitest", env), env: invocationEnv("vitest", env),
@@ -542,13 +480,20 @@ async function runVitest(args, label, testShard = null, exactFiles = false) {
}); });
} }
async function runGeneralSuites(routeTests, chatShards) { function selectChatSuites(shardIndex = null, shardCount = null) {
for (const shard of chatShards ?? []) { const active = chatSuites.filter((file) => !activeNightlyOnlySuites.has(file));
await runVitest(["--project", "@paperclipai/server", ...serializedServerVitestArgs, chatSuite], if (shardCount !== null && shardCount > 1) {
"chat integration test shard", shard); return selectGeneralServerShard(active, shardIndex, shardCount, chatShardDurations);
}
return active;
}
async function runGeneralSuites(routeTests, isolateChat) {
if (isolateChat) {
await runGeneralGroup(routeTests, generalChatGroupName, null, null);
} }
for (const groupName of generalGroupNames) { for (const groupName of generalGroupNames) {
await runGeneralGroup(routeTests, groupName, null, null, chatShards ? [chatSuite] : []); await runGeneralGroup(routeTests, groupName, null, null, isolateChat ? chatSuites : []);
} }
} }
@@ -568,14 +513,6 @@ async function runProjectGroup(projects, groupName, shardIndex = null, shardCoun
await runVitest([...projectArgs, ...excludeArgs, ...shardArgs, ...extraArgs], label); await runVitest([...projectArgs, ...excludeArgs, ...shardArgs, ...extraArgs], label);
} }
function chatShardWorkers(index, count) {
const workers = count > 1 && !hasSharedTestDatabase && !options.serialChat ? 3 : 1;
return Array.from({ length: workers }, (_, offset) => ({
index: (index ?? 0) * workers + offset,
count: (count ?? 1) * workers,
}));
}
function groupUsesPostgres(opts, sel) { function groupUsesPostgres(opts, sel) {
if (sel) { if (sel) {
return Boolean(sel["@paperclipai/server"]?.length || sel["@paperclipai/db"]?.length); return Boolean(sel["@paperclipai/server"]?.length || sel["@paperclipai/db"]?.length);
@@ -602,6 +539,9 @@ function hasScheduledSuitesForRun(opts, sel) {
if (opts.mode === serializedModeName) { if (opts.mode === serializedModeName) {
return selectSerializedSuites(activeRouteTests, opts.shardIndex, opts.shardCount).length > 0; return selectSerializedSuites(activeRouteTests, opts.shardIndex, opts.shardCount).length > 0;
} }
if (opts.mode === generalModeName && opts.group === generalChatGroupName) {
return selectChatSuites(opts.shardIndex, opts.shardCount).length > 0;
}
if (opts.mode === generalModeName && opts.group === generalServerNativeRunnerGroupName) { if (opts.mode === generalModeName && opts.group === generalServerNativeRunnerGroupName) {
return activeNativeRunnerSuites().length > 0; return activeNativeRunnerSuites().length > 0;
} }
@@ -618,16 +558,21 @@ function hasScheduledSuitesForRun(opts, sel) {
async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCount = null, additionalExcludedSuites = []) { async function runGeneralGroup(routeTests, groupName, shardIndex = null, shardCount = null, additionalExcludedSuites = []) {
if (groupName === generalChatGroupName) { if (groupName === generalChatGroupName) {
// Each invocation gets its own temporary home and disposable PostgreSQL database. const shardFiles = selectChatSuites(shardIndex, shardCount);
// Wait for all children even on failure so no sibling is abandoned. const shardSuffix = shardCount !== null && shardCount > 1 ? ` shard ${shardIndex + 1}/${shardCount}` : "";
const args = ["--project", "@paperclipai/server", ...serializedServerVitestArgs, chatSuite]; console.log(
const workers = chatShardWorkers(shardIndex, shardCount); `\n[test:run] general-chat${shardSuffix} running ${shardFiles.length} of ${chatSuites.length} suites`,
const collected = await collectVitestList(args, isolatedTestEnv(), "all"); );
const results = await Promise.allSettled(workers.map((shard) => if (shardFiles.length === 0) {
runVitest(args, "chat integration test shard", { ...shard, collected }), return;
)); }
const failed = results.find((result) => result.status === "rejected"); const parallelArgs = hasSharedTestDatabase || options.serialChat
if (failed) throw failed.reason; ? ["--pool=forks", "--isolate", ...serializedServerVitestArgs]
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`];
await runVitest(
["--project", "@paperclipai/server", ...parallelArgs, ...shardFiles],
`general-chat${shardSuffix}`,
);
return; return;
} }
if (groupName === generalServerNativeRunnerGroupName) { if (groupName === generalServerNativeRunnerGroupName) {
@@ -799,7 +744,14 @@ async function runSerializedSuites(suites, shardIndex, shardCount) {
} }
} }
const routeTests = walk(serverTestsDir) const allServerTestFiles = walk(serverTestsDir);
const chatSuites = allServerTestFiles
.map((file) => toRepoPath(file))
.filter((repoPath) => isChatChannelSuite(repoPath))
.sort((a, b) => a.localeCompare(b));
const chatSuiteSet = new Set(chatSuites);
const routeTests = allServerTestFiles
.filter((file) => isRouteOrAuthzTest(toRepoPath(file))) .filter((file) => isRouteOrAuthzTest(toRepoPath(file)))
.map((file) => ({ .map((file) => ({
repoPath: toRepoPath(file), repoPath: toRepoPath(file),
@@ -827,16 +779,24 @@ const generalServerTestFiles = [
.sort((a, b) => a.localeCompare(b)); .sort((a, b) => a.localeCompare(b));
const options = parseCliOptions(process.argv.slice(2)); const options = parseCliOptions(process.argv.slice(2));
const selectionProjects = options.mode === serializedModeName || generalServerGroups.includes(options.group) const selectionProjects =
? ["@paperclipai/server"] options.mode === serializedModeName ||
: options.group === generalWorkspacesAGroupName ? generalWorkspacesAProjects generalServerGroups.includes(options.group) ||
: options.group === generalWorkspacesBGroupName ? generalWorkspacesBProjects options.group === generalChatGroupName
: options.group === generalWorkspacesCGroupName ? generalWorkspacesCProjects : []; ? ["@paperclipai/server"]
: options.group === generalWorkspacesAGroupName ? generalWorkspacesAProjects
: options.group === generalWorkspacesBGroupName ? generalWorkspacesBProjects
: options.group === generalWorkspacesCGroupName ? generalWorkspacesCProjects : [];
const selection = process.env.PAPERCLIP_CI_TEST_SELECTION const selection = process.env.PAPERCLIP_CI_TEST_SELECTION
? selectedShard(loadSelection(), options, selectionProjects) : null; ? selectedShard(loadSelection(), options, selectionProjects) : null;
if (selection?.["@paperclipai/server"]) { if (selection?.["@paperclipai/server"]) {
const owned = new Set(options.mode === serializedModeName ? routeTests.map((test) => test.repoPath) const owned = new Set(
: generalServerTestFiles.filter((file) => !baseExcludedServerSuites(options.group).includes(file))); options.mode === serializedModeName
? routeTests.map((test) => test.repoPath)
: options.group === generalChatGroupName
? chatSuites
: generalServerTestFiles.filter((file) => !baseExcludedServerSuites(options.group).includes(file)),
);
for (const file of selection["@paperclipai/server"]) { for (const file of selection["@paperclipai/server"]) {
if (!owned.has(file)) fail(`Selected test belongs to another server lane: ${file}`); if (!owned.has(file)) fail(`Selected test belongs to another server lane: ${file}`);
} }
@@ -850,9 +810,7 @@ if (selection && options.dryRun) {
writeFileSync(1, JSON.stringify({ selection })); writeFileSync(1, JSON.stringify({ selection }));
process.exit(0); process.exit(0);
} }
const defaultChatShards = !selection && options.group === null && options.mode !== serializedModeName && !hasSharedTestDatabase const isolateDefaultChat = !selection && options.group === null && options.mode !== serializedModeName && !hasSharedTestDatabase && chatSuites.length > 0;
? Array.from({ length: 6 }, (_, index) => ({ index, count: 6 }))
: null;
function dryRunExcludedNightlySuites() { function dryRunExcludedNightlySuites() {
if (activeNightlyOnlySuites.size === 0) { if (activeNightlyOnlySuites.size === 0) {
@@ -903,8 +861,8 @@ if (options.dryRun) {
selectedSerializedSuites: serializedSuites.map((routeTest) => routeTest.repoPath), selectedSerializedSuites: serializedSuites.map((routeTest) => routeTest.repoPath),
generalServerSuiteCount: generalServerTestFiles.length, generalServerSuiteCount: generalServerTestFiles.length,
selectedGeneralServerSuites: selectedGeneralServerSuites:
defaultChatShards isolateDefaultChat
? generalServerTestFiles.filter(file => file !== chatSuite) ? generalServerTestFiles.filter((file) => !chatSuiteSet.has(file))
: options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName : options.mode === generalModeName && options.group === generalServerNativeRunnerGroupName
? activeNativeRunnerSuites() ? activeNativeRunnerSuites()
: options.mode === generalModeName && : options.mode === generalModeName &&
@@ -917,8 +875,13 @@ if (options.dryRun) {
generalServerShardDurations, generalServerShardDurations,
) )
: null, : null,
chatVitestShards: options.group === generalChatGroupName chatSuiteCount: chatSuites.length,
? chatShardWorkers(options.shardIndex, options.shardCount) : defaultChatShards, selectedChatSuites:
options.group === generalChatGroupName
? selectChatSuites(options.shardIndex, options.shardCount)
: isolateDefaultChat
? chatSuites
: null,
workspaceProjects: workspaceProjects:
options.group === generalWorkspacesAGroupName options.group === generalWorkspacesAGroupName
? generalWorkspacesAProjects ? generalWorkspacesAProjects
@@ -963,14 +926,14 @@ try {
? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("serialized")}`] ? ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("serialized")}`]
: ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`]; : ["--pool=forks", "--isolate", "--fileParallelism", `--maxWorkers=${resolveWorkers("general")}`];
await runVitest(["--project", project, ...serverArgs, ...files], await runVitest(["--project", project, ...serverArgs, ...files],
`selected ${project}: ${files.length} files`, null, true); `selected ${project}: ${files.length} files`, true);
} }
} else { } else {
if (options.mode === generalModeName || options.mode === allModeName) { if (options.mode === generalModeName || options.mode === allModeName) {
if (options.group) { if (options.group) {
await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount); await runGeneralGroup(routeTests, options.group, options.shardIndex, options.shardCount);
} else { } else {
await runGeneralSuites(routeTests, defaultChatShards); await runGeneralSuites(routeTests, isolateDefaultChat);
} }
} }
@@ -12,7 +12,7 @@ const output = path.resolve(process.argv[2] ?? mkdtempSync(path.join(tmpdir(), "
mkdirSync(output, { recursive: true }); mkdirSync(output, { recursive: true });
assert.equal(existsSync(path.join(output, "pairs.jsonl")), false, "Use a fresh output directory"); assert.equal(existsSync(path.join(output, "pairs.jsonl")), false, "Use a fresh output directory");
const baseline = "82c033ed127d07862e6765aa4b69a3cf339bde81"; const baseline = "82c033ed127d07862e6765aa4b69a3cf339bde81";
const integration = "server/src/__tests__/chat-channels.integration.test.ts"; const integration = "server/src/__tests__/chat-channels/telegram-media-and-recovery.integration.test.ts";
const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" }); const git = (...args) => execFileSync("git", args, { cwd: root, encoding: "utf8" });
assert.equal(git("status", "--porcelain").trim(), "", "Commit fixture changes first; use an isolated checkout"); assert.equal(git("status", "--porcelain").trim(), "", "Commit fixture changes first; use an isolated checkout");
const original = readFileSync(path.join(root, integration), "utf8"); const original = readFileSync(path.join(root, integration), "utf8");
@@ -30,7 +30,7 @@ const benchmark = String.raw` it("measures equivalent completed accepted-respon
const { appendFileSync } = await import("node:fs"); const { appendFileSync } = await import("node:fs");
const output = process.env.PAPERCLIP_PRESENTATION_BENCHMARK_OUTPUT; const output = process.env.PAPERCLIP_PRESENTATION_BENCHMARK_OUTPUT;
if (!output) throw new Error("Benchmark output directory is required"); if (!output) throw new Error("Benchmark output directory is required");
const { nativeResponsePresentationWork: baselineWork } = await import("../services/native-runtime/native-response-presentation-work.baseline.js"); const { nativeResponsePresentationWork: baselineWork } = await import("../../services/native-runtime/native-response-presentation-work.baseline.js");
const { createDatabaseResponseCapture, installDatabaseResponseCapture } = await import("@paperclipai/db/response-capture"); const { createDatabaseResponseCapture, installDatabaseResponseCapture } = await import("@paperclipai/db/response-capture");
const schema = await import("@paperclipai/db"); const schema = await import("@paperclipai/db");
appendFileSync(output + "/child-runtime.jsonl", appendFileSync(output + "/child-runtime.jsonl",
+1 -1
View File
@@ -34,7 +34,7 @@ const env = {
SLACK_GATE_PROCESS_LOG: process.env.SLACK_GATE_PROCESS_LOG, SLACK_GATE_PROCESS_LOG: process.env.SLACK_GATE_PROCESS_LOG,
}; };
const child = spawn(process.execPath, ['--require', guard, vitest, 'run', const child = spawn(process.execPath, ['--require', guard, vitest, 'run',
'src/__tests__/chat-channels.integration.test.ts', '--testNamePattern', testNamePattern, '--maxWorkers=1', '--no-file-parallelism', `--execArgv=--require=${guard}`], 'src/__tests__/chat-channels/slack-protocol.integration.test.ts', '--testNamePattern', testNamePattern, '--maxWorkers=1', '--no-file-parallelism', `--execArgv=--require=${guard}`],
{ cwd: server, env, stdio: 'inherit' }); { cwd: server, env, stdio: 'inherit' });
for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal)); for (const signal of ['SIGINT', 'SIGTERM']) process.on(signal, () => child.kill(signal));
child.on('error', error => { console.error(error); process.exitCode = 1; }); child.on('error', error => { console.error(error); process.exitCode = 1; });
@@ -0,0 +1,32 @@
import { describe, expect, it } from "vitest";
import { randomAgentAppearance } from "@paperclipai/shared";
import { configPatchFromSnapshot } from "../lib/agent-records.js";
const baseSnapshot = {
name: "Agent",
role: "engineer",
adapterType: "process",
budgetMonthlyCents: 0,
};
describe("configPatchFromSnapshot", () => {
it("restores icon and appearance from the snapshot", () => {
const appearance = randomAgentAppearance();
const patch = configPatchFromSnapshot({ ...baseSnapshot, icon: "bot", appearance });
expect(patch.icon).toBe("bot");
expect(patch.appearance).toEqual(appearance);
});
it("restores a null icon", () => {
expect(configPatchFromSnapshot({ ...baseSnapshot, icon: null }).icon).toBeNull();
});
it("leaves icon and appearance out when the snapshot lacks valid values", () => {
const patch = configPatchFromSnapshot({ ...baseSnapshot, icon: 5, appearance: { bad: true } });
expect(patch).not.toHaveProperty("icon");
expect(patch).not.toHaveProperty("appearance");
const legacy = configPatchFromSnapshot(baseSnapshot);
expect(legacy).not.toHaveProperty("icon");
expect(legacy).not.toHaveProperty("appearance");
});
});
@@ -3,7 +3,7 @@ import { randomUUID } from "node:crypto";
import { readFile } from "node:fs/promises"; import { readFile } from "node:fs/promises";
import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { eq, sql } from "drizzle-orm"; import { eq, sql } from "drizzle-orm";
import { agents, companies, createDb } from "@paperclipai/db"; import { agentConfigRevisions, agents, companies, createDb } from "@paperclipai/db";
import { agentAppearanceSchema, appearanceForPalette, legacyAgentAppearance } from "@paperclipai/shared"; import { agentAppearanceSchema, appearanceForPalette, legacyAgentAppearance } from "@paperclipai/shared";
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js"; import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
import { agentService } from "../services/agents.js"; import { agentService } from "../services/agents.js";
@@ -38,6 +38,49 @@ describe("persisted agent personas", () => {
const [row] = await db.select().from(agents).where(eq(agents.id, original.id)); const [row] = await db.select().from(agents).where(eq(agents.id, original.id));
expect(row.appearance).toEqual(appearance); expect(row.appearance).toEqual(appearance);
}); });
it("restores the revision's icon and appearance on rollback and records them in the rollback revision", async () => {
const service = agentService(db);
const appearance = appearanceForPalette("arctic-blue");
const newerAppearance = appearanceForPalette("cherry-pop");
const original = await createAgentLifecycle(db).requestHire(companyId, { name: "Restored persona", role: "engineer", adapterType: "process", icon: "bot", appearance });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await service.update(original.id, { title: "Second", icon: "brain", appearance: newerAppearance });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored).toMatchObject({ title: "First", icon: "bot", appearance });
const [row] = await db.select().from(agents).where(eq(agents.id, original.id));
expect(row).toMatchObject({ icon: "bot", appearance });
const [rollbackRevision] = await service.listConfigRevisions(original.id);
expect(rollbackRevision.source).toBe("rollback");
expect(rollbackRevision.changedKeys).toEqual(expect.arrayContaining(["icon", "appearance"]));
expect(rollbackRevision.afterConfig).toMatchObject({ title: "First", icon: "bot", appearance });
});
it("clears the icon when the rolled back revision recorded no icon", async () => {
const service = agentService(db);
const original = await createAgentLifecycle(db).requestHire(companyId, { name: "Iconless persona", role: "engineer", adapterType: "process", icon: null });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await service.update(original.id, { icon: "brain" });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored?.icon).toBeNull();
});
it.each([
["missing", (config: Record<string, unknown>) => {
const { icon: _icon, appearance: _appearance, ...rest } = config;
return rest;
}],
["invalid", (config: Record<string, unknown>) => ({ ...config, icon: 42, appearance: { paletteId: "not-a-palette" } })],
])("keeps the current icon and appearance when the revision's values are %s", async (kind, rewrite) => {
const service = agentService(db);
const newerAppearance = appearanceForPalette("cherry-pop");
const original = await createAgentLifecycle(db).requestHire(companyId, { name: `Older revision ${kind}`, role: "engineer", adapterType: "process", icon: "bot", appearance: appearanceForPalette("arctic-blue") });
await service.update(original.id, { title: "First" }, { recordRevision: { source: "test" } });
const [revision] = await service.listConfigRevisions(original.id);
await db.update(agentConfigRevisions).set({ afterConfig: rewrite(revision.afterConfig) }).where(eq(agentConfigRevisions.id, revision.id));
await service.update(original.id, { title: "Second", icon: "brain", appearance: newerAppearance });
const restored = await service.rollbackConfigRevision(original.id, revision.id, {});
expect(restored).toMatchObject({ title: "First", icon: "brain", appearance: newerAppearance });
});
it("backfills legacy IDs with exactly the same persisted identity as the runtime fallback", async () => { it("backfills legacy IDs with exactly the same persisted identity as the runtime fallback", async () => {
const ids = Array.from({ length: 20 }, () => randomUUID()); const ids = Array.from({ length: 20 }, () => randomUUID());
await db.insert(agents).values(ids.map((id, i) => ({ id, companyId, name: `Legacy ${i}`, role: "engineer", appearance: null, icon: "bot" }))); await db.insert(agents).values(ids.map((id, i) => ({ id, companyId, name: `Legacy ${i}`, role: "engineer", appearance: null, icon: "bot" })));
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,817 @@
// Shared GitHub endpoint, webhook, and pre-ingress fixture helpers.
import { githubChatManagementService } from "../../services/chat-github-management.js";
import { syncGitHubBotTools } from "../../services/chat-github-tools.js";
import { createHmac, generateKeyPairSync, randomUUID } from "node:crypto";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { beforeAll, expect, it, vi } from "vitest";
import { chatActions, chatDeliveries, chatEndpoints, chatSdkState, issues } from "@paperclipai/db";
import { type ChatChannelServiceOptions, type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions } from "../../services/chat-sdk-runtime.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { type TestDb, FakeEndpointRuntime, FakeChatSdkRuntime, makeThread, makeMessage } from "./providers.js";
import type { ChatChannelHarness } from "./harness.js";
export function createGitHubHarness(h: ChatChannelHarness) {
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { seedCompany, readChatEndpointsById, createService, deliverMessage } = h;
function githubWebhookVerificationResponse(
service: ChatChannelService,
publicId: string,
webhookSecret: string,
providerDeliveryId = `github-setup-ping-${randomUUID()}`,
) {
const body = JSON.stringify({ zen: "Keep it logically awesome." });
const signature = createHmac("sha256", webhookSecret)
.update(body)
.digest("hex");
return service.handleWebhook(
publicId,
"github",
new Request(
`https://paperclip.example/api/chat-webhooks/${publicId}/github`,
{
method: "POST",
headers: {
"content-type": "application/json",
"x-github-delivery": providerDeliveryId,
"x-github-event": "ping",
"x-hub-signature-256": `sha256=${signature}`,
},
body,
},
),
);
}
async function recordGitHubWebhookVerification(
service: ChatChannelService,
publicId: string,
webhookSecret: string,
) {
const providerDeliveryId = `github-setup-ping-${randomUUID()}`;
const response = await githubWebhookVerificationResponse(
service,
publicId,
webhookSecret,
providerDeliveryId,
);
expect([200, 202]).toContain(response.status);
const action = await db
.select({ id: chatActions.id })
.from(chatActions)
.innerJoin(chatEndpoints, eq(chatEndpoints.id, chatActions.endpointId))
.where(
and(
eq(chatEndpoints.publicId, publicId),
eq(
chatActions.providerActionId,
`github_webhook_ingress:${providerDeliveryId}`,
),
),
)
.then((rows) => rows[0] ?? null);
if (action) {
await service.processPendingGitHubWebhookIngress(1, action.id);
}
await vi.waitFor(async () => {
const setup = await db
.select({ setup: chatEndpoints.setup })
.from(chatEndpoints)
.where(eq(chatEndpoints.publicId, publicId))
.then((rows) => rows[0]?.setup);
expect(setup).toMatchObject({ webhookVerifiedAt: expect.any(String) });
});
}
function signedGitHubWebhookRequest(input: {
delivery: string;
event: string;
payload: unknown;
webhookSecret: string;
url?: string;
}) {
const body = JSON.stringify(input.payload);
const signature = createHmac("sha256", input.webhookSecret)
.update(body)
.digest("hex");
return new Request(input.url ?? "https://paperclip.example/github", {
method: "POST",
headers: {
"content-type": "application/json",
"x-github-event": input.event,
"x-github-delivery": input.delivery,
"x-hub-signature-256": `sha256=${signature}`,
},
body,
});
}
async function configuredGitHubEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "deferWebhookProcessing"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookReplayBarrier"
| "githubWebhookResponseBudgetMs"
| "publicBaseUrl"
| "webhookPublicBaseUrl"
| "scheduleDeferredWork"
| "setupSecretActivityLogger"
| "setupSecretCredentialPersistBarrier"
| "receiptReactionTransportBarrier"
| "storage"
>
> & { wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"] } = {},
useVerifiedAppId = false,
registerWithManifest = false,
connectExistingApp = false,
interruptAppVault = false,
) {
let setupComplete = false;
const deferredSchedule = overrides.scheduleDeferredWork;
let installationId = 2468;
let additionalInstallationIds: number[] = [];
let installationAvailable = true;
let repositories = [
{
id: 97531,
full_name: "paperclipai/paperclip",
html_url: "https://github.com/paperclipai/paperclip",
owner: { id: 1357, login: "paperclipai" },
private: false,
},
];
let appPermissions: Record<string, string> = {
contents: "read",
checks: "write",
issues: "write",
metadata: "read",
pull_requests: "write",
};
let installationPermissions: Record<string, string> = {
contents: "read",
checks: "write",
issues: "write",
metadata: "read",
pull_requests: "write",
};
let appEvents = [
"pull_request",
"github_app_authorization",
"installation",
"installation_repositories",
"issue_comment",
"pull_request_review_comment",
];
const webhookSyncRequests: Array<Record<string, unknown>> = [];
let webhookSyncResponse: (() => Promise<Response>) | null = null;
let supplementalProviderFetch:
| ((
input: string | URL | Request,
init?: RequestInit,
) => Promise<Response | undefined>)
| null = null;
const appRegistrationId = Number.parseInt(
fixture.companyId.replaceAll("-", "").slice(0, 8),
16,
);
const privateKey = generateKeyPairSync("rsa", { modulusLength: 2048 })
.privateKey.export({ type: "pkcs8", format: "pem" })
.toString();
const responseComments = new Map<number, { id: number; body: string; html_url: string; user: { login: string }; thread: string }>();
const responseWrites: Array<{ method: string; id: number; body: string }> = [];
let nextResponseId = 800000;
const providerFetch = (async (
input: string | URL | Request,
init?: RequestInit,
) => {
const url = String(input);
const supplemental = await supplementalProviderFetch?.(input, init);
if (supplemental) return supplemental;
const list = /\/repos\/paperclipai\/paperclip\/(issues|pulls)\/([1-9][0-9]*)\/comments(?:\?.*)?$/.exec(url);
const reply = /\/repos\/paperclipai\/paperclip\/pulls\/([1-9][0-9]*)\/comments\/[1-9][0-9]*\/replies$/.exec(url);
const item = /\/repos\/paperclipai\/paperclip\/(issues|pulls)\/comments\/([1-9][0-9]*)$/.exec(url);
if (item) {
const comment = responseComments.get(Number(item[2]));
if (!comment) return Response.json({ message: "Not Found" }, { status: 404 });
if (init?.method === "PATCH") {
comment.body = JSON.parse(String(init.body)).body;
responseWrites.push({ method: "PATCH", id: comment.id, body: comment.body });
}
return Response.json(comment);
}
if ((list || reply) && init?.method === "POST") {
const id = ++nextResponseId;
const thread = list ? `${list[1]}:${list[2]}` : `pulls:${reply![1]}`;
const body = JSON.parse(String(init.body)).body;
const comment = { id, body, thread, html_url: `https://github.com/paperclipai/paperclip/issues/${list?.[2] ?? reply![1]}#issuecomment-${id}`,
user: { login: `maya-${fixture.companyId.slice(0, 8)}[bot]` } };
responseComments.set(id, comment);
responseWrites.push({ method: "POST", id, body });
return Response.json(comment, { status: 201 });
}
if (list && (!init?.method || init.method === "GET")) return Response.json([...responseComments.values()].filter(row => row.thread === `${list[1]}:${list[2]}`));
if (url === "https://api.github.com/app/hook/config") {
expect(init?.method).toBe("PATCH");
const config = JSON.parse(String(init?.body)) as Record<
string,
unknown
>;
webhookSyncRequests.push(config);
if (webhookSyncResponse) return webhookSyncResponse();
return new Response(
JSON.stringify({
url: config.url,
content_type: config.content_type,
insecure_ssl: config.insecure_ssl,
}),
{ status: 200 },
);
}
if (url === "https://api.github.com/app") {
return new Response(
JSON.stringify({
id: appRegistrationId,
slug: `maya-${fixture.companyId.slice(0, 8)}`,
name: "Maya Paperclip",
owner: { login: "paperclipai" },
permissions: appPermissions,
events: appEvents,
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (url === `https://api.github.com/app/installations/${installationId}`)
return Response.json({ permissions: installationPermissions, suspended_at: null });
if (url === "https://api.github.com/app/installations?per_page=100") {
return new Response(
JSON.stringify(
installationAvailable
? [
{
id: installationId,
account: {
id: 1357,
login: "paperclipai",
type: "Organization",
},
permissions: installationPermissions,
suspended_at: null,
},
...additionalInstallationIds.map((id) => ({
id,
account: {
id: id + 10_000,
login: `additional-${id}`,
type: "Organization",
},
permissions: installationPermissions,
suspended_at: null,
})),
]
: [],
),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (
url ===
`https://api.github.com/app/installations/${installationId}/access_tokens`
) {
return new Response(JSON.stringify({ token: "installation-token" }), {
status: 201,
headers: { "content-type": "application/json" },
});
}
if (
url ===
"https://api.github.com/installation/repositories?per_page=100&page=1"
) {
return new Response(JSON.stringify({ repositories }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected provider request: ${url}`);
}) as typeof globalThis.fetch;
const context = createService(
new FakeChatSdkRuntime(),
providerFetch,
deferredSchedule
? {
...overrides,
scheduleDeferredWork: (task) => {
if (setupComplete) deferredSchedule(task);
else setImmediate(task);
},
}
: overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "github",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in GitHub",
},
"owner-user",
);
const { webhookSecret } = await context.service.generateSetupSecret(
endpoint.id,
"owner-user",
);
await recordGitHubWebhookVerification(
context.service,
endpoint.publicId,
webhookSecret,
);
if (registerWithManifest)
await context.service.startGitHubRegistration(endpoint.id, "owner-user", "Maya");
if (connectExistingApp) {
const credentials = { appId: String(appRegistrationId), privateKey, webhookSecret };
if (interruptAppVault) {
// Fail the real vault write after App identity has been durably claimed.
await db.execute(sql.raw("CREATE FUNCTION github_wizard_fail_vault() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'Simulated App vault failure'; END $$"));
await db.execute(sql.raw("CREATE TRIGGER github_wizard_fail_vault BEFORE INSERT ON company_secrets FOR EACH ROW WHEN (lower(NEW.key) LIKE '%privatekey%') EXECUTE FUNCTION github_wizard_fail_vault()"));
try {
await expect(context.service.storeGitHubApp(endpoint.id, "owner-user", credentials)).rejects.toThrow();
expect(await context.service.githubWizard.advance(endpoint.id, "owner-user")).toMatchObject({ state: "recovery" });
expect((await context.service.get(endpoint.id)).setup.github).toMatchObject({ initialSetupPending: true, initialRepositoryImportPending: true });
expect((await context.service.get(endpoint.id)).setup.github?.initialRepositoriesImported).not.toBe(true);
expect(await context.service.listResources(endpoint.id)).toHaveLength(0);
expect((await githubChatManagementService(db, providerFetch).configuration(endpoint.id, "owner-user")).revision).toBe(0);
} finally {
await db.execute(sql.raw("DROP TRIGGER github_wizard_fail_vault ON company_secrets"));
await db.execute(sql.raw("DROP FUNCTION github_wizard_fail_vault()"));
}
}
await context.service.storeGitHubApp(endpoint.id, "owner-user", credentials);
}
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
appId: useVerifiedAppId ? String(appRegistrationId) : "123456",
privateKey,
},
},
"owner-user",
);
if (!useVerifiedAppId) {
const [configured] = await readChatEndpointsById(endpoint.id);
// Legacy transport fixtures already have explicit tool authority. Do not
// save a review configuration: that would switch their admission model.
await db.transaction((tx) => syncGitHubBotTools(tx, configured!, "owner-user", true));
}
const resources = await context.service.listResources(endpoint.id);
if (!registerWithManifest && !connectExistingApp)
await context.service.replaceResources(endpoint.id, [
{ id: resources[0]!.id, enabled: true },
]);
setupComplete = true;
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive GitHub callbacks");
return {
...context,
endpoint,
callbacks,
webhookSecret,
providerFetch,
responseComments,
responseWrites,
webhookSyncRequests,
privateKey,
setSupplementalProviderFetch(value: typeof supplementalProviderFetch) {
supplementalProviderFetch = value;
},
setWebhookSyncResponse(value: (() => Promise<Response>) | null) {
webhookSyncResponse = value;
},
setInstallationId(value: number) {
installationId = value;
},
setAdditionalInstallationIds(value: number[]) {
additionalInstallationIds = value;
},
setInstallationAvailable(value: boolean) {
installationAvailable = value;
},
setRepositories(
value: Array<{
id: number;
full_name: string;
html_url: string;
owner: { id: number; login: string };
private: boolean;
}>,
) {
repositories = value;
},
setAppAccess(input: {
permissions?: Record<string, string>;
events?: string[];
}) {
if (input.permissions) appPermissions = input.permissions;
if (input.events) appEvents = input.events;
},
setInstallationAccess(permissions: Record<string, string>) {
installationPermissions = permissions;
},
};
}
async function deliverLegacyGitHubReceipt(
input: Parameters<typeof deliverMessage>[0], service: ChatChannelService,
) {
await deliverMessage(input);
const [delivery] = await db.select().from(chatDeliveries).where(and(
eq(chatDeliveries.endpointId, input.endpointId),
eq(chatDeliveries.providerEventId, `${input.thread.id}:${input.message.id}`),
));
if (!delivery) throw new Error("Expected admitted legacy GitHub delivery");
const fence = delivery.normalizedEvent.runtimeContext as { generation: number; credentialFingerprint: string };
const [action] = await db.insert(chatActions).values({ companyId: delivery.companyId,
endpointId: input.endpointId, deliveryId: delivery.id, kind: "receipt_reaction",
providerActionId: `receipt_reaction:${delivery.id}`, status: "received",
payload: { version: 1, operation: "add", threadId: input.thread.id, messageId: input.message.id,
reaction: "eyes", runtimeGeneration: fence.generation, credentialFingerprint: fence.credentialFingerprint },
}).returning();
await service.processPendingReceiptReactions(1, action.id);
}
function attachFakeGitHubIssueCommentWebhook(input: {
botUsername: string;
callbacks: CreateChatSdkEndpointRuntimeOptions["callbacks"];
endpointId: string;
runtime: FakeEndpointRuntime;
}) {
input.runtime.webhookHook = async (request) => {
const payload = (await request.clone().json()) as {
action?: unknown;
comment?: {
body?: unknown;
created_at?: unknown;
id?: unknown;
updated_at?: unknown;
user?: { id?: unknown; login?: unknown };
};
issue?: { number?: unknown; pull_request?: unknown };
repository?: {
full_name?: unknown;
name?: unknown;
owner?: { login?: unknown };
};
sender?: { id?: unknown; login?: unknown };
};
if (payload.action !== "created") return;
const fullName =
typeof payload.repository?.full_name === "string"
? payload.repository.full_name
: typeof payload.repository?.owner?.login === "string" &&
typeof payload.repository.name === "string"
? `${payload.repository.owner.login}/${payload.repository.name}`
: null;
const issueNumber = payload.issue?.number;
const messageId = payload.comment?.id;
const text = payload.comment?.body;
if (
!fullName ||
typeof issueNumber !== "number" ||
(typeof messageId !== "number" && typeof messageId !== "string") ||
typeof text !== "string"
) {
return;
}
const mentionNames = new Set([
input.botUsername,
input.botUsername.replace(/\[bot\]$/i, ""),
]);
const mentioned = [...mentionNames].some((identity) =>
new RegExp(
`(?<!\\w)@${identity.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}(?![\\w-])`,
"i",
).test(text),
);
const thread = makeThread({
channelId: fullName,
id: payload.issue?.pull_request
? `github:${fullName}:${issueNumber}`
: `github:${fullName}:issue:${issueNumber}`,
name: fullName,
}).thread;
const message = makeMessage({
id: String(messageId),
raw: payload,
text,
mentioned,
userId: String(payload.sender?.id ?? payload.comment?.user?.id ?? "42"),
userName: String(
payload.sender?.login ?? payload.comment?.user?.login ?? "octocat",
),
});
const createdAt = payload.comment?.created_at;
if (typeof createdAt === "string")
message.metadata.dateSent = new Date(createdAt);
await deliverMessage({
callbacks: input.callbacks,
endpointId: input.endpointId,
message,
provider: "github",
thread,
trigger: mentioned ? "mention" : "unaddressed_message",
});
};
}
async function githubPreIngressRecoveryFixture(
event: "issue_comment" | "pull_request_review_comment" = "issue_comment",
replayBarrier?: ChatChannelServiceOptions["githubWebhookReplayBarrier"],
) {
const fixture = await seedCompany();
const deferred: Array<() => void> = [];
const configured = await configuredGitHubEndpoint(
fixture,
{
deferWebhookProcessing: true,
githubWebhookReplayBarrier: replayBarrier,
scheduleDeferredWork: (task) => deferred.push(task),
},
true,
);
const { service, endpoint, runtime, callbacks } = configured;
// Setup admission is covered separately. Recovery is intentionally only
// eligible for an active endpoint with an explicitly enabled repository.
await db
.update(chatEndpoints)
.set({ status: "active" })
.where(eq(chatEndpoints.id, endpoint.id));
const current = await service.get(endpoint.id);
const providerRuntime = runtime.endpoints.get(endpoint.id)!;
attachFakeGitHubIssueCommentWebhook({
botUsername: current.botUsername!,
callbacks,
endpointId: endpoint.id,
runtime: providerRuntime,
});
const guid = randomUUID();
const deliveryId = "9007199254740993";
const webhookUrl = `https://paperclip.example/api/chat-webhooks/${endpoint.publicId}/github`;
const createdAt = new Date(Date.now() - 30_000).toISOString();
const body = `@${current.botUsername} recover the original request ${randomUUID()}`;
const comment = {
id: 9191,
body,
created_at: createdAt,
updated_at: createdAt,
user: { id: 42, login: "octocat", type: "User" },
...(event === "issue_comment"
? {
issue_url:
"https://api.github.com/repos/paperclipai/paperclip/issues/91",
}
: {
pull_request_url:
"https://api.github.com/repos/paperclipai/paperclip/pulls/91",
}),
};
const payload = {
action: "created",
installation: { id: 2468 },
repository: {
id: 97531,
full_name: "paperclipai/paperclip",
name: "paperclip",
owner: { id: 1357, login: "paperclipai" },
},
...(event === "issue_comment"
? { issue: { id: 9190, number: 91 } }
: { pull_request: { id: 9190, number: 91 } }),
comment,
sender: { id: 42, login: "octocat", type: "User" },
};
const original = {
id: deliveryId,
guid,
delivered_at: createdAt,
redelivery: false,
status_code: 502 as number | null,
event,
action: "created",
installation_id: 2468,
repository_id: 97531,
throttled_at: null as string | null,
};
let deliveries = [original];
const extraDetails = new Map<
string,
{ summary: typeof original; payload: unknown }
>();
let historyHasMore = false;
let historyPage = 0;
let canonicalComment = { ...comment };
let beforeList: (() => Promise<void>) | undefined;
let beforePost: (() => Promise<void>) | undefined;
const requests: Array<{ method: string; pathname: string }> = [];
const posts: string[] = [];
const commentPath = `/repos/paperclipai/paperclip/${event === "issue_comment" ? "issues" : "pulls"}/comments/9191`;
// Emit the actual unsafe JSON numeric literal, not a string-only mock.
const json = (value: unknown) =>
new Response(
JSON.stringify(value).replaceAll(`"${deliveryId}"`, deliveryId),
{
status: 200,
headers: { "content-type": "application/json" },
},
);
configured.setSupplementalProviderFetch(async (input, init) => {
const url = new URL(String(input));
const method = init?.method ?? "GET";
const isRecovery =
url.pathname.startsWith("/app/hook/") ||
url.pathname === commentPath ||
url.pathname === "/installation/token";
if (!isRecovery) return undefined;
requests.push({ method, pathname: url.pathname });
if (url.pathname === "/app/hook/config" && method === "GET") {
return json({
url: webhookUrl,
content_type: "json",
insecure_ssl: "0",
});
}
if (url.pathname === "/app/hook/deliveries") {
await beforeList?.();
const response = json(deliveries);
if (historyHasMore)
response.headers.set(
"link",
`<https://api.github.com/app/hook/deliveries?per_page=100&cursor=page${++historyPage}>; rel="next"`,
);
return response;
}
if (url.pathname === `/app/hook/deliveries/${deliveryId}`) {
return json({
...original,
url: webhookUrl,
request: {
headers: { authorization: "private-provider-header-canary" },
payload,
},
response: { payload: "private-proxy-body-canary" },
});
}
const extra = extraDetails.get(
url.pathname.replace(/^\/app\/hook\/deliveries\//, ""),
);
if (extra)
return json({
...extra.summary,
url: webhookUrl,
request: { payload: extra.payload },
});
if (
url.pathname === `/app/hook/deliveries/${deliveryId}/attempts` &&
method === "POST"
) {
posts.push(url.pathname);
await beforePost?.();
return new Response(null, { status: 202 });
}
if (url.pathname === commentPath) return json(canonicalComment);
if (url.pathname === "/installation/token" && method === "DELETE")
return new Response(null, { status: 204 });
return undefined;
});
const checkpoint = () =>
db
.select()
.from(chatSdkState)
.where(
and(
eq(chatSdkState.endpointId, endpoint.id),
eq(chatSdkState.stateKey, "paperclip:github-webhook-recovery:v1"),
),
)
.then((rows) => rows[0]!);
const makeScanDue = async (includeOriginal = true) => {
const state = await checkpoint();
await db
.update(chatSdkState)
.set({
value: {
...(state.value as Record<string, unknown>),
...(includeOriginal
? { floor: new Date(Date.now() - 120_000).toISOString() }
: {}),
nextScanAt: new Date(Date.now() - 1_000).toISOString(),
},
})
.where(eq(chatSdkState.id, state.id));
};
const ingress = () =>
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, `github_webhook_ingress:${guid}`),
),
)
.then((rows) => rows[0]);
const receipt = () =>
db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, `github_webhook_recovery:${guid}`),
),
)
.then((rows) => rows[0]);
const callback = (
webhookSecret = configured.webhookSecret,
incomingPayload: unknown = payload,
) =>
service.handleWebhook(
endpoint.publicId,
"github",
signedGitHubWebhookRequest({
delivery: guid,
event,
payload: incomingPayload,
webhookSecret,
url: webhookUrl,
}),
);
const initializedAt = Date.now();
await service.processFailedGitHubWebhookDeliveries(5, endpoint.id);
expect(requests).toEqual([]);
const initial = (await checkpoint()).value as Record<string, unknown>;
expect(initial).toMatchObject({
appId: current.botExternalId,
webhookUrl,
generation: expect.any(Number),
});
expect(Date.parse(String(initial.floor))).toBeGreaterThanOrEqual(
initializedAt,
);
expect(Date.parse(String(initial.nextScanAt))).toBeGreaterThanOrEqual(
initializedAt + 60_000,
);
return {
...configured,
fixture,
body,
guid,
deliveryId,
original,
payload,
providerRuntime,
requests,
posts,
checkpoint,
makeScanDue,
ingress,
receipt,
callback,
deferred,
setDeliveries(value: typeof deliveries) {
deliveries = value;
},
setDetail(summary: typeof original, incomingPayload: unknown) {
extraDetails.set(summary.id, { summary, payload: incomingPayload });
},
setHistoryHasMore(value: boolean) {
historyHasMore = value;
},
setCanonicalComment(value: Partial<typeof comment>) {
canonicalComment = { ...canonicalComment, ...value };
},
setBeforeList(value: typeof beforeList) {
beforeList = value;
},
setBeforePost(value: typeof beforePost) {
beforePost = value;
},
};
}
return { githubWebhookVerificationResponse, recordGitHubWebhookVerification, signedGitHubWebhookRequest, configuredGitHubEndpoint, deliverLegacyGitHubReceipt, attachFakeGitHubIssueCommentWebhook, githubPreIngressRecoveryFixture };
}
export type GitHubHarness = ReturnType<typeof createGitHubHarness>;
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,957 @@
// Shared PostgreSQL lifecycle and endpoint seeding harness for chat-channel integration suites.
import { reconcilePersistedRuntimeServicesOnStartup, readWorkspaceRuntimeIdleWork } from "../../services/workspace-runtime.js";
import { conflict } from "../../errors.js";
import { readIdleLocalWork } from "../../services/idle-local-work.js";
import { createDeliveryWorkCoordinator } from "../../services/delivery-work-coordinator.js";
import { chatGitHubRegistrations, chatGitHubReviews } from "@paperclipai/db";
import { createHash, createHmac, randomUUID } from "node:crypto";
import { mkdirSync, rmSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { Readable } from "node:stream";
import request from "supertest";
import { and, eq, inArray, notInArray, or, sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, expect, it, vi } from "vitest";
import { agents, agentWakeupRequests, authUsers, chatActions, chatConversations, chatDeliveries, chatEndpointLeases, chatEndpoints, chatExternalPrincipals, chatIdentityLinks, chatMessageLinks, chatPublications, chatTeamsFileTransfers, companies, companyMemberships, createDb, applyPendingMigrations, closeCheckpointDb, closeFileStorageDb, closeLivenessDb, heartbeatRuns, issueComments, issues, principalPermissionGrants, toolConnections } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import type { Message, Thread } from "chat";
import { chatChannelService, type ChatChannelServiceOptions, type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions, ChatSdkMessageTrigger, ChatSdkRuntime } from "../../services/chat-sdk-runtime.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { issueService } from "../../services/issues.js";
import type { StorageService } from "../../storage/types.js";
import { resolveChatRunPresentationAuthorizationReason } from "../../services/chat-run-publications.js";
import { startEmbeddedPostgresTestDatabase } from "../helpers/embedded-postgres.js";
import { type TestDb, slackProtocolCapture, slackProtocolDatabaseUrl, externalTestDatabaseUrl, FakeChatSdkRuntime, uniqueDiscordApplicationId, fakeSlackFetch, fakeDiscordFetch, fakeTelegramFetch, chatSdkProvider, makeThread, makeMessage } from "./providers.js";
export function createChatChannelHarness() {
let db!: TestDb;
let tempDb: Awaited<
ReturnType<typeof startEmbeddedPostgresTestDatabase>
> | null = null;
const previousKeyFile = process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
const secretsTmpDir = path.join(
os.tmpdir(),
`paperclip-chat-channels-${randomUUID()}`,
);
beforeAll(async () => {
if (slackProtocolDatabaseUrl) await applyPendingMigrations(slackProtocolDatabaseUrl);
mkdirSync(secretsTmpDir, { recursive: true });
process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = path.join(
secretsTmpDir,
"master.key",
);
if (!externalTestDatabaseUrl) {
tempDb = await startEmbeddedPostgresTestDatabase("paperclip-chat-channels-");
}
// Scheduler tests advance virtual time while PostgreSQL uses real I/O.
// Do not expire or time out its connections on those virtual clock jumps.
db = createDb(externalTestDatabaseUrl ?? tempDb!.connectionString, {
idleTimeoutSeconds: 0, connectTimeoutSeconds: 0, maxLifetimeSeconds: 0,
...(externalTestDatabaseUrl ? { maxConnections: 4 } : {}),
});
// The composed local-probe inventory includes the workspace owner. Match
// server startup on this fresh fixture; never adopt or start a leftover.
const [runtimeState] = await db.execute<{ configured: boolean }>(sql`SELECT
EXISTS (SELECT 1 FROM workspace_runtime_services)
OR EXISTS (SELECT 1 FROM project_workspaces)
OR EXISTS (SELECT 1 FROM execution_workspaces) AS configured`);
expect(runtimeState.configured).toBe(false);
expect(await reconcilePersistedRuntimeServicesOnStartup(db)).toEqual({
reconciled: 0, adopted: 0, stopped: 0, backfilled: 0, restarted: 0,
restartFailed: 0, exposureReservationDrift: [],
});
expect(readWorkspaceRuntimeIdleWork()).toBe("none");
}, 90_000);
afterAll(async () => {
if (slackProtocolCapture && db) { await closeCheckpointDb(db, 1); await closeFileStorageDb(db, 1); await closeLivenessDb(db, 1); }
await db?.$client.end();
await tempDb?.cleanup();
if (previousKeyFile === undefined)
delete process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE;
else process.env.PAPERCLIP_SECRETS_MASTER_KEY_FILE = previousKeyFile;
rmSync(secretsTmpDir, { recursive: true, force: true });
});
// Services scan this file's shared database. Retire each case's fixtures
// after its assertions so another case (or shard order) cannot claim them.
const fixtureCompanies = new Set<string>();
const fixtureServices = new Set<ChatChannelService>();
afterEach(async () => {
try {
await Promise.all([...fixtureServices].map((service) => service.shutdown()));
} finally {
const companyIds = [...fixtureCompanies];
await retireFixtureState(companyIds);
if (companyIds.length > 0) {
// Pausing an endpoint does not remove its rows from global recovery
// selectors. After every assertion and worker shutdown, settle leftover
// fixture work so later cases cannot claim its leases or retry its I/O.
await db.update(chatActions).set({ status: "cancelled" })
.where(and(inArray(chatActions.companyId, companyIds), notInArray(chatActions.status, ["processed", "cancelled"])));
await db.update(chatDeliveries).set({ state: "failed", nextAttemptAt: null })
.where(and(inArray(chatDeliveries.companyId, companyIds), inArray(chatDeliveries.state, ["received", "processing", "retry"])));
await db.update(chatPublications).set({ state: "cancelled", nextAttemptAt: null })
.where(and(inArray(chatPublications.companyId, companyIds), inArray(chatPublications.state, ["pending", "awaiting_consent", "streaming", "retry"])));
}
fixtureServices.clear();
fixtureCompanies.clear();
}
});
async function retireFixtureState(companyIds: string[]) {
if (companyIds.length === 0) return;
// Verifying endpoints can also own receipts. Once a receipt is 60s old,
// another test's global sweep can reclaim it. Retire every live endpoint,
// then release synthetic lease owners after their services have stopped.
await db.update(chatEndpoints).set({ status: "paused" })
.where(and(inArray(chatEndpoints.companyId, companyIds), notInArray(chatEndpoints.status, ["archived", "revoked"])));
await db.delete(chatEndpointLeases)
.where(inArray(chatEndpointLeases.companyId, companyIds));
// The milestone scanner includes paused endpoints with active bindings.
await db.update(chatConversations).set({ state: "completed" })
.where(and(inArray(chatConversations.companyId, companyIds), inArray(chatConversations.state, ["active", "waiting"])));
}
const companyPrefixAttempts = 8;
const freshCompanyPrefix = () => `C${randomUUID().replaceAll("-", "").slice(0, 7).toUpperCase()}`;
async function seedCompany(nextIssuePrefix = freshCompanyPrefix, companyId: string = randomUUID()) {
const assignedAgentId = randomUUID();
const replacementAgentId = randomUUID();
let inserted = false;
// Retired fixtures retain company rows. Retry only the short-prefix unique
// conflict; every other database error must still fail the test immediately.
for (let attempt = 0; attempt < companyPrefixAttempts; attempt += 1) {
const [company] = await db.insert(companies).values({
id: companyId,
name: `Chat Test ${companyId.slice(0, 8)}`,
issuePrefix: nextIssuePrefix(),
requireBoardApprovalForNewAgents: false,
}).onConflictDoNothing({ target: companies.issuePrefix }).returning({ id: companies.id });
if (company) {
inserted = true;
fixtureCompanies.add(companyId);
break;
}
}
if (!inserted) throw new Error(`Could not allocate a chat fixture company prefix after ${companyPrefixAttempts} attempts`);
const now = new Date();
await db
.insert(authUsers)
.values({
id: "owner-user",
name: "Owner User",
email: "owner-user@example.com",
emailVerified: true,
createdAt: now,
updatedAt: now,
})
.onConflictDoNothing();
await db.insert(companyMemberships).values({
companyId,
principalType: "user",
principalId: "owner-user",
status: "active",
membershipRole: "operator",
});
await db.insert(principalPermissionGrants).values({
companyId,
principalType: "user",
principalId: "owner-user",
permissionKey: "tools:manage_connections",
scope: null,
grantedByUserId: "owner-user",
});
await db.insert(agents).values([
{
id: assignedAgentId,
companyId,
name: "Maya",
role: "engineer",
status: "idle",
adapterType: "paperclip_runner",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: replacementAgentId,
companyId,
name: "Linus",
role: "engineer",
status: "idle",
adapterType: "paperclip_runner",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
]);
return { companyId, assignedAgentId, replacementAgentId };
}
function readChatConversationsByEndpointId(value: (typeof chatConversations.$inferSelect)["endpointId"]) {
return db.select().from(chatConversations).where(eq(chatConversations.endpointId, value));
}
function readChatEndpointsById(value: (typeof chatEndpoints.$inferSelect)["id"]) {
return db.select().from(chatEndpoints).where(eq(chatEndpoints.id, value));
}
function readIssueCommentsByIssueId(value: (typeof issueComments.$inferSelect)["issueId"]) {
return db.select().from(issueComments).where(eq(issueComments.issueId, value));
}
function readChatDeliveriesByEndpointId(value: (typeof chatDeliveries.$inferSelect)["endpointId"]) {
return db.select().from(chatDeliveries).where(eq(chatDeliveries.endpointId, value));
}
function readChatDeliveriesById(value: (typeof chatDeliveries.$inferSelect)["id"]) {
return db.select().from(chatDeliveries).where(eq(chatDeliveries.id, value));
}
function readHeartbeatRunsById(value: (typeof heartbeatRuns.$inferSelect)["id"]) {
return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, value));
}
function readIssuesById(value: (typeof issues.$inferSelect)["id"]) {
return db.select().from(issues).where(eq(issues.id, value));
}
function readChatActionsById(value: (typeof chatActions.$inferSelect)["id"]) {
return db.select().from(chatActions).where(eq(chatActions.id, value));
}
function readChatGitHubReviewsByEndpointId(value: (typeof chatGitHubReviews.$inferSelect)["endpointId"]) {
return db.select().from(chatGitHubReviews).where(eq(chatGitHubReviews.endpointId, value));
}
function readChatPublicationsByEndpointId(value: (typeof chatPublications.$inferSelect)["endpointId"]) {
return db.select().from(chatPublications).where(eq(chatPublications.endpointId, value));
}
function readChatPublicationsById(value: (typeof chatPublications.$inferSelect)["id"]) {
return db.select().from(chatPublications).where(eq(chatPublications.id, value));
}
function readChatGitHubRegistrationsByEndpointId(value: (typeof chatGitHubRegistrations.$inferSelect)["endpointId"]) {
return db.select().from(chatGitHubRegistrations).where(eq(chatGitHubRegistrations.endpointId, value));
}
function readToolConnectionsById(value: (typeof toolConnections.$inferSelect)["id"]) {
return db.select().from(toolConnections).where(eq(toolConnections.id, value));
}
function readChatConversationsById(value: (typeof chatConversations.$inferSelect)["id"]) {
return db.select().from(chatConversations).where(eq(chatConversations.id, value));
}
function readIssuesByCompanyId(value: (typeof issues.$inferSelect)["companyId"]) {
return db.select().from(issues).where(eq(issues.companyId, value));
}
function readChatPublicationsByCommentId(value: NonNullable<(typeof chatPublications.$inferSelect)["commentId"]>) {
return db.select().from(chatPublications).where(eq(chatPublications.commentId, value));
}
function readChatActionsByProviderActionId(value: (typeof chatActions.$inferSelect)["providerActionId"]) {
return db.select().from(chatActions).where(eq(chatActions.providerActionId, value));
}
function readChatPublicationsByIdempotencyKey(value: (typeof chatPublications.$inferSelect)["idempotencyKey"]) {
return db.select().from(chatPublications).where(eq(chatPublications.idempotencyKey, value));
}
function readHeartbeatRunsByCompanyId(value: (typeof heartbeatRuns.$inferSelect)["companyId"]) {
return db.select().from(heartbeatRuns).where(eq(heartbeatRuns.companyId, value));
}
function readAgentWakeupRequestsById(value: (typeof agentWakeupRequests.$inferSelect)["id"]) {
return db.select().from(agentWakeupRequests).where(eq(agentWakeupRequests.id, value));
}
function readIssueCommentsByCompanyId(value: (typeof issueComments.$inferSelect)["companyId"]) {
return db.select().from(issueComments).where(eq(issueComments.companyId, value));
}
function readChatTeamsFileTransfersById(value: (typeof chatTeamsFileTransfers.$inferSelect)["id"]) {
return db.select().from(chatTeamsFileTransfers).where(eq(chatTeamsFileTransfers.id, value));
}
// A truthy return is not a durable scheduler receipt. These transport tests
// record the same exact receipt identity; real scheduling/coalescing is
// separately exercised by durable-chat-wakeup.test.ts against heartbeat.
function receiptBackedWakeup(
wakeup: ChatChannelServiceOptions["heartbeat"]["wakeup"],
): ChatChannelServiceOptions["heartbeat"]["wakeup"] {
return async (agentId, opts) => {
const result = await wakeup(agentId, opts);
const request = opts.durableChatRequest;
if (request && result !== null && result !== undefined) {
const [existing] = await db
.select({ id: agentWakeupRequests.id })
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, request.id));
if (existing) return result;
await db.transaction(async (tx) => {
await request.authorize(
tx as unknown as Parameters<typeof request.authorize>[0],
);
await tx
.insert(agentWakeupRequests)
.values({
id: request.id,
companyId: request.companyId,
agentId,
source: opts.source ?? "assignment",
triggerDetail: opts.triggerDetail,
reason: opts.reason,
payload: opts.payload,
requestedByActorType: opts.requestedByActorType,
requestedByActorId: opts.requestedByActorId,
idempotencyKey: request.idempotencyKey,
requestedAt: request.requestedAt,
status: "queued",
})
.onConflictDoNothing();
});
}
return result;
};
}
function createService(
runtime = new FakeChatSdkRuntime(),
providerFetch: typeof globalThis.fetch = fakeSlackFetch() as typeof globalThis.fetch,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "credentialMutationLeaseRenewalIntervalMs"
| "deferWebhookProcessing"
| "discordGatewayEventBarrier"
| "discordGatewayMessageAdmissionBarrier"
| "discordRootThreadTransportBarrier"
| "discordGatewayLeaseRenewalIntervalMs"
| "discordGatewayLeaseTtlMs"
| "discordGatewayLeaseWaitMs"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookReplayBarrier"
| "githubWebhookResponseBudgetMs"
| "publicationTransportPreparationBarrier"
| "renderSlackAvatar"
| "slackManaged"
| "publicBaseUrl"
| "webhookPublicBaseUrl"
| "nativeBotIdentityClaimBarrier"
| "confirmationResolutionPersistBarrier"
| "conversationLeaseRenewalIntervalMs"
| "questionFormOpenAuthorizationBarrier"
| "questionResolutionPersistBarrier"
| "reactionLinkPreflightBarrier"
| "reactionReplayConversationLockBarrier"
| "reactionReplayEndpointLockBarrier"
| "receiptReactionTransportBarrier"
| "resolveNativeQuestion"
| "renewCredentialMutationLease"
| "renewConversationDeliveryLease"
| "renewDiscordGatewayLease"
| "scheduleDeferredWork"
| "slackTaskAdmissionClaimBarrier"
| "slackSessionSyncSelectionBarrier"
| "setupSecretActivityLogger"
| "setupSecretCredentialPersistBarrier"
| "setupSecretFinalOwnershipBarrier"
| "setupTestActivationBarrier"
| "storage"
| "reachAuthorizationBarrier"
>
> & {
cancelRun?: NonNullable<
ChatChannelServiceOptions["heartbeat"]["cancelRun"]
>;
wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"];
} = {},
) {
const {
cancelRun: cancelRunOverride,
wakeup: wakeupOverride,
...serviceOverrides
} = overrides;
const wakeup = vi.fn<ChatChannelServiceOptions["heartbeat"]["wakeup"]>(wakeupOverride ?? (async () => ({ accepted: true })));
const cancelRun = vi.fn<NonNullable<ChatChannelServiceOptions["heartbeat"]["cancelRun"]>>(
cancelRunOverride ?? (async () => ({ status: "cancelled" })),
);
const service = chatChannelService(db, {
fetch: providerFetch,
heartbeat: { cancelRun, wakeup: receiptBackedWakeup(wakeup) },
publicBaseUrl: "https://paperclip.example",
runtime: runtime as unknown as ChatSdkRuntime,
...serviceOverrides,
});
fixtureServices.add(service);
return { cancelRun, runtime, service, wakeup };
}
function createStorageService() {
const objects = new Map<string, Buffer>();
const putFile = vi.fn<StorageService["putFile"]>(async (input) => {
if (!Buffer.isBuffer(input.body)) throw new Error("Expected a buffered attachment body");
const objectKey = `${input.namespace}/${randomUUID()}-${input.originalFilename ?? "attachment"}`;
objects.set(objectKey, input.body);
return {
provider: "local_disk",
objectKey,
contentType: input.contentType,
byteSize: input.body.length,
sha256: createHash("sha256").update(input.body).digest("hex"),
originalFilename: input.originalFilename,
};
});
const storage: StorageService = {
provider: "local_disk",
putFile,
getObject: vi.fn(async (_companyId, objectKey) => {
const body = objects.get(objectKey);
if (!body) throw new Error(`Missing test object ${objectKey}`);
return {
stream: Readable.from([body]),
contentLength: body.length,
};
}),
headObject: vi.fn(async (_companyId, objectKey) => ({
exists: objects.has(objectKey),
contentLength: objects.get(objectKey)?.length,
})),
deleteObject: vi.fn(async (_companyId, objectKey) => {
objects.delete(objectKey);
}),
};
return { objects, putFile, storage };
}
async function retirePublicationFixture(
service: ChatChannelService,
endpointId: string,
) {
try {
await service.shutdown();
} finally {
// Workers scan the shared fixture database. Local shutdown alone leaves
// future retries/receipts eligible for the next test's service. Preserve
// their asserted audit state, but retire this endpoint after assertions.
await db
.update(chatEndpoints)
.set({ status: "paused" })
.where(
and(
eq(chatEndpoints.id, endpointId),
eq(chatEndpoints.status, "active"),
),
);
}
}
async function recordSlackUrlVerification(
service: ChatChannelService,
publicId: string,
signingSecret = "test-signing-secret",
) {
const response = await service.handleWebhook(
publicId,
"slack",
signedSlackWebhookRequest({
url: `https://paperclip.example/api/chat-webhooks/${publicId}/slack`,
contentType: "application/json",
body: JSON.stringify({ type: "url_verification", challenge: "verified-challenge" }),
signingSecret,
}),
);
expect(response.status).toBe(200);
expect(await response.json()).toEqual({ challenge: "verified-challenge" });
}
function signedSlackWebhookRequest(input: {
url: string;
body: string;
contentType: string;
signingSecret?: string;
timestamp?: string;
}) {
const timestamp = input.timestamp ?? String(Math.floor(Date.now() / 1000));
const signature = createHmac(
"sha256",
input.signingSecret ?? "test-signing-secret",
)
.update(`v0:${timestamp}:${input.body}`)
.digest("hex");
return new Request(input.url, {
method: "POST",
headers: {
"content-type": input.contentType,
"x-slack-request-timestamp": timestamp,
"x-slack-signature": `v0=${signature}`,
},
body: input.body,
});
}
async function chatWakeContext(input: {
endpointId: string;
issueId: string;
provider: ChatProvider;
providerMessageId: string;
}) {
const wakeCommentId = await db
.select({ commentId: chatMessageLinks.commentId })
.from(chatMessageLinks)
.where(
and(
eq(chatMessageLinks.endpointId, input.endpointId),
eq(chatMessageLinks.providerMessageId, input.providerMessageId),
eq(chatMessageLinks.direction, "inbound"),
),
)
.then((rows) => rows[0]?.commentId ?? null);
if (!wakeCommentId) {
throw new Error(
`Expected inbound comment link ${input.providerMessageId}`,
);
}
return {
issueId: input.issueId,
source: `chat:${input.provider}`,
wakeCommentId,
wakeCommentIds: [wakeCommentId],
};
}
async function addSelectedChatFinal(input: {
agentId: string;
body: string;
companyId: string;
issueId: string;
runId: string;
}) {
const authorizationReason =
await resolveChatRunPresentationAuthorizationReason(db, {
companyId: input.companyId,
issueId: input.issueId,
runId: input.runId,
});
return issueService(db).addComment(
input.issueId,
input.body,
{ agentId: input.agentId, runId: input.runId },
{ authorType: "agent", authorizationReason },
);
}
async function qualifySetupRoundTrip(
service: ChatChannelService,
endpointId: string,
userId = "U-EXTERNAL",
) {
const endpoint = await service.get(endpointId);
let conversation: typeof chatConversations.$inferSelect | undefined;
await vi.waitFor(async () => {
conversation = await readChatConversationsByEndpointId(endpointId)
.then((rows) => rows.at(-1));
expect(conversation).toBeDefined();
});
if (!conversation) throw new Error("Expected setup conversation");
const fakeRuntime = service.runtime as unknown as FakeChatSdkRuntime;
const callbacks = fakeRuntime.configurations.get(endpointId)?.callbacks;
if (!callbacks) throw new Error("Expected setup callbacks");
const { thread } = makeThread({
id: conversation.externalThreadId,
channelId: conversation.externalConversationId,
isDM: conversation.isDirectMessage,
name: conversation.externalLabel,
});
const setupFollowUpMessageId = `setup-follow-up-${randomUUID()}`;
await callbacks.onMessage({
endpointId,
provider: chatSdkProvider(endpoint.provider),
thread,
message: makeMessage({
id: setupFollowUpMessageId,
text: "Setup follow-up",
mentioned: endpoint.provider === "slack",
userId,
}),
trigger:
endpoint.provider === "telegram"
? "direct_message"
: "subscribed_message",
});
const contextSnapshot = await chatWakeContext({
endpointId,
issueId: conversation.issueId,
provider: endpoint.provider,
providerMessageId: setupFollowUpMessageId,
});
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId: endpoint.companyId,
agentId: endpoint.assignedAgentId,
status: "succeeded",
contextSnapshot,
});
if (endpoint.provider === "github") {
// Generic transport fixtures supply a confirmed task-tool receipt.
// Real tool execution and provider I/O have separate integration tests.
await db.insert(chatActions).values({ companyId: endpoint.companyId, endpointId, conversationId: conversation.id,
kind: "github_review_publication", providerActionId: `github_publication:setup:${runId}`,
payload: { operation: "comment", session: { companyId: endpoint.companyId, agentId: endpoint.assignedAgentId, issueId: conversation.issueId, runId } },
status: "processed", result: { id: "setup-tool-reply", url: "https://github.com/test/setup-tool-reply" } });
} else {
await addSelectedChatFinal({
agentId: endpoint.assignedAgentId,
body: "Setup round trip complete",
companyId: endpoint.companyId,
issueId: conversation.issueId,
runId,
});
}
await service.processPendingPublications();
const providerRuntime = fakeRuntime.endpoints.get(endpointId);
if (providerRuntime) providerRuntime.posts.length = 0;
return setupFollowUpMessageId;
}
async function configuredSlackEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: { allowUnlinkedPeople?: boolean; linkedBoardUser?: boolean; requireAtMention?: boolean } & Partial<
Pick<
ChatChannelServiceOptions,
| "credentialMutationLeaseRenewalIntervalMs"
| "conversationLeaseRenewalIntervalMs"
| "deferWebhookProcessing"
| "fetch"
| "questionFormOpenAuthorizationBarrier"
| "questionResolutionPersistBarrier"
| "reactionLinkPreflightBarrier"
| "reactionReplayConversationLockBarrier"
| "reactionReplayEndpointLockBarrier"
| "receiptReactionTransportBarrier"
| "reachAuthorizationBarrier"
| "resolveNativeQuestion"
| "renewCredentialMutationLease"
| "renewConversationDeliveryLease"
| "scheduleDeferredWork"
| "slackTaskAdmissionClaimBarrier"
| "storage"
>
> & {
cancelRun?: NonNullable<
ChatChannelServiceOptions["heartbeat"]["cancelRun"]
>;
wakeup?: ChatChannelServiceOptions["heartbeat"]["wakeup"];
} = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
overrides.fetch ?? (fakeSlackFetch() as typeof globalThis.fetch),
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "slack",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Slack",
},
"owner-user",
);
// Most transport fixtures exercise restricted guests explicitly. Production
// Slack creation defaults to linked accounts only (covered separately).
await context.service.update(endpoint.id, {
allowUnlinkedPeople: overrides.allowUnlinkedPeople ?? true,
// Existing transport tests explicitly exercise the optional unmentioned mode.
requireAtMention: overrides.requireAtMention ?? false,
}, "owner-user");
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
botToken: "xoxb-test-token",
signingSecret: "test-signing-secret",
},
},
"owner-user",
);
if (overrides.linkedBoardUser) {
const [principal] = await db.insert(chatExternalPrincipals).values({ companyId: fixture.companyId, provider: "slack", providerAccountId: "T-PAPERCLIP", externalId: "UBOARD" }).returning();
await db.insert(chatIdentityLinks).values({ companyId: fixture.companyId, endpointId: endpoint.id, principalId: principal.id, paperclipUserId: "owner-user", status: "linked", confirmedAt: new Date() });
}
await recordSlackUrlVerification(context.service, endpoint.publicId);
await context.service.configure(
endpoint.id,
{ action: "verify" },
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive endpoint callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredTeamsEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Partial<
Pick<
ChatChannelServiceOptions,
| "deferWebhookProcessing"
| "githubWebhookAuthenticationBarrier"
| "githubWebhookResponseBudgetMs"
| "scheduleDeferredWork"
| "storage"
| "reachAuthorizationBarrier"
>
> = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
(async () =>
new Response(JSON.stringify({ access_token: "teams-test-access" }), {
status: 200,
headers: { "content-type": "application/json" },
})) as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "microsoft-teams",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Teams",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
clientId: randomUUID(),
tenantId: randomUUID(),
clientSecret: "teams-test-secret",
},
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Teams callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredTelegramEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Parameters<typeof createService>[2] = {},
) {
const context = createService(
new FakeChatSdkRuntime(),
fakeTelegramFetch() as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "telegram",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Telegram",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: { botToken: "123456:telegram-interaction-test" },
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Telegram callbacks");
return { ...context, endpoint, callbacks };
}
async function configuredDiscordEndpoint(
fixture: Awaited<ReturnType<typeof seedCompany>>,
overrides: Parameters<typeof createService>[2] = {},
) {
const applicationId = uniqueDiscordApplicationId();
const context = createService(
new FakeChatSdkRuntime(),
fakeDiscordFetch(applicationId) as typeof globalThis.fetch,
overrides,
);
const endpoint = await context.service.create(
fixture.companyId,
{
provider: "discord",
assignedAgentId: fixture.assignedAgentId,
name: "Maya in Discord",
},
"owner-user",
);
await context.service.configure(
endpoint.id,
{
action: "configure",
credentials: {
applicationId,
botToken: "discord-secret",
guildId: "1457808928258658549",
},
},
"owner-user",
);
const callbacks = context.runtime.configurations.get(
endpoint.id,
)?.callbacks;
if (!callbacks)
throw new Error("Fake runtime did not receive Discord callbacks");
return { ...context, endpoint, callbacks };
}
async function recoverDiscordCommands(service: ChatChannelService) {
const onError = vi.fn();
const coordinator = createDeliveryWorkCoordinator({ owner: db, canRun: () => true, onError });
try {
await service.registerCommandWork(coordinator, () => true).ready;
expect(onError).not.toHaveBeenCalled();
} finally {
await coordinator.stop();
}
}
async function deliverMessage(input: {
callbacks: CreateChatSdkEndpointRuntimeOptions["callbacks"];
endpointId: string;
message: Message;
provider?: ChatProvider;
providerUpdateId?: number;
thread: Thread;
trigger: ChatSdkMessageTrigger;
}) {
await input.callbacks.onMessage({
endpointId: input.endpointId,
provider: chatSdkProvider(input.provider ?? "slack"),
providerUpdateId: input.providerUpdateId,
thread: input.thread,
message: input.message,
trigger: input.trigger,
});
}
async function waitForProcessedReceiptRemoval(
endpointId: string,
receipt: { threadId: string; messageId: string; emoji: string },
) {
// Publication settlement only schedules this non-critical provider I/O.
// A sweep skips an action already owned by a fresh processing worker.
const removals = await db
.select({
id: chatActions.id,
deliveryId: chatActions.deliveryId,
providerActionId: chatActions.providerActionId,
})
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
eq(chatActions.kind, "receipt_reaction"),
sql`${chatActions.payload}->>'operation' = 'remove'`,
sql`${chatActions.payload}->>'threadId' = ${receipt.threadId}`,
sql`${chatActions.payload}->>'messageId' = ${receipt.messageId}`,
sql`${chatActions.payload}->>'reaction' = ${receipt.emoji}`,
),
);
expect(removals).toHaveLength(1);
const removal = removals[0]!;
expect(removal.deliveryId).toEqual(expect.any(String));
expect(removal.providerActionId).toBe(
`receipt_reaction_remove:${removal.deliveryId}`,
);
await vi.waitFor(async () => {
await expect(
db
.select({ status: chatActions.status })
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpointId),
eq(chatActions.id, removal.id),
),
),
).resolves.toEqual([{ status: "processed" }]);
});
return removal.id;
}
async function registeredIdleProbeState() {
let state: string | undefined;
await readIdleLocalWork({ diagnostic: (reason, value) => { if (reason === "local.registered_probes") state = value; } });
return state;
}
async function linkLifecycleFixtureActor(input: {
companyId: string;
endpointId: string;
externalId: string;
}) {
const [principal] = await db
.select()
.from(chatExternalPrincipals)
.where(
and(
eq(chatExternalPrincipals.companyId, input.companyId),
eq(chatExternalPrincipals.externalId, input.externalId),
),
);
if (!principal) throw new Error("Expected original lifecycle principal");
await db.insert(chatIdentityLinks).values({
companyId: input.companyId,
endpointId: input.endpointId,
principalId: principal.id,
paperclipUserId: "owner-user",
status: "linked",
confirmedAt: new Date(),
});
await db
.update(chatEndpoints)
.set({ allowUnlinkedPeople: false })
.where(
and(
eq(chatEndpoints.companyId, input.companyId),
eq(chatEndpoints.id, input.endpointId),
),
);
return principal.id;
}
return {
get db(): TestDb { return db; },
get connectionString(): string { return externalTestDatabaseUrl ?? tempDb!.connectionString; },
fixtureCompanies, fixtureServices, retireFixtureState, companyPrefixAttempts, freshCompanyPrefix, seedCompany, readChatConversationsByEndpointId, readChatEndpointsById, readIssueCommentsByIssueId, readChatDeliveriesByEndpointId, readChatDeliveriesById, readHeartbeatRunsById, readIssuesById, readChatActionsById, readChatGitHubReviewsByEndpointId, readChatPublicationsByEndpointId, readChatPublicationsById, readChatGitHubRegistrationsByEndpointId, readToolConnectionsById, readChatConversationsById, readIssuesByCompanyId, readChatPublicationsByCommentId, readChatActionsByProviderActionId, readChatPublicationsByIdempotencyKey, readHeartbeatRunsByCompanyId, readAgentWakeupRequestsById, readIssueCommentsByCompanyId, readChatTeamsFileTransfersById, receiptBackedWakeup, createService, createStorageService, retirePublicationFixture, recordSlackUrlVerification, signedSlackWebhookRequest, chatWakeContext, addSelectedChatFinal, qualifySetupRoundTrip, configuredSlackEndpoint, configuredTeamsEndpoint, configuredTelegramEndpoint, configuredDiscordEndpoint, recoverDiscordCommands, deliverMessage, waitForProcessedReceiptRemoval, registeredIdleProbeState, linkLifecycleFixtureActor,
};
}
export type ChatChannelHarness = ReturnType<typeof createChatChannelHarness>;
@@ -0,0 +1,857 @@
// Shared fake chat provider runtimes, fetch mocks, and Express app builders.
import { resolveExternalTestDatabaseUrl } from "../helpers/external-test-database.js";
import { randomUUID } from "node:crypto";
import path from "node:path";
import express from "express";
import request from "supertest";
import { describe, vi } from "vitest";
import { agents, createDb } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import type { Attachment, Author, Message, Thread } from "chat";
import { errorHandler } from "../../middleware/index.js";
import { createChatWebhookDiagnostics, type ChatWebhookDiagnosticEvent } from "../../services/chat-webhook-diagnostics.js";
import { chatChannelRoutes, chatWebhookRoutes } from "../../routes/chat-channels.js";
import { type ChatChannelService } from "../../services/chat-channels.js";
import type { CreateChatSdkEndpointRuntimeOptions, ChatSdkEndpointRuntime, ChatSdkProvider } from "../../services/chat-sdk-runtime.js";
import type { TelegramDraftControl } from "../../services/chat-telegram-draft-stop.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { githubAttachmentLocator, rehydrateGitHubPublicAttachment } from "../../services/chat-github-attachments.js";
import { getEmbeddedPostgresTestSupport } from "../helpers/embedded-postgres.js";
export const historyTestDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_HISTORY_TEST_DATABASE_URL");
export const slackProtocolCapture = process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1";
export const slackProtocolDatabaseUrl = slackProtocolCapture ? resolveExternalTestDatabaseUrl("PAPERCLIP_SLACK_TEST_DATABASE_URL") : undefined;
if (slackProtocolCapture && !slackProtocolDatabaseUrl) throw new Error("Slack protocol capture requires an explicit dedicated test database");
export const externalTestDatabaseUrl = slackProtocolDatabaseUrl ?? historyTestDatabaseUrl ?? process.env.PAPERCLIP_TEST_DATABASE_URL;
export const embeddedPostgresSupport = externalTestDatabaseUrl
? { supported: true }
: await getEmbeddedPostgresTestSupport();
export const describeEmbeddedPostgres = embeddedPostgresSupport.supported
? describe
: describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping chat-channel integration tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
export type TestDb = ReturnType<typeof createDb>;
export class FakeEndpointRuntime {
readonly initialize = vi.fn(async () => {
await this.initializeHook?.(this.options.endpointId);
});
readonly shutdown = vi.fn(async () => undefined);
readonly posts: Array<{
threadId: string;
text: string;
attachments?: unknown[];
chunks?: string[];
files?: unknown[];
}> = [];
readonly edits: Array<{
threadId: string;
messageId: string;
text: string;
}> = [];
readonly editAttempts: Array<{
threadId: string;
messageId: string;
}> = [];
readonly reactions: Array<{
threadId: string;
messageId: string;
emoji: string;
}> = [];
readonly reactionErrors: Error[] = [];
readonly removedReactions: Array<{
threadId: string;
messageId: string;
emoji: string;
}> = [];
readonly removeReactionErrors: Error[] = [];
readonly rehydratedAttachmentDescriptors: unknown[] = [];
readonly postResultIds: string[] = [];
readonly slackFileReceiptLookups: Array<{
fileIds: string[];
threadId: string;
}> = [];
readonly slackFileReceiptResultIds: Array<string | null> = [];
slackFileReceiptCaptureRepeats = 1;
slackFilePublicationAttempts = 0;
slackFilePostAcceptanceError: Error | null = null;
slackFilePostAcceptanceHook: (() => Promise<void>) | undefined;
slackFileReceiptHook: (() => Promise<void>) | undefined;
readonly ensuredDiscordRootThreads: Array<{
channelId: string;
content: string;
messageId: string;
}> = [];
readonly recordedMicrosoftTeamsRoutes: Array<{
threadId: string;
serviceUrl: unknown;
}> = [];
private nextPostId = 0;
postError: Error | null = null;
editError: Error | null = null;
postHook: (() => Promise<void>) | undefined;
webhookHook: ((request: Request) => Promise<void>) | undefined;
webhookRequest: Request | null = null;
webhookResponse = new Response("accepted", {
status: 202,
headers: { "x-chat-test": "accepted" },
});
constructor(
private readonly options: CreateChatSdkEndpointRuntimeOptions,
private readonly attachmentBodies: Map<string, Buffer>,
private readonly initializeHook?: (endpointId: string) => Promise<void>,
) {}
get provider() {
return this.options.providerConfig.provider;
}
async handleWebhook(request: Request) {
this.webhookRequest = request;
await this.webhookHook?.(request);
return this.webhookResponse;
}
async ensureDiscordRootThread(input: {
channelId: string;
content: string;
messageId: string;
}) {
this.ensuredDiscordRootThreads.push(input);
}
async recordMicrosoftTeamsRoute(threadId: string, serviceUrl: unknown) {
this.recordedMicrosoftTeamsRoutes.push({ threadId, serviceUrl });
}
async postSlackFilePublication(
threadId: string,
message: unknown,
onUploadAccepted: (receipt: {
version: 1;
channelId: string;
fileIds: string[];
threadTs: string | null;
}) => Promise<void>,
) {
this.slackFilePublicationAttempts += 1;
await this.postHook?.();
if (this.postError) throw this.postError;
const parts = threadId.split(":");
const files =
message &&
typeof message === "object" &&
"files" in message &&
Array.isArray((message as { files?: unknown }).files)
? (message as { files: unknown[] }).files
: [];
for (
let attempt = 0;
attempt < this.slackFileReceiptCaptureRepeats;
attempt += 1
) {
await onUploadAccepted({
version: 1,
channelId: parts[1] ?? "",
fileIds: files.map((_, index) => `FTEST${index + 1}`),
threadTs: parts[2] || null,
});
}
await this.slackFilePostAcceptanceHook?.();
if (this.slackFilePostAcceptanceError) {
throw this.slackFilePostAcceptanceError;
}
const postHook = this.postHook;
this.postHook = undefined;
try {
return await this.thread(threadId).post(message);
} finally {
this.postHook = postHook;
}
}
async resolveSlackFileUploadReceipt(threadId: string, fileIds: string[]) {
this.slackFileReceiptLookups.push({
fileIds: [...fileIds],
threadId,
});
await this.slackFileReceiptHook?.();
return this.slackFileReceiptResultIds.shift() ?? null;
}
acceptsProviderScope(raw: unknown) {
if (this.options.providerConfig.provider !== "microsoft-teams") return true;
const expected = this.options.providerConfig.credentials.appTenantId;
if (!expected || !raw || typeof raw !== "object") return Boolean(!expected);
const payload = raw as {
conversation?: { tenantId?: unknown };
channelData?: { tenant?: { id?: unknown } };
recipient?: { isTargeted?: unknown };
};
if (payload.recipient?.isTargeted === true) return false;
const tenantIds = [
payload.conversation?.tenantId,
payload.channelData?.tenant?.id,
].filter((value): value is string => typeof value === "string");
return (
tenantIds.length > 0 && tenantIds.every((value) => value === expected)
);
}
async applySlackReceiptReaction(input: {
operation: "add" | "remove";
threadId: string;
messageId: string;
reaction: "eyes";
}) {
const adapter = this.thread(input.threadId).adapter;
if (input.operation === "add")
await adapter.addReaction(
input.threadId,
input.messageId,
input.reaction,
);
else
await adapter.removeReaction(
input.threadId,
input.messageId,
input.reaction,
);
}
async applyGitHubReceiptReaction(
input: Parameters<ChatSdkEndpointRuntime["applyGitHubReceiptReaction"]>[0],
assertCurrent: () => Promise<void>,
) {
await assertCurrent();
await this.applySlackReceiptReaction(input);
return input.githubReceipt ?? { botUserId: "9001", reactionId: "880012" };
}
async streamTelegramDraft(
threadId: string,
stream: AsyncIterable<string>,
control: TelegramDraftControl,
) {
if (!(await control.beforeDraft()) || !(await control.beforeFinal()))
return { paperclipDraftStopped: true as const };
return this.thread(threadId).post(stream);
}
thread(threadId: string) {
const parts = threadId.split(":");
const channelId =
this.options.providerConfig.provider === "discord"
? (parts[2] ?? threadId)
: (parts[1] ?? threadId);
const isTelegramDirectMessage =
this.options.providerConfig.provider === "telegram" &&
/^\d+$/.test(channelId);
return {
id: threadId,
channelId,
isDM: isTelegramDirectMessage || /^D[A-Z0-9-]*$/i.test(channelId),
channel: {
id: channelId,
name: "command-thread",
},
adapter: {
addReaction: async (
reactionThreadId: string,
messageId: string,
emoji: string,
) => {
const error = this.reactionErrors.shift();
if (error) throw error;
this.reactions.push({
threadId: reactionThreadId,
messageId,
emoji,
});
},
removeReaction: async (
reactionThreadId: string,
messageId: string,
emoji: string,
) => {
const error = this.removeReactionErrors.shift();
if (error) throw error;
this.removedReactions.push({
threadId: reactionThreadId,
messageId,
emoji,
});
},
editMessage: async (
editedThreadId: string,
messageId: string,
editedMessage: unknown,
) => {
this.editAttempts.push({ threadId: editedThreadId, messageId });
if (this.editError) throw this.editError;
if (this.postError) throw this.postError;
const text =
editedMessage &&
typeof editedMessage === "object" &&
"markdown" in editedMessage
? String((editedMessage as { markdown: unknown }).markdown)
: JSON.stringify(editedMessage);
this.edits.push({
threadId: editedThreadId,
messageId,
text,
});
return { id: messageId, threadId: editedThreadId };
},
},
startTyping: async () => undefined,
subscribe: async () => undefined,
post: async (message: unknown) => {
await this.postHook?.();
if (this.postError) throw this.postError;
let text: string;
let attachments: unknown[] | undefined;
let chunks: string[] | undefined;
let files: unknown[] | undefined;
if (typeof message === "string") text = message;
else if (
message &&
typeof message === "object" &&
Symbol.asyncIterator in message
) {
chunks = [];
for await (const chunk of message as AsyncIterable<unknown>)
chunks.push(String(chunk));
text = chunks.join("");
} else if (
message &&
typeof message === "object" &&
"markdown" in message
) {
text = String((message as { markdown: unknown }).markdown);
} else text = JSON.stringify(message);
if (
message &&
typeof message === "object" &&
"attachments" in message &&
Array.isArray((message as { attachments?: unknown }).attachments)
) {
attachments = (message as { attachments: unknown[] }).attachments;
}
if (
message &&
typeof message === "object" &&
"files" in message &&
Array.isArray((message as { files?: unknown }).files)
) {
files = (message as { files: unknown[] }).files;
}
this.posts.push({
threadId,
text,
...(attachments ? { attachments } : {}),
...(chunks ? { chunks } : {}),
...(files ? { files } : {}),
});
this.nextPostId += 1;
return {
id: this.postResultIds.shift() ?? `outbound-${this.nextPostId}`,
threadId,
};
},
};
}
attachmentRecoveryDescriptor(attachment: Attachment) {
if (this.options.providerConfig.provider === "github") {
const locator = githubAttachmentLocator(attachment);
return locator
? {
version: 1,
provider: "github",
attachment: { type: attachment.type, name: attachment.name },
locator,
}
: null;
}
const recoveryKey = attachment.fetchMetadata?.testRecoveryKey;
if (typeof recoveryKey !== "string") return null;
return {
version: 1,
provider: this.options.providerConfig.provider,
attachment: {
type: attachment.type,
name: attachment.name,
mimeType: attachment.mimeType,
size: attachment.size,
},
locator: { kind: "test_attachment", recoveryKey },
};
}
parseTelegramCommandMessage(raw: unknown): Message | null {
if (
this.options.providerConfig.provider !== "telegram" ||
!raw ||
typeof raw !== "object"
)
return null;
const document = (raw as { document?: Record<string, unknown> }).document;
const recoveryKey =
typeof document?.file_id === "string" ? document.file_id : null;
if (!recoveryKey || !document) return null;
return makeMessage({
id: `telegram-command:${recoveryKey}`,
text: "",
attachments: [
{
type: "file",
name:
typeof document.file_name === "string"
? document.file_name
: undefined,
mimeType:
typeof document.mime_type === "string"
? document.mime_type
: undefined,
size:
typeof document.file_size === "number"
? document.file_size
: undefined,
fetchMetadata: { testRecoveryKey: recoveryKey },
} as Attachment,
],
});
}
parseMicrosoftTeamsMessage(raw: unknown): Message | null {
if (
this.options.providerConfig.provider !== "microsoft-teams" ||
!raw ||
typeof raw !== "object"
)
return null;
const activity = raw as {
conversation?: { conversationType?: unknown; id?: unknown };
from?: { aadObjectId?: unknown; id?: unknown; name?: unknown };
id?: unknown;
serviceUrl?: unknown;
text?: unknown;
};
if (
typeof activity.id !== "string" ||
typeof activity.conversation?.id !== "string" ||
typeof activity.serviceUrl !== "string"
)
return null;
const conversationType = activity.conversation.conversationType;
const legacyIsDM = !activity.conversation.id.startsWith("19:");
const explicitIsDM = conversationType === "personal";
const includeConversationType =
(conversationType === "channel" ||
conversationType === "groupChat" ||
conversationType === "personal") &&
explicitIsDM !== legacyIsDM;
const threadId = [
"teams",
Buffer.from(activity.conversation.id).toString("base64url"),
...(includeConversationType ? [conversationType] : []),
].join(":");
const userId =
typeof activity.from?.id === "string" ? activity.from.id : "unknown";
const userName =
typeof activity.from?.name === "string" ? activity.from.name : userId;
return {
...makeMessage({
id: activity.id,
raw,
text: typeof activity.text === "string" ? activity.text : "",
userId,
userName,
}),
threadId,
} as Message;
}
rehydrateAttachment(
descriptor: unknown,
source?: { threadId: string; messageId: string },
): Attachment | null {
this.rehydratedAttachmentDescriptors.push(descriptor);
if (!descriptor || typeof descriptor !== "object") return null;
const value = descriptor as {
version?: unknown;
provider?: unknown;
attachment?: Attachment;
locator?: { kind?: unknown; recoveryKey?: unknown };
};
if (
this.options.providerConfig.provider === "github" &&
value.provider === "github" &&
value.version === 1 &&
source
) {
return rehydrateGitHubPublicAttachment(value.locator, source);
}
if (
value.version !== 1 ||
value.provider !== this.options.providerConfig.provider ||
value.locator?.kind !== "test_attachment" ||
typeof value.locator.recoveryKey !== "string" ||
!value.attachment
) {
return null;
}
const body = this.attachmentBodies.get(value.locator.recoveryKey);
if (!body) return null;
return {
...value.attachment,
fetchData: async () => body,
fetchMetadata: { testRecoveryKey: value.locator.recoveryKey },
} as Attachment;
}
async resolveGitHubAttachmentComment(
_request: { url: string; accept: string },
_signal: AbortSignal,
): Promise<unknown> {
return null;
}
}
export class FakeChatSdkRuntime {
readonly endpoints = new Map<string, FakeEndpointRuntime>();
readonly configurations = new Map<
string,
CreateChatSdkEndpointRuntimeOptions
>();
initializeHook: ((endpointId: string) => Promise<void>) | undefined;
replaceCount = 0;
constructor(readonly attachmentBodies: Map<string, Buffer> = new Map()) {}
get(endpointId: string) {
return this.endpoints.get(endpointId) ?? null;
}
hasUnsettledLifecycle() { return false; }
async replaceEndpoint(options: CreateChatSdkEndpointRuntimeOptions) {
this.replaceCount += 1;
this.configurations.set(options.endpointId, options);
const endpoint = new FakeEndpointRuntime(
options,
this.attachmentBodies,
this.initializeHook,
);
this.endpoints.set(options.endpointId, endpoint);
return endpoint;
}
async removeEndpoint(endpointId: string) {
const endpoint = this.endpoints.get(endpointId);
if (!endpoint) return false;
this.endpoints.delete(endpointId);
await endpoint.shutdown();
return true;
}
async shutdown() {
await Promise.all(
[...this.endpoints.values()].map(async (endpoint) => endpoint.shutdown()),
);
this.endpoints.clear();
}
}
export const TEST_SLACK_BOT_SCOPES =
"app_mentions:read,assistant:write,channels:history,channels:read,chat:write,commands,files:read,files:write,groups:history,groups:read,im:history,im:read,mpim:history,mpim:read,reactions:read,reactions:write,users:read";
export const discordApplicationPrefix = 1_400_000_000_000_000_000n +
BigInt(`0x${randomUUID().replaceAll("-", "").slice(0, 12)}`) * 1000n;
export let discordApplicationSequence = 0n;
export function uniqueDiscordApplicationId() {
discordApplicationSequence += 1n;
return (discordApplicationPrefix + discordApplicationSequence).toString();
}
export function fakeSlackFetch(botId = `U-BOT-${randomUUID()}`) {
return (input: string | URL | Request, init?: RequestInit) => {
const url = String(input);
const args = new URLSearchParams(String(init?.body ?? new URL(url).search));
if (url === "https://slack.com/api/auth.test") {
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
team_id: "T-PAPERCLIP",
team: "Paperclip Test",
user_id: botId,
user: `maya-${botId.slice(-8)}`,
}),
{
status: 200,
headers: {
"content-type": "application/json",
"x-oauth-scopes": TEST_SLACK_BOT_SCOPES,
},
},
),
);
}
if (url.startsWith("https://slack.com/api/conversations.list")) {
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
channels: [],
response_metadata: { next_cursor: "" },
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}
if (url.startsWith("https://slack.com/api/conversations.info")) {
const channelId = args.get("channel");
return Promise.resolve(
new Response(
JSON.stringify({
ok: true,
channel: {
id: channelId,
name: channelId?.toLowerCase(),
is_member: true,
is_archived: false,
},
}),
{ status: 200, headers: { "content-type": "application/json" } },
),
);
}
if (url === "https://slack.com/api/users.info") {
return Promise.resolve(Response.json({ ok: true, user: { id: args.get("user"), team_id: "T-PAPERCLIP" } }));
}
if (url === "https://slack.com/api/agents.sessions.setStatus") {
return Promise.resolve(Response.json({ ok: true }));
}
throw new Error(`Unexpected provider request: ${url}`);
};
}
export function fakeDiscordFetch(
applicationId: string,
guildId = "1457808928258658549",
) {
return async (input: string | URL | Request) => {
const path = new URL(String(input)).pathname;
const responses: Record<string, unknown> = {
"/api/v10/users/@me": {
id: applicationId,
username: `maya-${applicationId.slice(-8)}`,
global_name: "Maya",
bot: true,
},
"/api/v10/oauth2/applications/@me": {
id: applicationId,
name: "Maya",
flags: 1 << 18,
},
[`/api/v10/guilds/${guildId}`]: { id: guildId, name: "Clawd" },
[`/api/v10/guilds/${guildId}/members/${applicationId}`]: {
roles: ["222222222222222222"],
user: { id: applicationId },
},
[`/api/v10/guilds/${guildId}/roles`]: [
{ id: "222222222222222222", permissions: "309237763136" },
],
[`/api/v10/guilds/${guildId}/channels`]: [
{
id: "333333333333333333",
name: "agent-lab",
position: 1,
type: 0,
},
],
};
return new Response(JSON.stringify(responses[path]), {
status: path in responses ? 200 : 404,
headers: { "content-type": "application/json" },
});
};
}
export function fakeTelegramFetch(
botId = Number.parseInt(randomUUID().replaceAll("-", "").slice(0, 12), 16),
) {
return async (input: string | URL | Request) => {
const url = String(input);
if (url.endsWith("/getMe")) {
return new Response(
JSON.stringify({
ok: true,
result: {
id: botId,
username: `paperclip_${botId}_bot`,
first_name: "Paperclip Test",
},
}),
{ status: 200, headers: { "content-type": "application/json" } },
);
}
if (url.endsWith("/getWebhookInfo")) {
return new Response(JSON.stringify({ ok: true, result: { url: "" } }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
if (
url.endsWith("/setWebhook") ||
url.endsWith("/setMyCommands") ||
url.endsWith("/deleteWebhook") ||
url.endsWith("/deleteMyCommands")
) {
return new Response(JSON.stringify({ ok: true, result: true }), {
status: 200,
headers: { "content-type": "application/json" },
});
}
throw new Error(`Unexpected provider request: ${url}`);
};
}
export function chatSdkProvider(provider: ChatProvider): ChatSdkProvider {
if (provider === "agentmail" || provider === "speko") throw new Error(`${provider} has no Chat SDK runtime`);
return provider;
}
export function wizardStoreApp(service: ChatChannelService) {
return (
endpointId: string,
userId: string,
credentials: Record<string, string>,
managementContext?: Parameters<ChatChannelService["storeGitHubApp"]>[4],
) => service.storeGitHubApp(endpointId, userId, credentials, "manifest", managementContext);
}
export function makeThread(input: {
channelId: string;
id: string;
isDM?: boolean;
name?: string;
}) {
const addReaction = vi.fn(async () => undefined);
const startTyping = vi.fn(async () => undefined);
const subscribe = vi.fn(async () => undefined);
const postEphemeral = vi.fn(async (_user?: unknown, _message?: unknown, _options?: unknown) => ({
id: `thread-ephemeral-${randomUUID()}`,
threadId: input.id,
usedFallback: false,
}));
const post = vi.fn(async () => ({
id: `thread-post-${randomUUID()}`,
threadId: input.id,
}));
const thread = {
id: input.id,
channelId: input.channelId,
isDM: input.isDM ?? false,
channel: { id: input.channelId, name: input.name ?? input.channelId },
adapter: { addReaction },
startTyping,
subscribe,
post,
postEphemeral,
} as unknown as Thread;
return {
thread,
addReaction,
startTyping,
subscribe,
post,
postEphemeral,
};
}
export function makeMessage(input: {
attachments?: Attachment[];
id: string;
raw?: unknown;
text: string;
mentioned?: boolean;
userId?: string;
userName?: string;
}) {
return {
id: input.id,
raw: input.raw,
text: input.text,
isMention: input.mentioned ?? false,
attachments: input.attachments ?? [],
metadata: { dateSent: new Date(), edited: false },
author: {
userId: input.userId ?? "U-EXTERNAL",
userName: input.userName ?? "alex",
fullName: "Alex External",
isBot: false,
isMe: false,
isSystem: false,
} satisfies Author,
} as unknown as Message;
}
export function boardActor(companyId: string, userId = "owner-user") {
return {
type: "board" as const,
source: "session" as const,
userId,
isInstanceAdmin: false,
companyIds: [companyId],
memberships: [{ companyId, status: "active", membershipRole: "operator" }],
};
}
export function routesApp(
db: TestDb,
companyId: string,
service: ChatChannelService,
userId = "owner-user",
) {
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = boardActor(companyId, userId);
next();
});
app.use(
"/api",
chatChannelRoutes(db, {
heartbeat: { wakeup: async () => undefined },
service,
}),
);
app.use(errorHandler);
return app;
}
export function webhookApp(
service: ChatChannelService,
diagnostics?: (event: ChatWebhookDiagnosticEvent) => void,
) {
const app = express();
if (diagnostics) app.use(createChatWebhookDiagnostics({ emit: diagnostics }));
app.use(express.raw({ type: "*/*" }));
app.use(chatWebhookRoutes(service));
app.use(errorHandler);
return app;
}
@@ -0,0 +1,905 @@
// Shared retry and committed-response recovery fixture builders.
import { requestTaskRetry } from "../../services/task-retry.js";
import { withQueuedCommentIdsInWakePayload } from "../../services/issue-queued-comment-queue.js";
import { createSystemRecovery } from "../../services/system-recovery-state.js";
import { githubChatManagementService } from "../../services/chat-github-management.js";
import { githubResponseCommentService } from "../../services/chat-github-response-comments.js";
import { chatGitHubConfigurations } from "@paperclipai/db";
import { randomUUID } from "node:crypto";
import express from "express";
import request from "supertest";
import { and, eq, sql } from "drizzle-orm";
import { beforeAll, expect, vi } from "vitest";
import { agents, agentWakeupRequests, chatActions, chatDeliveries, chatEndpointResources, chatExternalPrincipals, chatMessageLinks, chatPublications, completionContracts, heartbeatRunEvents, heartbeatRuns, issueRecoveryActions, issues, nativeRunResults, nativeRunFinalizations, environmentLeases } from "@paperclipai/db";
import { type ChatProvider } from "@paperclipai/shared";
import { errorHandler } from "../../middleware/index.js";
import { issueRoutes } from "../../routes/issues.js";
import { type ChatChannelService } from "../../services/chat-channels.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { heartbeatService } from "../../services/heartbeat.js";
import { githubPublicAttachmentsFromMessage } from "../../services/chat-github-attachments.js";
import * as attachmentEgress from "../../services/remote-http-fetch.js";
import type { PrpStructuredRunResult, PrpTerminalState } from "../../vendor/paperclip-runner/index.js";
import { finalizeNativeRun, repairCommittedNativeChatResponse } from "../../services/native-runtime/native-run-finalizer.js";
import { NativeRunCoordinatorStore } from "../../services/native-runtime/native-run-coordinator-store.js";
import { PaperclipControlPlanePort } from "../../services/native-runtime/paperclip-control-plane-port.js";
import { type TestDb, makeThread, makeMessage, boardActor } from "./providers.js";
import type { ChatChannelHarness } from "./harness.js";
import type { GitHubHarness } from "./github-harness.js";
export function createRetryFixtures(h: ChatChannelHarness, gh: GitHubHarness) {
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { seedCompany, readChatConversationsByEndpointId, readIssuesById, readChatPublicationsByEndpointId, readAgentWakeupRequestsById, createStorageService, chatWakeContext, configuredSlackEndpoint, configuredTeamsEndpoint, configuredTelegramEndpoint, configuredDiscordEndpoint, deliverMessage, linkLifecycleFixtureActor } = h;
const { configuredGitHubEndpoint } = gh;
type SharedEndpointProgress = {
fixture: Awaited<ReturnType<typeof seedCompany>>;
configured: Awaited<ReturnType<typeof configuredTelegramEndpoint>> | Awaited<ReturnType<typeof configuredSlackEndpoint>>;
suffix: string;
};
async function failedChatRetryFixture(
provider: "slack" | "telegram" | "github",
externalActorId?: string,
linkedOriginalActor = false,
githubUnavailableFile = false,
currentGitHubPr = false,
shared?: SharedEndpointProgress,
) {
// Keep the policy under which the source was admitted. Inserting an
// upgraded GitHub policy after receipt correctly invalidates retry proof.
const context = await safeNativeProgressFixture(
provider,
shared?.suffix ?? "91",
"channel",
externalActorId,
linkedOriginalActor,
githubUnavailableFile,
false,
currentGitHubPr,
shared,
);
const [issue] = await readIssuesById(context.conversation.issueId);
const [action] = await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.conversationId, context.conversation.id),
eq(chatActions.kind, "inbound_wakeup"),
),
);
const [receipt] = await readAgentWakeupRequestsById(action.id);
const runId = randomUUID();
await db.insert(heartbeatRuns).values({
id: runId,
companyId: context.fixture.companyId,
agentId: context.fixture.assignedAgentId,
status: "failed",
errorCode: "adapter_failed",
finishedAt: new Date(),
wakeupRequestId: receipt.id,
contextSnapshot: {
issueId: issue.id,
taskKey: issue.identifier,
source: `chat:${provider}`,
wakeCommentId: action.payload.commentId,
wakeCommentIds: [action.payload.commentId],
},
});
await db
.update(agentWakeupRequests)
.set({ status: "failed", runId })
.where(eq(agentWakeupRequests.id, receipt.id));
await db
.update(issues)
.set({
description: "ORIGINAL task, not the failed request",
status: "blocked",
executionRunId: null,
})
.where(eq(issues.id, issue.id));
return { ...context, issue, action, receipt, runId };
}
async function currentGitHubTaskRetryFixture(withPending = false, pendingCount = 1) {
const f = await failedChatRetryFixture("github", "42", true);
const companyId = f.fixture.companyId, issueId = f.issue.id;
await githubResponseCommentService(db, f.providerFetch).tryAcknowledge(f.action.deliveryId!);
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId,
nativePhase: "terminal_failure", runnerProfileJson: {} }).where(eq(heartbeatRuns.id, f.runId));
await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId: f.runId, phase: "terminal_failure" });
await db.insert(heartbeatRunEvents).values({ companyId, agentId: f.fixture.assignedAgentId, runId: f.runId,
seq: 1, eventType: "native.local_process_stopped", payload: { processPid: 999999999, processGroupId: null } });
let pending: typeof chatActions.$inferSelect | undefined;
if (withPending) {
for (let index = 0; index < pendingCount; index++) {
await deliverMessage({ callbacks: f.runtime.configurations.get(f.endpoint.id)!.callbacks,
endpointId: f.endpoint.id, provider: "github", thread: f.thread.thread,
message: makeMessage({ id: String(990092 + index), text: `@maya continue saved follow-up ${index}`, userId: "42", mentioned: true }),
trigger: "mention" });
const [{ source }] = await db.select({ source: chatActions }).from(chatActions)
.innerJoin(chatDeliveries, eq(chatDeliveries.id, chatActions.deliveryId)).where(and(
eq(chatActions.conversationId, f.conversation.id), eq(chatActions.kind, "inbound_wakeup"),
eq(chatDeliveries.providerEventId, `${f.thread.thread.id}:${990092 + index}`)));
pending ??= source;
await db.update(agentWakeupRequests).set({ status: "deferred_issue_execution", runId: null })
.where(eq(agentWakeupRequests.id, source.id));
await githubResponseCommentService(db, f.providerFetch).tryAcknowledge(source.deliveryId!);
}
}
const [originalDelivery] = await db.select().from(chatDeliveries).where(eq(chatDeliveries.id, f.action.deliveryId!));
await db.update(agents).set({ adapterType: "paperclip_runner", status: "running",
runtimeConfig: { heartbeat: { wakeOnDemand: true, maxConcurrentRuns: 1 } } })
.where(eq(agents.id, f.fixture.assignedAgentId));
await db.insert(heartbeatRuns).values({ companyId, agentId: f.fixture.assignedAgentId,
status: "running", startedAt: new Date() });
f.wakeup.mockImplementation(heartbeatService(db).wakeup);
return { ...f, pending, originalDelivery };
}
async function busyChatRetryHttpFixture(withPending = false) {
const f = await currentGitHubTaskRetryFixture(withPending);
const originalPublications = await readChatPublicationsByEndpointId(f.endpoint.id);
const { issueRoutes } = await import("../../routes/issues.js");
const companyId = f.fixture.companyId, issueId = f.issue.id;
const app = express();
app.use(express.json());
app.use((req, _res, next) => { req.actor = boardActor(companyId); next(); });
app.use("/api", issueRoutes(db, createStorageService().storage, { chatRunRetries: f.service }));
app.use(errorHandler);
let release = () => {};
const held = new Promise<void>(resolve => { release = resolve; });
let acquired = () => {};
const locked = new Promise<void>(resolve => { acquired = resolve; });
const holding = db.transaction(async tx => {
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`chat-identity:${companyId}:${f.action.principalId}`}, 0))`);
acquired();
await held;
});
await locked;
f.wakeup.mockClear();
return { ...f, app, companyId, issueId, originalPublications,
releaseIdentity: async () => { release(); await holding; } };
}
async function successfulGitHubQueuedInputFixture() {
const f = await currentGitHubTaskRetryFixture(true);
const companyId = f.fixture.companyId, issueId = f.issue.id;
const [saved] = await readAgentWakeupRequestsById(f.pending!.id);
await db.update(agentWakeupRequests).set({ payload: withQueuedCommentIdsInWakePayload(saved.payload,
[String(f.pending!.payload.commentId)]) }).where(eq(agentWakeupRequests.id, saved.id));
const contractId = randomUUID(), resultId = randomUUID();
await db.insert(completionContracts).values({ id: contractId, companyId, issueId, revision: 1,
schemaVersion: "paperclip.completion-contract.v1", policyVersion: "test", risk: "standard",
completionAuthority: "server_arbiter", incompleteCriteriaPolicy: "preserve_non_terminal", contractJson: {},
canonicalSha256: contractId, createdByActorType: "system", createdByActorId: "test" });
await db.update(heartbeatRuns).set({ status: "succeeded", errorCode: null, nativePhase: "committed",
completionContractId: contractId }).where(eq(heartbeatRuns.id, f.runId));
const [result] = await db.insert(nativeRunResults).values({ id: resultId, companyId, issueId, runId: f.runId,
completionContractId: contractId, serverFingerprint: resultId, schemaStatus: "accepted", canonicalSha256: resultId,
resultJson: { terminal: { runTerminalState: "succeeded" }, summary: "Earlier review remains saved" } }).returning();
await db.update(nativeRunFinalizations).set({ phase: "committed", resultId }).where(eq(nativeRunFinalizations.runId, f.runId));
await db.update(agentWakeupRequests).set({ status: "completed" }).where(eq(agentWakeupRequests.id, f.receipt.id));
const input = { db, companyId, issueId, actorId: "owner-user", actorSource: "cloud_tenant",
observedRunId: f.runId, idempotencyKey: randomUUID(), prepareChatRetry: f.service.prepareFailedChatRunRetry };
return { ...f, input, result };
}
async function deferredFailedRetryNoticeFixture(wakeOnDemand = true) {
const context = await failedChatRetryFixture("telegram", undefined, true);
const companyId = context.fixture.companyId, issueId = context.issue.id, leaseId = randomUUID();
await db.update(heartbeatRuns).set({ runtimeMode: "native", nativeIssueId: issueId,
nativePhase: "terminal_failure", runnerProfileJson: {},
resultJson: { workspaceRestoreFailure: "restore_failed", workspaceRestoreRecovery: {
schema: "paperclip.workspace-restore-recovery.v1", runId: context.runId, leaseIds: [leaseId],
} },
}).where(eq(heartbeatRuns.id, context.runId));
await db.insert(nativeRunFinalizations).values({ companyId, issueId, runId: context.runId, phase: "terminal_failure" });
await db.insert(environmentLeases).values({ id: leaseId, companyId, issueId,
heartbeatRunId: context.runId, provider: "daytona", providerLeaseId: randomUUID(),
status: "pending_cleanup", cleanupStatus: "failed", leasePolicy: "retain_on_failure",
metadata: { remoteCwd: "/home/daytona/paperclip-workspace", pendingCleanupInFlight: false },
});
await db.insert(issueRecoveryActions).values({ companyId, sourceIssueId: issueId,
kind: "active_run_watchdog", status: "resolved", ownerType: "system",
cause: "native_continuation_requires_reconciliation", fingerprint: randomUUID(),
nextAction: "Verify and preserve the retained source before continuing.",
evidence: { runId: context.runId, automaticRecovery: { replay: "blocked" },
workspaceRestoreRecovery: { schema: "paperclip.workspace-restore-recovery.v1", leaseIds: [leaseId] },
historicalWorkspaceSource: { schema: "paperclip.historical-workspace-source.v1", runId: context.runId, leaseIds: [leaseId] },
systemRecovery: { ...createSystemRecovery(context.runId), state: "exhausted", attempts: 2, retriesUsed: 1,
attemptId: randomUUID(), firstFailureAt: Date.now() - 1000, deadlineAt: Date.now() + 60_000,
preservationOperationIds: [randomUUID()] },
},
});
const retry = await requestTaskRetry({ db, companyId, issueId, actorId: "owner-user",
actorSource: "cloud_tenant", observedRunId: context.runId, idempotencyKey: randomUUID(),
prepareChatRetry: context.service.prepareFailedChatRunRetry });
await db.update(agents).set({ adapterType: "paperclip_runner", status: "running",
runtimeConfig: { heartbeat: { wakeOnDemand, maxConcurrentRuns: 1 } },
}).where(eq(agents.id, context.fixture.assignedAgentId));
await db.insert(heartbeatRuns).values({ companyId, agentId: context.fixture.assignedAgentId,
status: "running", startedAt: new Date() });
context.wakeup.mockImplementation(heartbeatService(db).wakeup);
return { ...context, retry, admit: () => context.service.processFailedChatRunRetry(retry.chatActionId!) };
}
async function failedReviewedGitHubRetryFixture() {
const context = await failedChatRetryFixture("github");
await db
.update(issues)
.set({ status: "in_review" })
.where(eq(issues.id, context.issue.id));
await db
.update(heartbeatRuns)
.set({
errorCode: "setup_failed",
error: "reviewed_chat_execution_binding_not_authorized",
startedAt: new Date(Date.now() - 10),
finishedAt: new Date(),
// Admission captures the prior display/session identity before any
// execution starts. It is not evidence of a turn for this new run.
sessionIdBefore: "prior-provider-session",
})
.where(eq(heartbeatRuns.id, context.runId));
await db.insert(heartbeatRunEvents).values({
companyId: context.fixture.companyId,
agentId: context.fixture.assignedAgentId,
runId: context.runId,
seq: 1,
eventType: "error",
stream: "system",
level: "error",
message: "reviewed_chat_execution_binding_not_authorized",
});
return context;
}
async function safeNativeProgressFixture(
provider: ChatProvider,
suffix: string,
teamsSurface: "channel" | "personal" = "channel",
externalActorId?: string,
linkedOriginalActor = false,
githubUnavailableFile = false,
upgradedGitHub = true,
currentGitHubPr = false,
shared?: SharedEndpointProgress,
) {
const fixture = shared?.fixture ?? await seedCompany();
const configured = shared?.configured ?? (
provider === "slack"
? await configuredSlackEndpoint(fixture)
: provider === "github"
? await configuredGitHubEndpoint(
fixture,
githubUnavailableFile
? { storage: createStorageService().storage }
: {},
)
: provider === "discord"
? await configuredDiscordEndpoint(fixture)
: provider === "microsoft-teams"
? await configuredTeamsEndpoint(fixture)
: await configuredTelegramEndpoint(fixture));
const { callbacks, endpoint, runtime, service } = configured;
const telegramChatId = `77113${suffix.padStart(3, "0")}`;
const teamsConversationId = `19:safe-progress-${suffix}@thread.${teamsSurface === "channel" ? "tacv2" : "v2"}`;
const teamsServiceUrl = "https://smba.trafficmanager.net/amer/";
const messageId =
provider === "slack"
? `1789000${suffix}.100001`
: provider === "github"
? `9900${suffix}`
: provider === "discord"
? `55555555555556${suffix.padStart(3, "0")}`
: provider === "microsoft-teams"
? `17400000${suffix.padStart(5, "0")}`
: `${telegramChatId}:101`;
const thread =
provider === "slack"
? makeThread({
channelId: `C-SAFE-PROGRESS-${suffix}`,
id: `slack:C-SAFE-PROGRESS-${suffix}:${messageId}`,
name: `safe-progress-${suffix}`,
})
: provider === "github"
? makeThread({
channelId: currentGitHubPr ? "paperclipai/paperclip" : "github:paperclipai/paperclip",
id: currentGitHubPr ? `github:paperclipai/paperclip:${700 + Number(suffix)}` : `github:paperclipai/paperclip:issue:${700 + Number(suffix)}`,
name: "paperclipai/paperclip",
})
: provider === "discord"
? makeThread({
channelId: `33333333333334${suffix.padStart(3, "0")}`,
id: `discord:1457808928258658549:33333333333334${suffix.padStart(3, "0")}:${messageId}`,
name: `safe-progress-${suffix}`,
})
: provider === "microsoft-teams"
? makeThread({
channelId: `teams:${Buffer.from(teamsConversationId).toString("base64url")}:${Buffer.from(teamsServiceUrl).toString("base64url")}`,
id: `teams:${Buffer.from(`${teamsConversationId}${teamsSurface === "channel" ? `;messageid=${messageId}` : ""}`).toString("base64url")}:${Buffer.from(teamsServiceUrl).toString("base64url")}`,
isDM: teamsSurface === "personal",
name: `safe-progress-${suffix}`,
})
: makeThread({
channelId: telegramChatId,
id: `telegram:${telegramChatId}`,
isDM: true,
name: `safe-progress-${suffix}`,
});
if (provider === "microsoft-teams" && teamsSurface === "channel") {
await db.insert(chatEndpointResources).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
type: "channel",
providerResourceId: teamsConversationId,
label: "Native progress channel",
availability: "available",
enabled: true,
});
}
if (linkedOriginalActor) {
const currentEndpoint = await service.get(endpoint.id);
const originalActorId =
externalActorId ??
(provider === "telegram" ? telegramChatId : "U-SAFE-PROGRESS");
await db.insert(chatExternalPrincipals).values({
companyId: fixture.companyId,
provider,
providerAccountId: currentEndpoint.providerAccountId!,
externalId: originalActorId,
kind: "user",
isBot: false,
});
await linkLifecycleFixtureActor({
companyId: fixture.companyId,
endpointId: endpoint.id,
externalId: originalActorId,
});
}
if (provider === "github" && currentGitHubPr) {
const config = await githubChatManagementService(db).configuration(endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: fixture.companyId, endpointId: endpoint.id,
configuration: { ...config.configuration, toolsEnabled: true, defaults: { ...config.configuration.defaults,
invocation: "mentions_only", events: [] } }, updatedByUserId: "owner-user" });
}
const sourceMessage = makeMessage({
id: messageId,
mentioned: !thread.thread.isDM,
text: thread.thread.isDM
? "Show safe progress"
: "@maya show safe progress",
userId:
externalActorId ??
(provider === "telegram" ? telegramChatId : "U-SAFE-PROGRESS"),
});
if (currentGitHubPr) sourceMessage.raw = { action: "created", installation: { id: 2468 },
repository: { id: 97531, full_name: "paperclipai/paperclip" }, issue: { number: 791, pull_request: {} },
sender: { id: 42, login: "octocat", type: "User" }, comment: { id: Number(messageId), body: sourceMessage.text, user: { id: 42 } } };
if (githubUnavailableFile) {
const url =
"https://github.com/user-attachments/files/31967808/private-current.txt";
sourceMessage.text = `@maya inspect only this exact file: [file](${url})`;
Object.assign(sourceMessage, { threadId: thread.thread.id });
sourceMessage.raw = {
type: "issue_comment",
threadType: "issue",
prNumber: 700 + Number(suffix),
repository: { full_name: "paperclipai/paperclip" },
comment: {
id: Number(messageId),
body: sourceMessage.text,
user: { id: 42 },
},
};
sourceMessage.formatted = {
type: "root",
children: [{ type: "link", url, children: [] }],
};
sourceMessage.attachments.push(
...githubPublicAttachmentsFromMessage(sourceMessage),
);
}
await deliverMessage({
callbacks,
endpointId: endpoint.id,
provider,
thread: thread.thread,
message: sourceMessage,
trigger: thread.thread.isDM ? "direct_message" : "mention",
});
const conversations = await readChatConversationsByEndpointId(endpoint.id);
const conversation = shared ? conversations.find(row => row.externalThreadId === thread.thread.id) : conversations[0];
if (!conversation) throw new Error("Expected safe-progress conversation");
const providerRuntime = runtime.endpoints.get(endpoint.id);
if (!providerRuntime) throw new Error("Expected safe-progress runtime");
if (provider === "github" && upgradedGitHub) {
// These fixtures exercise upgraded bots' tool-owned reply model.
const config = await githubChatManagementService(db).configuration(endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: fixture.companyId, endpointId: endpoint.id, configuration: config.configuration, updatedByUserId: "owner-user" });
}
const createRun = async (label: string) => {
const runId = randomUUID();
const baseCreatedAt = new Date(Date.now() - 60_000);
await db.insert(heartbeatRuns).values({
id: runId,
companyId: fixture.companyId,
agentId: fixture.assignedAgentId,
runtimeMode: "native",
status: "running",
contextSnapshot: await chatWakeContext({
endpointId: endpoint.id,
issueId: conversation.issueId,
provider,
providerMessageId: messageId,
}),
});
await db.insert(chatPublications).values({
companyId: fixture.companyId,
endpointId: endpoint.id,
conversationId: conversation.id,
issueId: conversation.issueId,
idempotencyKey: `run:${runId}:working:${endpoint.id}`,
payload: {
text: `Maya is working on ${label}…`,
progressState: "working",
},
state: "pending",
createdAt: baseCreatedAt,
updatedAt: baseCreatedAt,
});
await service.processPendingPublications(100);
return { baseCreatedAt, runId };
};
const addEvent = async (
run: Awaited<ReturnType<typeof createRun>>,
eventType = "item.completed",
seq = 1,
createdAt = new Date(run.baseCreatedAt.getTime() + 30_000 + seq),
) => {
await db.insert(heartbeatRunEvents).values({
companyId: fixture.companyId,
runId: run.runId,
agentId: fixture.assignedAgentId,
seq,
eventType,
message: "PRIVATE native event prose must stay in Paperclip",
payload: {
toolName: "secret_internal_tool",
arguments: { token: "PRIVATE-NATIVE-TOKEN" },
result: "PRIVATE-NATIVE-RESULT",
target: "PRIVATE-NATIVE-TARGET",
},
createdAt,
});
};
return {
addEvent,
conversation,
createRun,
endpoint,
fixture,
messageId,
providerRuntime,
runtime,
service,
thread,
wakeup: configured.wakeup,
providerFetch:
"providerFetch" in configured ? (configured.providerFetch as typeof globalThis.fetch) : undefined,
};
}
async function committedChatResponseRecoveryFixture(
provider: "slack" | "telegram" | "github",
format: "coordinator" | "port" = "coordinator",
githubUnavailableFile = false,
beforeAcceptance?: (
context: Awaited<ReturnType<typeof failedChatRetryFixture>>,
) => Promise<void>,
summary?: (issueId: string) => string,
finalize = true,
shared?: SharedEndpointProgress,
) {
const context = await failedChatRetryFixture(
provider,
provider === "github" ? "42" : undefined,
false,
githubUnavailableFile,
false,
shared,
);
if (provider === "github") {
const config = await githubChatManagementService(db).configuration(context.endpoint.id, "owner-user");
await db.insert(chatGitHubConfigurations).values({ companyId: context.fixture.companyId, endpointId: context.endpoint.id, configuration: config.configuration, updatedByUserId: "owner-user" });
}
await beforeAcceptance?.(context);
const contractId = randomUUID();
const sessionId = randomUUID();
const runnerId = randomUUID();
const contractSha256 = `recovered-response-${randomUUID()}`;
await db.insert(completionContracts).values({
id: contractId,
companyId: context.fixture.companyId,
issueId: context.issue.id,
revision: 1,
schemaVersion: "paperclip.completion-contract.v1",
policyVersion: "phase6-v3",
risk: "low",
completionAuthority: "agent_claim_policy",
incompleteCriteriaPolicy: "preserve_non_terminal",
contractJson: {
revision: "recovered-response-v1",
objective: "Answer the exact message",
criteria: [
{ id: "response", requirement: "Return the requested answer" },
],
},
canonicalSha256: contractSha256,
createdByActorType: "system",
createdByActorId: "test",
});
await db
.update(heartbeatRuns)
.set({
runtimeMode: "native",
nativeIssueId: context.issue.id,
nativeSessionId: sessionId,
runnerInstanceId: runnerId,
completionContractId: contractId,
completionContractSha256: contractSha256,
status: "failed",
errorCode: "adapter_failed",
error: "provider_transport_failed: checkpoint is quarantined",
finishedAt: new Date(),
processPid: 987654,
runnerProfileJson: {
sessionCheckpoint: { retainedEvidence: "do not alter" },
},
})
.where(eq(heartbeatRuns.id, context.runId));
await db
.update(issues)
.set({ status: "in_review", executionRunId: null })
.where(eq(issues.id, context.issue.id));
const result: PrpStructuredRunResult = {
schema: "paperclip.run_result.v1",
reportedWorkDisposition: "yielded",
summary:
summary?.(context.issue.id) ??
"This is the exact accepted answer. I will wait for your next message.",
completionClaim: {
contractRevision: "recovered-response-v1",
objectiveSatisfied: true,
criteria: [
{ criterionId: "response", status: "satisfied", evidenceRefs: [] },
],
remainingWork: [],
},
evidence: [],
verification: [],
attentionRequests: [],
artifacts: [],
continuation: {
kind: "response_wake",
summary: "Wait for the next authorized message.",
idempotencyKey: `wait:${context.runId}`,
},
};
const terminal: PrpTerminalState = {
schema: "paperclip.prp.terminal.v1",
turnTerminalState: "completed",
runTerminalState: "succeeded",
reportedWorkDisposition: "yielded",
workAssessmentId: randomUUID(),
statusDecisionId: randomUUID(),
};
const binding = {
companyId: context.fixture.companyId,
issueId: context.issue.id,
runId: context.runId,
agentId: context.fixture.assignedAgentId,
normalizedSessionId: sessionId,
runnerSourceInstanceId: runnerId,
completionContractId: contractId,
completionContractSha256: contractSha256,
completionContractRevision: "recovered-response-v1",
completionContractCriterionIds: ["response"],
};
if (format === "coordinator") {
await new NativeRunCoordinatorStore(db, binding).completeRun({
result,
terminal,
turnId: `turn-${context.runId}`,
});
} else {
const controlPlaneSourceInstanceId = `control-${context.runId}`;
const port = new PaperclipControlPlanePort(db, {
companyId: binding.companyId,
issueId: binding.issueId,
runId: binding.runId,
agentId: binding.agentId,
sessionId,
completionContractId: contractId,
completionContractSha256: contractSha256,
sourceInstanceId: runnerId,
controlPlaneSourceInstanceId,
});
await port.openRun({
identity: {
companyId: binding.companyId,
issueId: binding.issueId,
runId: binding.runId,
agentId: binding.agentId,
sessionId,
},
backendKind: "mock",
sourceInstanceId: runnerId,
});
await port.completeRun({
result,
terminal,
turnId: `turn-${context.runId}`,
});
await db.insert(heartbeatRunEvents).values({
companyId: binding.companyId,
agentId: binding.agentId,
runId: binding.runId,
seq: 1,
eventType: "run.result.accepted",
sourceInstanceId: controlPlaneSourceInstanceId,
payload: { prpEvent: { sourceKind: "control_plane" } },
});
}
const [acceptedRow] = await db
.select()
.from(nativeRunResults)
.where(eq(nativeRunResults.runId, context.runId));
const accepted = { resultId: acceptedRow.id };
if (finalize) await finalizeNativeRun({
db,
runId: context.runId,
workspaceFinalizeStatus: "succeeded",
});
const [coordinator] = await db
.select()
.from(nativeRunFinalizations)
.where(eq(nativeRunFinalizations.runId, context.runId));
if (finalize) expect(coordinator.phase).toBe("committed");
else expect(coordinator.phase).not.toBe("committed");
await db
.update(heartbeatRuns)
.set({
resultJson: {
finalResponse: "PRIVATE provider narration must not be recovered",
privateTrace: "PRIVATE tool arguments",
},
})
.where(eq(heartbeatRuns.id, context.runId));
const [beforeIssue] = await readIssuesById(context.issue.id);
const repair = () =>
repairCommittedNativeChatResponse(db, {
companyId: context.fixture.companyId,
issueId: context.issue.id,
runId: context.runId,
});
return {
...context,
accepted,
result,
terminal,
binding,
coordinator,
beforeIssue,
repair,
};
}
async function githubOmissionFixture(
unavailable = true,
beforeAcceptance?: Parameters<
typeof committedChatResponseRecoveryFixture
>[3],
summary?: Parameters<typeof committedChatResponseRecoveryFixture>[4],
) {
const egress = vi
.spyOn(attachmentEgress, "guardedRemoteHttpFetch")
.mockResolvedValue(
new Response("private file unavailable", { status: 404 }),
);
try {
const context = await committedChatResponseRecoveryFixture(
"github",
"coordinator",
unavailable,
beforeAcceptance,
summary,
);
return {
...context,
egress,
cleanup: async () => {
try {
await context.service.shutdown();
} finally {
egress.mockRestore();
}
},
};
} catch (error) {
egress.mockRestore();
throw error;
}
}
async function linkedCommittedResponseFailure(
context: Awaited<ReturnType<typeof committedChatResponseRecoveryFixture>>,
runId: string = context.runId,
messageId = "same-run-message",
) {
const [failure] = await db
.insert(chatPublications)
.values({
companyId: context.fixture.companyId,
endpointId: context.endpoint.id,
conversationId: context.conversation.id,
issueId: context.issue.id,
idempotencyKey: `run:${runId}:failed:${context.endpoint.id}`,
payload: {
text: "Maya stopped before completing this turn.",
progressState: "failed",
},
state: "published",
providerMessageId: messageId,
publishedAt: new Date(),
attempts: 1,
})
.returning();
await db.insert(chatMessageLinks).values({
companyId: context.fixture.companyId,
endpointId: context.endpoint.id,
conversationId: context.conversation.id,
publicationId: failure.id,
providerMessageId: messageId,
direction: "outbound",
});
return failure;
}
async function deferredChatQueueFixture(admissionFails = false, beforeAdmission?: (service: ChatChannelService) => Promise<void>, linkedBoardUser = false) {
const fixture = await seedCompany();
let ownerId: string | null = null;
const configured = await configuredSlackEndpoint(fixture, {
linkedBoardUser,
wakeup: async (agentId, opts) => {
if (admissionFails)
throw new Error("PRIVATE admission failure token=do-not-publish");
const request = opts.durableChatRequest!;
await db.transaction(async (tx) => {
await request.authorize(
tx as unknown as Parameters<typeof request.authorize>[0],
);
const [owner] = ownerId
? await tx
.select()
.from(agentWakeupRequests)
.where(eq(agentWakeupRequests.id, ownerId))
: [];
const existingContext = owner?.payload?._paperclipWakeContext as
Record<string, unknown> | undefined;
const commentIds = [
...(Array.isArray(existingContext?.wakeCommentIds)
? existingContext.wakeCommentIds
: []),
request.commentId,
];
const payload = {
...opts.payload,
_paperclipWakeContext: {
...opts.contextSnapshot,
wakeCommentIds: commentIds,
},
};
if (owner)
await tx
.update(agentWakeupRequests)
.set({ payload, coalescedCount: owner.coalescedCount + 1 })
.where(eq(agentWakeupRequests.id, owner.id));
await tx.insert(agentWakeupRequests).values({
id: request.id,
companyId: fixture.companyId,
agentId,
source: "assignment",
reason: "issue_execution_deferred",
status: owner ? "coalesced" : "deferred_issue_execution",
payload: owner
? { ...opts.payload, coalescedIntoWakeupRequestId: owner.id }
: payload,
requestedByActorType: request.requestedByActorType,
requestedByActorId: request.requestedByActorId,
requestedAt: request.requestedAt,
idempotencyKey: request.idempotencyKey,
});
ownerId ??= request.id;
});
return { accepted: true };
},
});
const thread = makeThread({
channelId: "CDEFERREDNOTICE",
id: "slack:CDEFERREDNOTICE:1999000.1",
});
const send = async (id = "1999000.1") =>
deliverMessage({
callbacks: configured.callbacks,
endpointId: configured.endpoint.id,
thread: thread.thread,
message: makeMessage({
id,
text: "@maya exact queued request",
userId: linkedBoardUser ? "UBOARD" : undefined,
mentioned: id === "1999000.1",
}),
trigger: id === "1999000.1" ? "mention" : "subscribed_message",
});
await beforeAdmission?.(configured.service);
await send();
const [conversation] = await readChatConversationsByEndpointId(configured.endpoint.id);
const [action] = await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, configured.endpoint.id),
eq(chatActions.kind, "inbound_wakeup"),
),
);
const promote = async () => {
const [owner] = await readAgentWakeupRequestsById(ownerId!);
const runId = randomUUID();
const contextSnapshot = owner.payload!._paperclipWakeContext as Record<
string,
unknown
>;
await db.transaction(async (tx) => {
await tx.insert(heartbeatRuns).values({
id: runId,
companyId: fixture.companyId,
agentId: fixture.assignedAgentId,
status: "running",
runtimeMode: "native",
wakeupRequestId: owner.id,
contextSnapshot,
});
await tx
.update(agentWakeupRequests)
.set({ runId, status: "claimed" })
.where(eq(agentWakeupRequests.id, owner.id));
});
return runId;
};
return {
...configured,
action,
conversation,
fixture,
promote,
send,
thread,
};
}
return { failedChatRetryFixture, currentGitHubTaskRetryFixture, busyChatRetryHttpFixture, successfulGitHubQueuedInputFixture, deferredFailedRetryNoticeFixture, failedReviewedGitHubRetryFixture, safeNativeProgressFixture, committedChatResponseRecoveryFixture, githubOmissionFixture, linkedCommittedResponseFailure, deferredChatQueueFixture };
}
export type RetryFixtures = ReturnType<typeof createRetryFixtures>;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,726 @@
import { guardSlackFixtureNetwork } from "../helpers/slack-cloud/transport.js";
import { createChatRuntime } from "../../services/chat-runtime.js";
import { createHash, createHmac, randomUUID } from "node:crypto";
import path from "node:path";
import request from "supertest";
import { and, eq, like, or, sql } from "drizzle-orm";
import { beforeAll, expect, it, vi } from "vitest";
import { activityLog, authUsers, chatActions, chatDeliveries, chatEndpoints, chatExternalPrincipals, chatPublications, chatSdkState, companyMemberships, issueQuestionResponseDeliveries, issueThreadInteractions } from "@paperclipai/db";
import { chatChannelService, type ChatChannelService } from "../../services/chat-channels.js";
import type { InternalSetupState } from "../../services/chat-channels/runtime-types.js";
// Opt-in private physical candidate; normal CI uses the staged pinned package.
vi.mock("@chat-adapter/telegram", async (importOriginal) => {
const candidate = process.env.PAPERCLIP_TELEGRAM_STOP_ADAPTER_MODULE;
return candidate ? import(/* @vite-ignore */ candidate) : importOriginal();
});
import { issueThreadInteractionService } from "../../services/issue-thread-interactions.js";
import { type TestDb, slackProtocolCapture, describeEmbeddedPostgres, fakeSlackFetch, makeThread, makeMessage } from "./providers.js";
import { createChatChannelHarness } from "./harness.js";
describeEmbeddedPostgres("chat channels: slack protocol", () => {
const h = createChatChannelHarness();
let db!: TestDb;
beforeAll(() => { db = h.db; });
const { fixtureServices, seedCompany, readChatDeliveriesByEndpointId, readIssueCommentsByCompanyId, receiptBackedWakeup, retirePublicationFixture, qualifySetupRoundTrip, configuredSlackEndpoint, deliverMessage } = h;
it("recovers the visible receipt exactly once after wake acceptance contention", async () => {
const fixture = await seedCompany();
const { callbacks, endpoint, runtime, service, wakeup } =
await configuredSlackEndpoint(fixture);
const first = makeThread({
channelId: "C-RECEIPT-RETRY",
id: "slack:C-RECEIPT-RETRY:1000.1",
name: "receipt-retry",
});
const message = makeMessage({
id: "1000.1",
text: "@maya acknowledge this after retry",
mentioned: true,
});
let releaseLock!: () => void;
let lockEntered!: () => void;
const holdLock = new Promise<void>((resolve) => {
releaseLock = resolve;
});
const entered = new Promise<void>((resolve) => {
lockEntered = resolve;
});
let lockTransaction: Promise<unknown> | undefined;
first.subscribe.mockImplementationOnce(async () => {
lockTransaction = db.transaction(async (tx) => {
await tx
.select({ id: chatEndpoints.id })
.from(chatEndpoints)
.where(eq(chatEndpoints.id, endpoint.id))
.for("update");
lockEntered();
await holdLock;
});
await entered;
});
try {
await expect(
deliverMessage({
callbacks,
endpointId: endpoint.id,
thread: first.thread,
message,
trigger: "mention",
}),
).rejects.toMatchObject({ cause: { code: "55P03" } });
expect(wakeup).not.toHaveBeenCalled();
expect(runtime.endpoints.get(endpoint.id)?.reactions).toEqual([]);
} finally {
releaseLock();
await lockTransaction;
}
await vi.waitFor(
async () => {
await service.processPendingDeliveries();
expect(wakeup).toHaveBeenCalledTimes(1);
expect(runtime.endpoints.get(endpoint.id)?.reactions).toEqual([
{ threadId: first.thread.id, messageId: message.id, emoji: "eyes" },
]);
},
{ timeout: 10_000 },
);
await service.processPendingDeliveries();
expect(wakeup).toHaveBeenCalledTimes(1);
expect(runtime.endpoints.get(endpoint.id)?.reactions).toHaveLength(1);
const [delivery] = await readChatDeliveriesByEndpointId(endpoint.id);
expect(delivery).toMatchObject({ state: "processed" });
expect(
await readIssueCommentsByCompanyId(fixture.companyId),
).toHaveLength(1);
await service.shutdown();
});
it.each(slackProtocolCapture ? ["warm", "command-delayed", "action-delayed", "submission-delayed"] as const : ["warm"] as const)("captures signed Slack forwarding protocol with registered owners (%s)", async mode => {
const network = guardSlackFixtureNetwork({ requirePreload: slackProtocolCapture });
let configured: Awaited<ReturnType<typeof configuredSlackEndpoint>> | undefined;
let routedService: ChatChannelService | undefined;
let actualRuntime: ReturnType<typeof createChatRuntime> | undefined;
let failure: { error: unknown } | undefined;
try {
const fixture = await seedCompany();
configured = await configuredSlackEndpoint(fixture);
const { callbacks, endpoint, runtime, service, wakeup } = configured;
actualRuntime = createChatRuntime();
const custody: Array<{ lane: string; elapsedMs: number; acknowledgedWithin3s: boolean; originalTimestamp: string | null }> = [];
const protocol: Array<{ method: string; triggerAgeMs?: number; outcome: string }> = [];
let triggerCreatedAt = 0;
const channelId = "C-SIGNED-MODAL";
const threadTs = "1788.100";
const externalUserId = `U-MODAL-${randomUUID()}`;
const channel = makeThread({
channelId,
id: `slack:${channelId}:${threadTs}`,
name: "signed-modal",
});
// Existing fixture helpers establish the endpoint, conversation and
// published question. From block_actions onward, signed envelopes pass
// through the real adapter/SDK/runtime and unmocked service callbacks.
// Provider HTTP and the scheduler remain deterministic test boundaries.
await deliverMessage({
callbacks,
endpointId: endpoint.id,
thread: channel.thread,
message: makeMessage({
id: threadTs,
text: "@maya collect deployment details",
mentioned: true,
userId: externalUserId,
}),
trigger: "mention",
});
await qualifySetupRoundTrip(service, endpoint.id, externalUserId);
await service.test(endpoint.id);
const [conversation] = await service.listConversations(endpoint.id);
if (!conversation) throw new Error("Expected signed modal conversation");
const [principal] = await db
.select()
.from(chatExternalPrincipals)
.where(
and(
eq(chatExternalPrincipals.companyId, fixture.companyId),
eq(chatExternalPrincipals.provider, "slack"),
eq(chatExternalPrincipals.externalId, externalUserId),
),
);
const linkedUserId = `signed-modal-user-${randomUUID()}`;
const now = new Date();
await db.insert(authUsers).values({
id: linkedUserId,
name: "Modal Operator",
email: `${linkedUserId}@example.com`,
emailVerified: true,
createdAt: now,
updatedAt: now,
});
await db.insert(companyMemberships).values({
companyId: fixture.companyId,
principalType: "user",
principalId: linkedUserId,
status: "active",
membershipRole: "operator",
});
const intent = await service.createLinkIntent(
endpoint.id,
principal.id,
1_800,
);
const identityToken = new URL(intent.confirmationUrl).searchParams.get(
"token",
);
if (!identityToken) throw new Error("Expected modal identity token");
await service.confirmIdentityLink(identityToken, linkedUserId);
const interaction = await issueThreadInteractionService(db).create(
{ id: conversation.issueId, companyId: fixture.companyId },
{
kind: "ask_user_questions",
continuationPolicy: "wake_assignee",
title: "Deployment details",
payload: {
version: 1,
title: "Deployment details",
submitLabel: "Continue",
questions: [
{
id: "environment",
prompt: "Where should I deploy?",
selectionMode: "single",
required: true,
allowOther: false,
options: [
{ id: "staging", label: "Staging" },
{ id: "production", label: "Production" },
],
},
{
id: "reason",
prompt: "What should the release note say?",
selectionMode: "single",
required: true,
allowOther: true,
options: [
{
id: "__paperclip_text__",
label: "Type an answer",
freeText: true,
},
],
},
],
},
},
{ agentId: fixture.assignedAgentId },
);
runtime.endpoints.get(endpoint.id)!.postResultIds.push("1788.200");
await service.processPendingPublications();
const publication = await db
.select()
.from(chatPublications)
.where(
and(
eq(chatPublications.endpointId, endpoint.id),
eq(chatPublications.conversationId, conversation.id),
),
)
.then((rows) =>
rows.find((row) => row.payload.interactionId === interaction.id),
);
const openAction = publication?.payload.card?.actions?.find(
(action) => action.type === "callback",
);
if (!publication?.providerMessageId || openAction?.type !== "callback") {
throw new Error("Expected published question form action");
}
const configuration = runtime.configurations.get(endpoint.id)!;
if (
configuration.providerConfig.provider !== "slack" ||
!callbacks.onModalSubmit
) {
throw new Error("Expected Slack provider and service modal callback");
}
const credentials = configuration.providerConfig.credentials;
type SlackView = {
callback_id: string;
private_metadata: string;
blocks: Array<{
block_id: string;
element: {
type: string;
action_id: string;
options?: Array<{ text: { text: string }; value: string }>;
};
}>;
};
const views: SlackView[] = [];
const exchangedTriggers = new Set<string>();
const providerMethods: string[] = [];
const unexpectedProviderMethods: string[] = [];
const providerErrors: unknown[] = [];
const providerTransport = vi.fn(async (config: { url: string; baseURL: string; data: string }) => {
const target = new URL(config.url, config.baseURL);
expect(target.hostname).toBe("127.0.0.1");
const params = new URLSearchParams(config.data);
const method = target.pathname.split("/").at(-1) ?? "";
providerMethods.push(method);
let result: unknown;
if (method === "conversations.replies") {
result = {
ok: true,
messages: [
{
type: "message",
ts: publication.providerMessageId,
thread_ts: threadTs,
channel: channelId,
user: credentials.botUserId,
text: "Deployment details",
},
],
};
} else if (method === "users.info") {
result = {
ok: true,
user: {
id: params.get("user"),
name: "maya",
real_name: "Maya",
is_bot: true,
profile: { display_name: "Maya" },
},
};
} else if (method === "conversations.info") {
result = { ok: true, channel: { id: channelId, name: "signed-modal", is_im: false } };
} else if (method === "chat.postEphemeral") {
result = { ok: true, message_ts: "1788.250" };
} else if (method === "views.open") {
const triggerAgeMs = Date.now() - triggerCreatedAt;
const trigger = params.get("trigger_id")!;
const expired = triggerAgeMs >= 3_000;
const reused = exchangedTriggers.has(trigger);
protocol.push({ method, triggerAgeMs, outcome: expired ? "trigger_expired" : reused ? "trigger_exchanged" : "opened" });
if (expired || reused) result = { ok: false, error: expired ? "trigger_expired" : "trigger_exchanged" };
else {
exchangedTriggers.add(trigger);
views.push(JSON.parse(params.get("view")!) as SlackView);
result = { ok: true, view: { id: "V-SIGNED-MODAL" } };
}
} else {
unexpectedProviderMethods.push(method);
result = { ok: false, error: "unexpected_test_provider_method" };
}
return { data: result, status: 200, statusText: "OK", headers: {}, config, request: { path: target.pathname } };
});
const onSubmit = vi.fn(callbacks.onModalSubmit);
const onAction = vi.fn(callbacks.onAction);
const onCommand = vi.fn(callbacks.onSlashCommand);
const replace = actualRuntime.replaceEndpoint.bind(actualRuntime);
vi.spyOn(actualRuntime, "replaceEndpoint").mockImplementation(async input => {
if (input.providerConfig.provider !== "slack") throw new Error("Unexpected fixture provider");
onSubmit.mockImplementation(input.callbacks.onModalSubmit!);
onAction.mockImplementation(input.callbacks.onAction!);
onCommand.mockImplementation(input.callbacks.onSlashCommand!);
const value = await replace({ ...input, logger: "silent",
callbacks: { ...input.callbacks, onModalSubmit: onSubmit, onAction, onSlashCommand: onCommand },
providerConfig: { ...input.providerConfig,
credentials: { ...input.providerConfig.credentials, apiUrl: "http://127.0.0.1:1/api/" } } });
const client = (value.getProviderAdapter() as unknown as { _client: {
axios: { defaults: { adapter: unknown } }; views: { open(options: unknown): Promise<unknown> };
} })._client;
const open = client.views.open.bind(client.views);
client.views.open = async options => {
try { return await open(options); } catch (error) { providerErrors.push(error); throw error; }
};
client.axios.defaults.adapter = providerTransport;
return value;
});
routedService = chatChannelService(db, { runtime: actualRuntime,
fetch: fakeSlackFetch() as typeof globalThis.fetch,
heartbeat: { wakeup: receiptBackedWakeup(wakeup) }, publicBaseUrl: "https://paperclip.example" });
fixtureServices.add(routedService);
const callbackUrl = `https://paperclip.example/api/chat-webhooks/${endpoint.publicId}/slack`;
const forward = async (request: Request, lane: string) => {
const startedAt = Date.now();
const originalTimestamp = request.headers.get("x-slack-request-timestamp");
const originalSignature = request.headers.get("x-slack-signature");
const originalBody = await request.clone().text();
if (mode === "command-delayed" && lane === "command" || mode === "action-delayed" && lane === "action" || mode === "submission-delayed" && lane === "invalid_submission")
await new Promise(resolve => setTimeout(resolve, 3_500)); // test-budget:allow-sleep: tests Slack 3s webhook acknowledgment deadline
const response = await routedService!.handleWebhook(endpoint.publicId, "slack", request);
const elapsedMs = Date.now() - startedAt;
custody.push({ lane, elapsedMs, acknowledgedWithin3s: elapsedMs < 3_000, originalTimestamp });
expect(request.headers.get("x-slack-request-timestamp")).toBe(originalTimestamp);
expect(request.headers.get("x-slack-signature")).toBe(originalSignature);
expect(originalSignature).toBe(`v0=${createHmac("sha256", credentials.signingSecret!).update(`v0:${originalTimestamp}:${originalBody}`).digest("hex")}`);
return response;
};
const signed = (payload: unknown) => {
const body = new URLSearchParams({
payload: JSON.stringify(payload),
}).toString();
const timestamp = String(Math.floor(Date.now() / 1_000));
const signature = createHmac("sha256", credentials.signingSecret!)
.update(`v0:${timestamp}:${body}`)
.digest("hex");
return new Request(callbackUrl, {
method: "POST",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-slack-request-timestamp": timestamp,
"x-slack-signature": `v0=${signature}`,
},
body,
});
};
const wireUser = {
id: externalUserId,
username: "operator",
name: "Modal Operator",
};
const beforeEvidence = ((await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState).slackCallbackSurfaces;
const invalidAuth = signed({ type: "block_actions", team: { id: "T-PAPERCLIP" }, user: wireUser, actions: [] });
invalidAuth.headers.set("x-slack-signature", `v0=${"0".repeat(64)}`);
expect((await routedService.handleWebhook(endpoint.publicId, "slack", invalidAuth)).status).toBe(401);
expect(onAction).not.toHaveBeenCalled();
expect(((await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState).slackCallbackSurfaces).toEqual(beforeEvidence);
const commandBody = new URLSearchParams({ command: endpoint.setup.command!, text: "", user_id: externalUserId,
user_name: "operator", channel_id: channelId, team_id: "T-PAPERCLIP", trigger_id: "synthetic-command-trigger" }).toString();
const commandTimestamp = String(Math.floor(Date.now() / 1_000));
const commandRequest = new Request(callbackUrl, { method: "POST", headers: {
"content-type": "application/x-www-form-urlencoded", "x-slack-request-timestamp": commandTimestamp,
"x-slack-signature": `v0=${createHmac("sha256", credentials.signingSecret!).update(`v0:${commandTimestamp}:${commandBody}`).digest("hex")}`,
}, body: commandBody });
const commandResponse = await forward(commandRequest, "command");
expect(commandResponse.status).toBe(200);
expect(onCommand).toHaveBeenCalledOnce();
expect(await db.select().from(chatActions).where(and(eq(chatActions.endpointId, endpoint.id),
eq(chatActions.kind, "provider_effect"), sql`${chatActions.providerActionId} like 'provider_effect:slash_notice:%'`)))
.toEqual([expect.objectContaining({ companyId: fixture.companyId, endpointId: endpoint.id,
payload: expect.objectContaining({ effect: "ephemeral_message", authorizationMode: "safe_notice", userId: externalUserId }) })]);
expect(custody.find(value => value.lane === "command")!.acknowledgedWithin3s).toBe(mode !== "command-delayed");
const actionPayload = {
type: "block_actions",
team: { id: "T-PAPERCLIP" },
user: wireUser,
channel: { id: channelId },
container: {
type: "message",
channel_id: channelId,
message_ts: publication.providerMessageId,
thread_ts: threadTs,
},
message: { ts: publication.providerMessageId, thread_ts: threadTs },
actions: [{ action_id: openAction.actionId, value: interaction.id }],
trigger_id: "synthetic-signed-modal-trigger",
};
const actionRequest = signed(actionPayload);
triggerCreatedAt = Date.now();
const opened = await forward(actionRequest, "action");
expect(opened.status).toBe(200);
if (mode === "action-delayed") {
expect(protocol).toEqual([{ method: "views.open", triggerAgeMs: expect.any(Number), outcome: "trigger_expired" }]);
expect(protocol[0]!.triggerAgeMs).toBeGreaterThanOrEqual(3_000);
expect(views).toHaveLength(0);
const attempts = await db.select().from(chatActions).where(and(
eq(chatActions.endpointId, endpoint.id), eq(chatActions.kind, "question_form_open_attempt"),
));
expect(attempts).toEqual([expect.objectContaining({ status: "failed", result: expect.objectContaining({ retryable: false }) })]);
const pending = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.id, interaction.id));
expect(pending).toEqual([expect.objectContaining({ status: "pending" })]);
expect(await db.select().from(issueQuestionResponseDeliveries).where(eq(issueQuestionResponseDeliveries.interactionId, interaction.id))).toEqual([]);
await forward(signed(actionPayload), "duplicate_action");
expect(protocol).toHaveLength(1);
expect(onSubmit).not.toHaveBeenCalled();
expect(unexpectedProviderMethods).toEqual([]);
expect(providerErrors).toEqual([expect.objectContaining({ code: "slack_webapi_platform_error", data: expect.objectContaining({ error: "trigger_expired" }) })]);
await Promise.all(providerTransport.mock.results.map(result => result.value));
expect(custody.find(value => value.lane === "action")!.acknowledgedWithin3s).toBe(false);
const observed = (await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState;
expect(observed.slackCallbackSurfaces?.interactivity?.url).toBe(callbackUrl);
expect(observed.slackCallbackSurfaces?.slashCommands?.url).toBe(callbackUrl);
if (process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1") console.info(JSON.stringify({ mode, protocol, custody }));
return;
}
expect(protocol[0]).toMatchObject({ method: "views.open", outcome: "opened" });
expect(protocol[0]!.triggerAgeMs).toBeLessThan(3_000);
expect(views).toHaveLength(1);
await forward(signed(actionPayload), "duplicate_action");
expect(protocol).toHaveLength(1);
expect(views).toHaveLength(1);
const view = views[0]!;
const metadata = JSON.parse(view.private_metadata) as {
c: string;
m: string;
};
expect(metadata).toEqual({ c: expect.any(String), m: view.callback_id });
const select = view.blocks.find(
(block) => block.element?.type === "radio_buttons",
)!;
const text = view.blocks.find(
(block) => block.element?.type === "plain_text_input",
)!;
const production = select.element.options!.find(
(option) => option.text.text === "Production",
)!;
expect(production.value).not.toBe("production");
const submit = (value: string) =>
signed({
type: "view_submission",
team: { id: "T-PAPERCLIP" },
user: wireUser,
view: {
id: "V-SIGNED-MODAL",
callback_id: view.callback_id,
private_metadata: view.private_metadata,
state: {
values: {
[select.block_id]: {
[select.element.action_id]: {
type: "radio_buttons",
selected_option: production,
},
},
[text.block_id]: {
[text.element.action_id]: { type: "plain_text_input", value },
},
},
},
},
});
const sdkContextRows = () =>
db
.select({ id: chatSdkState.id })
.from(chatSdkState)
.where(
and(
eq(chatSdkState.companyId, fixture.companyId),
eq(chatSdkState.endpointId, endpoint.id),
eq(
chatSdkState.stateKey,
`cache:${createHash("sha256").update(`modal-context:slack:${metadata.c}`).digest("hex")}`,
),
),
);
const submissionState = async () => ({
interactions: await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.id, interaction.id)),
tokens: await db
.select()
.from(chatActions)
.where(
and(
eq(chatActions.endpointId, endpoint.id),
eq(chatActions.providerActionId, view.callback_id),
),
),
deliveries: await db
.select()
.from(issueQuestionResponseDeliveries)
.where(
eq(issueQuestionResponseDeliveries.interactionId, interaction.id),
),
audits: await db
.select()
.from(activityLog)
.where(
and(
eq(activityLog.companyId, fixture.companyId),
eq(activityLog.entityId, conversation.issueId),
eq(activityLog.action, "issue.thread_interaction_answered"),
),
),
});
await expect(sdkContextRows()).resolves.toHaveLength(1);
const before = await submissionState();
expect(before.interactions).toEqual([
expect.objectContaining({ status: "pending" }),
]);
expect(before.tokens).toEqual([
expect.objectContaining({ status: "issued" }),
]);
expect(before.deliveries).toEqual([]);
expect(before.audits).toEqual([]);
const wakeupsBefore = wakeup.mock.calls.length;
const invalidStartedAt = Date.now();
const invalid = await forward(submit(""), "invalid_submission");
expect(custody.find(value => value.lane === "invalid_submission")!.acknowledgedWithin3s).toBe(mode !== "submission-delayed");
if (mode === "submission-delayed") expect(Date.now() - invalidStartedAt).toBeGreaterThanOrEqual(3_500);
expect(invalid.status).toBe(200);
expect(await invalid.json()).toEqual({
response_action: "errors",
errors: { [text.block_id]: "Enter a response" },
});
expect(onSubmit.mock.calls[0]![0].event).toMatchObject({
relatedThread: { id: conversation.externalThreadId },
relatedMessage: { id: publication.providerMessageId },
});
await expect(sdkContextRows()).resolves.toEqual([]);
expect(await submissionState()).toEqual(before);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore);
const setRole = (membershipRole: "viewer" | "operator") =>
db
.update(companyMemberships)
.set({ membershipRole, updatedAt: new Date() })
.where(
and(
eq(companyMemberships.companyId, fixture.companyId),
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, linkedUserId),
),
);
await setRole("viewer");
const denied = await forward(submit("Add regional failover"), "current_authority_submission");
expect(denied.status).toBe(200);
expect(await denied.json()).toEqual({
response_action: "errors",
errors: {
[select.block_id]:
"This form is no longer authorized. Close it and open the linked Paperclip task.",
},
});
expect(await submissionState()).toEqual(before);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore);
const denials = await db
.select()
.from(chatDeliveries)
.where(
and(
eq(chatDeliveries.endpointId, endpoint.id),
sql`${chatDeliveries.normalizedEvent}->'modal'->>'code' = 'chat_modal_principal_not_authorized'`,
),
);
expect(denials).toHaveLength(1);
expect(denials[0]).toMatchObject({
state: "filtered",
conversationId: conversation.id,
});
await setRole("operator");
const corrected = await forward(submit(" Add regional failover "), "corrected_submission");
expect(corrected.status).toBe(200);
expect(await corrected.json()).toEqual({ response_action: "clear" });
await vi.waitFor(async () => {
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore + 1);
expect((await submissionState()).deliveries).toEqual([
expect.objectContaining({
status: "fallback_queued",
deliveryMode: "wake_fallback",
}),
]);
});
expect(wakeup).toHaveBeenLastCalledWith(
fixture.assignedAgentId,
expect.objectContaining({
idempotencyKey: `question-response:${interaction.id}`,
requestedByActorType: "user",
requestedByActorId: linkedUserId,
contextSnapshot: expect.objectContaining({
issueId: conversation.issueId,
interactionId: interaction.id,
source: "issue.interaction.respond",
}),
}),
);
const accepted = await submissionState();
expect(accepted.interactions).toEqual([
expect.objectContaining({
companyId: fixture.companyId,
issueId: conversation.issueId,
status: "answered",
resolvedByUserId: linkedUserId,
result: {
version: 1,
summaryMarkdown: null,
answers: [
{ questionId: "environment", optionIds: ["production"] },
{
questionId: "reason",
optionIds: [],
otherText: "Add regional failover",
},
],
},
}),
]);
expect(accepted.tokens).toEqual([
expect.objectContaining({
status: "processed",
conversationId: conversation.id,
principalId: principal.id,
result: {
code: "question_form_answered",
interactionId: interaction.id,
},
}),
]);
expect(accepted.deliveries).toHaveLength(1);
expect(accepted.audits).toEqual([
expect.objectContaining({
actorId: linkedUserId,
details: expect.objectContaining({
source: "external_chat_modal",
endpointId: endpoint.id,
conversationId: conversation.id,
publicationId: publication.id,
}),
}),
]);
const duplicate = await forward(submit(" Add regional failover "), "duplicate_submission");
expect(duplicate.status).toBe(200);
expect(await duplicate.json()).toEqual({ response_action: "clear" });
expect(await submissionState()).toEqual(accepted);
expect(wakeup).toHaveBeenCalledTimes(wakeupsBefore + 1);
expect(onSubmit).toHaveBeenCalledTimes(4);
for (const [event] of onSubmit.mock.calls.slice(1)) {
expect(event).toMatchObject({
endpointId: endpoint.id,
provider: "slack",
event: {
callbackId: view.callback_id,
privateMetadata: view.callback_id,
user: { userId: externalUserId },
},
});
expect(event.event.relatedThread).toBeUndefined();
expect(event.event.relatedMessage).toBeUndefined();
}
await expect(service.listConversations(endpoint.id)).resolves.toEqual([
expect.objectContaining({
id: conversation.id,
issueId: conversation.issueId,
externalThreadId: channel.thread.id,
}),
]);
expect(
providerMethods.filter((method) => method === "views.open"),
).toHaveLength(1);
expect(unexpectedProviderMethods).toEqual([]);
await Promise.all(providerTransport.mock.results.map(result => result.value));
expect(providerErrors).toEqual([]);
const observed = (await db.select({ setup: chatEndpoints.setup }).from(chatEndpoints).where(eq(chatEndpoints.id, endpoint.id)))[0]!.setup as InternalSetupState;
expect(observed.slackCallbackSurfaces?.interactivity?.url).toBe(callbackUrl);
expect(observed.slackCallbackSurfaces?.slashCommands?.url).toBe(callbackUrl);
if (process.env.PAPERCLIP_SLACK_PROTOCOL_CAPTURE === "1") console.info(JSON.stringify({ mode, protocol, custody, invalidSubmission: "errors", correctedSubmission: "clear", answerDeliveries: accepted.deliveries.length }));
} catch (error) {
failure = { error };
throw error;
} finally {
const errors: unknown[] = [];
for (const cleanup of [
() => routedService?.shutdown(),
() => actualRuntime?.shutdown(),
() => configured ? retirePublicationFixture(configured.service, configured.endpoint.id) : undefined,
() => network.assertQuiet(),
() => network.restore(),
]) {
try { await cleanup(); } catch (error) { errors.push(error); }
}
if (errors.length) throw new AggregateError([...(failure ? [failure.error] : []), ...errors], "Slack protocol work or cleanup failed");
}
});
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,74 @@
import request from "supertest";
import { expect, it } from "vitest";
import { issues } from "@paperclipai/db";
import { issueRoutes } from "../routes/issues.js";
import { issueService } from "../services/issues.js";
import {
describeEmbeddedPostgres,
resetCompanyIssueFixtures,
routeApp,
seedCompanyWithBoardAccess,
useEmbeddedPostgres,
} from "./helpers/route-test-harness.js";
describeEmbeddedPostgres("issue origin kind prefix", () => {
const ctx = useEmbeddedPostgres("paperclip-origin-prefix-", {
resetEach: resetCompanyIssueFixtures,
});
for (const attention of [undefined, "blocked"] as const) {
for (const method of ["list", "count"] as const) {
it.each(["%", "_", "plugin:sample_", "plugin:sample%", "plugin:sample\\", "plugin:", ""])(
`${method} matches literal prefix %j with attention ${attention}`,
async (prefix) => {
const { companyId } = await seedCompanyWithBoardAccess(ctx.db, "Origin prefix");
const other = await seedCompanyWithBoardAccess(ctx.db, "Other origins");
const originKinds = [
"%literal", "_literal", "manual", "plugin:sample_task",
"plugin:sampleXtask", "plugin:sample%task", "plugin:sample\\task",
"plugin:sample_task:child", "plugin:other",
];
const rows = await ctx.db.insert(issues).values(originKinds.map((originKind) => ({
companyId, title: originKind, originKind, status: "blocked",
}))).returning();
await ctx.db.insert(issues).values({
companyId: other.companyId, title: "Other company", originKind: `${prefix}other`, status: "blocked",
});
const expected = rows.filter((row) => row.originKind!.startsWith(prefix));
const svc = issueService(ctx.db);
const filters = { originKindPrefix: prefix, attention, includeRoutineExecutions: true };
if (method === "count") {
expect(await svc.count(companyId, filters)).toBe(expected.length);
} else {
const result = await svc.list(companyId, filters);
expect(result.map((row) => row.id).sort()).toEqual(expected.map((row) => row.id).sort());
}
},
);
}
}
async function seedRepeatedPrefixRoute() {
const { companyId, actor } = await seedCompanyWithBoardAccess(ctx.db, "Repeated origin prefix");
const [joined] = await ctx.db.insert(issues).values(["plugin:a,plugin:b", "plugin:a", "plugin:b"].map((originKind) => ({
companyId, title: originKind, originKind, status: "blocked",
}))).returning();
return { companyId, app: routeApp(ctx.db, actor, issueRoutes), joinedId: joined!.id };
}
it.each(["", "&attention=blocked"])("list route joins repeated prefixes with commas (%s)", async (attention) => {
const { companyId, app, joinedId } = await seedRepeatedPrefixRoute();
const res = await request(app)
.get(`/api/companies/${companyId}/issues?originKindPrefix=plugin:a&originKindPrefix=plugin:b${attention}`)
.expect(200);
expect((res.body as { id: string }[]).map((issue) => issue.id)).toEqual([joinedId]);
});
it("count route joins repeated prefixes with commas", async () => {
const { companyId, app } = await seedRepeatedPrefixRoute();
const res = await request(app)
.get(`/api/companies/${companyId}/issues/count?attention=blocked&originKindPrefix=plugin:a&originKindPrefix=plugin:b`)
.expect(200);
expect(res.body).toEqual(expect.objectContaining({ count: 1 }));
});
});
+46 -27
View File
@@ -7,54 +7,73 @@ import { expect, it } from "vitest";
const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../.."); const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../../..");
it("runs every active nested/parameterized fixture case exactly once through the real chat shard CLI", () => { it("runs every split chat integration suite exactly once through the real chat shard CLI", () => {
const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "pc-shards-"))); const root = realpathSync(mkdtempSync(path.join(os.tmpdir(), "pc-shards-")));
try { try {
const tests = path.join(root, "server/src/__tests__"); const chatDir = path.join(root, "server/src/__tests__/chat-channels");
mkdirSync(tests, { recursive: true }); mkdirSync(chatDir, { recursive: true });
mkdirSync(path.join(root, "server/scripts"), { recursive: true }); mkdirSync(path.join(root, "server/scripts"), { recursive: true });
symlinkSync(path.join(repoRoot, "node_modules"), path.join(root, "node_modules"), "junction"); symlinkSync(path.join(repoRoot, "node_modules"), path.join(root, "node_modules"), "junction");
writeFileSync(path.join(root, "package.json"), JSON.stringify({ private: true })); const rootPkg = JSON.parse(readFileSync(path.join(repoRoot, "package.json"), "utf8"));
writeFileSync(
path.join(root, "package.json"),
JSON.stringify({ private: true, ...(rootPkg.packageManager ? { packageManager: rootPkg.packageManager } : {}) }),
);
writeFileSync(path.join(root, "vitest.config.mjs"), `export default { writeFileSync(path.join(root, "vitest.config.mjs"), `export default {
test: { projects: [{ test: { name: "@paperclipai/server", root: ${JSON.stringify(path.join(root, "server"))}, test: { projects: [{ test: { name: "@paperclipai/server", root: ${JSON.stringify(path.join(root, "server"))},
include: ["src/**/*.test.ts"], pool: "forks", maxWorkers: 1 } }] } include: ["src/**/*.test.ts"], pool: "forks", maxWorkers: 1 } }] }
};`); };`);
const trace = path.join(root, "executed.jsonl"); const trace = path.join(root, "executed.jsonl");
const fixture = path.join(tests, "chat-channels.integration.test.ts"); const fixtures: Array<[string, string[]]> = [
writeFileSync(fixture, `import { appendFileSync } from "node:fs"; ["alpha.integration.test.ts", ["alpha-1", "alpha-2"]],
import { afterEach, beforeEach, describe, expect, it } from "vitest"; ["beta.integration.test.ts", ["beta-1", "beta-2"]],
let active = false; ["gamma.integration.test.ts", ["gamma-1"]],
beforeEach(() => { expect(active).toBe(false); active = true; }); ];
afterEach(() => { active = false; }); for (const [fileName, cases] of fixtures) {
function record(id) { expect(active).toBe(true); appendFileSync(${JSON.stringify(trace)}, JSON.stringify(id) + "\\n"); } writeFileSync(
it("top-level", () => record("top")); path.join(chatDir, fileName),
it("second top-level", () => record("top-second")); `import { appendFileSync } from "node:fs";
it("third top-level", () => record("top-third")); import { expect, it } from "vitest";
describe("nested", () => { for (const id of ${JSON.stringify(cases)}) {
it("first", () => record("nested-first")); it(id, () => {
it("second", () => record("nested-second")); expect(id).toBeTruthy();
it.each(["a", "b", "c", "d"])("parameter %s", (value) => record(value)); appendFileSync(${JSON.stringify(trace)}, JSON.stringify(id) + "\\n");
it.skip("intentionally skipped", () => { throw new Error("must stay skipped"); }); });
});`); }
it.skip("intentionally skipped", () => { throw new Error("must stay skipped"); });`,
);
}
const run = (index: number, count: number) => spawnSync(process.execPath, [ const run = (index: number, count: number) => spawnSync(process.execPath, [
path.join(repoRoot, "scripts/run-vitest-stable.mjs"), "--mode", "general", "--group", "general-chat", path.join(repoRoot, "scripts/run-vitest-stable.mjs"), "--mode", "general", "--group", "general-chat",
"--shard-index", String(index), "--shard-count", String(count), "--shard-index", String(index), "--shard-count", String(count),
], { cwd: root, env: { ...process.env, CI: "true", PAPERCLIP_CI_PROFILE: "false" }, encoding: "utf8", timeout: 45_000, maxBuffer: 4 * 1024 * 1024 }); ], {
cwd: root,
env: { ...process.env, CI: "true", PAPERCLIP_CI_PROFILE: "false", PAPERCLIP_TEST_POSTGRES_SHARED: "0" },
encoding: "utf8",
timeout: 45_000,
maxBuffer: 4 * 1024 * 1024,
});
for (const index of [0, 1]) { for (const index of [0, 1]) {
const result = run(index, 2); const result = run(index, 2);
expect(result.error, result.stderr).toBeUndefined(); expect(result.error, result.stderr).toBeUndefined();
expect(result.status, result.stdout + result.stderr).toBe(0); expect(result.status, result.stdout + result.stderr).toBe(0);
expect(result.stdout).toContain("exact filter coverage verified");
} }
const executed = readFileSync(trace, "utf8").trim().split("\n").map((line) => JSON.parse(line)); const executed = readFileSync(trace, "utf8").trim().split("\n").map((line) => JSON.parse(line));
expect(executed.sort()).toEqual(["a", "b", "c", "d", "nested-first", "nested-second", "top", "top-second", "top-third"]); expect(executed.sort()).toEqual(["alpha-1", "alpha-2", "beta-1", "beta-2", "gamma-1"]);
// A real assertion failure must still fail the wrapper after successful // Trailing empty shards exit cleanly without launching Vitest unfiltered.
// collection and filter validation. const emptyShard = run(4, 5);
writeFileSync(fixture, 'import { it } from "vitest"; it("fails", () => { throw new Error("fixture failure"); });'); expect(emptyShard.error, emptyShard.stderr).toBeUndefined();
expect(emptyShard.status, emptyShard.stdout + emptyShard.stderr).toBe(0);
expect(emptyShard.stdout).toContain("running 0 of 3 suites");
// A real assertion failure must fail the wrapper.
writeFileSync(
path.join(chatDir, "alpha.integration.test.ts"),
'import { it } from "vitest"; it("fails", () => { throw new Error("fixture failure"); });',
);
const failed = run(0, 1); const failed = run(0, 1);
expect(failed.error, failed.stderr).toBeUndefined(); expect(failed.error, failed.stderr).toBeUndefined();
expect(failed.stdout).toContain("exact filter coverage verified");
expect(failed.status).not.toBe(0); expect(failed.status).not.toBe(0);
expect(failed.stdout + failed.stderr).toContain("fixture failure"); expect(failed.stdout + failed.stderr).toContain("fixture failure");
} finally { } finally {
+4
View File
@@ -260,10 +260,14 @@ export function configPatchFromSnapshot(snapshot: unknown): Partial<typeof agent
throw unprocessable("Invalid revision snapshot: runtimeConfig"); throw unprocessable("Invalid revision snapshot: runtimeConfig");
} }
const appearance = agentAppearanceSchema.safeParse(snapshot.appearance);
return { return {
name: snapshot.name, name: snapshot.name,
role: snapshot.role, role: snapshot.role,
title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null, title: typeof snapshot.title === "string" || snapshot.title === null ? snapshot.title : null,
...(typeof snapshot.icon === "string" || snapshot.icon === null ? { icon: snapshot.icon } : {}),
...(appearance.success ? { appearance: appearance.data } : {}),
reportsTo: reportsTo:
typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null, typeof snapshot.reportsTo === "string" || snapshot.reportsTo === null ? snapshot.reportsTo : null,
capabilities: capabilities:
+7 -7
View File
@@ -2212,6 +2212,10 @@ function escapeLikePattern(value: string): string {
return value.replace(/[\\%_]/g, "\\$&"); return value.replace(/[\\%_]/g, "\\$&");
} }
function originKindPrefixCondition(prefix: string) {
return like(issues.originKind, `${escapeLikePattern(String(prefix))}%`);
}
export function clampIssueListLimit(limit: number): number { export function clampIssueListLimit(limit: number): number {
return Math.min(ISSUE_LIST_MAX_LIMIT, Math.max(1, Math.floor(limit))); return Math.min(ISSUE_LIST_MAX_LIMIT, Math.max(1, Math.floor(limit)));
} }
@@ -6800,7 +6804,7 @@ async function blockedInboxIssueConditions(
if (filters?.originKind) if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind)); conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix) if (filters?.originKindPrefix)
conditions.push(like(issues.originKind, `${filters.originKindPrefix}%`)); conditions.push(originKindPrefixCondition(filters.originKindPrefix));
if (filters?.originId) conditions.push(eq(issues.originId, filters.originId)); if (filters?.originId) conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) { if (filters?.hasPlanDocument !== undefined) {
conditions.push( conditions.push(
@@ -8720,9 +8724,7 @@ export function issueService(db: Db) {
if (filters?.originKind) if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind)); conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix) if (filters?.originKindPrefix)
conditions.push( conditions.push(originKindPrefixCondition(filters.originKindPrefix));
like(issues.originKind, `${filters.originKindPrefix}%`),
);
if (filters?.originId) if (filters?.originId)
conditions.push(eq(issues.originId, filters.originId)); conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) { if (filters?.hasPlanDocument !== undefined) {
@@ -9046,9 +9048,7 @@ export function issueService(db: Db) {
if (filters?.originKind) if (filters?.originKind)
conditions.push(eq(issues.originKind, filters.originKind)); conditions.push(eq(issues.originKind, filters.originKind));
if (filters?.originKindPrefix) if (filters?.originKindPrefix)
conditions.push( conditions.push(originKindPrefixCondition(filters.originKindPrefix));
like(issues.originKind, `${filters.originKindPrefix}%`),
);
if (filters?.originId) if (filters?.originId)
conditions.push(eq(issues.originId, filters.originId)); conditions.push(eq(issues.originId, filters.originId));
if (filters?.hasPlanDocument !== undefined) { if (filters?.hasPlanDocument !== undefined) {