Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/runtime-dependency.ts
T
DottaandClaude Opus 5.5 cbd636d652 fix(evals): wait for rendered replies, bound runs by role and grade chat outcomes structurally (#20685)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - The chat-feature eval catalog runs real chat journeys and grades
saved state, rendered links and run ledgers.
> - The second full-cohort run on master `9296c74e8d` failed 15 cases
where the product did the right thing and the harness did not.
> - The causes were three harness classes: links read before the reply
rendered, raw run counts that rejected product-caused follow-up runs,
and keyword graders on free-form replies. Four browser locators also
targeted retired controls.
> - This pull request fixes those harness layers. It does not change the
product.
> - The benefit is that these cases measure the feature again: correct
behaviour passes, and the relevant broken behaviour still fails.

## Linked Issues or Issue Description

**What happened**
In the second full-cohort chat-eval run on master `9296c74e8d`, these
cases failed although the reply and the saved state were correct:
`agents.choose-primary`, `cases.case-history`,
`budgets-costs.set-budget` (links read about 2s before the reply
rendered); `task-coordination.independent-review`,
`cases.update-case-facts`, `routines.manage-other-owner`,
`questions-and-approvals.review-plan` (a legitimate continuation or the
product's completion follow-up exceeded a raw run count or was
cancelled); `cases.cases-disabled`, `inbox-search.find-design`,
`navigation-preferences.broken-link`, `cases.browse-cases` (keyword or
clause graders rejected correct replies); `agent-chat.conference-room`,
`workspaces.inspect-git`, `task-coordination.block-on-design`,
`skills.author-skill` (browser steps used stale settings or controls).

**Expected behavior**
A correct reply and correct saved state pass. A wrong outcome, extra or
duplicate agent work, a substitution or a missing route still fails.

**Steps to reproduce**
Run `runner-full-stack-e2e.yml` with `cadence=manual`, `all=false` and
an `id` list of the cases above against master `9296c74e8d`. Read
`result.json` and `snapshots/` in each cell's evidence.

Refs #20600

## What Changed

- `chat-rendered-links.ts`: `collectConversationLinks` waits (at most
10s, once per reply per page) for the latest saved lead reply to render
when its conversation is open. A page that does not show the
conversation does not wait. `observeInternal` and the flow conversation
read use it.
- `budgets-costs.set-budget`: waits for the rendered reply before it
reads anchors. It fills the budget only after the form shows the saved
cap, and checks that the typed value stays.
- New `chat-catalog-domains/run-roles.ts`: identifies a run by role (a
worker woken by a comment that a named run saved on the task; the CEO's
chat completion follow-up).
- `task-coordination.independent-review`: admits one Morgan continuation
woken by the CEO's authorization comment and one Riley review run. The
review request may come from that continuation's native status decision.
Other runs still fail.
- `cases.update-case-facts`: a phase settles when its CEO turn and at
most one Morgan continuation woken by that turn's task comment finish. A
new `role-bound-runs` check rejects any other run. `terminal-counts`
gets an optional `maximumTerminalStatusCounts`.
- `routines.manage-other-owner`: admits one Morgan run on a task that
the CEO created for Morgan. A schedule change must be Morgan's own write
from that run. The ownership check is structural (a linked owner task,
or a link to the routine or Morgan's page). The keyword checks on the
reply are removed.
- `questions-and-approvals.review-plan`: after the stale-review check,
lets the product's completion follow-up settle before final run custody.
The existing grader already validates it.
- `cases.cases-disabled`: the negation-blind false-claim regex is
removed. The case passes with a reply link to the Experimental settings
page (the scripted person follows it and sees the Cases control) or a
pending choice card. Saved state still proves that nothing was created.
- `inbox-search.find-design`: the per-clause regex is removed. The first
task link in the reply must be the task with the approved revision.
- `navigation-preferences.broken-link`: a link to the similar task fails
only when its label names the original (identifier or exact title). A
separate mention passes.
- `cases.browse-cases`: an excluded case must not be a result row. When
the reply has no result list, every case link is a result, so an
excluded case must not be linked.
- Browser steps: `conference-room` reloads after the fixture enables the
flag. `inspect-git` and `block-on-design` open the panel with "Show
properties" and pick the tab from the side panel launcher.
`author-skill` does not repeat the full inspection in `verifyResult`
when `act` already inspected the same saved version.
- Each changed case has a new `oracleVersion`.
`chat-catalog-descriptors.json` is in sync.

## Verification

- `pnpm exec vitest run --config tests/runner-e2e/vitest.config.ts <119
affected test files> --testTimeout=180000`: 1673 passed, 3 skipped. One
file (`chat-factual-query-input.test.ts`) did not load in the local
worktree because `@paperclipai/plugin-sdk` is not built there. It does
not import changed code. CI runs it.
- `chat-catalog-consistency.test.ts` passes (242 descriptors).
- `npx tsc --noEmit -p tests/runner-e2e`: no errors in changed files.
- `node tests/runner-e2e/source-sdk-public-inputs.mjs <HEAD> --check`:
no pin change.
- `node --test` on the three `chat-full-catalog-testops-*.test.mjs`
files: 40 passed.
- Calibration against retained evidence: the retained replies and run
shapes of cases-disabled, browse-cases, find-design, broken-link,
independent-review, update-case-facts and manage-other-owner now pass.
Broken variants fail (closed case as a result row, earlier design linked
first, original label on the similar task's link, unprompted or
duplicate worker runs, a second review run, a routine change outside the
owner's run, no route link).
- Paid runs on this branch: see the PR comments.

## Risks

- Low risk. Only eval harness code changes.
- The structural graders do not read reply wording. A reply that words
the outcome wrongly but links the right records can pass. A person reads
the reply.
- `navigation-preferences.sidebar-order` is not changed. The shipped
sidebar has no per-project order or collapsible Agents section, so the
case premise needs an owner decision.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

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

## 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>
2026-11-10 20:24:41 -06:00

144 lines
15 KiB
TypeScript

import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely, chatCatalogNativePhaseRemainingBudget } from "../chat-catalog-contract.js";
import { expect, type Page } from "@playwright/test";
import type { Issue } from "../../../packages/shared/src/types/issue.js";
import type { HeartbeatRun } from "../../../packages/shared/src/types/heartbeat.js";
import { pollUntil } from "../api.js";
import { collectRunEvents } from "../run-observations.js";
import { readRecord, recordParams } from "./api-read-receipts.js";
import { sendChatMessage } from "../chat-flow.js";
import { checks, type Entity } from "./internal-support.js";
import { runtimeDefinition, runtimeWorker, runtimeObservation, observeRuntime } from "./runtime-support.js";
const record = (value: unknown): Record<string, unknown> => value && typeof value === "object" && !Array.isArray(value) ? value as Record<string, unknown> : {};
/**
* Whether a run re-read Website's saved state (its own retained events, never reply text): a successful
* call_api read of the task, its documents or the company task list, bound by its saved input digest
* (bodies are redacted before saving), or a completed dedicated task tool whose output names the task.
*/
export function readTaskState(events: readonly Record<string, unknown>[], task: { id?: string; identifier?: string | null; companyId?: string | null }) {
const params = recordParams("id", task.id, task.identifier);
if (task.id && readRecord(events, [
...["GET /api/issues/{id}", "GET /api/issues/{id}/documents", "GET /api/issues/{id}/work-products"].map(operationId => ({ operationId, pathParams: params })),
{ operationId: "GET /api/companies/{companyId}/issues", pathParams: [...recordParams("companyId", task.companyId), undefined], paged: true },
])) return true;
return events.some(row => {
const envelope = record(record(row.payload).prpEvent), payload = record(envelope.payload), output = typeof payload.output === "string" ? payload.output : "";
return row.eventType === "tool.execution.completed" && envelope.sourceKind === "runner" && payload.status === "completed"
&& ["paperclip_get_task", "paperclip_search_tasks"].includes(String(payload.name))
&& [task.id, task.identifier].some(id => !!id && output.includes(id));
});
}
async function chooseStatus(page: Page, status: "Todo" | "Done") {
await page.getByRole("button", { name: /^Change status \(current:/ }).first().click();
// Each option's accessible name also carries its status icon's label, so match the visible option text.
// (gha-42937394973: the exact-name locator never resolved while the menu showed "Todo".)
await page.getByRole("button").filter({ visible: true, hasText: new RegExp(`^\\s*${status}\\s*$`) }).first().click();
}
export function gradeDesignDependency(value: unknown) {
const c = checks(), o = runtimeObservation(value);
c.add("actual-dependency-and-native-admission-evidence", !!o, "The saved dependency, real unfinished prerequisite and later eligible native result must be independently read."); if (!o) return c.result();
const s = o.state, task = s.task as Entity, design = s.design as Entity, waiting = s.waitingTask as Issue, finished = o.tasks.find(row => row.id === task.id);
c.add("actual-first-class-blocker-saved", waiting?.id === task.id && waiting.companyId === o.companyId && waiting.assigneeAgentId === (s.worker as Entity).id
&& waiting.blockedBy?.length === 1 && waiting.blockedBy[0]?.id === design.id && s.designUnfinishedAtWait === true
&& o.activity.some(row => row.action === "issue.blockers_updated" && row.entityId === task.id && row.agentId === o.leadId
&& (row.details?.addedBlockedByIssueIds as string[] | undefined)?.includes(design.id)),
"The CEO actually installs the Design edge on the intended Website task; a comment alone is insufficient.");
c.add("blocked-ordinary-admission-and-usable-ui", s.blockerVisible === true && s.noWorkerBeforeApproval === true && s.attemptedBeforeApproval === true
&& [200, 422, 409].includes(Number(s.beforeApprovalStatus)),
"Ordinary human start is attempted while Design is unfinished, but no Website native run is admitted; the task UI exposes the exact blocker.");
c.add("one-eligible-worker-after-real-human-approval", s.humanApprovedDesign === true && s.workerAdmissionAfterApproval === true && finished?.status === "done"
&& finished.assigneeAgentId === (s.worker as Entity).id && o.tasks.length === 2 && s.actualWebsiteResult === true
&& o.runs.length === 3 && o.runs.every(row => row.status === "succeeded") && o.runs.filter(row => row.agentId === (s.worker as Entity).id).length === 1,
"After actual human Design completion clears the prerequisite, ordinary admission runs Morgan once and produces the genuine saved Website result.");
// The saved edge, admission and document prove the outcome; a person reads the replies for meaning.
c.add("later-own-phase-reports-actual-result", s.finalReplyAttributed === true && String(s.finalReply ?? "").trim().length > 0 && s.finalReadTaskState === true,
"A declared factual human follow-up receives its own native reply, answered from a fresh product read of saved task state rather than a pre-approval response.");
return c.result();
}
export const runtimeDependencyCases = [runtimeDefinition("task-coordination.block-on-design", async ctx => {
const worker = await runtimeWorker(ctx), root = `/api/companies/${ctx.input.fixtures.company.id}`, marker = `Approved website ${ctx.input.nonce}`;
for (const scope of [{ scopeType: "company", scopeId: ctx.input.fixtures.company.id }, { scopeType: "agent", scopeId: worker.id }])
await ctx.input.api.post(`${root}/budgets/policies`, { ...scope, amount: 500, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" });
const design = await ctx.input.api.post<Entity>(`${root}/issues`, { title: "Design", status: "backlog", description: `A semantic HTML website with accessible labels. Await the actual human approval; reference ${marker}.` });
const task = await ctx.input.api.post<Entity>(`${root}/issues`, { title: "Website", status: "backlog", assigneeAgentId: worker.id,
description: `Implement the approved Design as a small website plan. Once eligible, read the actual Design task and save a task document with the exact reference ${marker}, accessible labels and a clear primary action, then finish normally. Do not deploy, create other tasks or invent approval.` });
return { worker, task, design, marker };
}, gradeDesignDependency, {
expectedHumanMessageCount: 2, expectedRunCount: 3, attemptTimeoutMs: 720_000, oracleVersion: "paperclip.chat-catalog.runtime.block-on-design.v7",
sourceFiles: ["chat-catalog-domains/runtime-dependency.ts", "chat-catalog-domains/api-read-receipts.ts", "chat-catalog-domains/runtime-support.ts", "run-observations.ts", "chat-scenarios/task-coordination.yaml"],
async act(ctx, state) {
await pollUntil({ label: "Saved dependency and canonical reply before human approval", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000),
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns() }; },
accept: v => chatCatalogNativePhaseIsTimely(ctx) && v.source?.conversationState === "waiting" && v.runs.length === 1 && v.runs[0]?.status === "succeeded" });
state.queryReply = (await observeRuntime(ctx, state)).reply;
const source = ctx.input.page.url(), task = state.task as Entity, design = state.design as Entity, websiteRoot = `/api/issues/${task.id}`;
state.waitingTask = await ctx.input.api.get<Issue>(websiteRoot);
state.designUnfinishedAtWait = (await ctx.input.api.get<Issue>(`/api/issues/${design.id}`)).status !== "done";
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
// A backlog task shows its blockers in the properties panel; the thread's blocker banner appears only once it is Blocked.
const blockedBy = ctx.input.page.locator('[data-property-row]:not([inert] *):not([aria-hidden="true"] *)')
.filter({ has: ctx.input.page.locator('[data-property-label="Blocked by"]') }).filter({ visible: true });
// Open the panel through the control the page renders ("Show properties"); a fresh panel shows its tab
// launcher first, from which a person chooses Properties.
const panel = ctx.input.page.getByRole("button", { name: /^(Show properties|Properties|Toggle side panel)$/ }).filter({ visible: true }).first();
const propertiesTab = ctx.input.page.getByRole("option", { name: /^Properties/ }).filter({ visible: true }).first();
await expect.poll(async () => await blockedBy.isVisible() || await propertiesTab.isVisible() || await panel.isVisible()).toBe(true);
if (!await blockedBy.isVisible() && !await propertiesTab.isVisible()) await panel.click();
await expect.poll(async () => await blockedBy.isVisible() || await propertiesTab.isVisible()).toBe(true);
if (!await blockedBy.isVisible()) await propertiesTab.click();
await expect(blockedBy.getByText(design.identifier ?? "Design").first()).toBeVisible(); state.blockerVisible = true;
const pending = ctx.input.page.waitForResponse(row => row.request().method() === "PATCH" && new URL(row.url()).pathname === websiteRoot);
await chooseStatus(ctx.input.page, "Todo"); state.beforeApprovalStatus = (await pending).status(); state.attemptedBeforeApproval = true;
// Reload and independent reads observe the real admission gate, rather
// than setting a run's blocked status or pretending the worker executed.
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
state.noWorkerBeforeApproval = (await ctx.allRuns()).every(row => row.agentId !== (state.worker as Entity).id);
await ctx.input.capture("actual-design-dependency-wait", "Website retains its actual Design blocker before human approval", "runtime-design-blocker.png");
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${design.identifier ?? design.id}`, { waitUntil: "domcontentloaded" });
await chooseStatus(ctx.input.page, "Done");
const approved = await pollUntil({ label: "Real human Design completion", deadlineAt: Date.now() + 20_000,
load: () => ctx.input.api.get<Issue>(`/api/issues/${design.id}`), accept: row => row.status === "done" });
state.humanApprovedDesign = approved.status === "done"; state.designApprovedAt = Date.now();
const website = await ctx.input.api.get<Issue>(websiteRoot);
if (website.status === "backlog") {
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
await chooseStatus(ctx.input.page, "Todo");
}
const result = await pollUntil({ label: "One ordinary Website admission after Design approval", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 240_000),
load: async () => ({ runs: await ctx.allRuns(), task: await ctx.input.api.get<Issue>(websiteRoot) }),
accept: v => chatCatalogNativePhaseIsTimely(ctx) && v.runs.length === 2 && v.runs.every(row => row.status === "succeeded") && v.task.status === "done",
reject: v => v.runs.length > 2 || v.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Eligible Website admission failed or duplicated native work" : undefined });
const worker = result.runs.find(row => row.agentId === (state.worker as Entity).id)!;
const designActivity = await ctx.input.api.get<Entity[]>(`/api/issues/${design.id}/activity`);
const approval = designActivity.find(row => row.action === "issue.updated" && row.actorType === "user" && row.details?.status === "done");
const workerDetail = await ctx.input.api.get<HeartbeatRun>(`/api/heartbeat-runs/${worker.id}`);
state.workerAdmissionAfterApproval = !!approval && Date.parse(String(workerDetail.createdAt)) >= Date.parse(approval.createdAt ?? ""); state.websiteRunId = worker.id;
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
const followup = `I approved Design ${design.identifier ?? design.id}. What is the actual result of Website ${task.identifier ?? task.id} now?`;
await sendChatMessage(ctx.input.page, followup, chatCatalogNativePhaseRemainingBudget(ctx));
const final = await pollUntil({ label: "Own native reply reporting actual post-approval Website outcome", deadlineAt: chatCatalogNativePhaseDeadline(ctx, Date.now() + 150_000),
load: async () => { await ctx.refreshIssue(); return { source: ctx.issue(), runs: await ctx.allRuns() }; },
accept: v => chatCatalogNativePhaseIsTimely(ctx) && v.source?.conversationState === "waiting" && v.runs.length === 3 && v.runs.every(row => row.status === "succeeded") });
const run = final.runs.find(row => !result.runs.some(prior => prior.id === row.id))!, comments = await ctx.input.api.get<Entity[]>(`/api/issues/${ctx.issue()!.id}/comments?order=asc`);
const human = comments.filter(row => !row.authorAgentId && row.body === followup), replies = comments.filter(row => row.authorAgentId === ctx.input.fixtures.agent.id && row.createdByRunId === run.id);
const detail = await ctx.input.api.get<{ runnerProfileJson?: { nativeExecutionInput?: { task?: { prompt?: string } } } }>(`/api/heartbeat-runs/${run.id}`);
state.finalReplyAttributed = human.length === 1 && replies.length > 0 && detail.runnerProfileJson?.nativeExecutionInput?.task?.prompt?.includes(human[0]!.id) === true;
state.finalReply = replies.map(row => row.body).join("\n");
state.finalReadTaskState = readTaskState(await collectRunEvents<Record<string, unknown>>(afterSeq => ctx.input.api.get(`/api/heartbeat-runs/${run.id}/events?afterSeq=${afterSeq}&limit=1000`)), task);
},
async observe(ctx, state) {
const o = await observeRuntime(ctx, state);
state.actualWebsiteResult = o.revisions.some(row => row.createdByRunId === state.websiteRunId && row.createdByAgentId === (state.worker as Entity).id
&& (row.body ?? "").includes(String(state.marker)) && o.documents.some(doc => doc.id === row.documentId && doc.latestRevisionId === row.id));
return o;
},
async verifyResult(ctx, state) {
const source = ctx.input.page.url(), task = state.task as Entity;
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${task.identifier ?? task.id}`, { waitUntil: "domcontentloaded" });
await ctx.input.page.reload({ waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByRole("heading", { name: "Website", exact: true }).first()).toBeVisible();
await expect(ctx.input.page.getByRole("button", { name: "Change status (current: Done)", exact: true }).first()).toBeVisible();
await ctx.input.capture("actual-approved-website-result", "The same Website task completed after its real Design prerequisite", "runtime-approved-website.png");
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
},
})];