Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/runtime-hiring.ts
T
f4337bb5fb test(evals): land the chat catalog eval harness on master (#19614)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat-feature evals measure whether agents complete real chat
requests through the product
> - The chat catalog eval harness and its repairs live on the
`chat-eval/master-candidate` branch, not on master
> - Today's work made 139 of 242 chat evals pass in verified single-case
live runs. Each product fix landed on master as its own pull request
> - The eval-side changes (setups, graders, fault seams, evidence
capture) still exist only on the candidate
> - This pull request lands the harness on master. Master stays the
source of truth for product behavior
> - The benefit is one tree: evals run against master commits, and
product fixes reach the evals as soon as they merge

## Linked Issues or Issue Description

Refs #19441, Refs #19599, Refs #20270, Refs #20334, Refs #20342, Refs
#20344, Refs #20354, Refs #20360, Refs #20373, Refs #20382, Refs #20409

**What existing behavior does this improve?**
The chat catalog eval harness and the product it evaluates live on a
long-running branch outside master. Eval fixes do not reach master, so
master-based eval runs use old setups and graders.

**Subsystem affected**
`tests/runner-e2e` chat catalog harness, plus a small set of product
changes that exist only on the candidate.

**Proposed change**
Land the harness on master. Every product fix from this eval work
already merged to master as its own pull request. Conflicts keep
master's product behavior.

## What Changed

- Most of the diff (808 of 851 files) is under `tests/runner-e2e/`:
chat-catalog domains, scenarios, descriptors, the TestOps manifest,
private evidence tooling, and their tests.
- Graders now check saved state, setup literals and rendered or clicked
links. Many keyword and regex checks on free-form replies are removed.
Each changed grader has a bumped `oracleVersion` and calibration tests
(a valid reply, a reworded valid reply, and broken variants that must
fail).
- The shared link helper `hasLink` no longer treats a list link (for
example `/COM/issues?view=mine`) as a link to every task without a URL
key.
- Setup fixes build real state through supported product routes: routine
history, agent grants through the board grant route, budget holds with a
real cap, and a storage-layer archive fault for
`inbox-search.archive-partial-failure`.
- Browser boundary journeys (sign-in, chat-disabled, onboarding) now
write the standard pass evidence files.
- Retargeted cases, approved by the maintainer:
`agent-chat.chat-disabled` (Conference Room gate),
`agents.restore-instructions` (no saved instruction history),
`access.manage-membership` (member permission edits stay board-only).
- The private evidence trusted files (`manual-private-handoff.ts`,
`manual-private-retention.ts`, `manual-private-report-assets.ts`) are
byte-identical to master.
- Product files outside `tests/` (43 files, +1,328 −49) carry
candidate-only changes that master does not yet have. Most are tests.
The main code changes are in `request-human-input.ts`,
`heartbeat-run-summary.ts`, `native-completion-feedback.ts`,
`native-run-finalizer.ts`, `openapi.ts`, `secrets.ts` and
`IssueChatLongThreadPerf.tsx`.

## Verification

- `pnpm vitest run chat-catalog-domains chat-catalog-contract.test.ts
chat-catalog-consistency.test.ts unit-launcher.test.mjs
--testTimeout=180000` in `tests/runner-e2e`: 269 files pass, 3,550 tests
pass.
- `node --test chat-full-catalog-testops-manifest.test.mjs`: 10 pass.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`:
no change.
- `tsc` for `server` and `tests/runner-e2e`: clean.
- Live single-case verification: 139 of 242 cases passed on paid runs,
and a person read the saved evidence for each. These are single-case
runs, not one full-cohort run.

## Risks

- Large diff. Most of it is test-only, but the 43 non-test files change
product code paths. Review those files first.
- Some graders are now less strict on reply wording. A person must read
replies for meaning on those cases.
- 42 cases need disposable outside accounts (Notion, Slack, GitHub,
Daytona and others) and stay blocked. `access.invite-teammate` stays
failing until local agent isolation lands, because the runner's durable
state keeps a live invite token.
- The paid workflow compares the trusted private-evidence files with
master. They are unchanged, so this risk is low.

## Model Used

Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code
execution, in Claude Code. Subagents used the same model.

## 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
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-10 08:02:11 -06:00

124 lines
12 KiB
TypeScript

import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely } from "../chat-catalog-contract.js";
import { expect } from "@playwright/test";
import { pollUntil } from "../api.js";
import { sendChatMessage } from "../chat-flow.js";
import { checks, type Entity } from "./internal-support.js";
import { runtimeDefinition, runtimeObservation, observeRuntime, unchangedAgent, type RuntimeAgent, type RuntimeObservation } from "./runtime-support.js";
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
interface HireApproval { id: string; companyId: string; type: string; status: string; requestedByAgentId: string | null;
decidedByUserId: string | null; payload: { agentId?: string; name?: string; role?: string; title?: string; reportsTo?: string; adapterType?: string; adapterConfig?: unknown } }
async function pendingHire(ctx: ChatCatalogContext, name: string) {
return pollUntil({ label: `Actual governed ${name} proposal`, deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 180_000),
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns(),
approvals: await ctx.input.api.get<HireApproval[]>(`/api/companies/${ctx.input.fixtures.company.id}/approvals`),
agents: await ctx.input.api.get<RuntimeAgent[]>(`/api/companies/${ctx.input.fixtures.company.id}/agents`) }; },
accept: value => chatCatalogNativePhaseIsTimely(ctx) && value.source?.conversationState === "waiting" && value.approvals.filter(row => row.type === "hire_agent" && row.status === "pending" && row.payload.name === name).length === 1
&& value.agents.some(row => row.name === name && row.status === "pending_approval")
&& value.runs.every(run => run.agentId === ctx.input.fixtures.agent.id && run.status === "succeeded"),
reject: value => value.runs.length > 4 || value.runs.some(run => run.agentId !== ctx.input.fixtures.agent.id || ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Governed hire admitted unexpected work or failed" : undefined });
}
/**
* The reply reports the pending approval by giving the person the exact
* approval to open and decide. Its wording is not graded; whether the hire ran
* early is graded from saved state and runs.
*/
export function repliesLinkApproval(o: RuntimeObservation, commentIds: unknown, approvalId: string | undefined) {
const ids = Array.isArray(commentIds) ? commentIds.map(String) : [];
return !!approvalId && ids.length > 0 && (o.renderedLinkEvidence ?? []).some(link => {
if (link.source !== "reply" || !link.commentId || !ids.includes(link.commentId)) return false;
try {
const url = new URL(link.href, o.origin); const parts = url.pathname.split("/").map(decodeURIComponent);
return url.origin === new URL(o.origin).origin && parts.length === 4 && !!parts[1] && parts[1] !== "api" && parts[2] === "approvals" && parts[3] === approvalId;
} catch { return false; }
});
}
export function gradeGovernedHire(value: unknown) {
const c = checks(); const o = runtimeObservation(value);
c.add("independent-governed-hire-evidence", !!o, "Actual pending proposals, human decisions, preserved intended identity and no premature worker execution are required."); if (!o) return c.result();
const rejected = o.state.firstProposal as HireApproval | undefined; const accepted = o.state.secondProposal as HireApproval | undefined;
const approvals = o.state.approvalsAfter as HireApproval[] | undefined;
const first = approvals?.find(row => row.id === rejected?.id); const second = approvals?.find(row => row.id === accepted?.id);
c.add("one-proposal-per-explicit-request", !!rejected && !!accepted && rejected.id !== accepted.id && approvals?.length === 2
&& rejected.companyId === o.companyId && accepted.companyId === o.companyId
&& [rejected, accepted].every(row => row.type === "hire_agent" && row.status === "pending" && row.requestedByAgentId === o.leadId
&& row.payload.role === "qa" && !!row.payload.adapterType && row.payload.adapterConfig != null)
&& rejected.payload.name === "Morgan" && accepted.payload.name === "Jules" && o.state.secondRequestAttributed === true,
"The canonical Morgan proposal and separately changed human Jules request each produce one inspectable QA proposal with real configuration.");
c.add("rejected-hire-stays-inactive", first?.status === "rejected" && !!first.decidedByUserId && o.state.rejectedBeforeChangedRequest === true
&& !o.agents.some(row => row.id === rejected?.payload.agentId && row.lifecycleState === "ready")
&& o.state.noRepeatedProposalBeforeChangedRequest === true,
"The genuine human rejection leaves no working Morgan or repeated proposal before the person explicitly changes their request.");
const before = o.state.acceptedBefore as RuntimeAgent | undefined; const current = o.agents.find(row => row.id === accepted?.payload.agentId);
c.add("accepted-same-intended-hire", second?.status === "approved" && !!second.decidedByUserId && !!before && !!current
&& current.name === "Jules" && current.companyId === o.companyId && current.lifecycleState === "ready"
&& ["active", "idle"].includes(current.status ?? "") && unchangedAgent(before, current),
"Human acceptance activates the exact proposed Jules identity and admitted configuration, rather than a replacement employee.");
c.add("no-worker-before-or-after-decision", o.state.noWorkerBeforeFirstDecision === true && o.state.noWorkerBeforeSecondDecision === true
&& o.runs.length >= 2 && o.runs.length <= 4 && o.runs.every(run => run.agentId === o.leadId && run.status === "succeeded") && o.tasks.length === 0,
"Neither proposed employee executes before approval, and no unrequested task or employee work is created by either decision.");
const extra = o.runs.filter(run => !(o.state.requestRunIds as string[]).includes(run.id));
c.add("bounded-authoritative-decision-notifications", extra.every(run => ["approval.approved", "approval.rejected"].includes(String(run.contextSnapshot?.source))
&& [rejected?.id, accepted?.id].includes(String(run.contextSnapshot?.approvalId))),
"Any extra provider turn is independently tied to one of these exact real human approval decisions.");
c.add("reply-links-each-pending-approval", repliesLinkApproval(o, o.state.firstReplyCommentIds, rejected?.id)
&& repliesLinkApproval(o, o.state.secondReplyCommentIds, accepted?.id),
"Each request's own reply links the exact pending approval the person must decide.");
return c.result();
}
export const runtimeHiringCases = [runtimeDefinition("agents.hire-needs-approval", async ctx => {
await ctx.input.api.patch(`/api/companies/${ctx.input.fixtures.company.id}`, { requireBoardApprovalForNewAgents: true });
const company = await ctx.input.api.get<{ requireBoardApprovalForNewAgents: boolean }>(`/api/companies/${ctx.input.fixtures.company.id}`);
if (!company.requireBoardApprovalForNewAgents) throw new Error("Actual company hire approval policy did not persist");
return { companyRequiresApproval: true };
}, gradeGovernedHire, {
sourceFiles: ["chat-catalog-domains/runtime-hiring.ts", "chat-catalog-domains/runtime-support.ts", "chat-scenarios/agents.yaml"],
oracleVersion: "paperclip.chat-catalog.runtime-hiring.v3",
expectedHumanMessageCount: 2, expectedRunCount: 4, minimumRunCount: 2, attemptTimeoutMs: 720_000,
async act(ctx, state) {
const root = `/api/companies/${ctx.input.fixtures.company.id}`; const source = ctx.input.page.url();
const initial = await pendingHire(ctx, "Morgan"); const first = initial.approvals.find(row => row.payload.name === "Morgan" && row.status === "pending")!;
state.firstProposal = first; state.noWorkerBeforeFirstDecision = initial.runs.every(run => run.agentId === ctx.input.fixtures.agent.id);
state.firstReply = (await observeRuntime(ctx, state)).reply;
const firstRequestRuns = initial.runs.filter(run => run.contextSnapshot?.source !== "approval.approved" && run.contextSnapshot?.source !== "approval.rejected").map(run => run.id);
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/approvals/${first.id}`, { waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByText("Morgan", { exact: true }).first()).toBeVisible();
await ctx.input.page.getByRole("button", { name: "Reject", exact: true }).click();
const rejected = await pollUntil({ label: "Rejected Morgan stays inactive without a repeated proposal", deadlineAt: Date.now() + 60_000,
load: async () => ({ approvals: await ctx.input.api.get<HireApproval[]>(`${root}/approvals`), agent: await ctx.input.api.get<RuntimeAgent>(`/api/agents/${first.payload.agentId}`) }),
accept: value => value.approvals.find(row => row.id === first.id)?.status === "rejected" && value.agent.lifecycleState === "rejected" });
state.rejectedBeforeChangedRequest = true; state.noRepeatedProposalBeforeChangedRequest = rejected.approvals.length === 1;
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
const prior = (await ctx.allRuns()).map(run => run.id);
const changed = "I rejected Morgan. I am changing the request: propose a separate QA engineer named Jules using our currently admitted coding account and runtime. Do not create a task or start employee work. Keep the required board approval pending so I can inspect and accept that one intended hire.";
await sendChatMessage(ctx.input.page, changed);
const secondPhase = await pendingHire(ctx, "Jules"); const second = secondPhase.approvals.find(row => row.payload.name === "Jules" && row.status === "pending")!;
state.secondProposal = second; state.noWorkerBeforeSecondDecision = secondPhase.runs.every(run => run.agentId === ctx.input.fixtures.agent.id);
const comments = await ctx.input.api.get<Entity[]>(`/api/issues/${ctx.issue()!.id}/comments?order=asc`);
const human = comments.filter(row => row.body === changed && !row.authorAgentId);
const next = secondPhase.runs.filter(run => !prior.includes(run.id) && !["approval.approved", "approval.rejected"].includes(String(run.contextSnapshot?.source)));
const profiles = await Promise.all(next.map(run => ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${run.id}`)));
state.secondRequestAttributed = human.length === 1 && next.length === 1 && profiles.some(run => run.runnerProfileJson?.nativeExecutionInput?.task?.prompt?.includes(human[0]!.id));
state.requestRunIds = [...firstRequestRuns, ...next.map(run => run.id)];
const leadReplies = (runIds: string[]) => comments.filter(row => runIds.includes(String(row.createdByRunId)) && row.authorAgentId === ctx.input.fixtures.agent.id);
state.firstReplyCommentIds = leadReplies(firstRequestRuns).map(row => row.id);
state.secondReplyCommentIds = leadReplies(next.map(run => run.id)).map(row => row.id);
state.secondReply = leadReplies(next.map(run => run.id)).map(row => row.body ?? "").join("\n");
state.acceptedBefore = secondPhase.agents.find(row => row.id === second.payload.agentId);
state.worker = state.acceptedBefore;
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/approvals/${second.id}`, { waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByText("Jules", { exact: true }).first()).toBeVisible();
await ctx.input.page.getByRole("button", { name: "Approve", exact: true }).click();
await pollUntil({ label: "Accepted exact QA hire becomes genuinely admitted", deadlineAt: Date.now() + 90_000,
load: () => ctx.input.api.get<RuntimeAgent>(`/api/agents/${second.payload.agentId}`),
accept: row => row.lifecycleState === "ready" && ["idle", "active"].includes(row.status ?? ""),
reject: row => row.lifecycleState === "error" ? "Approved runtime did not qualify; no fake ready state is permitted" : undefined });
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByText("approved", { exact: true }).first()).toBeVisible();
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
},
async observe(ctx, state) {
state.approvalsAfter = await ctx.input.api.get<HireApproval[]>(`/api/companies/${ctx.input.fixtures.company.id}/approvals`);
return observeRuntime(ctx, state);
},
})];