Files
PaperClipAI/server/src/services/native-runtime/native-pull-request-completion.test.ts
T
Devin FoleyandPaperclip 24132dac16 fix(tasks): verify PR merges with the managed run identity (#22357)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Native task completion independently verifies that declared PR
deliverables are merged.
> - Runs can already use an authorized managed GitHub connection to
merge private PRs.
> - Completion used the background credential resolver, which cannot
select that run's managed identity.
> - This pull request reuses operation-time identity and grant checks
for completion verification.
> - Agents can finish delivered work while unavailable grants and
unverified merges remain blocked.

## Linked Issues or Issue Description

Related: #22244 introduced the native PR merge gate. No duplicate fix
was found in the open PR search. The roadmap's personal GitHub identity
capability already covers the intended identity model.

**What happened?**

A native agent with a managed GitHub connection merges a private PR,
then completion rejects it as not verified merged. The independent
server-side check only tries legacy company token names or an instance
token; it does not use the agent run's managed connection.

**Expected behavior**

Verify the merge with the run's current accepted GitHub identity,
retaining current grant, membership, trust and company boundaries.
GitHub must confirm the merge regardless of saved work-product metadata.

**Steps to reproduce**

1. Configure a managed GitHub identity with access to a private
repository and no legacy company GitHub token.
2. Use a native task run to merge and register a PR deliverable.
3. Finish the task. Before this change, the merge verifier cannot
authenticate with the managed identity and rejects completion.

## What Changed

- Bind completion credential lookup to the persisted company, native
task and run.
- Add a server-side completion credential path that shares managed
grant, membership and trust checks with command credentials. Both active
and succeeded runs capture identity under the existing task/run locks
and reconcile pending steering acknowledgements before credential
lookup. The command credential API still requires a running run.
- Resolve credentials once for all PRs in a verification attempt; do no
credential work for tasks without PR deliverables.
- Preserve legacy fallback only for runs without a managed identity, and
preserve the public-only restriction on server-environment credentials.
- Add 23 PostgreSQL-backed authorization regression cases and document
completion's identity behavior.

## Verification

- Local checks cover revision
`da2a3608b0375ead646bbbad35af853191488f07`. [Greptile
review](https://github.com/paperclipai/paperclip/pull/22357#issuecomment-7023243798)
is 5/5 on that revision with both prior threads resolved. [Required
CI](https://github.com/paperclipai/paperclip/actions/runs/44625662403)
passed on attempt 2 for the same revision, including typecheck, build,
canary, server/runner suites and all eight e2e shards.
- Red/green: the private-PR and identity-selection cases failed before
the initial fix. Review exposed a succeeded-run reassessment failure and
then an unsettled-steering gap in that path; each has a regression that
failed on the reviewed commit and passes after its correction.
Unresolved steering performs no token lookup, and durable
acknowledgement selects the new person. The full worker test completes
the task after automatic-review withdrawal while command credentials
remain unavailable to the finished run.
- `pnpm exec vitest run
server/src/services/native-runtime/native-pull-request-completion.test.ts
server/src/services/native-runtime/native-completion-feedback.test.ts
server/src/__tests__/github-operation-credentials.test.ts
server/src/__tests__/native-status-reassessment-work.test.ts
server/src/__tests__/run-identity.test.ts
server/src/__tests__/run-identity-projections.test.ts` — 222 tests pass
across six files, on macOS arm64 with Node 25.6.1 and embedded
PostgreSQL.
- `pnpm --filter @paperclipai/server typecheck` — passes.
- `pnpm verify --explain` — exits 2 because the subsystem documentation
selects broad CI coverage. Required CI supplies the broader test/build
coverage; this exit is not a full-suite pass.
- The credential selection, steering, grant and company checks use real
PostgreSQL state. Only the secret vault and GitHub HTTP transport are
mocked; test requests never reach GitHub.
- `git diff --check` and the staged secret/PII scan pass. No runtime
artifacts are committed.
- Earlier CI revision `4e42f64`: the [Build
job](https://github.com/paperclipai/paperclip/actions/runs/44624163145/job/135914203042)
ended after the runner received a shutdown signal and the workflow was
cancelled. Its log does not show a compiler error before interruption;
this interrupted attempt is not build verification. The current revision
subsequently passed its own CI build on attempt 2.
- Current revision canary: the [Canary Dry Run
job](https://github.com/paperclipai/paperclip/actions/runs/44625662403/job/135919504493)
was interrupted by runner shutdown before completion. The repository
runner-loss classifier returns `lost: true` for its actual annotation
and log. A targeted retry was refused while the workflow remained
active. The same revision subsequently passed Canary Dry Run and the
full workflow on attempt 2; the earlier interrupted attempt remains
recorded here separately.
- Live acceptance remains pending deployment; the change has not been
deployed.

## Risks

Completion now reads managed credentials through a server-side path
shared with the existing authorization checks. Successful finished runs
can be reassessed without granting them command execution credentials.
Denied or unavailable identities must remain blocked without falling
through to a different identity; regression tests cover revocation and
company/task isolation. Credential lookup is shared within one bounded
PR verification attempt, not cached across attempts. The existing HTTP
deadline and merge proof requirements remain in place. No migrations or
API contract changes.

## Model Used

OpenAI Codex, `gpt-6.1-sol`, xhigh reasoning, with repository
inspection, code editing and test execution. Context-window size is not
exposed by the harness.

## 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

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-19 14:44:03 -08:00

243 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import { connectionGrants, createDb, heartbeatRuns, heartbeatRunEvents, issueComments, issues, issueWorkProducts, runIdentityContexts } from "@paperclipai/db";
import { LOW_TRUST_REVIEW_PRESET } from "@paperclipai/shared";
import { githubCredentialsFixture } from "../../__tests__/helpers/github-credentials-fixture.js";
import { startRecoveryPostgres } from "../../__tests__/helpers/recovery-postgres.js";
import * as githubFetch from "../github-fetch.js";
import * as gitCredentials from "../git-credentials.js";
import { resolveGitHubOperationCredentials } from "../github-operation-credentials.js";
import { reserveSteeredIdentity } from "../run-identity.js";
import { validateNativeDeliverableEvidence } from "./native-deliverable-feedback.js";
import { verifyNativePullRequestCompletion } from "./native-pull-request-completion.js";
const vault = vi.hoisted(() => ({
getByName: vi.fn(async () => null),
resolveUserSecretValue: vi.fn(async (_company: string, input: { responsibleUserId: string }) => ({
value: `test-token-${input.responsibleUserId}`,
})),
resolveSecretValue: vi.fn(async () => "test-dedicated-token"),
}));
vi.mock("../secrets.js", () => ({ secretService: () => vault }));
const report = { artifacts: [{ kind: "pull_request", ref: "https://github.com/example/private-repo/pull/42" }] };
describe("native PR completion GitHub authorization", () => {
let temporary: Awaited<ReturnType<typeof startRecoveryPostgres>>;
let db: ReturnType<typeof createDb>;
const fixture = githubCredentialsFixture(() => db);
beforeAll(async () => {
temporary = await startRecoveryPostgres("native-pr-credentials-");
db = createDb(temporary.connectionString);
});
afterAll(async () => { await db?.$client.end(); await temporary?.cleanup(); });
beforeEach(() => { vi.restoreAllMocks(); vi.clearAllMocks(); });
async function seed() {
const binding = await fixture.seed();
await db.update(heartbeatRuns).set({ nativeIssueId: binding.issueId, runtimeMode: "native" })
.where(eq(heartbeatRuns.id, binding.runId));
await db.update(issues).set({ status: "in_progress", assigneeAgentId: binding.agentId })
.where(eq(issues.id, binding.issueId));
return binding;
}
it("verifies private merged PRs with the run's managed identity, resolving credentials once", async () => {
const binding = await seed();
await fixture.grant(binding, "A");
await db.insert(issueWorkProducts).values({ companyId: binding.companyId, issueId: binding.issueId,
type: "pull_request", provider: "github", title: "Another delivery", status: "merged",
url: "https://github.com/example/private-repo/pull/43" });
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async (_url, init) =>
new Headers(init?.headers).get("authorization") === "Bearer test-token-A"
? Response.json({ state: "closed", merged: true })
: new Response(null, { status: 404 }));
expect(await verifyNativePullRequestCompletion(db, binding, report))
.toEqual(new Set(["example/private-repo#42", "example/private-repo#43"]));
expect(fetcher).toHaveBeenCalledTimes(2);
expect(vault.resolveUserSecretValue).toHaveBeenCalledTimes(1);
expect(vault.getByName).not.toHaveBeenCalled();
});
it("uses the current accepted run identity and fails closed after its grant is revoked", async () => {
const binding = await seed();
await fixture.grant(binding, "A");
const other = await fixture.grant(binding, "B");
const fallback = vi.spyOn(gitCredentials, "resolveGitHubApiCredential")
.mockResolvedValue({ token: "test-ambient-token", source: "server_env", secretName: null });
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json({ merged: true }));
await verifyNativePullRequestCompletion(db, binding, report);
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get("authorization")).toBe("Bearer test-token-A");
await fixture.switchTo(binding, "B");
await verifyNativePullRequestCompletion(db, binding, report);
expect(new Headers(fetcher.mock.calls[1]![1]?.headers).get("authorization")).toBe("Bearer test-token-B");
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, other.id));
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).toHaveBeenCalledTimes(2);
expect(fallback).not.toHaveBeenCalled();
expect((await db.select().from(issues).where(eq(issues.id, binding.issueId)))[0]!.status).toBe("in_progress");
});
it("reassesses merged PR evidence from a succeeded run without permitting command credentials", async () => {
const binding = await seed();
const grant = await fixture.grant(binding, "A");
await db.update(heartbeatRuns).set({ status: "succeeded", finishedAt: new Date() })
.where(eq(heartbeatRuns.id, binding.runId));
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async (_url, init) =>
new Headers(init?.headers).get("authorization") === "Bearer test-token-A"
? Response.json({ state: "closed", merged: true }) : new Response(null, { status: 404 }));
const reassessment = { ...binding, objective: "Merge the implementation PR.", semanticToolReceipts: {}, authoritativeDone: true as const };
await expect(validateNativeDeliverableEvidence(db, reassessment, report)).resolves.toBeUndefined();
await expect(resolveGitHubOperationCredentials(db, binding)).rejects.toThrow("active run");
expect(fetcher).toHaveBeenCalledTimes(1);
await db.update(connectionGrants).set({ status: "revoked" }).where(eq(connectionGrants.id, grant.id));
await expect(validateNativeDeliverableEvidence(db, reassessment, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).toHaveBeenCalledTimes(1);
});
it.each([false, true])("reconciles pending steering before succeeded-run verification (acknowledged=%s)", async acknowledged => {
const binding = await seed();
await fixture.grant(binding, "A");
await fixture.grant(binding, "B");
const messageId = randomUUID();
await db.insert(issueComments).values({ id: messageId, companyId: binding.companyId, issueId: binding.issueId,
authorUserId: "B", body: "Next instruction" });
const pending = await reserveSteeredIdentity(db, { ...binding, messageId });
expect(pending?.status).toBe("pending");
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, binding.runId));
if (acknowledged) await db.insert(heartbeatRunEvents).values({ companyId: binding.companyId, runId: binding.runId,
agentId: binding.agentId, seq: 1, eventType: "item.completed", sourceEventId: randomUUID(),
payload: { prpEvent: { turnId: "turn-1", itemId: `turn-1:steer:${messageId}`, payload: { kind: "steering_acknowledgement" } } },
});
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json({ merged: true }));
if (acknowledged) {
expect(await verifyNativePullRequestCompletion(db, binding, report)).toEqual(new Set(["example/private-repo#42"]));
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get("authorization")).toBe("Bearer test-token-B");
} else {
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
expect(vault.getByName).not.toHaveBeenCalled();
}
expect((await db.select().from(runIdentityContexts).where(eq(runIdentityContexts.id, pending!.id)))[0]!.status)
.toBe(acknowledged ? "accepted" : "pending");
});
it.each(["failed", "cancelled"])("does not acquire a managed completion credential for a %s run", async status => {
const binding = await seed();
await fixture.grant(binding, "A");
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, binding.runId));
const fetcher = vi.spyOn(githubFetch, "ghFetch");
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
expect(vault.getByName).not.toHaveBeenCalled();
});
it("rejects an unaccepted identity during succeeded-run reassessment", async () => {
const binding = await seed();
await fixture.grant(binding, "A");
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, binding.runId));
await db.update(runIdentityContexts).set({ status: "rejected" }).where(eq(runIdentityContexts.runId, binding.runId));
const fetcher = vi.spyOn(githubFetch, "ghFetch");
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("rechecks trust restrictions before acquiring a succeeded run's credential", async () => {
const binding = await seed();
await fixture.grant(binding, "A");
await db.update(heartbeatRuns).set({ status: "succeeded", contextSnapshot: { issueId: binding.issueId,
executionPolicy: { authorizationPolicy: { trustPreset: LOW_TRUST_REVIEW_PRESET,
trustBoundary: { mode: LOW_TRUST_REVIEW_PRESET, companyId: binding.companyId, rootIssueId: binding.issueId,
issueIds: [binding.issueId], allowedAgentIds: [binding.agentId], allowedToolClasses: ["git.read", "github.pr.read"] } } },
} }).where(eq(heartbeatRuns.id, binding.runId));
const fetcher = vi.spyOn(githubFetch, "ghFetch");
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
expect(vault.getByName).not.toHaveBeenCalled();
});
it.each([
{ state: "open", merged: false },
{ state: "open", draft: true, merged: false },
{ state: "closed", merged: false },
])("still rejects a PR whose current GitHub state is %j", async fields => {
const binding = await seed();
await fixture.grant(binding, "A");
vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json(fields));
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
});
it.each([401, 403, 404, 500])("does not accept inaccessible merge evidence after GitHub HTTP %s", async status => {
const binding = await seed();
await fixture.grant(binding, "A");
vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => new Response(null, { status }));
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
});
it("does not borrow a managed credential from another company", async () => {
const binding = await seed(), other = await seed();
await fixture.grant(other, "A");
vi.spyOn(gitCredentials, "resolveGitHubApiCredential").mockResolvedValue(null);
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => new Response(null, { status: 404 }));
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
for (const [, init] of fetcher.mock.calls) expect(new Headers(init?.headers).has("authorization")).toBe(false);
});
it("preserves legacy credentials when no managed identity is configured", async () => {
const binding = await seed();
const fallback = vi.spyOn(gitCredentials, "resolveGitHubApiCredential")
.mockResolvedValue({ token: "test-company-token", source: "company_secret", secretName: "GH_TOKEN" });
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json({ merged: true }));
expect(await verifyNativePullRequestCompletion(db, binding, report)).toEqual(new Set(["example/private-repo#42"]));
expect(fallback).toHaveBeenCalledTimes(1);
expect(new Headers(fetcher.mock.calls[0]![1]?.headers).get("authorization")).toBe("Bearer test-company-token");
});
it("keeps the server-environment credential boundary for private repositories", async () => {
const binding = await seed();
vi.spyOn(gitCredentials, "resolveGitHubApiCredential")
.mockResolvedValue({ token: "test-instance-token", source: "server_env", secretName: null });
const fetcher = vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json({ private: true }));
await expect(verifyNativePullRequestCompletion(db, binding, report)).rejects.toThrow("not been verified as merged");
expect(fetcher).toHaveBeenCalledTimes(1);
expect(fetcher.mock.calls[0]![0]).toBe("https://api.github.com/repos/example/private-repo");
});
it("preserves the fallback for runs that predate managed identity contexts", async () => {
const binding = await seed();
await db.update(heartbeatRuns).set({ activeIdentityContextId: null }).where(eq(heartbeatRuns.id, binding.runId));
vi.spyOn(gitCredentials, "resolveGitHubApiCredential")
.mockResolvedValue({ token: "test-company-token", source: "company_secret", secretName: "GH_TOKEN" });
vi.spyOn(githubFetch, "ghFetch").mockImplementation(async () => Response.json({ merged: true }));
expect(await verifyNativePullRequestCompletion(db, binding, report)).toEqual(new Set(["example/private-repo#42"]));
});
it("does not acquire credentials for a run outside the bound company or task", async () => {
const binding = await seed(), other = await seed();
await fixture.grant(binding, "A");
const fetcher = vi.spyOn(githubFetch, "ghFetch");
for (const invalid of [{ ...binding, companyId: other.companyId }, { ...binding, issueId: other.issueId }]) {
await expect(verifyNativePullRequestCompletion(db, invalid, report)).rejects.toThrow("source is unavailable");
}
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
});
it("does not acquire credentials when the task has no PR deliverables", async () => {
const binding = await seed();
const fetcher = vi.spyOn(githubFetch, "ghFetch");
expect(await verifyNativePullRequestCompletion(db, binding, {})).toEqual(new Set());
expect(fetcher).not.toHaveBeenCalled();
expect(vault.resolveUserSecretValue).not.toHaveBeenCalled();
expect(vault.getByName).not.toHaveBeenCalled();
});
});