Files
PaperClipAI/server/src/services/native-runtime/paperclip-runner-tool-authority.test.ts
T
DottaandPaperclip dd777f4b73 feat(dot): complete onboarding and expand governed Runner capabilities (#15414)
## Thinking Path

> - Paperclip manages AI agents, their work, and their permissions.
> - Paperclip Runner supplies the same admitted tool authority to each
provider.
> - The Dot provider in #15402 needs reliable onboarding and useful
agent capabilities.
> - An idle Dot could not start work, assign a human, read skills, or
produce a workspace artifact.
> - Pairing also relied on a second configuration save before ordinary
admission could work.
> - This pull request adds governed idle admission and shared Runner
tools, and completes pairing atomically.
> - Operators can test Dot with fresh data while keeping normal company,
approval, budget, and run ownership checks.

## Linked Issues or Issue Description

**Subsystem affected**

Paperclip Runner, dedicated Dot MCP access, OAuth onboarding,
experimental settings, and empty worktree startup. This PR builds on
merged provider PR #15402. It reuses the merged MCP gateway from #14846
and assistant connection work from #14933 and #15380.

**Problem or motivation**

An idle Dot could see assignments but could not act on a conversation
request until someone created a task first. Its Runner catalog could not
assign tasks to humans or read pinned skills and workspace files.
First-time OAuth discovery and pairing also needed browser fixes, and a
completed pairing did not persist its binding reference on the agent.

**Proposed solution**

Keep Dot within the existing Runner. Admit a visible agent-authored
intake task for idle requests. Add people, human assignment, cross-task,
skill, and optional sandbox workspace tools through shared authority.
Relay assigned app calls through the configured MCP gateway. Add lease
renewal and follow-up references. Save pairing and its configuration
revision atomically. Show prerequisites and provide a complete copy
prompt.

**Roadmap alignment**

This extends the experimental provider in #15402. It uses the existing
governed gateway, task model, skills, artifact path, and native Runner.
It adds no separate execution subsystem.

## What Changed

- Add a standalone OpenAI Dot agent choice with an independent
experimental opt-in. It works with the general Runner option off.
Require Assistant connections (MCP), authenticated sign-in, and public
HTTPS for pairing.
- Use Dot’s own option for company package import. Allow an unpaired Dot
configuration to save after external billing acknowledgement; task
admission still requires pairing. Prepare the shared dev binary for
Dot-only opt-in.
- Label saved Dot agents as OpenAI Dot. Use prerequisite-check copy in
setup and runtime configuration.
- Route Dot creation directly to pairing after explicit external billing
acknowledgement. Hide local CLI, model, and harness setup for Dot.
Preserve the shared Runner implementation and canonical API type. Other
Runner providers still require their general opt-in.
- Add an empty worktree option with fresh signing keys and no production
data copy.
- Fix public-client OAuth negotiation, discovery compatibility, and
optional separate browser authorization origin.
- Add one-use pairing consent preview, clear copied setup instructions,
and atomic binding persistence and cleanup.
- Add idle request admission with stable request IDs and normal
scheduling, permissions, budgets, and task ownership.
- Add identity and people discovery, human task assignment and
reassignment, and authorized cross-task comments and documents.
- Read assigned skill files from pinned manifests. Relay assigned app
calls through the merged gateway without exposing credentials.
- Add an off-by-default workspace bridge. Constrain paths and writes.
Run commands in a deny-by-default OS sandbox with no network or injected
credentials. Reserve mutations before effects and never blindly repeat
uncertain work.
- Add rolling lease renewal, task pagination, bounded operation limits,
and deduplicated follow-up references without comment bodies in
webhooks.
- Add an off-by-default attachment reading setting. Restrict reads to
files on the current assigned task. Verify size and hash, cache bounded
verified copies per run, paginate text or binary bytes, and recheck live
authority before returning.
- Keep file grants operator-owned. Reject agent self-grants across
configuration routes. Preserve attachment consent in create/import
forms. Close generic API file bypasses while retaining current-run
response snapshots and permitted uploads.
- Keep provider limits explicit. Do not inherit a Dot binding,
attachment permission, or workspace permission when hiring another
agent.
- Include the required Markdown format in cross-task document writes and
validate the API title limit. Verify real creation and revision
persistence.
- Restrict command execution to Linux bubblewrap with descendant
containment. macOS retains workspace file tools and artifact publishing,
while refusing command calls. Explain the platform limit in setup.
- Exclude Paperclip instance state from workspace files, uploads,
artifact publication, and sandbox commands. Protect nested directories
and case variants. Fail closed when the directory protection scan
exceeds 4,096 directories.
- Add static UI compression for slow public tunnels. Document setup, the
complete tool inventory, and qualification limits.

## Verification

- Merge preparation on `00ca2c75b` integrates merged base #15402 and
master `fc6304dfe`. The ancestry commit preserves the reviewed follow-up
source tree. The subsequent security fix excludes instance state from
file tools, uploads, artifact publication, and sandbox commands. It
preserves private task authorization and task monitors. It regenerates
the combined tool catalog, seeded catalog digest, and protocol manifest.
Workspace typecheck, full build, and UI token gates pass. All sixteen
real Dot broker cases and 93 company import cases pass after the review
fixes and creator-attribution test correction. The exported
human-assignment catalog and Unicode page boundaries are also fixed. All
ten catalog tests and nine workspace/skill bridge tests pass. All 35
workspace bridge and authority tests passed after the instance-state
fix, including real macOS commands in that intermediate version. The
subsequent document and descendant-containment fixes pass 44 focused
tests across bridge, authority, and setup UI, with six Linux command
cases skipped on macOS. Real cross-task documents pass the route
validator and persist two revisions. macOS refuses command execution and
does not advertise the tool. Full workspace typecheck and build, changed
server/UI typechecks, and token gates pass again on the final commit.
Greptile rates final head 00ca2c75b 5/5 and its completed check
concludes success; all review threads are resolved. All 58 current-head
checks are complete: 54 passed and 4 intentionally skipped. This
includes full tests, typecheck, build, Runner, browser E2E, release
verification, and Canary Dry Run. The older full local root attempt
finished with 16,602 passes, 93 skips, and ten failures across two
suites: it began before source edits and retained earlier imported
implementations while loading later tests. Both suites pass a clean
final-head rerun (25 passed, six Linux-only command cases skipped on
macOS). This mixed-source full attempt is not a final-head full-suite
pass; use the fresh CI evidence below.
- Full workspace typecheck and build pass for the standalone Dot change
on head `392d54f80`. UI token gates are clean. The full workspace
typecheck passed before the final importer UI edit; the changed UI
typecheck, build, and token gates pass again on the final commit. The
server build passes for its unchanged final source.
- Standalone selection, creation, settings, harness visibility,
inventory, and runtime admission checks pass. OAuth onboarding and the
real Rust/PostgreSQL broker suite pass 27 cases with the general Runner
option disabled. Dot and MCP revocation still block pairing; other
Runner providers remain disabled. Create, hire, conversion, and
inherited-hire route regressions pass 68 cases. The runtime selection
suite passes 20 cases. The setup UI suite passes 50 cases. Company
import and dev binary checks pass 97 cases. Import UI checks pass 29
cases, including Dot-only selection, preservation of imported Dot
agents, generic Runner fallback, canonical configuration serialization,
and required billing acknowledgement. A read of the synthetic instance
reports the native binary required with Dot enabled, the general rollout
disabled, and no persisted native work.
- The latest attachment, operator-consent, generic API file-guard, and
bridge checks pass 80 tests. Cache and native lifecycle checks pass 550
tests; create/import builders pass 45 tests; attachment setup UI checks
pass 16 tests. The real Rust/PostgreSQL Dot broker suite passes 15
cases.
- Earlier authority, human assignment, pinned skill, confinement,
cancellation, inheritance, onboarding, replay, OpenAPI, and gateway
regressions pass their focused rechecks. Workspace writes reject
concurrent stale hashes.
- In the live empty test-drive, turn the general Runner option off and
leave Dot and MCP on. Add agent shows a separate OpenAI Dot choice.
Create rejects missing billing acknowledgement, saves the canonical Dot
configuration, and opens pairing. The existing paired Dot remains ready
and passes its prerequisite checks. No new plugin pairing was needed for
this UI change. The final browser import preview keeps a Dot source
agent as OpenAI Dot, falls back a generic Runner agent while its switch
is off, and offers Dot independently.
- Real Dot completed OAuth, signed MCP Events readiness, and an
event-only assigned document task in an empty synthetic instance.
Pairing saved its binding without a second configuration save.
- Real Dot verified human assignment, cross-task comments and documents,
pinned skill reading, sandbox commands, lease renewal, follow-up input,
and a downloaded artifact whose bytes and hash matched its receipt. An
idle conversation request created an intake, created a task for its
human owner, continued after a definite missing-file read error, and
finalized Done with exit code 0.
- After operator approval, real Dot read a synthetic assigned-task
attachment and wrote its file-only random proof into an agent-authored
document. Its first test required accepting review because the existing
document tool removed the final newline.
- On head `2626c8f9b`, real Dot read a 13,849-byte synthetic attachment
in two pages, used `expectedSha256` on page two, saved exactly its final
random marker, verified readback, and finalized Done with exit code 0. A
direct inbox check was required for this attachment qualification; it
does not claim event-only delivery.
- Previous head `392d54f80` passes all 55 checks (53 passed, two
intentionally skipped), including the full test, typecheck, build,
native Runner, browser, and release verification gates. Greptile rates
this head 5/5; all review threads are resolved.
- Head `2626c8f9b` passed all 56 checks: 54 passed and two intentionally
skipped. This includes full typecheck, build, native Runner, server
tests, serialized suites, browser E2E, and Canary Dry Run. The unchanged
Cursor managed-runtime test exceeded its five-second deadline on the
first attempt; its focused local suite passed all eight cases, and the
single CI rerun plus dependent verify gate passed.
- A prior full local serial test attempt reported 19 failures (16,141
passed, 88 skipped) and stopped before later wrapper groups. It began
before the final source edits. Every failed suite has a passing fresh
recheck; the macOS snapshot stress case passes alone in 227 seconds. The
previous head `000fb9261` passed all 56 CI checks. PRs leave
`pnpm-lock.yaml` unchanged; CI and the refresh bot own dependency
resolution.

## Risks

- Dot remains off by default. Its own opt-in does not enable other
Runner providers. It still requires the MCP option; disabling Dot blocks
new work while keeping existing recovery and saved bindings.
- Dot requires a stable public HTTPS origin. Its base provider in #15402
is merged. Temporary tunnels are useful for testing but are not
permanent deployments.
- Idle intake creates a visible agent-authored task. It does not
fabricate a human message or bypass ordinary admission.
- Workspace commands require Linux bubblewrap with a private PID
namespace; deployment qualification is still needed. macOS file tools
and artifact publishing remain available, but commands are disabled
because sandbox-exec does not contain detached descendants. There is no
unrestricted fallback. Command protection fails closed above 4,096
workspace directories. The historical macOS command walkthrough does not
qualify the current Linux implementation.
- Provider model choice, token usage, cost, native thread control, and
global external stopping remain unavailable. Known Paperclip budget
gates still apply.
- The workspace bridge and attachment reader are separate opt-in
settings. Reading assigned task files sends their contents to OpenAI.
Revocation prevents future reads but cannot withdraw bytes already sent.
Files are read on request; automatic inbound attachment staging remains
disabled.
- An existing event registration can retain earlier instructions that
prohibit extra tasks. Dot asked for permission before a second intake
after the final event-only bootstrap; that extra no-nudge continuation
is not live-qualified under that earlier registration. The later
attachment qualification submitted normally through the composer. The
revised onboarding prompt describes the new idle entry point, and its
protocol polling path is tested.
- OpenAI event delivery can be delayed; a webhook acknowledgement is not
proof that Dot has begun work.
- A running Dot can retain an old plugin catalog after tool refresh.
Refresh and actual tool exposure must be checked before using new
top-level actions.
- Hosted and remote controller modes are not qualified.

## 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, test inspection, and browser
control.

## 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 linked existing issues or described the issue in-PR
following the relevant issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links
- [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 (focused suites and all
fresh failure rechecks pass; the earlier full attempt is disclosed
above)
- [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:44:17 -05:00

1407 lines
53 KiB
TypeScript

import * as cloudIdentity from "../cloud-runtime-identity.js";
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { randomUUID } from "node:crypto";
import { upsertIssueDocumentSchema } from "@paperclipai/shared";
import { and, eq, inArray } from "drizzle-orm";
import {
activityLog,
agents,
authUsers,
approvals,
companies,
companyMemberships,
createDb,
documents,
heartbeatRuns,
issueApprovals,
issueComments,
issueThreadInteractions,
issues,
} from "@paperclipai/db";
import { startEmbeddedPostgresTestDatabase } from "../../__tests__/helpers/embedded-postgres.js";
import { initializeRunIdentity, reserveSteeredIdentity, reconcileSteeredIdentity } from "../run-identity.js";
import { documentService } from "../documents.js";
import { issueService } from "../issues.js";
import { PaperclipRunnerToolAuthority } from "./paperclip-runner-tool-authority.js";
import { createAssignedMcpTools } from "./assigned-mcp-tools.js";
import type { ToolGatewayService } from "../tool-gateway.js";
import { READ_CURRENT_WAKE_COMMENTS_TOOL_NAME } from "./current-wake-comments.js";
import { CAPABILITY_SEMANTIC_TOOL_CATALOG, runnerCodexDynamicToolsFit } from "../../vendor/paperclip-runner/index.js";
describe("PaperclipRunnerToolAuthority", () => {
const credentialDocumentBody = "Use a secret manager for credential handling.\nAuthorization: Bearer intentional-document-credential";
let temporary: Awaited<
ReturnType<typeof startEmbeddedPostgresTestDatabase>
> | null = null;
let db: ReturnType<typeof createDb>;
const companyId = "00000000-0000-4000-8000-000000000101";
const agentId = "00000000-0000-4000-8000-000000000102";
const issueId = "00000000-0000-4000-8000-000000000103";
const runId = "00000000-0000-4000-8000-000000000104";
beforeEach(() => {
vi.stubEnv("PAPERCLIP_RUNNER_API_TOOLS_ENABLED", undefined);
vi.stubEnv("PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS", undefined);
});
afterEach(() => vi.unstubAllEnvs());
beforeAll(async () => {
temporary = await startEmbeddedPostgresTestDatabase(
"paperclip-runner-tools-",
);
db = createDb(temporary.connectionString);
await db.insert(companies).values({
id: companyId,
name: "Runner tools",
issuePrefix: "RNT",
issueCounter: 1,
});
await db.insert(agents).values({
id: agentId,
companyId,
name: "Runner agent",
adapterType: "paperclip_runner",
adapterConfig: { provider: "codex", apiKey: "must-not-leak" },
runtimeConfig: { token: "must-not-leak" },
status: "active",
});
await db.insert(issues).values({
id: issueId,
companyId,
issueNumber: 1,
identifier: "RNT-1",
title: "Exercise real runner tools",
status: "in_progress",
workMode: "standard",
assigneeAgentId: agentId,
});
await db.insert(heartbeatRuns).values({
id: runId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: issueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId },
});
await db
.update(issues)
.set({ executionRunId: runId })
.where(eq(issues.id, issueId));
});
afterAll(async () => {
await temporary?.cleanup();
});
it("advertises only real bindings and reads the bound task", async () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
expect(authority.definitions()).toHaveLength(44);
expect(authority.definitions().map(tool => tool.name)).not.toContain("read_chat_attachment");
expect(authority.definitions().map(tool => tool.name)).not.toContain("read_current_wake_comments");
const questions = authority.definitions().find(tool => tool.name === "request_human_input")!;
expect(questions.description).toContain("ask only the next unanswered question");
expect(questions.description).toContain("Never fabricate answers");
expect(questions.description).toContain("resolve-from-comment");
expect(questions.description).toContain("Existing resolver permissions still apply");
expect(questions.description).toContain("Do not fabricate answer links");
expect(JSON.stringify(questions.inputSchema)).toContain("at least two meaningful options");
expect(questions.inputSchema).toMatchObject({ properties: { payload: { properties: { questionSet: {
properties: { questions: { items: { properties: { answerMode: { enum: ["single_select", "multi_select", "text"] } } } } },
} } } } });
expect(authority.definitions().map((tool) => tool.name)).toEqual(
expect.arrayContaining([
"connections_search",
"connection_request", "create_project", "list_project_repositories", "list_projects",
"search_api", "call_api", "hire_agent",
"get_task_context",
"get_task_history",
"search_tasks",
"report_progress",
"submit_complaint",
"submit_suggestion",
"request_human_input",
"create_task",
"set_dependencies",
"set_task_monitor",
"list_documents",
"read_document",
"list_document_revisions",
"write_document",
"create_skill",
"update_skill",
"list_agents",
"get_agent",
"list_approvals",
"get_approval",
"get_approval_context",
"list_chat_attachments",
"reuse_chat_attachment",
]),
);
const context = await authority.execute({
tool: "get_task_context",
callId: "context",
arguments: {},
});
expect(context).toMatchObject({
activeTask: { id: issueId, identifier: "RNT-1" },
actor: { id: agentId },
});
expect(JSON.stringify(context)).not.toContain("must-not-leak");
await expect(
authority.execute({
tool: "finish_task",
callId: "hidden",
arguments: {},
}),
).rejects.toThrow("paperclip_runner_tool_not_advertised");
await expect(
authority.execute({
tool: "list_chat_attachments",
callId: "historical-list-without-chat-binding",
arguments: {},
}),
).rejects.toThrow("paperclip_runner_chat_attachment_binding_denied");
await expect(
authority.execute({
tool: READ_CURRENT_WAKE_COMMENTS_TOOL_NAME,
callId: "reader-without-bound-wake",
arguments: {},
}),
).rejects.toThrow("paperclip_runner_tool_not_advertised");
});
it("returns public task URLs from the current claimed origin in context and search results", async () => {
const origin = vi.spyOn(cloudIdentity, "runtimeCanonicalOrigin").mockReturnValue("https://board.example");
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
try {
expect(await authority.execute({ tool: "get_task_context", callId: "public-task-url", arguments: {} }))
.toMatchObject({ activeTask: { id: issueId, url: `https://board.example/issues/${issueId}` } });
expect(await authority.execute({ tool: "search_tasks", callId: "search-public-task-url", arguments: { query: "Exercise real runner tools" } }))
.toMatchObject({ tasks: expect.arrayContaining([expect.objectContaining({ id: issueId, url: `https://board.example/issues/${issueId}` })]) });
origin.mockReturnValue("https://renamed.example");
expect(await authority.execute({ tool: "get_task_context", callId: "renamed-task-url", arguments: {} }))
.toMatchObject({ activeTask: { url: `https://renamed.example/issues/${issueId}` } });
origin.mockReturnValue("https://localhost");
expect(await authority.execute({ tool: "get_task_context", callId: "unsafe-task-url", arguments: {} }))
.toMatchObject({ activeTask: { url: null } });
} finally {
origin.mockRestore();
}
});
it("exposes existing child tasks on continuation without crossing company boundaries", async () => {
const completedChildId = randomUUID();
const activeChildId = randomUUID();
const unrelatedId = randomUUID();
const otherCompanyId = randomUUID();
const foreignChildId = randomUUID();
const hiddenChildIds = Array.from({ length: 101 }, () => randomUUID());
await db.insert(companies).values({ id: otherCompanyId, name: "Other company", issuePrefix: "OTHER" });
await db.insert(issues).values([
{ id: completedChildId, companyId, parentId: issueId, title: "Existing completed draft", status: "done", assigneeAgentId: agentId },
{ id: activeChildId, companyId, parentId: issueId, title: "Existing active review", status: "in_progress", assigneeAgentId: agentId },
{ id: unrelatedId, companyId, title: "Unrelated task", status: "todo" },
// Even inconsistent imported data cannot expose another company's task.
{ id: foreignChildId, companyId: otherCompanyId, parentId: issueId, title: "Foreign child", status: "todo" },
// Hidden rows must neither enter context nor consume the visible child limit.
...hiddenChildIds.map((id) => ({ id, companyId, parentId: issueId, title: "Hidden child",
hiddenAt: new Date(), createdAt: new Date(Date.now() + 1000) })),
]);
try {
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
const context = await authority.execute({ tool: "get_task_context", callId: "context-existing-children", arguments: {} });
expect(context).toMatchObject({
childTasks: expect.arrayContaining([
expect.objectContaining({ id: completedChildId, status: "done", parentId: issueId }),
expect.objectContaining({ id: activeChildId, status: "in_progress", assigneeAgentId: agentId }),
]),
childTasksTruncated: false,
delegationGuidance: expect.stringContaining("Reuse existing child tasks"),
});
expect(JSON.stringify(context)).not.toContain(foreignChildId);
expect(JSON.stringify(context)).not.toContain(unrelatedId);
for (const id of hiddenChildIds) expect(JSON.stringify(context)).not.toContain(id);
} finally {
await db.delete(issues).where(inArray(issues.id, [completedChildId, activeChildId, unrelatedId, foreignChildId, ...hiddenChildIds]));
await db.delete(companies).where(eq(companies.id, otherCompanyId));
}
});
it("advertises API tools by default and preserves direct-chat file tools when disabled", () => {
const previousEnabled = process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED;
const previousCompanies =
process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS;
const createAuthority = () =>
new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
workspaceRoot: "/tmp/paperclip-runner-tools",
executionTargetKind: "local",
});
const requiredChatFileTools = [
"list_chat_attachments",
"reuse_chat_attachment",
"register_deliverable",
];
try {
delete process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED;
delete process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS;
const defaultNames = createAuthority()
.definitions()
.map((tool) => tool.name);
expect(defaultNames).toEqual(
expect.arrayContaining(requiredChatFileTools),
);
expect(defaultNames).toContain("search_api");
expect(defaultNames).toContain("call_api");
expect(defaultNames).toContain("hire_agent");
process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED = "true";
process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS = companyId;
const enabledNames = createAuthority()
.definitions()
.map((tool) => tool.name);
expect(enabledNames).toEqual(
expect.arrayContaining([
...requiredChatFileTools,
"search_api",
"call_api",
"hire_agent",
]),
);
const hire = createAuthority().definitions().find((tool) => tool.name === "hire_agent")!;
const hireSchema = hire.inputSchema as { properties: Record<string, unknown> };
expect(hireSchema.properties).toEqual(expect.objectContaining({ name: expect.any(Object), role: expect.any(Object) }));
expect(hireSchema.properties).not.toHaveProperty("adapterConfig");
expect(hireSchema.properties).not.toHaveProperty("env");
process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED = "false";
const disabledNames = createAuthority().definitions().map((tool) => tool.name);
expect(disabledNames).toEqual(expect.arrayContaining(requiredChatFileTools));
for (const name of ["search_api", "call_api", "hire_agent"]) {
expect(disabledNames).not.toContain(name);
}
} finally {
if (previousEnabled === undefined) {
delete process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED;
} else {
process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED = previousEnabled;
}
if (previousCompanies === undefined) {
delete process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS;
} else {
process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS = previousCompanies;
}
}
});
it("dispatches hire_agent with fixed caller context and replays its API receipt", async () => {
const previousEnabled = process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED;
const previousCompanies = process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS;
const previousSecret = process.env.PAPERCLIP_AGENT_JWT_SECRET;
process.env.PAPERCLIP_AGENT_JWT_SECRET = "hire-agent-test-secret";
process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED = "true";
process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS = companyId;
const fetchMock = vi.spyOn(globalThis, "fetch").mockResolvedValue(
new Response(JSON.stringify({ id: randomUUID(), status: "active" }), {
status: 201,
headers: { "content-type": "application/json" },
}),
);
try {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
apiUrl: "http://runner-test.invalid",
});
const call = {
tool: "hire_agent",
callId: "hire-agent-receipt",
arguments: {
name: "QA teammate",
role: "qa",
title: "Quality lead",
capabilities: "Test native workflows",
instructions: "Use the assigned workspace and report findings.",
},
} as const;
const first = await authority.execute(call);
expect(first).toMatchObject({ ok: true, status: 201, apiOperationId: "POST /api/companies/{companyId}/agent-hires" });
expect(fetchMock).toHaveBeenCalledTimes(1);
const [url, request] = fetchMock.mock.calls[0] as [string, RequestInit];
expect(String(url)).toBe(`http://runner-test.invalid/api/companies/${companyId}/agent-hires`);
const body = JSON.parse(String(request.body));
expect(body).toMatchObject({
name: "QA teammate",
role: "qa",
title: "Quality lead",
capabilities: "Test native workflows",
adapterType: "paperclip_runner",
inheritRuntimeFrom: "caller",
reportsTo: agentId,
sourceIssueId: issueId,
instructionsBundle: { entryFile: "AGENTS.md", files: { "AGENTS.md": "Use the assigned workspace and report findings." } },
});
expect(body).not.toHaveProperty("adapterConfig");
expect(body).not.toHaveProperty("runtimeConfig");
expect(body).not.toHaveProperty("env");
await expect(authority.execute(call)).resolves.toEqual(first);
expect(fetchMock).toHaveBeenCalledTimes(1);
} finally {
fetchMock.mockRestore();
if (previousEnabled === undefined) delete process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED;
else process.env.PAPERCLIP_RUNNER_API_TOOLS_ENABLED = previousEnabled;
if (previousCompanies === undefined) delete process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS;
else process.env.PAPERCLIP_RUNNER_API_TOOLS_COMPANY_IDS = previousCompanies;
if (previousSecret === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET;
else process.env.PAPERCLIP_AGENT_JWT_SECRET = previousSecret;
}
});
it("dispatches cross-task Markdown documents that pass route validation and persist revisions", async () => {
vi.stubEnv("PAPERCLIP_AGENT_JWT_SECRET", "document-test-secret");
const taskId = randomUUID();
await db.insert(issues).values({ id: taskId, companyId, title: "Cross-task document target", status: "todo" });
const service = documentService(db);
const fetchMock = vi.spyOn(globalThis, "fetch").mockImplementation(async (url, request) => {
expect(String(url)).toBe(`http://runner-test.invalid/api/issues/${taskId}/documents/notes`);
expect(new Headers(request?.headers).get("authorization")).toMatch(/^Bearer /);
// Use the real route validator and persistence service, so a missing
// required format or stale base revision cannot be hidden by a spy.
const body = upsertIssueDocumentSchema.parse(JSON.parse(String(request?.body)));
const saved = await service.upsertIssueDocument({ issueId: taskId, key: "notes", ...body,
createdByAgentId: agentId, createdByRunId: runId });
return new Response(JSON.stringify(saved.document), { status: 200, headers: { "content-type": "application/json" } });
});
try {
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId,
apiToolsEnabled: true, apiUrl: "http://runner-test.invalid" });
const first = { tool: "write_task_document", callId: "cross-task-document-create", arguments: {
taskId, key: "notes", title: "Notes", body: "# First revision", baseRevisionId: null,
} };
expect(await authority.execute(first)).toMatchObject({ ok: true, status: 200 });
const saved = await service.getIssueDocumentByKey(taskId, "notes");
expect(saved).toMatchObject({ format: "markdown", body: "# First revision" });
expect(await authority.execute({ ...first, callId: "cross-task-document-update", arguments: {
...first.arguments, body: "# Second revision", baseRevisionId: saved!.latestRevisionId,
} })).toMatchObject({ ok: true, status: 200 });
expect(await service.getIssueDocumentByKey(taskId, "notes")).toMatchObject({ body: "# Second revision" });
expect(await service.listIssueDocumentRevisions(taskId, "notes")).toHaveLength(2);
const tooLong = await authority.execute({ ...first, callId: "cross-task-document-long-title", arguments: {
...first.arguments, title: "x".repeat(201),
} });
expect(tooLong).toMatchObject({ outcome: "failed", code: "runner_bridge_invalid_arguments" });
expect(fetchMock).toHaveBeenCalledTimes(2);
} finally {
fetchMock.mockRestore();
const saved = await service.getIssueDocumentByKey(taskId, "notes");
if (saved) await db.delete(documents).where(eq(documents.id, saved.id));
await db.delete(issues).where(eq(issues.id, taskId));
}
});
it("advertises structured human input in ask mode", () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
workMode: "ask",
});
expect(authority.definitions().map((tool) => tool.name)).toContain(
"request_human_input",
);
expect(authority.definitions().map((tool) => tool.name)).not.toContain(
"create_task",
);
expect(authority.definitions().map((tool) => tool.name)).not.toContain(
"set_dependencies",
);
});
it.each(["standard", "ask"] as const)(
"advertises real task-bound questions and provider-dependent controls in %s mode",
(workMode) => {
const original = CAPABILITY_SEMANTIC_TOOL_CATALOG.find(
(tool) => tool.operationId === "request_human_input",
)!;
const originalSnapshot = structuredClone(original);
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
workMode,
});
const advertised = JSON.parse(
JSON.stringify(authority.definitions()),
).find((tool: { name: string }) => tool.name === "request_human_input");
expect(advertised.description).toContain(
"current Paperclip task bound to this run",
);
expect(advertised.description).toContain(
"one complete payload.questionSet",
);
expect(advertised.description).toContain(
"Paperclip renders it and authenticates the response",
);
expect(advertised.description).toContain(
"Preserve existing review gates",
);
expect(advertised.description).not.toContain("mock");
expect(advertised.description).not.toContain("questionSpec");
expect(advertised.inputSchema).toEqual(original.inputSchema);
expect(advertised.inputSchema.properties).toHaveProperty("payload");
expect(advertised.inputSchema.properties).not.toHaveProperty(
"questionSpec",
);
expect(original).toEqual(originalSnapshot);
},
);
it.each(["choice", "text", "mixed"] as const)("executes the advertised %s question once on the bound reviewed task", async (answerMode) => {
const binding = {
companyId: randomUUID(),
agentId: randomUUID(),
issueId: randomUUID(),
runId: randomUUID(),
};
await db.insert(companies).values({
id: binding.companyId,
name: "Question invocation",
issuePrefix: answerMode === "choice" ? "RQA" : answerMode === "text" ? "RQT" : "RQM",
});
await db.insert(agents).values({
id: binding.agentId,
companyId: binding.companyId,
name: "Question agent",
adapterType: "paperclip_runner",
status: "active",
});
await db.insert(issues).values({
id: binding.issueId,
companyId: binding.companyId,
title: "Question on reviewed task",
status: "in_review",
workMode: "standard",
reviewPolicy: "human_only",
assigneeAgentId: binding.agentId,
});
await db.insert(heartbeatRuns).values({
id: binding.runId,
companyId: binding.companyId,
agentId: binding.agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: binding.issueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId: binding.issueId },
});
await db
.update(issues)
.set({ executionRunId: binding.runId })
.where(eq(issues.id, binding.issueId));
const authority = new PaperclipRunnerToolAuthority(db, binding);
const advertised = authority
.definitions()
.find((tool) => tool.name === "request_human_input")!;
expect(advertised.description).toContain("payload.questionSet");
const questions = [
{
id: "color",
prompt: "Choose one color",
selectionMode: "single",
required: true,
options: [
{ id: "amber", label: "Amber" },
{ id: "cobalt", label: "Cobalt" },
],
},
];
const payloadDescription = (advertised.inputSchema as {
properties: { payload: { description: string } };
}).properties.payload.description;
expect(payloadDescription).toContain("at least two meaningful options");
expect(payloadDescription).toContain("questionSet");
expect(payloadDescription).not.toContain("use exactly");
const payload = answerMode === "choice"
? { version: 1, questions }
: {
version: 1,
questionSet: {
schema: "paperclip.question_set.v1",
questions: [
{ id: "goal", prompt: "What should we accomplish?", answerMode: "text", required: true },
...(answerMode === "mixed" ? [{ id: "color", prompt: "Choose one color", answerMode: "single_select", required: true, options: questions[0].options }] : []),
],
},
};
const call = {
tool: "request_human_input",
callId: "advertised-question",
arguments: {
idempotencyKey: "advertised-question",
interactionKind: "questions",
title: "Choose one color",
prompt: "Choose one color",
continuationPolicy: "wake_assignee",
payload,
},
};
const first = await authority.execute(call);
expect(first).toMatchObject({
disposition: "applied",
interaction: {
companyId: binding.companyId,
issueId: binding.issueId,
sourceRunId: binding.runId,
kind: "ask_user_questions",
status: "pending",
continuationPolicy: "wake_assignee",
payload,
},
});
await expect(
authority.execute({ ...call, callId: "advertised-question-replay" }),
).resolves.toEqual(first);
const rows = await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.issueId, binding.issueId));
expect(rows).toHaveLength(1);
expect((rows[0].payload as { questions: { id: string }[] }).questions.map((question) => question.id))
.toEqual(answerMode === "choice" ? ["color"] : answerMode === "text" ? ["goal"] : ["goal", "color"]);
const [task] = await db
.select()
.from(issues)
.where(eq(issues.id, binding.issueId));
expect(task).toMatchObject({
status: "in_review",
reviewPolicy: "human_only",
assigneeAgentId: binding.agentId,
executionRunId: binding.runId,
});
const entries = await db
.select()
.from(activityLog)
.where(eq(activityLog.entityId, binding.issueId));
expect(
entries.filter(
(entry) => entry.action === "issue.thread_interaction_created",
),
).toHaveLength(1);
});
it("does not project a foreign-company task through approval context", async () => {
const foreignCompanyId = "00000000-0000-4000-8000-000000000211";
const foreignIssueId = "00000000-0000-4000-8000-000000000212";
const approvalId = "00000000-0000-4000-8000-000000000213";
await db.insert(companies).values({
id: foreignCompanyId,
name: "Foreign approval company",
issuePrefix: "FAC",
issueCounter: 1,
});
await db.insert(issues).values({
id: foreignIssueId,
companyId: foreignCompanyId,
issueNumber: 1,
identifier: "FAC-1",
title: "Must not cross the approval boundary",
status: "todo",
});
await db.insert(approvals).values({
id: approvalId,
companyId,
type: "runner_review",
status: "pending",
payload: {},
});
// The schema deliberately stores companyId independently on the link. A
// corrupt or historical cross-tenant link must still fail closed at read.
await db.insert(issueApprovals).values({
companyId,
approvalId,
issueId: foreignIssueId,
linkedByAgentId: agentId,
});
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
await expect(
authority.execute({
tool: "get_approval_context",
callId: "foreign-approval-context",
arguments: { approvalId },
}),
).resolves.toMatchObject({ approval: { id: approvalId }, tasks: [] });
});
it("rejects Dot artifact publication from instance state before reading a file", async () => {
const [actor] = await db.select().from(agents).where(eq(agents.id, agentId));
await db.update(agents).set({ adapterConfig: { ...actor.adapterConfig, dotWorkspaceAccess: true } }).where(eq(agents.id, agentId));
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId,
dotRuntime: true, workspaceBridge: true, workspaceRoot: "/tmp/fixture-workspace" });
try {
for (const contentRef of [".paperclip/.env", "nested/.PaPeRcLiP/config.json"]) {
await expect(authority.execute({ tool: "register_deliverable", callId: contentRef, arguments: {
idempotencyKey: contentRef, filename: "config.txt", title: "Config", contentType: "text/plain",
byteSize: 10, sha256: "0".repeat(64), contentRef,
} })).rejects.toThrow("runner_workspace_instance_state_denied");
}
} finally {
await db.update(agents).set({ adapterConfig: actor.adapterConfig }).where(eq(agents.id, agentId));
}
});
it("fits large assigned catalogs alongside workspace and completion tools without dropping task tools", async () => {
const listToolsForNamedGateway = vi.fn().mockResolvedValue(Array.from({ length: 224 }, (_, i) => ({
name: `app.action_${i}`, displayName: `Action ${i}`, description: "Read a fixture",
parametersSchema: { type: "object", properties: {} }, risk: "read",
})));
const assignedMcpTools = await createAssignedMcpTools({
gateway: { listToolsForNamedGateway } as unknown as ToolGatewayService,
gatewayPublicId: "fixture", bearerToken: "fixture-token",
});
const binding = { companyId, agentId, issueId, runId, workspaceRoot: "/tmp/fixture-workspace" };
const baseline = new PaperclipRunnerToolAuthority(db, binding).definitions();
expect(runnerCodexDynamicToolsFit([...baseline, ...assignedMcpTools.definitions()])).toBe(false);
const authority = new PaperclipRunnerToolAuthority(db, { ...binding, assignedMcpTools });
const tools = authority.definitions();
expect(runnerCodexDynamicToolsFit(tools)).toBe(true);
expect(tools).toEqual(expect.arrayContaining(baseline));
expect(tools.filter(tool => String(tool.name).startsWith("app_"))).toEqual([]);
expect(tools.map(tool => tool.name)).toEqual(expect.arrayContaining([
"paperclip_search_assigned_tools", "paperclip_call_assigned_tool", "register_deliverable",
]));
const call = { tool: "paperclip_search_assigned_tools", callId: "discover", arguments: { query: "Action 223" } };
await expect(authority.execute(call)).resolves.toMatchObject({ tools: [expect.objectContaining({ description: "Action 223: Read a fixture" })] });
listToolsForNamedGateway.mockClear();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId));
try {
await expect(authority.execute(call)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
expect(listToolsForNamedGateway).not.toHaveBeenCalled();
} finally {
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
}
});
it("relays assigned MCP calls only while the native run still owns its task", async () => {
const tool = { name: "app_mem0_recall", description: "Recall memory", inputSchema: { type: "object" } };
const execute = vi.fn().mockResolvedValue({ content: "synthetic memory" });
const authority = new PaperclipRunnerToolAuthority(db, {
companyId, agentId, issueId, runId,
assignedMcpTools: { definitions: () => [tool], has: (name) => name === tool.name, execute },
});
expect(authority.definitions()).toContainEqual(tool);
const call = { tool: tool.name, callId: "assigned-mcp", arguments: { query: "compass" } };
await expect(authority.execute(call)).resolves.toEqual({ content: "synthetic memory" });
expect(execute).toHaveBeenCalledWith(call, "standard");
await db.update(issues).set({ workMode: "ask" }).where(eq(issues.id, issueId));
try {
await authority.execute(call);
expect(execute).toHaveBeenLastCalledWith(call, "ask");
} finally {
await db.update(issues).set({ workMode: "standard" }).where(eq(issues.id, issueId));
}
execute.mockClear();
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, runId));
try {
await expect(authority.execute(call)).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
expect(execute).not.toHaveBeenCalled();
} finally {
await db.update(heartbeatRuns).set({ status: "running" }).where(eq(heartbeatRuns.id, runId));
}
});
it("does not advertise delegation tools during pre-acceptance planning", () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
workMode: "planning",
});
expect(authority.definitions().map((tool) => tool.name)).not.toContain(
"create_task",
);
expect(authority.definitions().map((tool) => tool.name)).not.toContain(
"set_dependencies",
);
});
it("writes progress through the real issue service and replays idempotently", async () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
const call = {
tool: "report_progress",
callId: "progress",
arguments: { body: "Runner progress", idempotencyKey: "progress-1" },
};
const first = await authority.execute(call);
const replay = await authority.execute({
...call,
callId: "progress-replay",
});
expect(replay).toEqual(first);
expect(
await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, issueId)),
).toHaveLength(1);
const progressActivity = await db
.select()
.from(activityLog)
.where(and(eq(activityLog.entityId, issueId), eq(activityLog.action, "issue.comment_added")));
expect(progressActivity).toHaveLength(1);
expect(progressActivity[0]).toMatchObject({
action: "issue.comment_added",
actorType: "agent",
actorId: agentId,
agentId,
runId,
entityType: "issue",
entityId: issueId,
details: expect.objectContaining({
bodySnippet: "Runner progress",
identifier: "RNT-1",
issueTitle: "Exercise real runner tools",
source: "paperclip_runner_protocol",
}),
});
await expect(
authority.execute({
...call,
arguments: { body: "Changed", idempotencyKey: "progress-1" },
}),
).rejects.toThrow("paperclip_runner_tool_idempotency_conflict");
});
it("creates checkbox interactions through the real interaction service", async () => {
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
const call = {
tool: "request_human_input",
callId: "ask-checkbox",
arguments: {
idempotencyKey: "favorite-animals",
interactionKind: "checkbox",
title: "Favorite zoo animals",
prompt: "Which zoo animals are your favorites?",
continuationPolicy: "wake_assignee",
payload: {
options: [
{ id: "giraffes", label: "Giraffes" },
{ id: "lions", label: "Lions" },
],
},
},
};
const first = await authority.execute(call);
await expect(
authority.execute({ ...call, callId: "ask-checkbox-replay" }),
).resolves.toEqual(first);
expect(first).toMatchObject({
interaction: { kind: "request_checkbox_confirmation", status: "pending" },
});
expect(
await db
.select()
.from(issueThreadInteractions)
.where(eq(issueThreadInteractions.issueId, issueId)),
).toHaveLength(1);
expect(
(
await db
.select()
.from(activityLog)
.where(eq(activityLog.entityId, issueId))
).filter((entry) => entry.action === "issue.thread_interaction_created"),
).toHaveLength(1);
await expect(
authority.execute({
...call,
callId: "ask-checkbox-conflict",
arguments: {
...call.arguments,
prompt: "Use the same key for a different prompt.",
},
}),
).rejects.toThrow("paperclip_runner_tool_idempotency_conflict");
});
it("writes a real revisioned document and replays the mutation receipt", async () => {
const body = credentialDocumentBody;
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
const call = {
tool: "write_document",
callId: "write-plan",
arguments: {
idempotencyKey: "write-plan-1",
key: "plan",
title: "Execution plan",
body,
// Provider bridges may serialize nullable string inputs as the literal
// "null". The protocol boundary treats that as document creation.
baseRevisionId: "null",
changeSummary: "Initial plan",
},
};
const first = await authority.execute(call);
const replay = await authority.execute({
...call,
callId: "write-plan-replay",
});
expect(replay).toEqual(first);
expect(first).toMatchObject({
disposition: "applied",
created: true,
document: { key: "plan", body },
documentHref: "/RNT/issues/RNT-1#document-plan",
});
expect(
await db
.select()
.from(documents)
.where(eq(documents.companyId, companyId)),
).toHaveLength(1);
expect(await documentService(db).getIssueDocumentByKey(issueId, "plan"))
.toMatchObject({ body: credentialDocumentBody });
const documentActivity = await db
.select()
.from(activityLog)
.where(eq(activityLog.entityId, issueId));
expect(
documentActivity.filter(
(entry) => entry.action === "issue.document_created",
),
).toEqual([
expect.objectContaining({
actorType: "agent",
actorId: agentId,
agentId,
runId,
entityType: "issue",
details: expect.objectContaining({
key: "plan",
source: "paperclip_runner_protocol",
}),
}),
]);
await expect(
authority.execute({
...call,
arguments: { ...call.arguments, body: "Conflicting retry." },
}),
).rejects.toThrow("paperclip_runner_tool_idempotency_conflict");
});
it("returns the exact accepted plan revision in task context", async () => {
const plan = await documentService(db).getIssueDocumentByKey(
issueId,
"plan",
);
expect(plan).not.toBeNull();
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
const requested = await authority.execute({
tool: "request_human_input",
callId: "approve-plan",
arguments: {
idempotencyKey: `confirmation:${issueId}:plan:${plan!.latestRevisionId}`,
interactionKind: "confirmation",
title: "Approve the plan",
prompt: "Approve this exact plan revision?",
payload: {
target: {
type: "issue_document",
issueId,
documentId: plan!.id,
key: "plan",
revisionId: plan!.latestRevisionId,
revisionNumber: plan!.latestRevisionNumber,
},
},
targetRevisionId: plan!.latestRevisionId,
continuationPolicy: "wake_assignee_on_accept",
},
});
expect(requested).toMatchObject({
interaction: {
kind: "request_confirmation",
status: "pending",
payload: {
target: {
type: "issue_document",
issueId,
key: "plan",
revisionId: plan!.latestRevisionId,
},
},
},
});
await db
.update(issueThreadInteractions)
.set({
status: "accepted",
resolvedByUserId: "test-user",
resolvedAt: new Date(),
result: { outcome: "accepted" } as never,
})
.where(
eq(
issueThreadInteractions.id,
(requested as { interaction: { id: string } }).interaction.id,
),
);
await db
.update(heartbeatRuns)
.set({
contextSnapshot: {
issueId,
workspaceRefreshReason: "accepted_plan_confirmation",
planReviewInteraction: {
acceptedTargetRevision: {
issueId,
documentId: plan!.id,
key: "plan",
revisionId: plan!.latestRevisionId,
revisionNumber: plan!.latestRevisionNumber,
},
},
},
})
.where(eq(heartbeatRuns.id, runId));
await expect(
authority.execute({
tool: "get_task_context",
callId: "accepted-context",
arguments: {},
}),
).resolves.toMatchObject({
acceptedPlan: {
documentId: plan!.id,
revisionId: plan!.latestRevisionId,
revisionNumber: plan!.latestRevisionNumber,
markdown: credentialDocumentBody,
},
});
});
it("creates ordinary children, preserves blockers, and deduplicates across runs", async () => {
const wakes: Array<{ agentId: string; options: Record<string, unknown> }> =
[];
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
workMode: "standard",
enqueueWakeup: async (wakeAgentId, options) => {
wakes.push({ agentId: wakeAgentId, options });
return null;
},
});
expect(authority.definitions().map((tool) => tool.name)).toContain(
"create_task",
);
const prerequisite = await authority.execute({
tool: "create_task",
callId: "create-prerequisite",
arguments: {
idempotencyKey: "ordinary-prerequisite",
title: "Prepare delegated input",
description:
"A self-contained prerequisite delegated from the active task.",
},
});
expect(prerequisite).toMatchObject({
disposition: "applied",
task: {
parentId: issueId,
status: "todo",
assigneeActorId: agentId,
},
});
expect(wakes).toHaveLength(1);
expect(wakes[0]).toMatchObject({
agentId,
options: {
reason: "issue_assigned",
payload: { parentIssueId: issueId },
},
});
const prerequisiteId = (prerequisite as { task: { id: string } }).task.id;
expect(await db.select().from(activityLog).where(eq(activityLog.entityId, prerequisiteId)))
.toEqual(expect.arrayContaining([expect.objectContaining({ action: "issue.created", agentId, runId, companyId })]));
const dependent = await authority.execute({
tool: "create_task",
callId: "create-dependent",
arguments: {
idempotencyKey: "ordinary-dependent",
title: "Use delegated input",
blockedByTaskIds: [prerequisiteId],
},
});
expect(dependent).toMatchObject({
disposition: "applied",
scheduledWakeIds: [],
task: { parentId: issueId, status: "blocked", assigneeActorId: agentId },
});
expect(wakes).toHaveLength(1);
await expect(
issueService(db).getRelationSummaries(issueId),
).resolves.toMatchObject({
blockedBy: [],
});
await authority.execute({
tool: "set_dependencies",
callId: "wait-for-prerequisite",
arguments: {
idempotencyKey: "source-waits-for-prerequisite",
blockedByTaskIds: [prerequisiteId],
},
});
await expect(
issueService(db).getRelationSummaries(issueId),
).resolves.toMatchObject({
blockedBy: [expect.objectContaining({ id: prerequisiteId })],
});
await issueService(db).update(prerequisiteId, {
status: "done",
actorAgentId: agentId,
});
await expect(
authority.execute({
tool: "create_task",
callId: "create-dependency-ready-child",
arguments: {
idempotencyKey: "ordinary-ready-dependent",
title: "Start after completed delegated input",
blockedByTaskIds: [prerequisiteId],
},
}),
).resolves.toMatchObject({
disposition: "applied",
task: { parentId: issueId, status: "todo", assigneeActorId: agentId },
scheduledWakeIds: [expect.any(String)],
});
expect(wakes).toHaveLength(2);
const nextRunId = "00000000-0000-4000-8000-000000000106";
await db
.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, runId));
await db.insert(heartbeatRuns).values({
id: nextRunId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: issueId,
invocationSource: "automation",
triggerDetail: "system",
contextSnapshot: { issueId },
});
await db
.update(issues)
.set({ executionRunId: nextRunId })
.where(eq(issues.id, issueId));
const retryWakes: Array<unknown> = [];
const retryAuthority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId: nextRunId,
workMode: "standard",
enqueueWakeup: async (_wakeAgentId, options) => {
retryWakes.push(options);
return null;
},
});
await expect(
retryAuthority.execute({
tool: "create_task",
callId: "cross-run-retry",
arguments: {
idempotencyKey: "ordinary-prerequisite",
title: "Prepare delegated input",
description:
"A self-contained prerequisite delegated from the active task.",
},
}),
).resolves.toMatchObject({
disposition: "duplicate",
task: { id: prerequisiteId },
});
await expect(
retryAuthority.execute({
tool: "create_task",
callId: "cross-run-conflicting-retry",
arguments: {
idempotencyKey: "ordinary-prerequisite",
title: "Conflicting title for the same caller key",
},
}),
).rejects.toThrow("paperclip_runner_tool_idempotency_conflict");
const creationEvents = (await db.select().from(activityLog).where(eq(activityLog.entityId, prerequisiteId)))
.filter(event => event.action === "issue.created");
expect(creationEvents).toHaveLength(1);
const foreignCompanyId = "00000000-0000-4000-8000-000000000201";
const foreignAgentId = "00000000-0000-4000-8000-000000000202";
const foreignIssueId = "00000000-0000-4000-8000-000000000203";
await db.insert(companies).values({
id: foreignCompanyId,
name: "Foreign company",
issuePrefix: "FGN",
issueCounter: 1,
});
await db.insert(agents).values({
id: foreignAgentId,
companyId: foreignCompanyId,
name: "Foreign agent",
adapterType: "paperclip_runner",
adapterConfig: { provider: "codex" },
runtimeConfig: {},
status: "active",
});
await db.insert(issues).values({
id: foreignIssueId,
companyId: foreignCompanyId,
issueNumber: 1,
identifier: "FGN-1",
title: "Foreign blocker",
status: "todo",
});
await expect(
retryAuthority.execute({
tool: "create_task",
callId: "foreign-assignee",
arguments: {
idempotencyKey: "foreign-assignee",
title: "Invalid foreign assignment",
assigneeActorId: foreignAgentId,
},
}),
).rejects.toThrow("paperclip_runner_agent_not_found");
await expect(
retryAuthority.execute({
tool: "create_task",
callId: "foreign-blocker",
arguments: {
idempotencyKey: "foreign-blocker",
title: "Invalid foreign blocker",
blockedByTaskIds: [foreignIssueId],
},
}),
).rejects.toThrow();
expect(retryWakes).toHaveLength(0);
expect(
await db.select().from(issues).where(eq(issues.parentId, issueId)),
).toHaveLength(3);
});
it("rejects mutations after reassignment, run replacement, or terminalization", async () => {
const guardedIssueId = "00000000-0000-4000-8000-000000000107";
const guardedRunId = "00000000-0000-4000-8000-000000000108";
const guardedReplacementRunId = "00000000-0000-4000-8000-000000000109";
await db.insert(issues).values({
id: guardedIssueId,
companyId,
issueNumber: 999,
identifier: "RNT-999",
title: "Guard mutation authorization",
status: "in_progress",
workMode: "standard",
assigneeAgentId: agentId,
});
await db.insert(heartbeatRuns).values({
id: guardedRunId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: guardedIssueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId: guardedIssueId },
});
await db.insert(heartbeatRuns).values({
id: guardedReplacementRunId,
companyId,
agentId,
status: "running",
runtimeMode: "native",
nativeIssueId: guardedIssueId,
invocationSource: "assignment",
triggerDetail: "system",
contextSnapshot: { issueId: guardedIssueId },
});
await db
.update(issues)
.set({ executionRunId: guardedRunId })
.where(eq(issues.id, guardedIssueId));
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId: guardedIssueId,
runId: guardedRunId,
});
const mutation = {
tool: "report_progress",
callId: "guarded-progress",
arguments: {
body: "Must remain authorized",
idempotencyKey: "guarded-progress",
},
};
await db
.update(issues)
.set({ assigneeAgentId: null })
.where(eq(issues.id, guardedIssueId));
await expect(authority.execute(mutation)).rejects.toThrow(
"paperclip_runner_tool_binding_not_authorized",
);
await db
.update(issues)
.set({
assigneeAgentId: agentId,
executionRunId: guardedReplacementRunId,
})
.where(eq(issues.id, guardedIssueId));
await expect(
authority.execute({ ...mutation, callId: "replaced-run" }),
).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
await db
.update(issues)
.set({ executionRunId: guardedRunId })
.where(eq(issues.id, guardedIssueId));
await db
.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, guardedRunId));
await expect(
authority.execute({ ...mutation, callId: "terminal-run" }),
).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
expect(
await db
.select()
.from(issueComments)
.where(eq(issueComments.issueId, guardedIssueId)),
).toHaveLength(0);
});
it("captures delegation and approval origins before steering and preserves replay identity", async () => {
const issueId = "00000000-0000-4000-8000-000000000120";
const runId = "00000000-0000-4000-8000-000000000121";
await db.insert(issues).values({ id: issueId, companyId, title: "Identity delegation",
status: "in_progress", assigneeAgentId: agentId });
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId,
status: "running", runtimeMode: "native", nativeIssueId: issueId,
invocationSource: "assignment", triggerDetail: "system", contextSnapshot: { issueId } });
await db.update(issues).set({ executionRunId: runId }).where(eq(issues.id, issueId));
await db.insert(authUsers).values(["person-a", "person-b"].map(id => ({ id, name: id, email: `${id}@example.test`, createdAt: new Date(), updatedAt: new Date() })));
await db.insert(companyMemberships).values(["person-a", "person-b"].map(principalId => ({ companyId, principalType: "user", principalId, status: "active", membershipRole: "operator" })));
const origin = await initializeRunIdentity(db, {
companyId, runId, issueId, responsibleUserId: "person-a", cause: "instruction",
});
const [message] = await db.insert(issueComments).values({
companyId, issueId, body: "New instruction", authorUserId: "person-b",
}).returning();
const authority = new PaperclipRunnerToolAuthority(db, { companyId, agentId, issueId, runId });
const call = { tool: "create_task", callId: "identity-child", arguments: {
idempotencyKey: "identity-child", title: "Keep the initiating identity",
responsibleUserId: "forged-user", originIdentityContextId: "forged-context",
} };
const first = await authority.execute(call) as { task: { id: string } };
const pending = await reserveSteeredIdentity(db, { companyId, runId, issueId, messageId: message.id });
await reconcileSteeredIdentity(db, pending!);
await expect(authority.execute({ ...call, callId: "identity-child-replay" })).resolves.toEqual(first);
const [child] = await db.select().from(issues).where(eq(issues.id, first.task.id));
expect(child).toMatchObject({ originRunId: runId, originIdentityContextId: origin.id,
continuationIdentityContextId: origin.id });
const second = await authority.execute({ ...call, callId: "identity-child-b", arguments: {
idempotencyKey: "identity-child-b", title: "Use the next instruction identity",
} }) as { task: { id: string } };
const [nextChild] = await db.select().from(issues).where(eq(issues.id, second.task.id));
expect(nextChild.originIdentityContextId).toBe(pending!.id);
await authority.execute({ tool: "request_human_input", callId: "identity-approval", arguments: {
idempotencyKey: "identity-approval", interactionKind: "confirmation", title: "Approve continuation",
prompt: "Continue?", continuationPolicy: "wake_assignee", payload: {},
} });
const interactions = await db.select().from(issueThreadInteractions).where(eq(issueThreadInteractions.issueId, issueId));
expect(interactions.find((row) => row.title === "Approve continuation")?.sourceIdentityContextId).toBe(pending!.id);
});
it("fails closed once the run is no longer active", async () => {
await db
.update(heartbeatRuns)
.set({ status: "succeeded" })
.where(eq(heartbeatRuns.id, runId));
const authority = new PaperclipRunnerToolAuthority(db, {
companyId,
agentId,
issueId,
runId,
});
await expect(
authority.execute({
tool: "get_task_context",
callId: "late",
arguments: {},
}),
).rejects.toThrow("paperclip_runner_tool_binding_not_authorized");
});
});