mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-23 13:13:46 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - The chat eval catalog checks real chat journeys against saved
product state, not reply wording
> - Full cohort 11 (OpenCode with DeepSeek v4.1 Flash, master
d16becac04) failed five cases where the agent behaved correctly
> - Four graders read the reply or question wording with keyword checks,
and one harness locator hit a duplicate DOM id that the product rendered
> - Keyword checks reject true replies and accept false ones, so they do
not measure the product
> - This pull request grades those cases on saved state, setup literals
and rendered links, and makes the interaction DOM id unique
> - The benefit is that these five cases measure the product again, and
each one still fails a broken product
## Linked Issues or Issue Description
**What happened?**
In full cohort 11, five cases failed for eval or product-markup reasons:
- `cases.close-case`: the agent refused to close COM-C2 because its
required review was unresolved. COM-C2 stayed open, as the setup
intends. A keyword regex did not match "could not close" and failed the
case.
- `steering.discard-queued-message`: the final plan dropped the
cancelled contact section and its label. The grader required that the
earlier section was a Markdown heading. The agent saved the label as a
plain line, so the check failed.
- `cases.cases-disabled`: the agent asked a correct question card. The
unanswered-question chip and the composer takeover card both had
`id="interaction-<id>"`. The harness locator hit Playwright strict mode.
The harness also matched the question wording with regexes.
- `companies.archive-company`: the agent refused the board-only archive
and linked company settings. A `/restore/` regex did not match
"restoring".
- `tasks.ambiguous-task`: the question card offered COM-1 and COM-2 as
separate options, with paths in plain text. The grader required rendered
links to both tasks.
**Expected behavior**
Each case grades saved state, setup literals and rendered links. Reply
meaning is left to human review. The page has one element for each DOM
id.
**Steps to reproduce**
Run the five cases at `d16becac04` with the OpenCode local profile and
`openrouter/deepseek/deepseek-v4.1-flash-1017`.
## What Changed
- `ui/.../TaskChatInteractionCard.tsx`: only the timeline item has the
`interaction-<id>` page anchor. The composer takeover card has no id.
Every variant has `data-interaction-id`.
- Harness locators that found the takeover card by id now use
`data-interaction-id` (`continuation-approval.ts`, `runner.spec.ts`,
`external-secret-proposal.ts`, `external-company-secret.ts`,
`external-team-configure.ts`, and their fixtures).
- `integrator-case-close.ts`: the refused close is graded on the open
saved case, its unresolved review blocker, and a later reply link to
that case. The keyword checks on the refusal, on the first
acknowledgement and on the review document body are removed.
- `runtime-discard.ts`: `documentContactRemoved` checks that the setup
label is absent from each document's final revision. The heading check
is removed. The consuming run must still have saved the label.
- `integrator-cases.ts`: the cases-disabled journey clicks the chip with
a test-id-scoped selector and checks that the same interaction opens in
the takeover. The wording regexes are removed. The grader and the
journey share one rule for a pending choice card.
- `identity-company-lifecycle.ts`: the archive guidance check uses saved
state. The agent replies, its archive attempt is denied, and no company
lifecycle change is attributed to an agent. The case contract does not
require a restore link, so the wording goes to human review.
- `chat-linked-question.ts` and `internal-tasks.ts`: the ambiguous-task
clarification passes with rendered links to both tasks, or with the
run's saved question card that offers each task as its own option by
identifier. Options render inside choice buttons, which cannot hold
links.
- `chat-catalog-descriptors.json`: oracle versions for the five cases.
## Verification
- Red/green unit tests for each fix. Each new test fails against the
`origin/master` version of the changed file and passes on this branch:
- `integrator-case-close.test.ts`, `runtime-discard.test.ts`,
`integrator-cases-locator.test.ts`,
`identity-company-lifecycle.test.ts`,
`chat-linked-question-grade.test.ts`
- `ui/src/components/task-chat/TaskChatInteractionCard.test.tsx` ("keeps
the interaction id unique ...")
- Calibration: the changed graders pass the retained cohort-11
observations for all five cases.
- `pnpm check:token-gates`, `node scripts/typecheck-test-projects.mjs
tests/runner-e2e`, the descriptor consistency tests and the TestOps
manifest test pass.
- A narrow paid run of the five full case ids on this branch. The result
is in a comment on this pull request.
## Risks
- Low risk for the product. The composer takeover card loses its DOM id.
Page anchors (`#interaction-<id>`) already resolve to the timeline item.
Harness code that used the takeover id now uses `data-interaction-id`.
- The graders accept more reply wordings. Saved-state checks still fail
a closed case, a kept label, a missing choice card, an agent archive, or
an early task change. Reply meaning needs human review.
- `steering.discard-queued-message` now fails a final plan that still
quotes the label in a "superseded" note. The setup label is the
discarded content.
## Model Used
- Claude (Anthropic), model ID `claude-opus-5-5`, used through Claude
Code with tool use and code execution.
## 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>
127 lines
12 KiB
TypeScript
127 lines
12 KiB
TypeScript
import type { IssueThreadInteraction } from "../../../packages/shared/src/types/issue.js";
|
|
import type { cases } from "../../../packages/db/src/schema/cases.js";
|
|
import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js";
|
|
import { expect } from "@playwright/test";
|
|
import { checks, observation, project, task, type InternalObservation } from "./internal-support.js";
|
|
import { integratorDefinition, inspectResult, resultHref, observeInternal } from "./integrator-support.js";
|
|
type CaseRecord = typeof cases.$inferSelect;
|
|
interface CasesObservation extends InternalObservation { cases: CaseRecord[]; casesEnabled: boolean; casesReadStatus: number; casesReadError?: string; interactions?: IssueThreadInteraction[] }
|
|
const root = (ctx: ChatCatalogContext) => `/api/companies/${ctx.input.fixtures.company.id}`;
|
|
async function observeCases(ctx: ChatCatalogContext, state: Record<string, unknown>): Promise<CasesObservation> {
|
|
const base = await observeInternal(ctx, state);
|
|
const settings = await ctx.input.api.get<{ enableCases: boolean }>("/api/instance/settings/experimental");
|
|
const response = await ctx.input.page.request.get(`${root(ctx)}/cases?limit=200`);
|
|
const interactions = ctx.issue() ? await ctx.input.api.get<IssueThreadInteraction[]>(`/api/issues/${ctx.issue()!.id}/interactions`) : [];
|
|
return { ...base, interactions, casesEnabled: settings.enableCases, casesReadStatus: response.status(), cases: response.ok() ? await response.json() : [], casesReadError: response.ok() ? undefined : (await response.json() as { error?: string }).error };
|
|
}
|
|
function caseObservation(value: unknown): CasesObservation | undefined {
|
|
const o = value as CasesObservation;
|
|
return observation(value) && Array.isArray(o.cases) && typeof o.casesEnabled === "boolean" && typeof o.casesReadStatus === "number" ? o : undefined;
|
|
}
|
|
export function gradeIntegratorCases(value: unknown) {
|
|
const c = checks(); const o = caseObservation(value);
|
|
c.add("public-case-and-task-evidence", !!o, "Requires public case response/status, actual experiment state, task and audit evidence.");
|
|
if (!o) return c.result();
|
|
if (o.scenarioId === "cases.cases-disabled") {
|
|
c.add("disabled-route-remains-disabled", !o.casesEnabled && o.casesReadStatus === 403 && o.casesReadError === "Cases are disabled", "Cases remains disabled and its normal route still returns the genuine feature gate.");
|
|
c.add("no-silent-case-or-task-creation", !o.activity.some(event => event.agentId === o.leadId && /^(?:case\.|issue\.created)/.test(event.action ?? "")) && o.tasks.length === 0, "No case or task is created before the person makes the consequential choice.");
|
|
// The choice is graded by structure: a reply link to the page where Cases is enabled (opened by the scripted
|
|
// person in verifyCases), or a pending question card offering choices. Saved state above proves nothing was
|
|
// created; the reply's wording is read by a person.
|
|
c.add("truthful-availability-and-choice", !!experimentalSettingsHref(o) || pendingChoices(o).length > 0,
|
|
"The reply links the Experimental settings page where an authorized person can enable Cases, or ends on a pending choice card; no case or task exists until the person chooses.");
|
|
} else if (o.scenarioId === "cases.browse-cases") {
|
|
const expected = o.state.openCases as CaseRecord[] | undefined; const excluded = o.state.excludedCases as CaseRecord[] | undefined;
|
|
c.add("original-filter-fixtures", Array.isArray(expected) && Array.isArray(excluded) && new Set([...expected, ...excluded].map(row => row.id)).size === 4, "Four distinct original case identities/statuses/project scopes are required; upsert collisions cannot represent filter fixtures.");
|
|
if (!Array.isArray(expected) || !Array.isArray(excluded)) return c.result();
|
|
c.add("real-project-and-case-status", o.casesEnabled && o.casesReadStatus === 200 && expected.length === 2
|
|
&& expected.every(before => o.cases.some(now => now.id === before.id && now.status === before.status && now.projectId === before.projectId))
|
|
&& o.tasks.some(row => row.id === (o.state.finishedTask as { id: string } | undefined)?.id && row.status === "done"), "Two actual open Launch cases remain open even when related task work is done.");
|
|
// Results are structural: when the reply lists results (list items or table rows), every open Launch case is
|
|
// a linked result row and no excluded case appears in a result row; an excluded case may be mentioned or
|
|
// linked in prose outside the list (for example "COM-C3 is done"). Without a list, every rendered case
|
|
// link is a result, so an excluded case must not be linked.
|
|
const resultRows = o.reply.split("\n").filter(line => /^\s*(?:[-*+]|\d+[.)]|\|)\s*/.test(line));
|
|
const inRow = (row: CaseRecord) => resultRows.some(line => line.includes(row.title) || (!!row.identifier && new RegExp(`(?<![\\w-])${row.identifier}(?![\\w-])`).test(line)));
|
|
const listed = expected.every(inRow);
|
|
c.add("exact-filtered-case-results", expected.every(row => !!caseHref(o, row)) && excluded.every(row => !inRow(row) && (listed || !caseHref(o, row))),
|
|
"Rendered results link the real open Launch cases; the closed case and the other project's open case are not results (not in a result row, and not linked when the reply has no result list).");
|
|
c.add("read-does-not-mutate-cases-or-columns", !o.activity.some(event => event.agentId === o.leadId && /^case\./.test(event.action ?? ""))
|
|
&& !/\b(?:changed|saved|updated|reordered)\b[^.!?\n]{0,45}\b(?:columns?|board layout)\b/i.test(o.reply), "Browsing does not mutate case records or claim browser-only presentation changes.");
|
|
} else c.add("owned-case-oracle", false, "No independent oracle exists for this case scenario.");
|
|
return c.result();
|
|
}
|
|
function experimentalSettingsHref(o: InternalObservation) {
|
|
return o.links.find(href => { try { const url = new URL(href, o.origin); return url.origin === new URL(o.origin).origin && /\/company\/settings\/instance\/experimental\/?$/.test(url.pathname); } catch { return false; } });
|
|
}
|
|
/** Pending question cards that offer the person a real choice. */
|
|
function pendingChoices(o: CasesObservation) {
|
|
return (o.interactions ?? []).filter(card => card.kind === "ask_user_questions" && card.status === "pending"
|
|
&& card.payload.questions?.some(question => (question.options?.length ?? 0) >= 2));
|
|
}
|
|
/** The timeline chip for one pending question; the docked takeover card shows the same interaction. */
|
|
export function unansweredQuestionSelector(interactionId: string) {
|
|
return `[data-testid="task-chat-unanswered-question"][id=${JSON.stringify(`interaction-${interactionId}`)}]`;
|
|
}
|
|
function caseHref(o: InternalObservation, row: Pick<CaseRecord, "id" | "identifier">) { return resultHref(o, row.id, "cases") ?? resultHref(o, row.identifier, "cases"); }
|
|
async function verifyCases(ctx: ChatCatalogContext, _state: Record<string, unknown>, value: unknown) {
|
|
const o = caseObservation(value); if (!o) throw new Error("Missing case UI observation");
|
|
if (!o.casesEnabled) {
|
|
if (!o.reply && o.interactions?.length) {
|
|
// The person opens the saved choice from its timeline chip and sees that same card docked in the composer.
|
|
// The question's wording is left to human review.
|
|
const choices = pendingChoices(o);
|
|
if (choices.length !== 1) throw new Error("Missing unambiguous pending choice card in real UI");
|
|
const request = ctx.input.page.locator(unansweredQuestionSelector(choices[0]!.id));
|
|
await expect(request).toBeVisible(); await request.click();
|
|
await expect(ctx.input.page.getByTestId("task-chat-composer-takeover").locator(`[data-interaction-id=${JSON.stringify(choices[0]!.id)}]`)).toBeVisible();
|
|
}
|
|
const settings = experimentalSettingsHref(o);
|
|
if (settings) {
|
|
// The person follows the reply's own link and finds the Cases control there.
|
|
const source = ctx.input.page.url(), link = ctx.input.page.locator(`[id^="comment-"] a[href=${JSON.stringify(settings)}]`).first();
|
|
await expect(link).toBeVisible(); await link.click();
|
|
await expect(ctx.input.page).toHaveURL(url => url.pathname.endsWith("/company/settings/instance/experimental"));
|
|
await expect(ctx.input.page.getByText("Cases", { exact: true }).first()).toBeVisible();
|
|
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
|
|
}
|
|
await expect(ctx.input.page.getByTestId("task-chat-composer-input")).toBeVisible(); return;
|
|
}
|
|
for (const row of o.state.openCases as CaseRecord[]) {
|
|
const href = caseHref(o, row); if (!href) throw new Error("No actual open case link");
|
|
const pathname = new URL(href, o.origin).pathname;
|
|
await inspectResult(ctx, pathname, row.title, href);
|
|
}
|
|
}
|
|
const previousExperiments = new WeakMap<ChatCatalogContext, boolean>();
|
|
function define(id: string, enabled: boolean, setup: ChatCatalogCase["setup"]): ChatCatalogCase {
|
|
return integratorDefinition("cases", id, async ctx => {
|
|
const previous = await ctx.input.api.get<{ enableCases: boolean }>("/api/instance/settings/experimental");
|
|
previousExperiments.set(ctx, previous.enableCases);
|
|
try { await ctx.input.api.patch("/api/instance/settings/experimental", { enableCases: enabled }); return await setup(ctx); }
|
|
catch (error) { await ctx.input.api.patch("/api/instance/settings/experimental", { enableCases: previous.enableCases }); previousExperiments.delete(ctx); throw error; }
|
|
}, observeCases, gradeIntegratorCases, verifyCases, { async cleanup(ctx) {
|
|
const previous = previousExperiments.get(ctx); if (previous !== undefined) { await ctx.input.api.patch("/api/instance/settings/experimental", { enableCases: previous }); previousExperiments.delete(ctx); }
|
|
} });
|
|
}
|
|
export const integratorCasesCases: readonly ChatCatalogCase[] = [
|
|
{ ...define("cases.cases-disabled", false, async ctx => {
|
|
await ctx.input.api.post(`/api/companies/${ctx.input.fixtures.company.id}/chats/${ctx.input.fixtures.agent.id}`);
|
|
await ctx.refreshIssue();
|
|
if (!ctx.issue()) throw new Error("Customer bug context requires its actual standing conversation");
|
|
await ctx.input.api.patch(`/api/issues/${ctx.issue()!.id}`, { description: "Customer bug: the checkout button stops responding on mobile Safari after a trial item and a test address are entered. The person is asking about this bug." });
|
|
return {};
|
|
}), oracleVersion: "paperclip.chat-catalog.cases-disabled.structural.v2" },
|
|
{ ...define("cases.browse-cases", true, async ctx => {
|
|
const launch = await project(ctx, "Launch"); const other = await project(ctx, "Research");
|
|
const create = (title: string, projectId: string, status: string) => ctx.input.api.post<CaseRecord>(`${root(ctx)}/cases`, { caseType: "customer", key: `browse-${ctx.input.nonce}-${title.toLowerCase().replace(/[^a-z0-9]+/g, "-")}`, title, projectId, status });
|
|
const open = await create("Mobile checkout failure", launch.id, "in_progress"); const second = await create("Keyboard focus loss", launch.id, "in_review");
|
|
const closed = await create("Resolved image clipping", launch.id, "done"); const elsewhere = await create("Research signup failure", other.id, "in_progress");
|
|
const finishedTask = await task(ctx, "Initial customer diagnosis", launch.id, { status: "done" });
|
|
await ctx.input.api.post(`/api/cases/${open.id}/links`, { issueId: finishedTask.id, role: "work" });
|
|
const saved = await ctx.input.api.get<CaseRecord[]>(`${root(ctx)}/cases?limit=200`);
|
|
if (new Set([open, second, closed, elsewhere].map(row => row.id)).size !== 4 || ![open, second, closed, elsewhere].every(row => saved.some(now => now.id === row.id && now.status === row.status && now.projectId === row.projectId))) throw new Error("Case browsing setup did not retain four distinct scoped status records");
|
|
return { project: launch, openCases: [open, second], excludedCases: [closed, elsewhere], finishedTask };
|
|
}), oracleVersion: "paperclip.chat-catalog.cases-browse.structural.v3" },
|
|
];
|