Files
PaperClipAI/server/src/__tests__/connection-instructions.test.ts
T
DottaandPaperclip fc6304dfe5 feat(runner): add experimental OpenAI Dot provider over MCP Events (#15402)
## Thinking Path

> - Paperclip manages AI agents, tasks, permissions, and execution
budgets.
> - Paperclip Runner gives each provider the same admitted task and tool
authority.
> - OpenAI Dot runs outside the local process tree and needs
asynchronous work delivery.
> - The merged MCP gateway supplies OAuth consent and signed event
delivery.
> - A personal assistant grant cannot safely stand in for an assigned
agent.
> - This pull request adds a separate Dot agent connection and a durable
Rust Runner bridge.
> - The operator can assign work to Dot and inspect its accepted work,
tool receipts, and result.

## Linked Issues or Issue Description

**Agent or provider**

OpenAI Dot, as an experimental provider of the existing Paperclip Runner
adapter.

**Why this adapter is useful**

An operator can assign normal Paperclip tasks to an existing Dot. Dot
can read its mailbox, request work on an assigned task, use admitted
task tools, and submit a result. Paperclip keeps company scope,
checkout, approvals, known budget limits, and activity attribution.

**How the agent is invoked**

A dedicated `/mcp/runner` OAuth resource pairs one Dot grant with one
agent. A signed MCP mailbox event wakes Dot. Dot explicitly accepts the
assignment. The Rust Runner owns the durable turn and operation
receipts. The first release supports self-hosted instances with a local
Runner controller.

**Additional context**

This extends the merged public MCP gateway from #14846 and the assistant
invitation and device-consent work from #14933. This also integrates the
merged assistant tool and configuration expansion in #15380. Dot retains
its dedicated agent resource and cannot receive personal configuration
permission. The public assistant connection remains a personal
connection.

## What Changed

- Add a durable Rust Dot provider and its TypeScript Runner driver.
- Add closed PRP v3 external-provider operations and native execution
input v6.
- Add company-scoped pairing, mailbox, assignment, and operation
records.
- Reuse merged browser/device consent, client metadata verification,
webhook admissions, refresh, secret rotation, and warm-standby gates.
- Keep Dot scopes, issuer, grants, event workers, and tool access
separate from personal assistant access.
- Add Dot configuration, pairing, readiness, and consent UI. Keep agent
grants out of the personal Connections entry.
- Regenerate the Dot-only migration after master. Preserve published
gateway migrations. Make the new migration safe to reapply.
- Document setup, recovery, accounting limits, evidence, and remaining
account qualification.
- Reverify reconnect callbacks and wake outstanding work with a fresh
mailbox reference; preserve the existing assignment and operation
receipts.
- Clean up Dot bindings and waiting runs on OAuth revoke and
refresh-token replay. Old grants cannot revoke replacement bindings.
- Restore the pairing reference when an unsaved agent form is reopened;
document board-only pairing routes in OpenAPI.
- Accept a clean Rust exit after the acknowledged shutdown receipt.
Unexpected exits still require recovery.
- Clear the cached binding after a successful revoke so a failed
connection refresh cannot restore it.
- Add production-component Storybook states and screenshots for pairing
and connection review. All preview account data is synthetic.
- Persist normalized completion, serialize Dot turns and durable work
admission, and poll subscription readiness.
- Serialize mailbox writes and cursor reads; retain paused fence
acknowledgement without task authority.
- Authorize admitted review runs without changing the worker assignee.
Include the fenced assignment ID in production stop notices.

## Verification

- This PR integrates master `4a8178e9c`. Dot migration
`0317_messy_famine.sql` follows the published history and is safe to
reapply. The merge preserves the reserved migration connection,
batch-commit handling, private task checks, task monitors, and native
accounting.
- Local workspace typecheck, full build, and UI token gates pass. The
server typecheck passes after the review fixes. Database and native
executor regressions pass.
- All twelve real Rust/PostgreSQL Dot integration tests and twelve Dot
driver tests pass. The tests cover native document writing and
finalization, durable replay, queue admission, mailbox ordering,
admitted reviews, stale authority, production stop references, and
paused acknowledgements.
- Current head `d0e7e0626` passes all 57 checks: 53 pass and four are
intentionally skipped. This includes full typecheck, build, tests, Rust
Runner verification, browser E2E, release verification, and Canary Dry
Run. Greptile rates this exact head 5/5. All review threads are
resolved.
- The full local root test run is slower than the sharded CI run and has
not completed. The full CI test gates pass on the current commit.
Focused local regressions pass.
- Real-account pairing and event delivery on this base commit remain
unqualified. Live account and setup proof are recorded in the follow-up
#15414.

The following screenshots use synthetic preview data. They show the
production pairing component and do not qualify a real account or the
full agent setup journey.

![Synthetic pairing
preview](https://github.com/paperclipai/paperclip/blob/codex/dot-events-prototype/doc/screenshots/openai-dot-runner/pairing.jpg?raw=true)

![Synthetic connected
preview](https://github.com/paperclipai/paperclip/blob/codex/dot-events-prototype/doc/screenshots/openai-dot-runner/connected.jpg?raw=true)

## Risks

- This base adapter uses `PAPERCLIP_ENABLE_OPENAI_DOT=1` plus Public MCP
and Paperclip Runner. The separate experimental-settings follow-up in
#15414 replaces this environment flag with saved operator settings.
- Dot does not expose provider token usage or cost. The operator must
acknowledge external billing. Known Paperclip budget gates still apply.
- Cancellation fences Paperclip authority. It does not confirm that Dot
stopped all external activity.
- Assigned skill files and third-party MCP bindings are unsupported and
reject admission. There is no mounted workspace, model selector, or
provider thread identifier.
- Hosted agent-broker and remote controller deployments are not
qualified.
- The new migration follows the merged master history. Existing
prototype databases still need the normal master migration history
before this Dot-only migration.

## Model Used

OpenAI Codex, based on GPT-6. The exact deployment ID and context window
size are not exposed in this session. Capabilities used: reasoning,
repository editing, code execution, and test inspection.

## 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 #123` 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 references)
- [x] My branch name describes the change 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-07 19:11:50 -05:00

263 lines
18 KiB
TypeScript

import { tmpdir } from "node:os";
import { join } from "node:path";
import { nativeSystemInstructions } from "../../../packages/paperclip-runner/src/backends/runtime-context.js";
import type { NativeExecutionInput } from "../vendor/paperclip-runner/index.js";
import { randomUUID } from "node:crypto";
import { access, mkdtemp, writeFile, rm, readFile } from "node:fs/promises";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { agents, companies, companyMemberships, connectionGrants, createDb, heartbeatRuns, issues, toolApplications, toolCatalogEntries, toolConnections, toolPolicies, toolProfileBindings, toolActionRequests } from "@paperclipai/db";
import { createToolGatewayService } from "../services/tool-gateway.js";
import { toolDiscoveryScheduler } from "../services/tool-discovery-scheduler.js";
import { toolAccessService, projectedConnectionToolArguments, projectedConnectionToolInputSchema } from "../services/tool-access.js";
import { composeConnectionInstructions, prepareConnectionInstructionDelivery } from "../services/connection-instructions.js";
import { renderPaperclipWakePrompt } from "@paperclipai/adapter-utils/server-utils";
import { canonicalNativeRuntimeContextDigest, parseNativeRuntimeContext } from "../vendor/paperclip-runner/index.js";
import { nativeRuntimeContextFixture } from "../services/native-runtime/runtime-context.test-fixture.js";
import { execute as executeProcess } from "../adapters/process/execute.js";
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
const support = await getEmbeddedPostgresTestSupport();
const paragraph = "Use the release handbook before changing a deployment. Cite the relevant release checklist.";
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 };
}
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 };
}
(support.supported ? describe : describe.skip)("generic connection instruction delivery", () => {
let db: ReturnType<typeof createDb>;
let temp: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
beforeAll(async () => { temp = await startEmbeddedPostgresTestDatabase("paperclip-connection-instructions-"); db = createDb(temp.connectionString); }, 30000);
afterAll(async () => { await temp?.cleanup(); });
async function fixture() {
const run = await createRunFixture(db);
const connection = await createRemoteMcpToolFixture(db, run.company.id);
const service = toolAccessService(db);
await service.updateConnection(connection.connection.id, { agentInstructions: { enabled: true, text: paragraph } });
await service.finishGalleryAppConnection(run.company.id, connection.connection.id, {
enabledCatalogEntryIds: [connection.catalogEntry.id], askFirstCatalogEntryIds: [], access: { agentIds: [run.agent.id] },
});
const gateway = createToolGatewayService(db);
const binding = { companyId: run.company.id, agentId: run.agent.id, runId: run.run.id };
return { ...run, ...connection, gateway, service, binding, resolve: () => gateway.resolveConnectionInstructionsForRun(binding) };
}
it("keeps guidance stable and checks revocation even when the discovery queue is saturated", async () => {
const f = await fixture();
const snapshot = await f.resolve();
expect(snapshot?.text).toContain(paragraph);
let release!: () => void;
const barrier = new Promise<void>((resolve) => { release = resolve; });
const listings = Array.from({ length: 34 }, () => toolDiscoveryScheduler.run(() => barrier));
try {
expect(await f.resolve()).toEqual(snapshot);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, f.connection.id));
expect(await f.resolve()).toBeNull();
} finally {
release();
await Promise.all(listings);
}
});
it("persists a non-memory paragraph and captures it in actual process input and both prompt composers", async () => {
const f = await fixture();
expect((await f.service.getConnection(f.connection.id)).agentInstructions).toEqual({ enabled: true, text: paragraph });
const context: Record<string, unknown> = { connectionInstructions: { text: "forged" }, paperclipWake: { connectionInstructions: { text: "forged wake" } } };
const config = await prepareConnectionInstructionDelivery({ resolve: f.resolve, context, config: { paperclipConnectionInstructions: { text: "forged config" } }, native: false });
const snapshot = config.paperclipConnectionInstructions as { text: string; digest: string };
expect(snapshot.text).toContain(paragraph);
expect(snapshot.text).not.toContain("forged");
expect(renderPaperclipWakePrompt(context.paperclipWake)).toContain(paragraph);
const runtimeContext = { ...nativeRuntimeContextFixture(), connectionInstructions: snapshot };
runtimeContext.aggregateDigest = canonicalNativeRuntimeContextDigest(runtimeContext);
const parsed = parseNativeRuntimeContext(runtimeContext);
const bundle = await mkdtemp(join(tmpdir(), "connection-instruction-input-"));
try {
await writeFile(join(bundle, "AGENTS.md"), "Agent entry instructions.");
parsed.instructions.bundle.rootPath = bundle;
expect(nativeSystemInstructions({ provider: { kind: "codex" }, runtimeContext: parsed } as NativeExecutionInput)).toContain(paragraph);
} finally { await rm(bundle, { recursive: true, force: true }); }
expect(() => parseNativeRuntimeContext({ ...runtimeContext, connectionInstructions: { ...snapshot, text: "forged" } })).toThrow();
expect(parseNativeRuntimeContext(nativeRuntimeContextFixture()).connectionInstructions).toBeUndefined();
const captured: string[] = [];
const result = await executeProcess({ runId: f.run.id, agent: { ...f.agent, adapterType: "process" }, runtime: { sessionId: null, sessionParams: null, sessionDisplayId: null, taskKey: null }, context,
config: { command: process.execPath, args: ["-e", "const fs=require('node:fs');const file=process.env.PAPERCLIP_CONNECTION_INSTRUCTIONS_FILE;console.log(JSON.stringify({file,mode:fs.statSync(file).mode&511,snapshot:JSON.parse(fs.readFileSync(file,'utf8'))}))"], env: { PAPERCLIP_CONNECTION_INSTRUCTIONS_FILE: "/forged" } },
onLog: async (_stream, text) => { captured.push(text); },
});
expect(result.exitCode).toBe(0);
const received = JSON.parse(captured.join("").trim());
expect(received.snapshot).toEqual(snapshot);
expect(received.mode).toBe(0o600);
await expect(access(received.file)).rejects.toThrow();
});
it("backfills existing template connections without replacing custom text or opt-outs", async () => {
const f = await fixture();
await db.update(toolConnections).set({ agentInstructions: null, config: { ...f.connection.config, sourceTemplateKey: "mem0" } }).where(eq(toolConnections.id, f.connection.id));
const migration = await readFile(new URL("../../../packages/db/src/migrations/0298_connection_agent_instructions.sql", import.meta.url), "utf8");
await db.$client.unsafe(migration);
const populated = await f.service.getConnection(f.connection.id);
expect(populated.agentInstructions).toMatchObject({ enabled: true, template: { id: "mem0.usage", version: 1 } });
await f.service.updateConnection(f.connection.id, { agentInstructions: { enabled: false, text: paragraph } });
await db.$client.unsafe(migration);
expect((await f.service.getConnection(f.connection.id)).agentInstructions).toEqual({ enabled: false, text: paragraph });
});
it("freezes active turns and removes instructions on the next turn without removing tools", async () => {
const f = await fixture();
const first = await f.resolve();
await f.service.updateConnection(f.connection.id, { agentInstructions: { enabled: true, text: "New release procedure." } });
expect((await f.resolve())?.digest).not.toBe(first?.digest);
expect(first?.text).toContain(paragraph);
await f.service.updateConnection(f.connection.id, { agentInstructions: { enabled: false, text: paragraph } });
expect(await f.resolve()).toBeNull();
const session = await f.gateway.createSession(f.binding);
expect((await f.gateway.listToolsForSession(session.token)).some(tool => tool.connectionId === f.connection.id)).toBe(true);
const context: Record<string, unknown> = { connectionInstructions: first, paperclipWake: { connectionInstructions: first } };
const config = await prepareConnectionInstructionDelivery({ resolve: f.resolve, context, config: { paperclipConnectionInstructions: first }, native: false });
expect(config.paperclipConnectionInstructions).toBeNull();
expect(renderPaperclipWakePrompt(context.paperclipWake)).not.toContain(paragraph);
});
it("follows assignment, action policy, grant revocation, and company boundaries", async () => {
const f = await fixture();
expect(await f.resolve()).not.toBeNull();
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.connectionId, f.connection.id));
expect(await f.resolve()).toBeNull();
await db.update(connectionGrants).set({ status: "active" }).where(eq(connectionGrants.connectionId, f.connection.id));
const [block] = await db.insert(toolPolicies).values({ companyId: f.company.id, name: "Block handbook", policyType: "block", priority: 1000, selectors: { connectionId: f.connection.id } }).returning();
expect(await f.resolve()).toBeNull();
await db.delete(toolPolicies).where(eq(toolPolicies.id, block.id));
await db.delete(toolProfileBindings).where(eq(toolProfileBindings.targetId, f.agent.id));
expect(await f.resolve()).toBeNull();
const other = await fixture();
await expect(f.gateway.resolveConnectionInstructionsForRun({ ...f.binding, companyId: other.company.id })).rejects.toMatchObject({ status: 403 });
await expect(f.gateway.resolveConnectionInstructionsForRun({ ...f.binding, agentId: other.agent.id })).rejects.toMatchObject({ status: 403 });
});
it("invalidates a pending approval when the configured Honcho workspace changes", async () => {
const f = await fixture();
const config = { ...f.connection.config, sourceTemplateKey: "honcho", connectionMethodKey: "mcp-api-key", methodConfig: { workspaceId: "before" } };
await f.service.updateConnection(f.connection.id, { config });
await db.update(toolCatalogEntries).set({ inputSchema: { type: "object", properties: { workspace_id: { type: "string" }, query: { type: "string" } }, required: ["workspace_id"] } }).where(eq(toolCatalogEntries.id, f.catalogEntry.id));
await f.service.finishGalleryAppConnection(f.company.id, f.connection.id, { enabledCatalogEntryIds: [f.catalogEntry.id], askFirstCatalogEntryIds: [f.catalogEntry.id], access: { agentIds: [f.agent.id] } });
let providerCalls = 0;
const gateway = createToolGatewayService(db, { toolActionSigningSecret: "instruction-workspace-test", remoteHttpRequest: async () => { providerCalls++; throw new Error("Stale approval must not reach Honcho"); } });
const session = await gateway.createSession(f.binding);
const tool = (await gateway.listToolsForSession(session.token)).find(tool => tool.connectionId === f.connection.id)!;
expect(JSON.stringify(tool.parametersSchema)).not.toContain("workspace_id");
await expect(gateway.executeTool({ sessionToken: session.token, tool: tool.name, parameters: { query: "release", workspace_id: "forged" } })).rejects.toMatchObject({ reasonCode: "approval_required" });
const [approval] = await db.select().from(toolActionRequests).where(eq(toolActionRequests.issueId, f.issue.id));
await f.service.updateConnection(f.connection.id, { config: { ...config, methodConfig: { workspaceId: "after" } } });
await expect(gateway.approveActionRequest({ companyId: f.company.id, actionRequestId: approval.id, actor: { userId: "reviewer" } })).rejects.toMatchObject({ reasonCode: "approved_tool_target_changed" });
expect(providerCalls).toBe(0);
});
it("requires the responsible person's active membership and personal identity", async () => {
const f = await fixture();
await db.update(toolConnections).set({ credentialPolicy: "per_user" }).where(eq(toolConnections.id, f.connection.id));
await db.update(connectionGrants).set({ kind: "user", subjectUserId: "instruction-owner", isDefault: false }).where(eq(connectionGrants.connectionId, f.connection.id));
expect(await f.resolve()).toBeNull();
await db.insert(companyMemberships).values({ companyId: f.company.id, principalType: "user", principalId: "instruction-owner", membershipRole: "member", status: "active" });
await db.update(heartbeatRuns).set({ responsibleUserId: "instruction-owner" }).where(eq(heartbeatRuns.id, f.run.id));
expect(await f.resolve()).not.toBeNull();
await db.update(companyMemberships).set({ status: "inactive" }).where(eq(companyMemberships.companyId, f.company.id));
expect(await f.resolve()).toBeNull();
});
});
describe("Honcho workspace configuration", () => {
const schema = { type: "object", properties: { workspace_id: { type: "string" }, query: { type: "string" } }, required: ["workspace_id", "query"] };
const connection = { config: { sourceTemplateKey: "honcho", connectionMethodKey: "mcp-api-key", methodConfig: { workspaceId: "team-workspace" } } } as typeof toolConnections.$inferSelect;
it("projects the workspace and hides its argument while keeping old unconfigured tools usable", () => {
expect(projectedConnectionToolArguments(connection, { workspace_id: "forged", query: "decisions" }, "query", schema)).toEqual({ workspace_id: "team-workspace", query: "decisions" });
expect(projectedConnectionToolInputSchema(connection, schema, "query")).toEqual({ type: "object", properties: { query: { type: "string" } }, required: ["query"] });
const old = { ...connection, config: { ...connection.config, methodConfig: {} } };
expect(projectedConnectionToolArguments(old, { workspace_id: "chosen" }, "query", schema)).toEqual({ workspace_id: "chosen" });
const source = { connection: { ...old, id: "honcho", name: "Honcho", agentInstructions: { enabled: true, text: paragraph } }, grantId: "grant" };
expect(composeConnectionInstructions([source])).toBeNull();
const configured = composeConnectionInstructions([{ ...source, connection: { ...source.connection, config: connection.config } }]);
expect(configured?.text).toContain('"workspaceId":"team-workspace"');
const changed = composeConnectionInstructions([{ ...source, connection: { ...source.connection, config: { ...connection.config, methodConfig: { workspaceId: "other" } } } }]);
expect(changed?.digest).not.toBe(configured?.digest);
const legacy = { ...source, connection: { ...source.connection, config: {}, transportConfig: connection.config } };
expect(composeConnectionInstructions([legacy])).toEqual(configured);
expect(projectedConnectionToolArguments({ ...connection, config: {}, transportConfig: connection.config }, { workspace_id: "forged" }, "query", schema)).toEqual({ workspace_id: "team-workspace" });
expect(composeConnectionInstructions([{ ...legacy, connection: { ...legacy.connection, transportConfig: old.config } }])).toBeNull();
const methodChanged = { ...legacy, connection: { ...legacy.connection, config: { connectionMethodKey: "new-method" } } };
expect(composeConnectionInstructions([methodChanged])?.digest).not.toBe(configured?.digest);
});
});