perf(ci): shard native-server and chat lanes and split >85s Vitest files (#22974)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Pull request CI runs Vitest suites across five lanes: Runner native
server, general chat, general server, serialized server, and Runner
package tests.
> - Even after pre-baked AMIs and 8-vCPU runners, single-shard `vitest
native server`, 2-shard `general-chat`, and several oversized
single-file Vitest specs still exceed the 85s per-shard ceiling and
dominate pull request wall-clock time.
> - Splitting those oversized test files and expanding AWS sharding
where needed lowers the slowest Vitest shard under the sub-3-minute pull
request budget while preserving every test case and keeping
`ubuntu-latest` fallback fan-out compact.
> - This pull request shards `vitest native server` (`1 -> 2` on AWS,
`1` on hosted runners) and `general-chat` (`2 -> 3` on AWS, `1` on
hosted runners), splits the remaining `>85s` single-file Vitest tails
across all five lanes into focused `<1,000 LOC` sibling test files with
shared harnesses, and refreshes the four Vitest timing manifests.
> - The benefit is faster pull request feedback with lower tail variance
across every Vitest lane and zero deleted tests.

## Linked Issues or Issue Description

Refs #22916

**What existing behavior does this improve?**
Pull request Vitest shard wall-clock time across `vitest native server`,
`general-chat`, `general server`, `serialized server`, and `Runner
vitest package`.

**Current behavior**
Single-shard `vitest native server`, 2-shard `general-chat`, and several
monolithic test files still run above 85s on 8-vCPU AWS PR runners,
holding back pull request CI completion.

**Proposed behavior**
Expand AWS sharding for `vitest native server` (`1 -> 2` with
`release_crate: true` on both, `1` compacted shard on `ubuntu-latest`)
and `general-chat` (`2 -> 3` on AWS, `1` on `ubuntu-latest`), split the
remaining oversized single-file Vitest suites into focused sibling files
under 1,000 LOC with shared test harnesses, and refresh the four Vitest
shard duration manifests so LPT packing balances the split files
immediately.

**Reason and benefit**
Cuts Vitest critical-path wall clock under 95s per shard while
preserving 100% of test coverage, lane ownership boundaries, and compact
33-job `ubuntu-latest` fallback fan-out.

**Breaking changes**
None. Pure test-file refactoring and shard matrix configuration.

## What Changed

- Expanded AWS sharding in `.github/ci-task-matrix.json`,
`.github/workflows/pr-trusted.yml`, and `scripts/run-vitest-stable.mjs`:
- `Verify Paperclip Runner (vitest native server)`: `1 -> 2` shards on
AWS (`release_crate: true` on both), `1` shard on `ubuntu-latest` via
`HOSTED_SHARD_COUNTS["ci:runner-vitest"] = 1` and
`nativeServerLanePattern`.
- `General tests (chat)`: `2 -> 3` shards on AWS, `1` shard on
`ubuntu-latest`.
- Split the remaining `>85s` single-file Vitest tails across all five
lanes into focused `<1,000 LOC` sibling test files with shared harnesses
(zero deleted tests, zero cross-test-file imports, anchor filenames and
lane ownership preserved):
- Runner package lane (`packages/paperclip-runner`): split oversized
daemon/provider integration files.
- Native server lane: split `native-ingress-bootstrap-retry` while
keeping `native-ingress-bootstrap-retry-opencode` strictly in
`native-runner`.
- Chat lane: split oversized Telegram/GitHub/connection-management
integration tests.
- General server lane: split `tool-gateway-service.test.ts` and
`attention-service` tests using shared harnesses.
- Serialized server lane: split `heartbeat-dependency-scheduling` /
`native-wakes` and `agent-adapter-validation` tests, keeping serialized
ownership intact.
- Refreshed all four Vitest shard duration manifests
(`packages/paperclip-runner/scripts/vitest-lane-durations.json`,
`scripts/chat-shard-durations.json`,
`scripts/general-server-shard-durations.json`,
`scripts/serialized-shard-durations.json`) and updated CI contract
tests.

## Verification

- Ran all CI contract suites after rebasing onto `origin/master`:
- `node --test .github/scripts/tests/ci-plan.test.mjs
scripts/ci/runner-release-crate-cache.test.mjs
scripts/ci/run-vitest-stable-shard.test.mjs
scripts/ci/run-vitest-stable-pr-mode.test.mjs
scripts/ci/runner-vitest-package-lanes.test.mjs
scripts/ci/test-selection-pr-timings.test.mjs
scripts/ci/e2e-shard.test.mjs scripts/ci/check-test-budget.test.mjs`
  - `node scripts/check-test-budget.mjs`
  - `node scripts/check-maps.mjs`
- Verified every new test file is under 1,000 LOC, zero cross-test-file
imports exist, zero files are missing from the four timing manifests,
and `ubuntu-latest` remains strictly at 33 jobs.

## Risks

- Low risk: pure test-file refactoring and shard matrix expansion with
zero production code changes.
- Reverted cleanly by a single `git revert` if any shard balance or
manifest adjustment is needed.

## Model Used

- Google Gemini (Antigravity / Gemini 4 Neon (High), tool use and code
execution enabled).

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
This commit is contained in:
Dotta authored and GitHub committed 2026-11-25 13:52:16 -06:00
1 parent 7563842165
commit 331e1a9fd3
47 files changed
+11760 -10252

No files matched your search

@@ -0,0 +1,238 @@
import express from "express";
import request from "supertest";
import { vi } from "vitest";
import type { ServerAdapterModule } from "../../adapters/index.js";
export const externalAdapter: ServerAdapterModule = {
type: "external_test",
execute: async () => ({ exitCode: 0, signal: null, timedOut: false }),
testEnvironment: async () => ({
adapterType: "external_test",
status: "pass",
checks: [],
testedAt: new Date(0).toISOString(),
}),
};
export const missingAdapterType = "missing_adapter_validation_test";
export async function createAgentValidationApp(actorOverride: Record<string, unknown> = {}) {
const [{ agentRoutes }, { errorHandler }] = await Promise.all([
vi.importActual<typeof import("../../routes/agents.js")>("../../routes/agents.js"),
vi.importActual<typeof import("../../middleware/index.js")>("../../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
userId: "local-board",
companyIds: ["company-1"],
source: "local_implicit",
isInstanceAdmin: false,
...actorOverride,
};
next();
});
const db = {
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn(async () => [
{
id: "company-1",
requireBoardApprovalForNewAgents: false,
},
]),
})),
})),
};
app.use("/api", agentRoutes(db as any));
app.use(errorHandler);
return app;
}
export async function requestAgentValidationApp(
app: express.Express,
buildRequest: (baseUrl: string) => request.Test,
) {
const { createServer } = await vi.importActual<typeof import("node:http")>("node:http");
const server = createServer(app);
try {
await new Promise<void>((resolve) => {
server.listen(0, "127.0.0.1", resolve);
});
const address = server.address();
if (!address || typeof address === "string") {
throw new Error("Expected HTTP server to listen on a TCP port");
}
return await buildRequest(`http://127.0.0.1:${address.port}`);
} finally {
if (server.listening) {
await new Promise<void>((resolve, reject) => {
server.close((error) => {
if (error) reject(error);
else resolve();
});
});
}
}
}
export async function unregisterTestAdapter(type: string) {
const { unregisterServerAdapter } = await import("../../adapters/index.js");
unregisterServerAdapter(type);
}
type AnyMock = ReturnType<typeof vi.fn<(...args: any[]) => any>>;
export interface AgentValidationMockSet {
mockAgentService: {
create: AnyMock;
getById: AnyMock;
getConfigRevision: AnyMock;
rollbackConfigRevision: AnyMock;
update: AnyMock;
};
mockAdapterPluginStore: {
getDisabledAdapterTypes: ReturnType<typeof vi.fn<() => string[]>>;
};
mockAccessService: {
canUser: AnyMock;
decide: AnyMock;
hasPermission: AnyMock;
ensureMembership: AnyMock;
setPrincipalPermission: AnyMock;
};
mockCompanySkillService: {
listRuntimeSkillEntries: AnyMock;
resolveRequestedSkillKeys: AnyMock;
};
mockSecretService: {
normalizeAdapterConfigForPersistence: AnyMock;
resolveAdapterConfigForRuntime: AnyMock;
syncEnvBindingsForTarget: AnyMock;
};
mockAgentInstructionsService: {
materializeManagedBundle: AnyMock;
getBundle: AnyMock;
readFile: AnyMock;
updateBundle: AnyMock;
writeFile: AnyMock;
deleteFile: AnyMock;
exportFiles: AnyMock;
ensureManagedBundle: AnyMock;
};
mockCheckProtectedKeys: AnyMock;
mockInstanceSettingsService: {
get: AnyMock;
getGeneral: AnyMock;
getExperimental: AnyMock;
};
mockManagedAgentProfileService: { requireQualified: AnyMock };
mockRemoteAgentProfileService: { requireQualified: AnyMock };
mockLogActivity: AnyMock;
}
export async function resetAgentValidationMocks(mocks: AgentValidationMockSet) {
const {
mockAgentService,
mockAdapterPluginStore,
mockAccessService,
mockCompanySkillService,
mockSecretService,
mockAgentInstructionsService,
mockCheckProtectedKeys,
mockInstanceSettingsService,
mockManagedAgentProfileService,
mockRemoteAgentProfileService,
mockLogActivity,
} = mocks;
vi.clearAllMocks();
mockAdapterPluginStore.getDisabledAdapterTypes.mockReturnValue([]);
mockCompanySkillService.listRuntimeSkillEntries.mockResolvedValue([]);
mockCompanySkillService.resolveRequestedSkillKeys.mockResolvedValue([]);
mockAccessService.canUser.mockResolvedValue(true);
mockAccessService.decide.mockResolvedValue({
allowed: true,
reason: "allow_explicit_grant",
explanation: "Allowed by test grant",
});
mockAccessService.hasPermission.mockResolvedValue(true);
mockAccessService.ensureMembership.mockResolvedValue(undefined);
mockAccessService.setPrincipalPermission.mockResolvedValue(undefined);
mockLogActivity.mockResolvedValue(undefined);
mockSecretService.syncEnvBindingsForTarget.mockResolvedValue(undefined);
mockInstanceSettingsService.get.mockResolvedValue({ defaultEnvironmentId: null });
mockCheckProtectedKeys.mockReset();
mockCheckProtectedKeys.mockResolvedValue([]);
mockInstanceSettingsService.getExperimental.mockResolvedValue({ enableNativeRunner: false });
mockManagedAgentProfileService.requireQualified.mockResolvedValue({
id: "managed-primary",
companyId: "company-1",
enabled: true,
});
mockRemoteAgentProfileService.requireQualified.mockResolvedValue({
id: "agentcore-primary",
companyId: "company-1",
enabled: true,
});
mockAgentInstructionsService.materializeManagedBundle.mockImplementation(async (agent: { adapterConfig: unknown }) => ({
adapterConfig: agent.adapterConfig,
}));
mockAgentService.create.mockImplementation(async (_companyId: string, input: Record<string, unknown>) => ({
id: String(input.id ?? "11111111-1111-4111-8111-111111111111"),
companyId: "company-1",
name: String(input.name ?? "Agent"),
urlKey: "agent",
role: String(input.role ?? "general"),
title: null,
icon: null,
status: "idle",
reportsTo: null,
capabilities: null,
adapterType: String(input.adapterType ?? "process"),
adapterConfig: (input.adapterConfig as Record<string, unknown> | undefined) ?? {},
runtimeConfig: (input.runtimeConfig as Record<string, unknown> | undefined) ?? {},
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
pauseReason: null,
pausedAt: null,
permissions: { canCreateAgents: false },
lastHeartbeatAt: null,
metadata: null,
createdAt: new Date(),
updatedAt: new Date(),
}));
mockAgentService.getById.mockResolvedValue({
id: "11111111-1111-4111-8111-111111111111",
companyId: "company-1",
name: "Codex",
urlKey: "codex",
role: "engineer",
title: null,
icon: null,
status: "idle",
reportsTo: null,
capabilities: null,
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
budgetMonthlyCents: 0,
spentMonthlyCents: 0,
pauseReason: null,
pausedAt: null,
permissions: { canCreateAgents: false },
lastHeartbeatAt: null,
metadata: null,
createdAt: new Date(),
updatedAt: new Date(),
});
mockAgentService.getConfigRevision.mockResolvedValue(null);
mockAgentService.update.mockImplementation(async (_id: string, patch: Record<string, unknown>) => ({
...(await mockAgentService.getById()),
...patch,
}));
await unregisterTestAdapter("external_test");
await unregisterTestAdapter(missingAdapterType);
}
@@ -0,0 +1,184 @@
import { randomUUID } from "node:crypto";
import { sql } from "drizzle-orm";
import { afterAll, afterEach, beforeAll, describe } from "vitest";
import { agents, companies, createDb, issues } from "@paperclipai/db";
import { resolveExternalTestDatabaseUrl } from "./external-test-database.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./embedded-postgres.js";
const externalUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_ATTENTION_TEST_DATABASE_URL");
const embeddedPostgresSupport = externalUrl ? { supported: true, reason: undefined } : await getEmbeddedPostgresTestSupport();
export const describeAttentionEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
if (!embeddedPostgresSupport.supported) {
console.warn(
`Skipping embedded Postgres attention service tests on this host: ${embeddedPostgresSupport.reason ?? "unsupported environment"}`,
);
}
export function createAttentionServiceHarness() {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
beforeAll(async () => {
if (!externalUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-attention-service-");
db = createDb(externalUrl ?? tempDb!.connectionString, { maxConnections: 6 });
}, 30_000);
afterEach(async () => {
await db.transaction(async (tx) => {
// CASCADE emits a notice for every related table; keep cleanup quiet while
// retaining warnings/errors and the same complete database reset.
await tx.execute(sql`SET LOCAL client_min_messages = warning`);
await tx.execute(sql`TRUNCATE TABLE companies CASCADE`);
});
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
async function seedCompany(prefix = "ATN") {
const companyId = randomUUID();
const workerId = randomUUID();
const reviewerId = randomUUID();
const errorAgentId = randomUUID();
await db.insert(companies).values({
id: companyId,
name: `${prefix} Co`,
issuePrefix: prefix,
requireBoardApprovalForNewAgents: false,
});
await db.insert(agents).values([
{
id: workerId,
companyId,
name: "Worker",
role: "engineer",
status: "idle",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: reviewerId,
companyId,
name: "Reviewer",
role: "qa",
status: "idle",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
{
id: errorAgentId,
companyId,
name: "Broken Agent",
role: "engineer",
status: "error",
errorReason: "adapter config missing",
adapterType: "codex_local",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
},
]);
return { companyId, workerId, reviewerId, errorAgentId, prefix };
}
async function insertIssue(input: {
companyId: string;
id?: string;
identifier: string;
title: string;
status: string;
priority?: string;
parentId?: string | null;
assigneeAgentId?: string | null;
assigneeUserId?: string | null;
originKind?: string;
originId?: string | null;
originFingerprint?: string;
projectId?: string | null;
projectWorkspaceId?: string | null;
executionState?: Record<string, unknown> | null;
updatedAt?: Date;
createdAt?: Date;
unblockDescriptor?: { owner: { userId: string } | "board"; action: string } | null;
blockedTransitionAt?: Date | null;
visibility?: "open" | "private";
privacyRootIssueId?: string | null;
responsibleUserId?: string | null;
harnessKind?: string | null;
reviewPolicy?: "anyone" | "not_creator" | "human_only" | null;
}) {
const id = input.id ?? randomUUID();
await db.insert(issues).values({
id,
companyId: input.companyId,
identifier: input.identifier,
title: input.title,
status: input.status,
priority: input.priority ?? "medium",
reviewPolicy: input.reviewPolicy ?? null,
parentId: input.parentId ?? null,
projectId: input.projectId ?? null,
projectWorkspaceId: input.projectWorkspaceId ?? null,
assigneeAgentId: input.assigneeAgentId ?? null,
assigneeUserId: input.assigneeUserId ?? null,
originKind: input.originKind ?? "manual",
originId: input.originId ?? null,
originFingerprint: input.originFingerprint ?? "default",
executionState: input.executionState ?? null,
unblockDescriptor: input.unblockDescriptor ?? null,
blockedTransitionAt: input.blockedTransitionAt ?? null,
visibility: input.visibility ?? "open",
privacyRootIssueId: input.privacyRootIssueId ?? null,
responsibleUserId: input.responsibleUserId ?? null,
harnessKind: input.harnessKind ?? null,
createdAt: input.createdAt,
updatedAt: input.updatedAt,
});
return id;
}
function pendingUserExecutionState(userId = "board-user") {
return {
status: "pending",
currentStageId: null,
currentStageIndex: null,
currentStageType: "review",
currentParticipant: { type: "user", userId },
returnAssignee: null,
reviewRequest: null,
completedStageIds: [],
lastDecisionId: null,
lastDecisionOutcome: null,
monitor: null,
};
}
function pendingAgentExecutionState(agentId: string) {
return {
...pendingUserExecutionState(),
currentParticipant: { type: "agent", agentId },
};
}
return {
get db() {
return db;
},
seedCompany,
insertIssue,
pendingUserExecutionState,
pendingAgentExecutionState,
};
}
@@ -0,0 +1,293 @@
import { execFileSync, type ChildProcess } from "node:child_process";
import { createHash, randomUUID } from "node:crypto";
import { readFileSync } from "node:fs";
import { chmod, copyFile, mkdir, readFile, stat, writeFile } from "node:fs/promises";
import https, { createServer as createHttpsServer } from "node:https";
import { createServer as createTcpServer } from "node:net";
import { join, resolve } from "node:path";
import { getCACertificates, setDefaultCACertificates } from "node:tls";
import { eq, sql } from "drizzle-orm";
import WebSocket, { WebSocketServer, type RawData } from "ws";
import { beforeAll, expect, it, vi } from "vitest";
import { completionContracts, executionWorkspaces, heartbeatRuns, issues, nativeRunFinalizations, nativeRunResults } from "@paperclipai/db";
import type { RunnerIngressEndpoint } from "@paperclipai/adapter-utils/runner-connectivity";
import { environmentRunnerIngressErrorData, JsonRpcCallError, PluginEnvironmentRunnerIngressError } from "@paperclipai/plugin-sdk";
import { canonicalNativeRuntimeContextDigest, createNativeSessionBackend, createRunnerdCodexTransport, parseNativeExecutionInput,
type RunnerProcessHandle } from "../../vendor/paperclip-runner/index.js";
import { nativeRestartFixture, describeEmbeddedPostgres, stopOwnedProcessGroup } from "./native-restart.js";
import { canonicalNativeJson, nativeSha256 } from "../../services/native-runtime/canonical.js";
import { executePaperclipNativeSession, nativeSessionWorkspaceScope, resolveNativeBilling } from "../../services/native-runtime/native-session-executor.js";
import { createNativeRunnerExecutionDriver } from "../../services/native-runtime/native-runner-execution-driver.js";
import { claimNativeSessionResumptions, reconcileNativeFinalizations } from "../../services/native-runtime/native-finalization-reconciler.js";
import { currentNativeControllerIdentity } from "../../services/native-runtime/native-restart-recovery.js";
import { loadNativeRunnerCheckpoint } from "../../services/native-runtime/native-runner-checkpoint.js";
import { buildNativeCompletionContract } from "../../services/native-runtime/completion-contracts.js";
import { releaseMaterializedNativeRuntimeSkills, spawnRunner } from "../../vendor/paperclip-runner/testing.js";
import { materializeAsset } from "../../services/native-runtime/runtime-context.js";
import { nativeRuntimeContextFixture } from "../../services/native-runtime/runtime-context.test-fixture.js";
import { createNativeUsageDelivery } from "../../services/native-runtime/native-usage-delivery.js";
import { accountRunCost } from "../../services/run-cost-accounting.js";
export function registerNativeIngressBootstrapRetrySuite(provider: "codex" | "opencode") {
describeEmbeddedPostgres(`native ingress bootstrap retry through the real Runner (${provider})`, () => {
const environment = nativeRestartFixture();
const runnerWorkspace = resolve(import.meta.dirname, "../../../../packages/paperclip-runner/runner");
const runnerBinary = join(runnerWorkspace, "target/release/paperclip-runnerd");
const fakeProvider = join(runnerWorkspace, "target/release/fake-codex-app-server");
beforeAll(() => {
execFileSync(process.execPath, [resolve(runnerWorkspace, "../scripts/build-verified-provider-entrypoints.mjs")],
{ cwd: resolve(runnerWorkspace, ".."), stdio: "pipe", timeout: 30_000 });
execFileSync("cargo", ["build", "--release", "--locked", "-p", "paperclip-runner-core",
"--bin", "paperclip-runnerd", "--bin", "fake-codex-app-server"],
{ cwd: runnerWorkspace, stdio: "ignore", timeout: 600_000 });
}, 660_000);
it(`reacquires ${provider} ingress and commits exactly one result on the automatic second attempt`, async () => {
const fixture = await environment.seedRun(`INGRESS-BOOTSTRAP-RETRY-${provider}`);
const { db, runId, issueId, native } = fixture;
const { companyId, agentId, runtimeRoot } = environment.current;
const [issue] = await db.select().from(issues).where(eq(issues.id, issueId));
const [contract] = await db.select().from(completionContracts).where(eq(completionContracts.issueId, issueId));
const sandbox = join(runtimeRoot, `ingress-sandbox-${provider}`);
const stateBase = join(runtimeRoot, `ingress-controller-${provider}`);
const codexHome = join(runtimeRoot, `ingress-codex-home-${provider}`);
const filesystem = join(runtimeRoot, `ingress-filesystem-${provider}`);
await mkdir(sandbox, { recursive: true });
await mkdir(codexHome, { recursive: true });
await mkdir(join(filesystem, "codex-home"), { recursive: true });
await db.insert(executionWorkspaces).values({ id: runId, companyId, sourceIssueId: issueId,
mode: "isolated", strategyType: "directory", name: "Owned retry fixture", cwd: sandbox });
await db.update(issues).set({ executionWorkspaceId: runId }).where(eq(issues.id, issueId));
const runtimeContext = nativeRuntimeContextFixture();
const skillContent = "---\nname: retry-fixture\ndescription: Controlled sealed retry skill.\n---\nKeep the admitted task and configuration.\n";
runtimeContext.instructions.bundle = await materializeAsset([{ path: "AGENTS.md", mode: 0o444,
content: Buffer.from("Complete only the controlled fixture task.\n") }]);
if (provider === "codex") runtimeContext.skills = [{ key: "company/retry-fixture", runtimeName: "retry-fixture",
versionId: "fixture-v1", bundle: await materializeAsset([{ path: "SKILL.md", mode: 0o444, content: Buffer.from(skillContent) }]) }];
runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(runtimeContext);
const execution = parseNativeExecutionInput({
schema: "paperclip.native-execution-input.v5", executionMode: "default", planningContext: null, runtimeContext,
binding: { companyId, agentId, issueId, runId, executionWorkspaceId: runId },
provider: provider === "codex" ? { kind: "codex", model: "fixture-model", approvalPolicy: "never" }
: { kind: "opencode", model: "openrouter/deepseek/deepseek-v4.1-flash-1017", permissionMode: "allow" },
task: { identifier: "fixture", title: issue!.title, description: null,
prompt: "Complete the controlled fixture task.", workMode: "standard" },
workspace: { cwd: sandbox, repoUrl: null, repoRef: null, branchName: null },
session: { normalizedSessionId: native.normalizedSessionId, driverKind: provider === "codex" ? "codex_app_server" : "opencode_server", protocolVersion: 1,
lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null } },
completionContract: { id: contract!.id, sha256: contract!.canonicalSha256, schemaVersion: "paperclip.completion-contract.v1",
contract: buildNativeCompletionContract(issue!, { revision: contract!.revision }) }, interactionResponses: [], credentialBindings: [],
});
await db.update(heartbeatRuns).set({ runnerProfileJson: sql`coalesce(${heartbeatRuns.runnerProfileJson}, '{}'::jsonb)
|| ${JSON.stringify({ nativeExecutionInput: execution })}::jsonb` }).where(eq(heartbeatRuns.id, runId));
const root = join(stateBase, nativeSha256({ schema: "paperclip.native-session-scope.v2", companyId, agentId,
workspace: nativeSessionWorkspaceScope(execution), provider: { driverKind: execution.session.driverKind,
identity: { kind: provider } }, normalizedSessionId: native.normalizedSessionId }));
const digest = (file: string) => `sha256:${createHash("sha256").update(readFileSync(file)).digest("hex")}`;
const opencode = join(runtimeRoot, "fake-opencode-ingress");
const providerNode = provider === "opencode" && process.platform === "linux"
? join(runtimeRoot, "node") : process.execPath;
const providerCalls = join(sandbox, "provider-calls.log");
if (provider === "opencode") {
if (process.platform === "linux") {
await copyFile(process.execPath, providerNode);
await chmod(providerNode, 0o500);
}
const script = resolve(runnerWorkspace, "../test/fixtures/fake-opencode-server.mjs");
execFileSync("cc", ["-x", "c", "-o", opencode, "-"], { input:
`#include <unistd.h>\n#include <stdlib.h>\n#include <stdio.h>\nint main(int argc, char **argv) { FILE *log = fopen(${JSON.stringify(providerCalls)}, "a"); if (!log) return 126; fputs("process-start\\n", log); fclose(log); char **args = calloc(argc + 2, sizeof(char *)); args[0] = ${JSON.stringify(providerNode)}; args[1] = ${JSON.stringify(script)}; for (int i = 1; i < argc; i++) args[i + 1] = argv[i]; execv(args[0], args); return 127; }` });
await chmod(opencode, 0o755);
}
const proxy = join(filesystem, "opencode-app-server-proxy.cjs");
if (provider === "opencode") await copyFile(resolve(runnerWorkspace, "../dist/cli/opencode-app-server-proxy.cjs"), proxy);
const identity = { runnerInstanceId: native.runnerInstanceId, environmentLeaseId: runId, runId,
normalizedSessionId: native.normalizedSessionId, turnId: `turn-${runId}`, itemId: `item-${runId}` };
const assertSealedSkills = async () => {
if (provider !== "codex") return;
const skill = join(root, "codex-home", "skills", "retry-fixture", "SKILL.md");
expect(await readFile(skill, "utf8")).toBe(skillContent);
expect((await stat(skill)).mode & 0o222).toBe(0);
expect((await stat(join(root, "codex-home", "skills", "retry-fixture"))).mode & 0o222).toBe(0);
};
const resultFile = join(sandbox, "fixture-result.json");
await writeFile(resultFile, canonicalNativeJson({ schema: "paperclip.run_result.v1", reportedWorkDisposition: "done",
summary: "Controlled retry completed.", completionClaim: { contractRevision: execution.completionContract.contract.revision,
objectiveSatisfied: true, criteria: execution.completionContract.contract.criteria.map(criterion => ({
criterionId: criterion.id, status: "satisfied", evidenceRefs: [] })), remainingWork: [] },
evidence: [], verification: [], artifacts: [], attentionRequests: [] }));
const key = join(sandbox, "preview.key"), certificate = join(sandbox, "preview.crt");
execFileSync("openssl", ["req", "-x509", "-newkey", "rsa:2048", "-nodes", "-keyout", key, "-out", certificate,
"-days", "1", "-subj", "/CN=localhost", "-addext", "subjectAltName=IP:127.0.0.1,DNS:localhost"], { stdio: "ignore" });
const previousCertificates = getCACertificates("default");
const certificates = [...previousCertificates, await readFile(certificate, "utf8")];
setDefaultCACertificates(certificates);
const previousHttpsAgent = https.globalAgent;
const fixtureHttpsAgent = new https.Agent({ ca: certificates });
https.globalAgent = fixtureHttpsAgent;
const portProbe = createTcpServer();
await new Promise<void>(done => portProbe.listen(0, "127.0.0.1", done));
const address = portProbe.address();
if (!address || typeof address === "string") throw new Error("Missing fixture port");
const runnerPort = address.port;
let healthy = false, acquisitions = 0, previewUrl = "";
const preview = createHttpsServer({ key: await readFile(key), cert: await readFile(certificate) }, (request, response) => {
if (request.url !== "/preview") { response.writeHead(404).end(); return; }
acquisitions++;
response.writeHead(healthy ? 200 : 502, { "content-type": "application/json" });
response.end(JSON.stringify(healthy ? { url: previewUrl, token: "fixture-preview" } : { message: "fixture upstream unavailable" }));
});
const sockets = new Set<WebSocket>();
const websocket = new WebSocketServer({ noServer: true });
preview.on("upgrade", (request, socket, head) => {
if (request.url !== `/api/runner/v1/connect/${runId}` || request.headers["x-fixture-preview-token"] !== "fixture-preview") {
socket.end("HTTP/1.1 403 Forbidden\r\n\r\n"); return;
}
websocket.handleUpgrade(request, socket, head, front => {
const back = new WebSocket(`ws://127.0.0.1:${runnerPort}${request.url}`, { perMessageDeflate: false });
const pending: Array<{ data: RawData; binary: boolean }> = [];
sockets.add(front); sockets.add(back);
front.on("message", (data, binary) => {
if (back.readyState === WebSocket.OPEN) back.send(data, { binary });
else pending.push({ data, binary });
});
back.on("open", () => { for (const message of pending.splice(0)) back.send(message.data, { binary: message.binary }); });
back.on("message", (data, binary) => { if (front.readyState === WebSocket.OPEN) front.send(data, { binary }); });
front.on("close", () => { sockets.delete(front); back.terminate(); });
back.on("close", () => { sockets.delete(back); front.terminate(); });
front.on("error", error => { diagnostics.push(`fixture front: ${error.message}`); back.terminate(); });
back.on("error", error => { diagnostics.push(`fixture back: ${error.message}`); front.terminate(); });
});
});
preview.on("tlsClientError", error => { diagnostics.push(`fixture TLS: ${error.message}`); });
try {
await new Promise<void>(done => preview.listen(0, "127.0.0.1", done));
} finally { await new Promise<void>(done => portProbe.close(() => done())); }
const previewAddress = preview.address();
if (!previewAddress || typeof previewAddress === "string") throw new Error("Missing preview address");
expect(previewAddress.port).not.toBe(runnerPort);
previewUrl = `wss://127.0.0.1:${previewAddress.port}/api/runner/v1/connect/${runId}`;
const bundles: ReturnType<typeof createRunnerdCodexTransport>[] = [];
const handles: RunnerProcessHandle[] = [];
const diagnostics: string[] = [];
let usageDelivery: Awaited<ReturnType<typeof createNativeUsageDelivery>> | undefined;
vi.stubEnv("PAPERCLIP_RUNNER_STATE_DIR", stateBase);
const endpoint: () => Promise<RunnerIngressEndpoint> = async () => {
const response = await fetch(`https://127.0.0.1:${previewAddress.port}/preview`);
if (!response.ok) {
const error = new PluginEnvironmentRunnerIngressError({ phase: "private_preview", httpStatus: response.status });
throw new JsonRpcCallError({ code: -32000, message: error.message, data: environmentRunnerIngressErrorData(error) });
}
return { kind: "authenticated_websocket" as const, websocketUrl: previewUrl,
secretHeaders: [{ name: "X-Fixture-Preview-Token", value: "fixture-preview" }], generation: "fixture",
refresh: endpoint, close: async () => {} };
};
const target = { kind: "remote", transport: "sandbox", remoteCwd: sandbox, leaseId: randomUUID(),
effectiveCapabilities: { runnerWebSocketIngress: true }, getRunnerIngressEndpoint: endpoint } as never;
const backend = () => createNativeSessionBackend(execution, {
runnerInstanceId: native.runnerInstanceId, environment: { CODEX_HOME: codexHome, PATH: process.env.PATH },
codexTransportFactory: () => {
let started!: () => void;
const processStarted = new Promise<void>(done => { started = done; });
const bundle = createRunnerdCodexTransport({
provider, runnerBinary, codexCommand: fakeProvider, codexArgs: ["--state-file", join(sandbox, "provider.json"),
"--terminal-result-file", resultFile, "--call-log", providerCalls, "--record-process-start"],
stateDirectory: root, runnerStateDirectory: join(sandbox, "runner"), runnerFilesystemRoot: filesystem,
runtimeContext, runnerRuntimeContext: runtimeContext, closeGraceMs: 1_000,
onDiagnostic: message => { diagnostics.push(message); },
onAccountingEvent: async event => { await usageDelivery?.capture(event); },
environment: { CODEX_HOME: codexHome, PATH: process.env.PATH, OPENROUTER_API_KEY: "synthetic-fixture-key" }, sourceCodexHome: codexHome,
...(provider === "opencode" ? { opencodeCommand: opencode, opencodeCommandSha256: digest(opencode),
opencodeProxyPath: proxy, opencodeProxySha256: digest(proxy), providerNodeCommand: providerNode,
providerNodeCommandSha256: digest(providerNode), opencodePermissionMode: "allow" as const } : {}),
prpIdentity: identity, lifecyclePolicy: { mode: "per_turn", idleTimeoutMs: null },
controlPlaneRegistration: async authority => {
const controller = await currentNativeControllerIdentity();
return createNativeRunnerExecutionDriver({ target, binding: execution.binding,
runnerIngressAuthorized: true,
prepareRemote: async () => { await copyFile(join(root, "runtime-context.json"), join(filesystem, "runtime-context.json")); },
processStarted,
onLog: async (_stream, message) => { diagnostics.push(message); },
controllerPersistence: { db, bootId: controller.bootId } }).controlPlaneRegistration!(authority);
},
runnerProcessLauncher: spec => {
const handle = spawnRunner({ ...spec.nativeRunner!, runnerBinaryPath: spec.command, environment: spec.environment,
connection: { mode: "listen", listenAddress: "0.0.0.0", listenPort: runnerPort,
listenPath: `/api/runner/v1/connect/${runId}` } });
(handle.child as ChildProcess).once("spawn", started);
handles.push(handle); return handle;
},
});
bundles.push(bundle); return bundle.transport;
},
});
const execute = (leaseOwner?: string) => executePaperclipNativeSession({ db, execution,
runnerInstanceId: native.runnerInstanceId, useRunnerd: true, runnerExecutionTarget: target,
backend: backend(), leaseOwner, turnTimeoutMs: 15_000 });
try {
await expect(execute()).rejects.toThrow("HTTP 502");
expect(acquisitions).toBe(1);
expect(handles).toHaveLength(0);
await assertSealedSkills();
const saved = await loadNativeRunnerCheckpoint(db, execution.binding);
expect(saved?.records.size).toBe(4);
const savedBootstrapIds = [...saved!.records].filter(([part]) => part.startsWith("command:"))
.map(([, value]) => JSON.parse(value).commandId);
expect(savedBootstrapIds).toHaveLength(2);
const [beforeRetry] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(beforeRetry.usageJson?.accountingProviderWorkStarted).not.toBe(false);
expect(beforeRetry.costAccountedAt).toBeNull();
const [failed] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
expect(failed).toMatchObject({ phase: "retryable_failure", attempt: 1, failureDetail: { recoveryMode: "bootstrap_retry" } });
const [claim] = await claimNativeSessionResumptions({ db, runnerInstanceId: "fixture-resumption", runIds: [runId],
now: new Date(failed!.nextAttemptAt!.getTime() + 1), deferIneligible: false });
expect(claim).toBeDefined();
usageDelivery = await createNativeUsageDelivery(db, { companyId, runId, runnerInstanceId: native.runnerInstanceId,
provider: execution.provider, billing: resolveNativeBilling(execution.provider) });
healthy = true;
let timer: ReturnType<typeof setTimeout> | undefined;
const retry = execute(claim!.leaseOwner);
try {
await expect(Promise.race([retry, new Promise<never>((_done, reject) => {
timer = setTimeout(() => reject(new Error(`Controlled retry deadline exceeded: ${diagnostics.slice(-12).join("\n")}`)), 20_000);
})])).resolves.toMatchObject({ exitCode: 0, timedOut: false });
} finally { if (timer) clearTimeout(timer); }
expect(acquisitions).toBe(2);
expect(handles).toHaveLength(1);
await assertSealedSkills();
const completed = await loadNativeRunnerCheckpoint(db, execution.binding);
const commands = [...completed!.records].filter(([part]) => part.startsWith("command:")).map(([, value]) => JSON.parse(value));
expect(commands.filter(command => command.type === "run.prepare")).toHaveLength(1);
expect(commands.filter(command => command.type === "session.open")).toHaveLength(1);
expect(commands.filter(command => ["run.prepare", "session.open"].includes(command.type))
.map(command => command.commandId)).toEqual(savedBootstrapIds);
expect((await readFile(providerCalls, "utf8")).split("\n").filter(line => line === "process-start")).toHaveLength(1);
const results = await db.select().from(nativeRunResults).where(eq(nativeRunResults.runId, runId));
expect(results).toHaveLength(1);
expect(results[0]).toMatchObject({ schemaStatus: "accepted" });
await reconcileNativeFinalizations(db, [runId]);
const [settled] = await db.select().from(nativeRunFinalizations).where(eq(nativeRunFinalizations.runId, runId));
expect(settled).toMatchObject({ phase: "committed", attempt: 2 });
const [completedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(completedRun.usageJson?.accountingProviderWorkStarted).not.toBe(false);
expect(completedRun.usageJson?.accountingReceiptReady).toBe(true);
expect(Number(completedRun.usageJson?.inputTokens)).toBeGreaterThan(0);
expect(await accountRunCost(db, runId)).toBe(true);
expect(await accountRunCost(db, runId)).toBe(false);
const [accountedRun] = await db.select().from(heartbeatRuns).where(eq(heartbeatRuns.id, runId));
expect(accountedRun.costAccountedAt).toBeInstanceOf(Date);
} finally {
for (const bundle of bundles) await bundle.transport.close().catch(() => undefined);
for (const handle of handles) await stopOwnedProcessGroup(handle.child.pid ?? null, sandbox);
if (provider === "codex") await releaseMaterializedNativeRuntimeSkills(join(root, "codex-home", "skills"));
for (const socket of sockets) socket.terminate();
websocket.close(); preview.closeAllConnections();
await new Promise<void>(done => preview.close(() => done()));
https.globalAgent = previousHttpsAgent;
fixtureHttpsAgent.destroy();
setDefaultCACertificates(previousCertificates);
vi.unstubAllEnvs();
}
}, 60_000);
});
}
@@ -0,0 +1,244 @@
import { randomUUID } from "node:crypto";
import { afterAll, afterEach, beforeAll, describe, vi } from "vitest";
import {
activityLog,
agentWakeupRequests,
agents,
approvals,
companies,
companyMemberships,
companySecrets,
connectionGrants,
createDb,
heartbeatRuns,
issueApprovals,
issueThreadInteractions,
issues,
projects,
toolAccessAuditEvents,
toolActionRequests,
toolApplications,
toolCallEvents,
toolCatalogEntries,
toolConnections,
toolGatewaySessions,
toolInvocations,
toolPolicies,
} from "@paperclipai/db";
import type { PluginToolDispatcher } from "../../services/plugin-tool-dispatcher.js";
import { createToolGatewayService } from "../../services/tool-gateway.js";
import {
getEmbeddedPostgresTestSupport,
startEmbeddedPostgresTestDatabase,
} from "./embedded-postgres.js";
import { resolveExternalTestDatabaseUrl } from "./external-test-database.js";
const externalDatabaseUrl = resolveExternalTestDatabaseUrl("PAPERCLIP_TOOL_REVIEW_TEST_DATABASE_URL");
const embeddedPostgresSupport = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
export const describeToolGatewayEmbeddedPostgres = embeddedPostgresSupport.supported ? describe : describe.skip;
export const testToolActionSigningSecret = "test-tool-action-signing-secret";
export type ToolGatewayServiceOptions = NonNullable<Parameters<typeof createToolGatewayService>[1]>;
export function createTestToolGatewayService(db: ReturnType<typeof createDb>, options: ToolGatewayServiceOptions = {}) {
return createToolGatewayService(db, {
...options,
toolActionSigningSecret: options.toolActionSigningSecret ?? testToolActionSigningSecret,
remoteHttpRequest: options.remoteHttpRequest ?? (async (url, init) => fetch(url, init)),
});
}
export async function createRunFixture(db: ReturnType<typeof createDb>) {
const company = await db.insert(companies).values({
name: `Gateway ${randomUUID()}`,
issuePrefix: `TG${randomUUID().slice(0, 6).toUpperCase()}`,
}).returning().then((rows) => rows[0]!);
const agent = await db.insert(agents).values({
companyId: company.id,
name: `Gateway Agent ${randomUUID()}`,
role: "engineer",
adapterType: "process",
adapterConfig: {},
runtimeConfig: {},
permissions: {},
}).returning().then((rows) => rows[0]!);
const issue = await db.insert(issues).values({
companyId: company.id,
title: "Gateway approval work",
status: "in_progress",
assigneeAgentId: agent.id,
}).returning().then((rows) => rows[0]!);
const run = await db.insert(heartbeatRuns).values({
companyId: company.id,
agentId: agent.id,
invocationSource: "assignment",
status: "running",
contextSnapshot: { issueId: issue.id },
}).returning().then((rows) => rows[0]!);
return { company, agent, issue, run };
}
export async function createRemoteMcpToolFixture(db: ReturnType<typeof createDb>, companyId: string) {
const application = await db.insert(toolApplications).values({
companyId,
applicationKey: `remote-${randomUUID().slice(0, 8)}`,
name: "Remote MCP",
type: "mcp_http",
status: "active",
}).returning().then((rows) => rows[0]!);
const connection = await db.insert(toolConnections).values({
companyId,
applicationId: application.id,
name: "Remote connection",
uid: `test/${randomUUID()}`,
transport: "mcp_remote",
status: "active",
enabled: true,
healthStatus: "ok",
// Use a public IP literal so protocol tests remain independent of DNS while
// still exercising the production egress guard and their global fetch stub.
credentialPolicy: "shared",
config: { url: "https://8.8.8.8/mcp" },
}).returning().then((rows) => rows[0]!);
await db.insert(connectionGrants).values({
companyId,
connectionId: connection.id,
kind: "organization",
credentialSecretRefs: [],
status: "active",
isDefault: true,
});
const catalogEntry = await db.insert(toolCatalogEntries).values({
companyId,
applicationId: application.id,
connectionId: connection.id,
entryKind: "tool",
name: "needs_input",
toolName: "needs_input",
title: "Needs input",
riskLevel: "read",
isReadOnly: true,
status: "active",
versionHash: randomUUID(),
schemaHash: randomUUID(),
}).returning().then((rows) => rows[0]!);
return { application, connection, catalogEntry };
}
export function fakePluginDispatcher(): PluginToolDispatcher {
return {
initialize: async () => {},
teardown: () => {},
listToolsForAgent: () => [
{
name: "fixture:delete_everything",
displayName: "Delete everything",
description: "Destructive fixture tool.",
parametersSchema: { type: "object" },
pluginId: "fixture-plugin",
},
],
getTool: () => null,
executeTool: async (_name, parameters) => ({
pluginId: "fixture-plugin",
toolName: "delete_everything",
result: { content: "deleted", data: parameters },
}),
registerPluginTools: () => {},
unregisterPluginTools: () => {},
toolCount: () => 1,
getRegistry: () => {
throw new Error("not implemented");
},
};
}
type IdRef = { id: string };
export function reviewNotePolicyRow(company: IdRef): typeof toolPolicies.$inferInsert {
return {
companyId: company.id,
name: "Review note writes",
policyType: "require_approval",
selectors: { toolName: "mcp-remote-fixture:update_note" },
};
}
export function readPolicyRow(company: IdRef, name: string): typeof toolPolicies.$inferInsert {
return {
companyId: company.id,
name,
policyType: "allow",
selectors: { riskLevel: "read" },
};
}
export function runSessionInput(company: IdRef, agent: IdRef, run: IdRef): Parameters<ReturnType<typeof createToolGatewayService>["createSession"]>[0] {
return {
companyId: company.id,
agentId: agent.id,
runId: run.id,
};
}
export async function clearToolGatewayFixtures(db: ReturnType<typeof createDb>) {
vi.unstubAllEnvs();
await db.delete(activityLog);
await db.delete(agentWakeupRequests);
await db.delete(toolGatewaySessions);
await db.delete(toolCallEvents);
await db.delete(toolAccessAuditEvents);
await db.delete(toolActionRequests);
await db.delete(toolInvocations);
await db.delete(issueApprovals);
await db.delete(approvals);
await db.delete(issueThreadInteractions);
await db.delete(toolCatalogEntries);
await db.delete(toolConnections);
await db.delete(toolApplications);
await db.delete(companySecrets);
await db.delete(toolPolicies);
await db.delete(heartbeatRuns);
await db.delete(issues);
await db.delete(projects);
await db.delete(agents);
await db.delete(companyMemberships);
await db.delete(companies);
}
export function createToolGatewayDbHarness() {
let db!: ReturnType<typeof createDb>;
let tempDb: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>> | null = null;
let stopReviewWorker: (() => Promise<void>) | undefined;
beforeAll(async () => {
if (!externalDatabaseUrl) tempDb = await startEmbeddedPostgresTestDatabase("paperclip-tool-gateway-");
db = createDb(externalDatabaseUrl ?? tempDb!.connectionString, {
maxConnections: 6, idleTimeoutSeconds: 0, maxLifetimeSeconds: 0,
});
await clearToolGatewayFixtures(db);
}, 20_000);
afterEach(async () => {
await stopReviewWorker?.();
stopReviewWorker = undefined;
await clearToolGatewayFixtures(db);
});
afterAll(async () => {
await db?.$client.end({ timeout: 1 });
await tempDb?.cleanup();
});
return {
get db() {
return db;
},
get connectionString() {
return externalDatabaseUrl ?? tempDb!.connectionString;
},
setStopReviewWorker(stop: (() => Promise<void>) | undefined) {
stopReviewWorker = stop;
},
clearFixtures: () => clearToolGatewayFixtures(db),
};
}