Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/external-provider-choice.ts
DottaandClaude Opus 5.5 98c18784c6 fix(evals): grade full cohort 4 chat cases on saved state and rendered links (#21034)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog runs real agents through chat journeys and
grades the saved results
> - Full cohort 4 (OpenCode with DeepSeek v4.1 flash, master f1aef0cb58)
failed 14 cases for eval reasons, not product reasons
> - Some phase captures read links before the reply rendered. Some
graders matched keywords in free-form replies. One locator was stale.
One fixture answer looked like a placeholder. Some checks could not say
what failed
> - This pull request grades those cases on saved state, setup literals
and rendered links, and it fixes the observers and fixtures
> - The benefit is that these cases fail only when the product fails,
and a failure names the part that broke

## Linked Issues or Issue Description

**What happened?**
In full chat cohort 4, valid agent behavior failed these cases:
case-history, goals.explain-purpose and workspaces.preview-service
(phase captures read before the reply rendered); routines.pause-owned
("If you want that one stopped too, use Pause on its task page" matched
a cancellation regex); budgets-costs.spend-breakdown ("unknown, not
$0.00" matched a stated-zero regex); steering.edit-queued-message
("change ... and drag it above" missed a keyword list);
connection-setup.choose-provider (the resumed page says "Finish with
Notion"); questions-and-approvals.necessary-question (the answer "Acorn
2a4f72ec4ae2-1" was saved as "Acorn"). Some checks could not say what
failed: onboarding.new-company compared the whole members response as
JSON and saved no after-state; agents.choose-primary threw one combined
error.

**Expected behavior**
Each case grades the feature contract on saved state, setup literals and
rendered or clicked links. A valid reworded reply passes. A broken
product still fails. A failure names the clause and its values.

**Steps to reproduce**
Grade the retained cohort 4 evidence for the cases above with the
earlier oracles.

Refs #21009, #21002, #21007

## What Changed

- Phase captures (case-history first phase, goals.explain-purpose
phases, preview-service query phase, ambiguous-task clarification,
edit-queued-message guidance) now wait for the saved reply to render
(`waitForTurnReplyLinks`) before they observe. When a saved reply yields
no rendered links, the observation records thread and anchor diagnostics
(`linkDiagnostics`) and logs them.
- routines.pause-owned: remove the reply keyword clause. Saved state at
the reply proves the run kept running, and the final state proves it
completed normally.
- budgets-costs.spend-breakdown: the unresolved record is graded
structurally. The reply must identify it (rendered link, identifier or
run id), and a chat run must have read its saved accounting (cost
summary, run record or unranged company report, bound by input digest).
"$0.00" in the reply is not matched.
- steering.edit-queued-message: grade the rendered task link in the
reply, the refused agent edit and reorder (403), and the unchanged queue
at the reply. Keyword lists are removed.
- connection-setup.choose-provider: the sign-in locator also accepts
"Finish with Notion" (the resumed-draft label). The button has no test
id or other stable name.
- questions-and-approvals.necessary-question: the answer is now
"Quillmere". The case also accepts the exact answer in a saved
deliverable (a document revision or text attachment on the linked task,
saved by an agent of the company after the answer). The yaml expected
outcome records this decision, with a `changedFields` entry in the
testops manifest.
- onboarding.new-company: save the members after-state and compare
identity, role, status and grants, and name what changed. Guidance is
graded on a rendered link to `/onboarding` (the new-organization
wizard), the business literal from the query, and the saved company
count. The source company and person get realistic names for this case
and are restored at cleanup, because the CEO reasoned from the generated
names that the request was a graded test.
- agents.choose-primary: the settled-Chat check is split into four named
clauses with values, saved as evidence on failure.
- A question card the turn ended on counts as its reply (decision after
cohort 4) in cli-operations.owned-dev-instance, onboarding.new-company
and status-cards.other-authors-card. The card's Markdown-rendered fields
(question form description; confirmation prompt and details) count as
reply links. Link requirements still apply.
- Every changed case bumps its `oracleVersion`; the descriptor snapshot
and inventory digest are updated.

Why each old check was wrong and why the new one still catches a broken
product:

| Case | Old check was wrong because | A broken product still fails
because |
|---|---|---|
| phase captures | runs succeeded and the chat waited before the reply
rendered, so links were empty | the same link checks run on the rendered
reply |
| routines.pause-owned | a correct offer to pause the run read as a
cancellation | the checkpoint run must be running and the run must later
succeed |
| spend-breakdown | "unknown, not $0.00" read as "$0" | the reply must
identify the record and a chat run must read its saved accounting;
totals and per-agent amounts stay graded |
| edit-queued-message | correct wording missed a keyword list | the
reply must link the task, the agent's edit and reorder must be refused,
and the queue must be unchanged at the reply |
| choose-provider | the resumed page label was not accepted | the button
must still be visible on the selected Notion surface |
| necessary-question | the answer read as a placeholder; deliverables
did not count | the exact answer must be saved in the linked work after
the answer, by an agent of the company |
| new-company | timestamps and profiles made the JSON compare fail
without saying why | membership identity, role, status and grants must
be unchanged |
| choose-primary | one combined error | the same four conditions, each
named |
| card as reply | a card answer read as an empty reply | card text must
exist and link requirements still apply |

## Verification

- Calibration tests (valid, reworded valid, broken) for each changed
grader: `integrator-routine-pause.test.ts`,
`identity-accounting.test.ts` (includes the cohort 4 reply),
`runtime-queue-controls.test.ts` (includes the cohort 4 reply),
`external-provider-choice.test.ts`, `identity.test.ts`,
`identity-onboarding-work.test.ts`,
`runtime-primary-ready-chat.test.ts`, `integrator-status-cards.test.ts`,
`turn-response-card.test.ts`, `chat-rendered-links.test.ts`.
- The corrected spend-breakdown grader passes on the retained cohort 4
evidence (its cost-summary read binds to the unresolved task) and fails
with the reads removed.
- `npx vitest run --config tests/runner-e2e/vitest.config.ts
chat-catalog chat-rendered chat-linked`: 284 files passed.
- `node --test
tests/runner-e2e/chat-full-catalog-testops-manifest.test.mjs`: 10/10
passed.
- `node scripts/typecheck-test-projects.mjs tests/runner-e2e`: passed.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <sha> --check`:
unchanged.
- Paid run (8 cells, OpenCode + DeepSeek v4.1 flash) on this branch
combined with the guidance PR: see the PR comment for results.

## Risks

- The new-company guidance check now needs a rendered link to
`/onboarding`. A reply that only names the company switcher fails. The
companion guidance PR tells agents this route.
- spend-breakdown does not grade wording, so a reply that reads the
record and still calls it "$0" is not caught. The amounts, total and
identification are still graded.
- The new-company case renames the source company and the person for the
case and restores them at cleanup.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use, shell execution and code editing.

## 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
- [ ] 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>
2026-11-12 00:37:42 -06:00

449 lines
16 KiB
TypeScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { expect } from "@playwright/test";
import { isDeepStrictEqual } from "node:util";
import type { AppDefinition } from "../../../packages/shared/src/types/app-definition.js";
import type { ConnectionIntentInteraction } from "../../../packages/shared/src/types/issue.js";
import { getAvailableConnectionMethods } from "../../../packages/shared/src/app-definitions.js";
import {
definition,
root,
checks,
externalObservation,
observeExternal,
} from "./external-support.js";
import { waitForReply } from "./identity-support.js";
import { collectRunEvents } from "../run-observations.js";
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
/** The setup page's sign-in control: "Continue to Notion" on a new draft, "Finish with Notion" when the page resumes
* a draft the agent already created (ConnectionSetupFlow), or the generic sign-in step. The button has no test id. */
export const NOTION_SIGN_IN_CONTROL = /Continue to (?:Notion|sign in)|Finish with Notion|Sign in to Notion/;
interface Gallery {
apps: AppDefinition[];
credentialSources: {
vercelConnect: { available: boolean; reason: string | null };
};
}
export function notionSetupChoices(gallery: Gallery) {
const notion = gallery.apps.find((app) => app.slug === "notion"),
methods = notion ? getAvailableConnectionMethods(notion) : [];
const oauth = methods.find(
(method) =>
method.auth === "oauth" &&
method.transport === "mcp_remote" &&
method.defaults?.serverUrl === "https://mcp.notion.com/mcp",
);
const managed = gallery.credentialSources.vercelConnect;
if (
!oauth?.credentialSources?.vercelConnect?.services.includes("notion") ||
managed.available ||
!managed.reason
)
throw new Error(
"Setup blocker: actual reviewed Notion catalog must offer official sign-in and supported unavailable Vercel Connect with its prerequisite",
);
return {
methodKey: oauth.key,
serverUrl: oauth.defaults!.serverUrl!,
unavailableReason: managed.reason,
advertisedChoices: {
service: "notion",
methodKey: oauth.key,
auth: oauth.auth,
transport: oauth.transport,
whenToUse: oauth.whenToUse,
serverUrl: oauth.defaults!.serverUrl!,
alternative: {
source: "vercel_connect",
available: managed.available,
reason: managed.reason,
},
},
};
}
/** The question asks only for the easiest way to connect Notion, so the answer's wording is left to a
* human reader: which methods it names, and whether it mentions the unavailable one, are not graded.
* The catalog it must use is checked independently, and the setup path it leads to is graded by
* clicking the attributed card or method link (no protocol substitution). The answer must exist and
* must not claim an account is already connected. `_reason` is kept for call-site compatibility. */
export function truthfulNotionChoices(reply: string, _reason?: string) {
return (
!!reply.trim() &&
!/\b(?:I(?:['’]ve| have)?|we(?:['’]ve| have)?)\s+(?:already\s+)?connected\b|\bnotion\s+is\s+(?:now\s+)?connected\b/i.test(
reply,
)
);
}
const record = (v: unknown): Record<string, unknown> =>
v && typeof v === "object" && !Array.isArray(v)
? (v as Record<string, unknown>)
: {};
interface MessageEvent {
seq?: number;
runId?: string;
companyId?: string;
agentId?: string;
eventType?: string;
payload?: unknown;
}
export function publicChoiceMessages(
events: MessageEvent[],
expected: { companyId: string; agentId: string; runId: string },
) {
return events.flatMap((event) => {
const prp = record(record(event.payload).prpEvent),
payload = record(prp.payload),
item = record(payload.item);
return event.companyId === expected.companyId &&
event.agentId === expected.agentId &&
event.runId === expected.runId &&
prp.runId === expected.runId &&
event.eventType === "item.completed" &&
item.type === "agentMessage" &&
item.status === "completed" &&
["commentary", "final_answer"].includes(String(item.phase)) &&
typeof item.id === "string" &&
typeof item.text === "string" &&
item.text.length <= 12000
? [{ runId: expected.runId, eventId: item.id, body: item.text }]
: [];
});
}
export function intendedNotionCard(
cards: ConnectionIntentInteraction[],
expected: {
companyId: string;
issueId: string;
agentId: string;
humanId: string;
runIds: string[];
},
) {
const matches = cards.filter(
(c) =>
c.kind === "connection_intent" &&
c.status === "pending" &&
c.companyId === expected.companyId &&
c.issueId === expected.issueId &&
c.createdByAgentId === expected.agentId &&
c.addresseeUserId === expected.humanId &&
c.payload.serviceSlug === "notion" &&
!!c.sourceRunId &&
expected.runIds.includes(c.sourceRunId),
);
return matches.length === 1 ? matches[0] : undefined;
}
export function supportedNotionLink(
link: string,
origin: string,
prefix: string,
method: string,
) {
try {
const u = new URL(link, origin);
return (
u.origin === origin &&
u.pathname === `/${prefix}/apps/connect` &&
[u.searchParams.get("source"), u.searchParams.get("appKey")].includes(
"notion",
) &&
(!u.searchParams.has("method") || u.searchParams.get("method") === method)
);
} catch {
return false;
}
}
const visibleText = (s: string) =>
s
.replace(/\[([^\]]+)\]\([^)]*\)/g, "$1")
.replace(/[*`_]/g, "")
.replace(/\s+/g, " ")
.trim();
async function observeChoiceExplanation(
ctx: ChatCatalogContext,
state: Record<string, unknown>,
) {
const runs = (await ctx.allRuns()).filter(
(r) =>
r.agentId === ctx.input.fixtures.agent.id && r.status === "succeeded",
),
messages = [];
for (const run of runs) {
const events = await collectRunEvents<MessageEvent>((afterSeq, limit) =>
ctx.input.api.getRunObservation(
`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=${limit}`,
),
);
messages.push(
...publicChoiceMessages(events, {
companyId: ctx.input.fixtures.company.id,
agentId: ctx.input.fixtures.agent.id,
runId: run.id,
}),
);
}
// The last completed message is the answer the person reads; earlier ones may be progress notes and
// cannot rescue a final answer that claims a connected account.
const last = messages.at(-1);
const selected = last && truthfulNotionChoices(last.body) ? last : undefined;
if (selected) {
await expect(
ctx.input.page
.getByText(visibleText(selected.body), { exact: true })
.first(),
).toBeVisible();
state.choiceExplanation = selected;
state.choiceExplanationVisible = true;
}
}
export function completeAdvertisedNotionChoices(
value: unknown,
reason: unknown,
) {
const c = record(value),
a = record(c.alternative);
return (
c.service === "notion" &&
c.methodKey === "mcp-oauth" &&
c.auth === "oauth" &&
c.transport === "mcp_remote" &&
c.serverUrl === "https://mcp.notion.com/mcp" &&
typeof c.whenToUse === "string" &&
!!c.whenToUse.trim() &&
a.source === "vercel_connect" &&
a.available === false &&
typeof reason === "string" &&
!!reason.trim() &&
a.reason === reason
);
}
export function gradeProviderChoice(value: unknown) {
const c = checks(),
o = externalObservation(value);
c.add(
"complete-catalog-choice-evidence",
!!o,
"Actual public catalog choices, prerequisite and attributed human setup selection are required.",
);
if (!o) return c.result();
const explanation = record(o.state.choiceExplanation),
body = typeof explanation.body === "string" ? explanation.body : o.reply;
c.add(
"real-catalog-and-truthful-choices",
o.state.catalogChoicesIndependentlyMatched === true &&
completeAdvertisedNotionChoices(
o.state.advertisedChoices,
o.state.unavailableReason,
) &&
typeof o.state.unavailableReason === "string" &&
truthfulNotionChoices(body, o.state.unavailableReason) &&
o.state.choiceExplanationVisible === true &&
o.runs.some(
(r) =>
r.id === explanation.runId &&
r.agentId === o.leadId &&
r.status === "succeeded",
),
"The reviewed catalog is unchanged and a real visible model answer from the source native run exists without claiming a connected account; a bare setup card cannot replace that answer. Its wording is left to a human reader.",
);
c.add(
"directed-official-setup-path",
o.state.modelDirectedNotionSetup === true &&
["inline-card", "method-link"].includes(String(o.state.selectionLane)) &&
o.state.selectionAttributionMatched === true &&
o.state.selectedNotionVisible === true &&
o.state.signInControlVisible === true,
"The person selects the attributed real inline request or supported actual method link, then sees the selected Notion setup without protocol substitution.",
);
c.add(
"original-intent-retained-without-phantom-account",
o.state.originalConversationRetained === true &&
o.state.originalQueryRetained === true &&
o.connections.length === 0,
"The original task and exact query remain intact; no authorization or usable account is invented.",
);
return c.result();
}
export const providerChoiceExternalCases = [
definition(
"connection-setup.choose-provider",
async (ctx) => {
const choices = notionSetupChoices(
await ctx.input.api.get<Gallery>(`${root(ctx)}/tools/gallery`),
);
const before = await ctx.input.api.get<{ connections: unknown[] }>(
`${root(ctx)}/tools/connections`,
);
if (before.connections.length)
throw new Error(
"Catalog choice requires no existing account in the disposable company",
);
return {
...choices,
humanId: (
await ctx.input.api.get<{ user: { id: string } }>(
"/api/auth/get-session",
)
).user.id,
};
},
gradeProviderChoice,
{
authentication: "human-session",
oracleVersion: "paperclip.chat-catalog.provider-choice.structural.v3",
sourceFiles: [
"chat-catalog-domains/external-provider-choice.ts",
"run-observations.ts",
"chat-catalog-domains/external-support.ts",
"chat-catalog-domains/internal-support.ts",
"chat-catalog-domains/identity-support.ts",
"../../packages/shared/src/app-definitions.ts",
"../../packages/shared/src/app-definitions/notion.json",
"../../ui/src/features/connections/ConnectionIntentInteractionBody.tsx",
"../../ui/src/features/connections/ConnectionSetupFlow.tsx",
"chat-scenarios/connection-setup.yaml",
],
async verifySetup(ctx, state) {
const actual = notionSetupChoices(
await ctx.input.api.get<Gallery>(`${root(ctx)}/tools/gallery`),
),
c = checks();
c.add(
"actual-reviewed-advertised-choices",
isDeepStrictEqual(actual.advertisedChoices, state.advertisedChoices),
"Independent public gallery retains reviewed Notion method identity and actual unsupported credential-source prerequisite.",
);
return c.result();
},
async act(ctx, state) {
await waitForReply(ctx);
await observeChoiceExplanation(ctx, state);
if (!state.choiceExplanationVisible)
throw new Error(
"No visible source-run answer, or the answer claims an account is already connected",
);
const o = await observeExternal(ctx, state),
source = ctx.input.page.url(),
issueId = ctx.issue()!.id,
runs = await ctx.allRuns();
const cards = await ctx.input.api.get<ConnectionIntentInteraction[]>(
`/api/issues/${issueId}/interactions`,
),
card = intendedNotionCard(cards, {
companyId: o.companyId,
issueId,
agentId: o.leadId,
humanId: String(state.humanId),
runIds: runs
.filter((r) => r.status === "succeeded")
.map((r) => r.id),
});
if (card) {
state.selectionLane = "inline-card";
state.selectedIntentId = card.id;
await ctx.input.page
.locator(`[id=${JSON.stringify(`interaction-${card.id}`)}]`)
.getByRole("button", { name: "Connect", exact: true })
.click();
await expect(ctx.input.page.getByRole("dialog")).toContainText(
"Notion",
);
} else {
const href = o.links.find((link) =>
supportedNotionLink(
link,
o.origin,
String(ctx.input.fixtures.company.issuePrefix),
String(state.methodKey),
),
);
if (!href)
throw new Error(
"No attributed inline request or actual supported Notion method link",
);
state.selectionLane = "method-link";
state.selectedMethodHref = href;
await ctx.input.page
.locator(`[id^="comment-"] a[href=${JSON.stringify(href)}]`)
.first()
.click();
await expect(ctx.input.page.getByRole("main")).toContainText(
"Notion",
);
}
state.modelDirectedNotionSetup = true;
state.selectedNotionVisible = true;
const surface =
state.selectionLane === "inline-card"
? ctx.input.page.getByRole("dialog")
: ctx.input.page.getByRole("main");
await expect(
surface
.getByRole("button", {
name: NOTION_SIGN_IN_CONTROL,
})
.first(),
).toBeVisible();
state.signInControlVisible = true;
if (state.selectionLane === "inline-card")
await surface
.getByRole("button", { name: "Close", exact: true })
.click();
else
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
await ctx.refreshIssue();
state.originalConversationRetained = ctx.issue()?.id === issueId;
const comments = await ctx.input.api.get<
Array<{ body: string; authorUserId?: string }>
>(`/api/issues/${issueId}/comments?order=asc`);
state.originalQueryRetained = comments.some(
(comment) =>
comment.authorUserId === state.humanId &&
comment.body === ctx.scenario.query,
);
},
async observe(ctx, state) {
const actual = notionSetupChoices(
await ctx.input.api.get<Gallery>(`${root(ctx)}/tools/gallery`),
);
state.catalogChoicesIndependentlyMatched = isDeepStrictEqual(
actual.advertisedChoices,
state.advertisedChoices,
);
const o = await observeExternal(ctx, state);
state.selectionAttributionMatched =
state.selectionLane === "inline-card"
? intendedNotionCard(
o.interactions as unknown as ConnectionIntentInteraction[],
{
companyId: o.companyId,
issueId: ctx.issue()!.id,
agentId: o.leadId,
humanId: String(state.humanId),
runIds: o.runs
.filter((r) => r.status === "succeeded")
.map((r) => r.id),
},
)?.id === state.selectedIntentId
: typeof state.selectedMethodHref === "string" &&
o.links.includes(state.selectedMethodHref) &&
supportedNotionLink(
state.selectedMethodHref,
o.origin,
String(ctx.input.fixtures.company.issuePrefix),
String(state.methodKey),
);
return { ...o, state };
},
async verifyResult(ctx, state) {
const explanation = record(state.choiceExplanation);
if (typeof explanation.body !== "string")
throw new Error("Missing actual source-run choice explanation");
await expect(
ctx.input.page
.getByText(visibleText(explanation.body), { exact: true })
.first(),
).toBeVisible();
},
},
),
];