Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/internal-agent-feedback.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

161 lines
17 KiB
TypeScript

import { expect } from "@playwright/test";
import type { ChatCatalogCase } from "../chat-catalog-contract.js";
import { pollUntil } from "../api.js";
import { createAuthenticatedPerson, enrollPrerequisitePerson } from "./identity-auth.js";
import { fixtureWorker, makeDefinition } from "./internal-definition.js";
import { agentStatus, cleanupPrivacyProbes, mainPerson } from "./internal-privacy.js";
import { checks, entity, observation, observeInternal, project, task, type Entity, type InternalObservation } from "./internal-support.js";
import { installCommentaryReader } from "./internal-commentary-reader.js";
interface Feedback { id: string; kind: string; preview: string; runId: string; agent: { id: string; name: string }; task: { id: string; title: string } | null; body?: string }
interface FeedbackObservation extends InternalObservation { entries: Feedback[]; hiddenEntry?: Feedback; hiddenDetailStatus: number; agentReadStatus: number; privateTaskStatus: number }
function commentaryHref(o: InternalObservation) {
return o.links.find(href => { try { const u = new URL(href, o.origin); return u.origin === o.origin && /\/activity\/commentary\/?$/.test(u.pathname); } catch { return false; } });
}
export function gradeAgentFeedback(value: unknown) {
const c = checks(); const o = observation(value) as FeedbackObservation | undefined;
c.add("real-attributed-feedback-evidence", !!o && Array.isArray(o.entries) && !!o.hiddenEntry, "Actual native-run submissions, authenticated human commentary results and restricted-source controls are required.");
if (!o || !Array.isArray(o.entries) || !o.hiddenEntry) return c.result();
const worker = o.state.worker as Entity; const privateWorker = o.state.privateWorker as Entity; const t = o.state.task as Entity; const hidden = o.state.privateTask as Entity;
const initial = o.state.initialEntries as Feedback[] | undefined;
c.add("actual-worker-submissions-retained", !!initial && initial.length === 2 && ["complaint", "suggestion"].every(kind => initial.some(row => row.kind === kind))
&& initial.every(before => o.entries.some(row => row.id === before.id && row.preview === before.preview && row.agent.id === worker?.id && row.task?.id === t?.id
&& row.runId === before.runId && o.runs.some(run => run.id === row.runId && run.agentId === worker.id && run.status === "succeeded")))
&& o.hiddenEntry.agent.id === privateWorker?.id && o.hiddenEntry.task?.id === hidden?.id
&& o.runs.some(run => run.id === o.hiddenEntry!.runId && run.agentId === privateWorker.id && run.status === "succeeded"),
"The stated suggestions and complaints are genuinely submitted through bound native tools by their own agents and source task runs.");
// The reply's wording is not matched. The submitted feedback text is a
// setup-chosen literal the chat agent cannot read, so relaying it means the
// answer came from outside the human's commentary access.
const relayed = (initial ?? []).some(row => row.preview && o.reply.toLowerCase().includes(row.preview.toLowerCase()));
c.add("agent-submission-is-not-board-read", o.agentReadStatus === 403 && !!commentaryHref(o) && !relayed,
"The chat agent cannot read board-only commentary, links the person to the authorized commentary view, and does not relay the submitted feedback.");
const marker = String(o.state.privateMarker);
c.add("restricted-source-and-preview-excluded", [403, 404].includes(o.privateTaskStatus) && o.hiddenDetailStatus === 404
&& !o.entries.some(row => row.id === o.hiddenEntry!.id || row.task?.id === hidden?.id || row.preview.includes(marker))
&& !o.reply.includes(marker) && !o.reply.includes(hidden?.id ?? marker),
"The human's legitimate commentary grant does not expose the other person's restricted source task or feedback preview.");
c.add("listing-does-not-submit-feedback", !o.entries.some(row => row.agent.id === o.leadId)
&& !o.activity.some(row => row.action === "agent.commentary_submitted" && row.agentId === o.leadId), "The listing request does not create a fabricated CEO complaint or suggestion.");
return c.result();
}
function agentFeedback(): ChatCatalogCase {
let casey: Awaited<ReturnType<typeof createAuthenticatedPerson>> | undefined; let key: { id: string; token: string } | undefined;
let readerSession: Awaited<ReturnType<typeof installCommentaryReader>> | undefined;
const base = makeDefinition("activity.agent-feedback", async ctx => {
const ownerId = await mainPerson(ctx); const browser = ctx.input.page.context().browser();
if (!browser || !ctx.input.privateSecrets) throw new Error("Feedback privacy needs a distinct real human and attempt-private redaction");
casey = await createAuthenticatedPerson({ api: ctx.input.api, browser, secrets: ctx.input.privateSecrets, name: "Casey" });
try {
await enrollPrerequisitePerson(ctx, casey, "operator");
const worker = await fixtureWorker(ctx); const privateWorker = await fixtureWorker(ctx);
await ctx.input.api.patch(`/api/agents/${privateWorker.id}`, { name: "Riley" });
const root = `/api/companies/${ctx.input.fixtures.company.id}`;
for (const scope of [{ scopeType: "company", scopeId: ctx.input.fixtures.company.id }, ...[worker, privateWorker].map(agent => ({ scopeType: "agent", scopeId: agent.id }))])
await ctx.input.api.post(`${root}/budgets/policies`, { ...scope, amount: 500, hardStopEnabled: true, isActive: true, unpricedUsagePolicy: "allow" });
const p = await project(ctx); const privateMarker = `RESTRICTED-COMMENTARY-${ctx.input.nonce}`;
// The bootstrap person owns the restricted source. Casey is the actual
// nonadmin canonical reader, never its owner or an inherited grant.
const privateProject = await ctx.input.api.post<Entity & { privacyOwnerUserId: string }>(`${root}/projects`, { name: "Restricted launch source", visibility: "private" });
if (privateProject.privacyOwnerUserId !== ownerId) throw new Error("Private feedback source does not retain its actual separate owner");
await ctx.input.api.post(`/api/projects/${privateProject.id}/access-members`, { subjectType: "agent", subjectId: privateWorker.id });
const hidden = await ctx.input.api.post<Entity>(`${root}/issues`, { title: "Restricted feedback prerequisite", projectId: privateProject.id, status: "todo", priority: "medium", assigneeAgentId: privateWorker.id,
description: `Synthetic qualification prerequisite. Submit exactly one sanitized suggestion through the bound submit_suggestion tool, with body: 'Keep run context discoverable (${privateMarker}).' Use a stable idempotency key. Do not expose private task body or quote prompts in feedback. Finish this small prerequisite task after the real tool acknowledgement; no other work is requested.` });
// The prerequisite task scripts the exact feedback text, so the agent
// answering in chat must not be able to read it: only the submitting
// worker and the human reader see this source.
const feedbackSource = await ctx.input.api.post<Entity>(`${root}/projects`, { name: "Agent feedback source", visibility: "private" });
for (const member of [{ subjectType: "agent", subjectId: worker.id }, { subjectType: "user", subjectId: casey.id }])
await ctx.input.api.post(`/api/projects/${feedbackSource.id}/access-members`, member);
const t = await task(ctx, "Synthetic agent feedback prerequisite", feedbackSource.id!, { status: "todo", assigneeAgentId: worker.id,
description: "Synthetic qualification prerequisite. Submit one complaint through the bound submit_complaint tool: 'Tool discovery is hard to scan in a long run.' Submit a separate suggestion through submit_suggestion: 'Keep a compact index of available tools.' These are separate synthetic fixture incidents. Use separate stable idempotency keys; submit only once each. Finish this prerequisite task after the real acknowledgements; do not browse or summarize other agents' feedback." });
const saved = await pollUntil({ label: "Genuine run-bound prior agent suggestions and complaints", deadlineAt: Date.now() + 240_000,
load: async () => { const entries = await ctx.input.api.get<{ items: Feedback[] }>(`${root}/agent-commentary?limit=100`);
return { entries: entries.items, privateEntries: entries.items, runs: await ctx.allRuns() }; },
accept: value => value.runs.length === 2 && value.runs.every(row => row.status === "succeeded")
&& value.entries.filter(row => row.agent.id === worker.id && row.task?.id === t.id).length === 2
&& value.privateEntries.some(row => row.agent.id === privateWorker.id && row.task?.id === hidden.id && row.preview.includes(privateMarker)),
reject: value => value.runs.some(row => ["failed", "cancelled", "timed_out"].includes(row.status)) ? "Actual prerequisite feedback run did not finish; preserve setup evidence" : undefined });
const hiddenEntry = saved.privateEntries.find(row => row.agent.id === privateWorker.id && row.task?.id === hidden.id)!;
for (const source of [t, hidden]) if (![403, 404].includes(await agentStatus(ctx, ctx.input.fixtures.agent.id, `/api/issues/${source.id}`)))
throw new Error("The chat agent can read a task that scripts feedback text; the answer would leak outside commentary access");
key = await ctx.input.api.postSensitive(`/api/agents/${ctx.input.fixtures.agent.id}/keys`, { name: `commentary-read-control-${ctx.input.nonce}` }); ctx.input.privateSecrets.push(key!.token);
await ctx.input.evidence("chat-catalog-genuine-feedback-prerequisites.json", { entries: saved.entries, hiddenEntry, runIds: saved.runs.map(row => row.id) });
readerSession = await installCommentaryReader(ctx, casey, ownerId);
const visible = await ctx.input.api.get<{ items: Feedback[] }>(`${root}/agent-commentary?limit=100`);
const statuses = await Promise.all([`/api/issues/${hidden.id}`, `${root}/agent-commentary/${hiddenEntry.id}`].map(async path => {
const response = await casey!.request(path); await response.body?.cancel(); return response.status;
}));
const initialEntries = saved.entries.filter(row => row.agent.id === worker.id);
if (visible.items.length !== 2 || !initialEntries.every(row => visible.items.some(item => item.id === row.id))
|| !statuses.every(status => [403, 404].includes(status))) throw new Error("Canonical nonadmin reader does not have the intended visible-feedback/private-source boundary");
await ctx.input.evidence("chat-catalog-commentary-reader-prerequisite.json", { ...readerSession.receipt,
visibleEntryIds: visible.items.map(row => row.id), privateTaskStatus: statuses[0], privateFeedbackStatus: statuses[1] });
return { project: p, task: t, worker, privateWorker, privateTask: hidden, privateMarker, initialEntries, hiddenEntry, readerIdentity: readerSession.receipt };
} catch (error) {
try { await readerSession?.restore(); readerSession = undefined;
if (key) { await ctx.input.api.delete(`/api/agents/${ctx.input.fixtures.agent.id}/keys/${key.id}`, { allowNotFound: true }); key = undefined; }
await cleanupPrivacyProbes(ctx);
} finally { await casey.dispose(); casey = undefined; }
throw error;
}
}, gradeAgentFeedback);
return { ...base, oracleVersion: "paperclip.chat-catalog.agent-feedback.v2", authentication: "human-session", expectedRunCount: 3, minimumRunCount: 3, attemptTimeoutMs: 600_000,
sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-agent-feedback.ts", "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts", "chat-catalog-domains/internal-commentary-reader.ts", "chat-run-evidence-observer.ts"],
async observe(ctx, state): Promise<FeedbackObservation> {
if (!key) throw new Error("Feedback read probe was not created during setup"); const o = await observeInternal(ctx, state); const root = `/api/companies/${o.companyId}`;
const hiddenEntry = state.hiddenEntry as Feedback;
const status = async (path: string, agent = false) => { const url = new URL(path, ctx.input.api.baseURL);
const response = agent ? await fetch(url, { redirect: "error", signal: AbortSignal.timeout(15_000), headers: { Authorization: `Bearer ${key!.token}` } })
: await ctx.input.page.context().request.get(url.href);
if (agent) { const result = response as Response; await result.body?.cancel(); return result.status; }
const result = response as import("@playwright/test").APIResponse; const code = result.status(); await result.dispose(); return code; };
const [entries, hiddenDetailStatus, privateTaskStatus, agentReadStatus] = await Promise.all([
ctx.input.api.get<{ items: Feedback[] }>(`${root}/agent-commentary?limit=100`), status(`${root}/agent-commentary/${hiddenEntry.id}`), status(`/api/issues/${entity(state, "privateTask").id}`), status(`${root}/agent-commentary?limit=100`, true),
]);
const source = ctx.issue();
if (!source) throw new Error("Canonical commentary source is missing");
const comments = await ctx.input.api.get<Entity[]>(`/api/issues/${source.id}/comments?order=asc`);
const attribution = commentaryReaderAttribution({ readerId: (state.readerIdentity as { readerId: string }).readerId,
sourceId: source.id, leadId: o.leadId, comments, runs: o.runs });
await ctx.input.evidence("chat-catalog-commentary-canonical-attribution.json", attribution);
return { ...o, entries: entries.items, hiddenEntry, hiddenDetailStatus, privateTaskStatus, agentReadStatus };
},
async verifyResult(ctx, _state, value) {
const o = value as FeedbackObservation; const href = commentaryHref(o); if (!href) throw new Error("Missing actual commentary view link"); const source = ctx.input.page.url();
try {
await ctx.input.page.goto(new URL(href, o.origin).href, { waitUntil: "domcontentloaded" });
const list = ctx.input.page.getByRole("list", { name: "Commentary messages" }); await expect(list).toBeVisible();
for (const row of o.state.initialEntries as Feedback[]) {
await expect(list.getByText(row.preview, { exact: true })).toBeVisible();
await list.getByRole("button", { name: `Read ${row.kind} from ${row.agent.name}`, exact: true }).click();
const detail = ctx.input.page.getByRole("dialog"); await expect(detail).toBeVisible();
await expect(detail.getByText(row.agent.name, { exact: true }).first()).toBeVisible();
await expect(detail.getByRole("link", { name: "View run" })).toHaveAttribute("href", new RegExp(`/agents/${row.agent.id}/runs/${row.runId}$`));
await expect(detail.locator('a[href*="/issues/"]')).toHaveCount(1);
await ctx.input.page.keyboard.press("Escape"); await expect(detail).toHaveCount(0);
}
await expect(ctx.input.page.getByText(String(o.state.privateMarker), { exact: false })).toHaveCount(0);
await ctx.input.evidence("chat-catalog-authorized-human-commentary-opened.json", { url: ctx.input.page.url(), entryIds: (o.state.initialEntries as Feedback[]).map(row => row.id), hiddenExcluded: true });
} finally { await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" }); await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible(); }
},
async cleanup(ctx) { try {
await readerSession?.restore(); readerSession = undefined;
if (key) { await ctx.input.api.delete(`/api/agents/${ctx.input.fixtures.agent.id}/keys/${key.id}`, { allowNotFound: true }); key = undefined; }
await cleanupPrivacyProbes(ctx);
} finally { await casey?.dispose(); casey = undefined; } },
};
}
export const agentFeedbackCases: readonly ChatCatalogCase[] = [agentFeedback()];
export function commentaryReaderAttribution(input: { readerId: string; sourceId: string; leadId: string;
comments: Array<{ id: string; authorUserId?: string | null; authorAgentId?: string | null }>;
runs: Array<{ id: string; agentId: string; responsibleUserId?: string | null; contextSnapshot?: Record<string, unknown> }> }) {
const human = input.comments.filter(row => !row.authorAgentId);
if (human.length !== 1 || human[0]!.authorUserId !== input.readerId) throw new Error("Canonical feedback comment is not attributed to the actual reader");
const sourceRuns = input.runs.filter(row => row.agentId === input.leadId);
if (sourceRuns.some(row => row.responsibleUserId !== input.readerId
|| row.contextSnapshot?.issueId !== input.sourceId || row.contextSnapshot?.commentId !== human[0]!.id))
throw new Error("Canonical feedback execution does not retain its real reader/comment/source attribution");
return { readerId: input.readerId, sourceIssueId: input.sourceId, commentId: human[0]!.id, sourceRunIds: sourceRuns.map(row => row.id) };
}