mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-15 18:56:05 +01:00
## 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>
161 lines
14 KiB
TypeScript
161 lines
14 KiB
TypeScript
import { expect } from "@playwright/test";
|
|
import { checks, type Entity } from "./internal-support.js";
|
|
import { createAuthenticatedPerson, enrollPrerequisitePerson } from "./identity-auth.js";
|
|
import { probeAgentPermission, waitForReply, waitForTurnReplyLinks, remainingIdentityObservationBudget } from "./identity-support.js";
|
|
import { runtimeDefinition, runtimeWorker, runtimeObservation, observeRuntime, openRuntimeAgentProfile, verifyRuntimeResult, agentLink, type RuntimeAgent } from "./runtime-support.js";
|
|
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
|
|
interface Primary { companyId: string; userId: string; primaryAgentId: string | null }
|
|
type Person = Awaited<ReturnType<typeof createAuthenticatedPerson>>;
|
|
const people = new WeakMap<ChatCatalogContext, Person>();
|
|
const endpoint = (companyId: string) => `/api/companies/${companyId}/primary-agent/me`;
|
|
async function personPrimary(person: Person, companyId: string): Promise<Primary> {
|
|
const response = await person.request(endpoint(companyId));
|
|
if (!response.ok) { await response.body?.cancel(); throw new Error(`Secondary primary read returned ${response.status}`); }
|
|
return response.json() as Promise<Primary>;
|
|
}
|
|
export function gradePrimary(value: unknown) {
|
|
const c = checks(); const o = runtimeObservation(value);
|
|
c.add("complete-human-primary-evidence", !!o, "Real user-scoped saved preferences and human replacement control are required."); if (!o) return c.result();
|
|
const worker = o.state.worker as RuntimeAgent; const before = o.state.primaryBefore as Primary;
|
|
const after = o.state.primaryAfter as Primary | undefined; const otherBefore = o.state.otherPersonBefore as Primary;
|
|
const otherAfter = o.state.otherPersonAfter as Primary | undefined;
|
|
c.add("only-human-replaces-existing-primary", !!before && before.primaryAgentId === o.leadId
|
|
&& o.state.beforeHumanPrimary === o.leadId && o.state.replacementConfirmed === true
|
|
&& after?.primaryAgentId === worker.id && after.companyId === o.companyId && after.userId === before.userId,
|
|
"The original primary survives the chat response and is replaced only after the visible human confirmation.");
|
|
c.add("agent-preference-write-denied", o.state.agentWriteStatus === 403, "The preference endpoint rejects the real CEO agent bearer.");
|
|
c.add("other-person-company-unaffected", !!otherAfter && !!otherBefore && otherAfter.userId !== before.userId
|
|
&& JSON.stringify(otherAfter) === JSON.stringify(otherBefore)
|
|
&& JSON.stringify(o.state.otherCompanyAfter) === JSON.stringify(o.state.otherCompanyBefore),
|
|
"Independent authenticated person and company preference readbacks do not change.");
|
|
c.add("recent-chat-precedence-without-work", o.state.reopenedRecentAgent === o.leadId
|
|
&& o.state.runsAfterNavigation === 1 && o.state.chatCountBeforeNavigation === o.state.chatCountAfterNavigation,
|
|
"Opening Chat may reopen this valid recent source conversation and creates no duplicate chat or execution.");
|
|
// The reply's wording is not graded: the person must reach the control
|
|
// through the exact profile link the reply rendered, and saved state proves
|
|
// the agent wrote nothing before that human confirmation.
|
|
const href = agentLink(o, worker);
|
|
c.add("reply-links-chosen-profile", !!href && o.state.profileLinkFollowed === href,
|
|
"The reply links Morgan's profile, and the person reaches the primary control by clicking that rendered link.");
|
|
return c.result();
|
|
}
|
|
/** The settled Chat landing, checked clause by clause so a failure names which part changed and its values. */
|
|
export function settledReadyChatChecks(input: { currentIssueId?: string; sourceId: string; companyId: string; userId: string; workerId: string; leadId: string;
|
|
primary: Primary; chats: Entity[]; chatCountBefore: unknown; runs: Array<{ id: string; agentId?: string | null; status?: string }>; nativeRunId: string }) {
|
|
const { primary, chats, runs } = input;
|
|
return [
|
|
{ id: "same-conversation-open", passed: input.currentIssueId === input.sourceId, detail: `open conversation ${input.currentIssueId ?? "none"}, expected ${input.sourceId}` },
|
|
{ id: "primary-readback", passed: primary.companyId === input.companyId && primary.userId === input.userId && primary.primaryAgentId === input.workerId,
|
|
detail: `primary ${primary.primaryAgentId ?? "none"} for user ${primary.userId} in ${primary.companyId}, expected ${input.workerId}` },
|
|
{ id: "chat-count-unchanged", passed: chats.length === input.chatCountBefore && chats.filter(row => row.id === input.sourceId).length === 1,
|
|
detail: `${chats.length} chats (${chats.filter(row => row.id === input.sourceId).length} of them the source), expected ${String(input.chatCountBefore)} with the source once` },
|
|
{ id: "no-extra-run", passed: runs.length === 1 && runs[0]?.id === input.nativeRunId && runs[0].agentId === input.leadId && runs[0].status === "succeeded",
|
|
detail: `runs ${runs.map(run => `${run.id}:${run.agentId}:${run.status}`).join(",") || "none"}, expected only ${input.nativeRunId} succeeded` },
|
|
];
|
|
}
|
|
export async function verifyReadyPrimaryChat(ctx: ChatCatalogContext, state: Record<string, unknown>, value: unknown) {
|
|
const o = runtimeObservation(value); const before = state.primaryBefore as Primary; const worker = state.worker as RuntimeAgent;
|
|
const sourceId = state.sourceBeforeNavigation; const nativeIds = state.nativeIdsBeforeNavigation;
|
|
if (!o || o.companyId !== ctx.input.fixtures.company.id || o.leadId !== ctx.input.fixtures.agent.id
|
|
|| typeof sourceId !== "string" || !sourceId || !Array.isArray(nativeIds) || nativeIds.length !== 1 || typeof nativeIds[0] !== "string")
|
|
throw new Error("Primary Chat readiness requires its exact original conversation and native run");
|
|
const budget = () => remainingIdentityObservationBudget(ctx);
|
|
const lead = o.agents.find(row => row.id === o.leadId); if (!lead) throw new Error("Primary Chat lead is missing");
|
|
await expect(ctx.input.page).toHaveURL(url => {
|
|
const parts = url.pathname.split("/").filter(Boolean).map(decodeURIComponent);
|
|
return parts.length === 3 && parts[0] === ctx.input.fixtures.company.issuePrefix && parts[1] === "chats" && [lead.id, lead.urlKey].includes(parts[2]);
|
|
}, { timeout: budget() }); budget();
|
|
const composer = ctx.input.page.getByTestId("task-chat-composer-input");
|
|
await expect(composer).toBeVisible({ timeout: budget() }); budget();
|
|
await expect(composer.locator('[contenteditable="true"], textarea').first()).toBeEditable({ timeout: budget() }); budget();
|
|
const chat = await ctx.input.api.get<Entity & { conversationAgentId?: string; conversationUserId?: string }>(`/api/companies/${o.companyId}/chats/${o.leadId}`, { timeout: budget() }); budget();
|
|
if (chat.id !== sourceId || chat.companyId !== o.companyId || chat.conversationAgentId !== o.leadId || chat.conversationUserId !== before.userId)
|
|
throw new Error("Ready Chat reopened a different conversation or person");
|
|
const comments = await ctx.input.api.get<Entity[]>(`/api/issues/${sourceId}/comments?order=asc`, { timeout: budget() }); budget();
|
|
const humans = comments.filter(row => !row.authorAgentId);
|
|
const reply = comments.find(row => row.authorAgentId === o.leadId && row.createdByRunId === nativeIds[0] && !!row.body?.trim());
|
|
if (humans.length !== 1 || humans[0]!.authorUserId !== before.userId || humans[0]!.body?.trim() !== ctx.scenario.query.trim() || !reply)
|
|
throw new Error("Ready Chat lacks its original human request and native response");
|
|
for (const comment of [humans[0]!, reply]) {
|
|
await expect(ctx.input.page.locator(`[id=${JSON.stringify(`comment-${comment.id}`)}]`)).toBeVisible({ timeout: budget() }); budget();
|
|
}
|
|
await ctx.refreshIssue(); budget();
|
|
const primary = await ctx.input.api.get<Primary>(endpoint(o.companyId), { timeout: budget() }); budget();
|
|
const chats = await ctx.input.api.get<Entity[]>(`/api/companies/${o.companyId}/chats`, { timeout: budget() }); budget();
|
|
const runs = await ctx.allRuns(); budget();
|
|
const failed = settledReadyChatChecks({ currentIssueId: ctx.issue()?.id, sourceId, companyId: o.companyId, userId: before.userId, workerId: worker.id, leadId: o.leadId,
|
|
primary, chats, chatCountBefore: state.chatCountBeforeNavigation, runs, nativeRunId: nativeIds[0] }).filter(check => !check.passed);
|
|
if (failed.length) {
|
|
await ctx.input.evidence("chat-primary-ready-conversation-failure.json", { failed, primary, chatIds: chats.map(row => row.id), runs: runs.map(run => ({ id: run.id, agentId: run.agentId, status: run.status })) });
|
|
throw new Error(`Settled Chat failed ${failed.map(check => `${check.id} (${check.detail})`).join("; ")}`);
|
|
}
|
|
state.reopenedRecentAgent = o.leadId; state.runsAfterNavigation = runs.length; state.chatCountAfterNavigation = chats.length;
|
|
await ctx.input.evidence("chat-primary-ready-conversation.json", { companyId: o.companyId, agentId: o.leadId, sourceId, userId: before.userId,
|
|
primaryAgentId: primary.primaryAgentId, originalNativeIds: nativeIds, chatCount: chats.length, composerReady: true, originalConversationVisible: true, noExtraWork: true }); budget();
|
|
}
|
|
export const runtimePrimaryCases = [runtimeDefinition("agents.choose-primary", async ctx => {
|
|
const secrets = ctx.input.privateSecrets; if (!secrets) throw new Error("Primary fixture requires private credential sink");
|
|
const browser = ctx.input.page.context().browser(); if (!browser) throw new Error("Real browser required");
|
|
const primaryBefore = await ctx.input.api.get<Primary>(endpoint(ctx.input.fixtures.company.id));
|
|
if (primaryBefore.primaryAgentId !== ctx.input.fixtures.agent.id) throw new Error("Catalog requires an existing primary agent");
|
|
const worker = await runtimeWorker(ctx);
|
|
const person = await createAuthenticatedPerson({ api: ctx.input.api, browser, secrets, name: "Second primary reader" }); people.set(ctx, person);
|
|
await enrollPrerequisitePerson(ctx, person, "operator");
|
|
const otherCompany = await ctx.input.api.post<Entity>("/api/companies", { name: `Other primary company ${ctx.input.nonce}` });
|
|
return { worker, primaryBefore, otherCompany, otherPersonBefore: await personPrimary(person, ctx.input.fixtures.company.id),
|
|
otherCompanyBefore: await ctx.input.api.get<Primary>(endpoint(otherCompany.id)) };
|
|
}, gradePrimary, {
|
|
authentication: "human-session", oracleVersion: "paperclip.chat-catalog.runtime-primary.v5",
|
|
sourceFiles: ["chat-catalog-domains/runtime-primary.ts", "chat-catalog-domains/runtime-support.ts", "chat-catalog-domains/identity-support.ts", "chat-scenarios/agents.yaml"],
|
|
async act(ctx, state) {
|
|
remainingIdentityObservationBudget(ctx);
|
|
await waitForReply(ctx, ctx.observationDeadlineAt);
|
|
remainingIdentityObservationBudget(ctx);
|
|
const worker = state.worker as RuntimeAgent;
|
|
state.beforeHumanPrimary = (await ctx.input.api.get<Primary>(endpoint(ctx.input.fixtures.company.id))).primaryAgentId;
|
|
state.agentWriteStatus = await probeAgentPermission(ctx, endpoint(ctx.input.fixtures.company.id), "PUT", { primaryAgentId: worker.id });
|
|
// The run is recorded finished before its reply is saved and rendered; read the reply's links only once it is on the page.
|
|
await waitForTurnReplyLinks(ctx);
|
|
const o = await observeRuntime(ctx, state);
|
|
const source = ctx.input.page.url();
|
|
const href = agentLink(o, worker);
|
|
if (!href) throw new Error("The reply rendered no link to Morgan's profile for the person to follow");
|
|
await openRuntimeAgentProfile(ctx, worker, o);
|
|
state.profileLinkFollowed = href;
|
|
await ctx.input.page.getByRole("button", { name: "Set as my primary", exact: true }).click();
|
|
const dialog = ctx.input.page.getByRole("alertdialog");
|
|
await expect(dialog).toContainText("Change your primary agent?"); await expect(dialog).toContainText("Morgan");
|
|
await dialog.getByRole("button", { name: "Set as my primary", exact: true }).click();
|
|
await expect(ctx.input.page.getByRole("img", { name: "My primary agent", exact: true }).first()).toBeVisible();
|
|
state.replacementConfirmed = true;
|
|
// Revisit the valid recent source before opening the normal Chat landing.
|
|
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
|
|
await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible();
|
|
const chats = `/api/companies/${ctx.input.fixtures.company.id}/chats`;
|
|
state.chatCountBeforeNavigation = (await ctx.input.api.get<Entity[]>(chats)).length;
|
|
state.sourceBeforeNavigation = ctx.issue()?.id;
|
|
state.nativeIdsBeforeNavigation = (await ctx.allRuns()).map(run => run.id);
|
|
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/chats`, { waitUntil: "domcontentloaded" });
|
|
const lead = o.agents.find(row => row.id === ctx.input.fixtures.agent.id)!;
|
|
await ctx.input.page.waitForURL(url => [lead.id, lead.urlKey].includes(decodeURIComponent(url.pathname.split("/").at(-1)!)));
|
|
await verifyReadyPrimaryChat(ctx, state, o);
|
|
},
|
|
async observe(ctx, state) {
|
|
const person = people.get(ctx); if (!person) throw new Error("Secondary authenticated person missing");
|
|
state.primaryAfter = await ctx.input.api.get<Primary>(endpoint(ctx.input.fixtures.company.id));
|
|
state.otherPersonAfter = await personPrimary(person, ctx.input.fixtures.company.id);
|
|
state.otherCompanyAfter = await ctx.input.api.get<Primary>(endpoint((state.otherCompany as Entity).id));
|
|
return observeRuntime(ctx, state);
|
|
},
|
|
async verifyResult(ctx, state, value) {
|
|
remainingIdentityObservationBudget(ctx);
|
|
await verifyRuntimeResult(ctx, state, value);
|
|
remainingIdentityObservationBudget(ctx);
|
|
await verifyReadyPrimaryChat(ctx, state, value);
|
|
},
|
|
async cleanup(ctx, state) {
|
|
const person = people.get(ctx); people.delete(ctx); await person?.dispose();
|
|
await ctx.input.api.delete(`/api/companies/${(state.otherCompany as Entity).id}`, { allowNotFound: true });
|
|
},
|
|
})];
|