Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/identity-plan-review.ts
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

252 lines
27 KiB
TypeScript

import { chatCatalogNativePhaseDeadline, chatCatalogNativePhaseIsTimely } from "../chat-catalog-contract.js";
import { expect } from "@playwright/test";
import { createIssueThreadInteractionSchema } from "../../../packages/shared/src/validators/issue.js";
import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js";
import type { IssueWorkProduct } from "../../../packages/shared/src/types/work-product.js";
import type { IssueDocument, IssueDocumentSummary, DocumentRevision } from "../../../packages/shared/src/types/issue.js";
import { pollUntil } from "../api.js";
import { checks, entity, hasLink, putDocument, verifyInternalResult, type Entity } from "./internal-support.js";
import { identityDefinition, identityObservation, identityWorker, observeIdentity, openStandingChat, type Interaction, type IdentityObservation } from "./identity-support.js";
import { turnResponseCards, type TurnResponseCard } from "./turn-response-card.js";
/** A review card that ended the turn returns the draft when it is bound to the draft's exact saved revision on this chat. */
function draftReviewCard(o: IdentityObservation, draft: Entity): TurnResponseCard | undefined {
return turnResponseCards({ companyId: o.companyId, leadId: o.leadId, runs: o.runs, interactions: o.interactions }).find(card => card.kind === "request_confirmation"
&& card.target?.type === "issue_document" && card.target.key === draft.key && card.target.revisionId === draft.latestRevisionId
&& (card.target.issueId === undefined || card.target.issueId === o.state.sourceId));
}
interface PlanInteraction extends Interaction { payload: Interaction["payload"] & { target?: { revisionId?: string } } }
function gradePlanReviewOutcome(value: unknown) {
const c = checks(); const o = identityObservation(value); c.add("complete-versioned-workflow", !!o, "Actual versioned decisions, attributed ordinary work and browser receipts are required."); if (!o) return c.result();
const original = o.state.original as PlanInteraction | undefined; const current = o.interactions.find(row => row.id === original?.id) as PlanInteraction | undefined;
const plan = o.state.plan as Entity | undefined; const saved = o.tasks[0]; const worker = o.state.worker as Entity | undefined;
c.add("same-request-version", !!original && !!current && typeof plan?.latestRevisionId === "string" && JSON.stringify(current.payload) === JSON.stringify(original.payload)
&& original.payload.target?.revisionId === plan?.latestRevisionId,
"The actual current request retains the reviewed source document revision without authorizing another version.");
if (o.scenarioId === "questions-and-approvals.review-plan") {
c.add("ordinary-linked-execution", o.tasks.length === 1 && saved?.companyId === o.companyId && saved.id !== o.state.sourceId && saved.parentId == null
&& saved.assigneeAgentId === worker?.id && hasLink(o, "issues", saved) && o.activity.some(row => row.action === "issue.created" && row.entityId === saved.id && row.agentId === o.leadId)
&& o.state.sourceRetainsConversation === true && o.runs.some(run => run.agentId === worker?.id && (run.contextSnapshot?.issueId === saved.id || (run as unknown as { nativeIssueId?: string }).nativeIssueId === saved.id)),
"The agent creates one linked ordinary task assigned to the real Morgan, whose actual admitted execution is bound to that task; chat remains a conversation.");
c.add("canonical-human-approval-bound", current?.status === "accepted" && current.resolvedByAgentId === o.leadId
&& o.state.sourcePlanRevisionAfter === plan?.latestRevisionId && typeof o.state.canonicalCommentId === "string" && current.result?.commentId === o.state.canonicalCommentId
&& o.activity.some(row => row.action === "issue.thread_interaction_accepted" && row.details?.interactionId === original?.id && row.details?.responseCommentId === o.state.canonicalCommentId),
"The exact canonical conversational approval is attached to the real reviewed revision and decision audit.");
const scopeInBrief = !!saved && `${saved.title} ${saved.description}`.includes(String(o.state.scopeMarker));
const scopeInSavedPlan = !!saved && o.documents.some(doc => doc.issueId === saved.id && doc.key === "plan"
&& (doc.body ?? "").includes(String(o.state.scopeMarker)) && typeof plan?.latestRevisionId === "string"
&& (doc.body ?? "").includes(plan.latestRevisionId) && typeof doc.latestRevisionId === "string"
&& o.revisions.some(revision => revision.id === doc.latestRevisionId && revision.documentId === doc.id
&& o.runs.some(run => run.id === revision.createdByRunId && run.agentId === revision.createdByAgentId
&& (run.agentId === o.leadId || run.agentId === worker?.id
&& (run.contextSnapshot?.issueId === saved.id || (run as unknown as { nativeIssueId?: string }).nativeIssueId === saved.id)))));
c.add("reviewed-scope-handed-off", scopeInBrief || scopeInSavedPlan, "The actual ordinary task retains the approved scope in its brief or an attributed saved plan bound to the reviewed source revision.");
c.add("stale-review-shows-new-version", o.state.staleAttemptStatus === 409 && o.state.staleErrorCode === "interaction_stale_target" && o.state.newerRevisionVisible === true
&& o.state.newerRevisionId !== o.state.staleRevisionId && o.state.staleExpired === true,
"A separately opened real old revision becomes unapprovable after a public edit; the browser shows the actual newer version instead of approving unseen work.");
} else if (o.scenarioId === "questions-and-approvals.reject-and-revise") {
c.add("publication-decision-declined", ["rejected", "superseded"].includes(current?.status ?? "") && !o.activity.some(row => row.action === "issue.thread_interaction_accepted" && row.details?.interactionId === original?.id)
&& o.state.rejectedReceiptVisible === true, "The old publication request remains visibly declined or superseded and is never accepted.");
c.add("real-local-review-draft", o.documents.length > 0 && o.documents.some(row => row.id !== plan?.id && !!row.body?.trim()
&& !!row.latestRevisionId && row.latestRevisionId !== plan?.latestRevisionId && o.revisions.some(revision => revision.id === row.latestRevisionId && revision.documentId === row.id
&& o.runs.some(run => run.id === revision.createdByRunId && run.agentId === revision.createdByAgentId && [o.leadId, worker?.id].includes(run.agentId)))
&& (row.issueId === o.state.sourceId ? o.links.some(link => link.includes(`#document-${encodeURIComponent(row.key!)}`)) || !!draftReviewCard(o, row) : o.tasks.some(task => task.id === row.issueId && hasLink(o, "issues", task))))
&& o.state.sourceRetainsConversation === true && o.state.noPublishedWorkProduct === true,
"The revised scope produces an actual attributed new local document, separate from the declined plan and returned for review by a reply link or by the pending review card that ended the turn bound to its exact saved revision, without a published delivery record. Its wording (including whether it repeats the setup's internal scope tag) and the reply's wording are not graded.");
} else c.add("known-plan-workflow", false, "No oracle exists for this workflow.");
return c.result();
}
interface PlanComment { id: string; authorAgentId?: string | null; authorUserId?: string | null; createdByRunId?: string | null; createdAt?: string; bodyPresent: boolean; matchesQuery: boolean }
const stamp = (value: unknown) => typeof value === "string" ? Date.parse(value) : NaN;
/** Counts every actual turn. A second CEO turn is permitted only as the server's
* distinct, settled completion delivery for this source's exact delegated work. */
/** The first line of rendered text in a Markdown body: block markers, images, link syntax, autolinks, HTML tags and emphasis removed. */
export function markdownFirstLine(body: string) {
return body.split("\n").map(line => line
.replace(/^\s*(?:[#>]+|[-*+]|\d+[.)])\s*/, "")
.replace(/!\[[^\]]*\]\([^)]*\)/g, "")
.replace(/\[([^\]]*)\]\([^)]*\)/g, "$1")
.replace(/<((?:https?:\/\/|mailto:)[^>]+)>/g, "$1")
.replace(/<[^>]+>/g, "")
.replace(/[*_`~]+/g, "")
.trim()).find(Boolean) ?? "";
}
export function planDecisionSourceComplete(value: unknown) {
const o = identityObservation(value); if (!o || typeof o.state.sourceId !== "string" || !o.state.sourceId || !Array.isArray(o.state.planDecisionComments) || !o.runs.length || o.runs.length > 3 || new Set(o.runs.map(run => run.id)).size !== o.runs.length) return false;
const comments = o.state.planDecisionComments as PlanComment[], humans = comments.filter(row => !row.authorAgentId);
if (humans.length !== 1 || typeof o.state.personId !== "string" || humans[0]!.authorUserId !== o.state.personId || humans[0]!.id !== o.state.canonicalCommentId || !humans[0]!.matchesQuery) return false;
if (o.runs.some(run => run.companyId !== o.companyId || run.runtimeMode !== "native" || !["queued", "running", "succeeded"].includes(run.status))) return false;
const ceos = o.runs.filter(run => run.agentId === o.leadId && run.contextSnapshot?.issueId === o.state.sourceId);
const initial = ceos.filter(run => run.contextSnapshot?.commentId === humans[0]!.id);
if (initial.length !== 1 || initial[0]!.status !== "succeeded" || !(stamp(humans[0]!.createdAt) <= stamp(initial[0]!.startedAt))) return false;
const worker = o.state.worker as Entity | undefined;
const others = o.runs.filter(run => !ceos.includes(run));
if (others.length > 1 || others.some(run => run.agentId !== worker?.id || !o.tasks.some(task => task.id === run.contextSnapshot?.issueId && task.companyId === o.companyId && task.assigneeAgentId === worker?.id))) return false;
if (ceos.length === 1) return o.runs.length === ceos.length + others.length;
if (ceos.length !== 2 || others.length !== 1 || others[0]!.status !== "succeeded") return false;
const completion = ceos.find(run => run.id !== initial[0]!.id)!;
const task = o.tasks.find(task => task.id === others[0]!.contextSnapshot?.issueId);
if (!task || task.status !== "done" || completion.status !== "succeeded" || completion.contextSnapshot?.wakeReason !== "chat_task_completed" || completion.contextSnapshot?.wakeSource !== "automation") return false;
const ids = completion.contextSnapshot.chatCompletionDeliveryIds, updates = completion.contextSnapshot.chatCompletionUpdates;
if (!Array.isArray(ids) || ids.length !== 1 || typeof ids[0] !== "string" || !ids[0] || ids[0].length > 240 || !Array.isArray(updates) || updates.length !== 1 || updates[0]?.id !== task.id || updates[0]?.status !== "done") return false;
const completedAt = stamp(updates[0]?.completedAt), initialAt = stamp(initial[0]!.startedAt), workerAt = stamp(others[0]!.startedAt), continuationAt = stamp(completion.startedAt);
if (![completedAt, initialAt, workerAt, continuationAt].every(Number.isFinite) || initialAt > workerAt || workerAt > completedAt || completedAt > continuationAt) return false;
const savedResponse = comments.filter(row => row.authorAgentId === o.leadId && row.createdByRunId === completion.id && row.bodyPresent && stamp(row.createdAt) >= continuationAt);
const savedOutput = o.documents.some(doc => doc.issueId === task.id && !!doc.body?.trim() && !!doc.latestRevisionId
&& o.revisions.some(revision => revision.id === doc.latestRevisionId && revision.documentId === doc.id && revision.createdByRunId === others[0]!.id && revision.createdByAgentId === worker?.id))
|| o.comments.some(comment => comment.companyId === o.companyId && comment.issueId === task.id && comment.authorAgentId === worker?.id && comment.createdByRunId === others[0]!.id && !!comment.body?.trim());
return savedResponse.length === 1 && savedOutput;
}
export function gradePlanReview(value: unknown) {
const base = gradePlanReviewOutcome(value), source = planDecisionSourceComplete(value);
return { passed: base.passed && source, checks: [...base.checks, { id: "original-source-and-optional-completion", passed: source,
detail: "The original human/source/native decision retains all actual runs; an optional second CEO turn needs a unique real completed-worker/output/source-delivery join." }] };
}
function planDecisionWorkReady(o: IdentityObservation) {
const grade = gradePlanReviewOutcome(o), review = o.scenarioId.endsWith("review-plan");
const required = review ? ["same-request-version", "ordinary-linked-execution", "canonical-human-approval-bound", "reviewed-scope-handed-off"] : ["same-request-version", "real-local-review-draft"];
if (!required.every(id => grade.checks.find(check => check.id === id)?.passed)) return false;
if (review) return true;
const current = o.interactions.find(row => row.id === (o.state.original as Entity | undefined)?.id);
return ["rejected", "superseded"].includes(current?.status ?? "") && !o.activity.some(row => row.action === "issue.thread_interaction_accepted" && row.details?.interactionId === current?.id);
}
async function observePlanReview(ctx: ChatCatalogContext, state: Record<string, unknown>) {
const scenarioId = ctx.scenario.id;
const o = await observeIdentity(ctx, state); o.tasks = o.tasks.filter(row => row.id !== state.staleTaskId);
const comments = await ctx.input.api.get<Entity[]>(`/api/issues/${ctx.issue()!.id}/comments?order=asc`);
state.planDecisionComments = comments.map(row => ({ id: row.id, authorAgentId: row.authorAgentId, authorUserId: row.authorUserId,
createdByRunId: row.createdByRunId, createdAt: row.createdAt, bodyPresent: !!row.body?.trim(), matchesQuery: row.body?.trim() === ctx.scenario.query }));
state.canonicalCommentId = comments.find(row => row.authorUserId === state.personId && !row.authorAgentId && row.body?.trim() === ctx.scenario.query)?.id;
state.sourcePlanRevisionAfter = (await ctx.input.api.get<IssueDocument>(`/api/issues/${ctx.issue()!.id}/documents/plan`)).latestRevisionId;
state.sourceRetainsConversation = ctx.issue()?.assigneeAgentId === ctx.input.fixtures.agent.id && ctx.issue()?.status === "in_review" && ctx.issue()?.conversationState === "waiting";
o.documents = [];
o.comments = [];
let published = false;
const documentIssueIds = [...o.tasks.map(task => task.id), ...(scenarioId.endsWith("reject-and-revise") ? [ctx.issue()!.id] : [])];
for (const issueId of documentIssueIds) {
const docs = await ctx.input.api.get<IssueDocumentSummary[]>(`/api/issues/${issueId}/documents`);
const full = await Promise.all(docs.map(doc => ctx.input.api.get<IssueDocument>(`/api/issues/${issueId}/documents/${encodeURIComponent(doc.key)}`)));
if (full.some(doc => doc.companyId !== ctx.input.fixtures.company.id || doc.issueId !== issueId)) throw new Error("Plan document readback escaped the selected source task");
o.documents.push(...full.map(doc => ({ id: doc.id, issueId: doc.issueId, key: doc.key, body: doc.body, latestRevisionId: doc.latestRevisionId ?? undefined })));
}
// Normal task comments are also inspectable saved work; completion does not
// require an unrequested document format. Raw user-facing output remains in
// the protected original so existing privacy/evidence checks still apply.
for (const task of o.tasks) {
const comments = await ctx.input.api.get<Entity[]>(`/api/issues/${task.id}/comments?order=asc`);
if (comments.some(comment => comment.companyId !== ctx.input.fixtures.company.id || comment.issueId !== task.id)) throw new Error("Plan output comment escaped the selected source task");
o.comments.push(...comments);
}
for (const issueId of [ctx.issue()!.id, ...o.tasks.map(task => task.id)]) {
const products = await ctx.input.api.get<IssueWorkProduct[]>(`/api/issues/${issueId}/work-products`);
published ||= products.some(product => !["document", "artifact"].includes(product.type) || product.provider !== "paperclip"
|| product.url != null && new URL(product.url, ctx.input.api.baseURL).origin !== ctx.input.api.baseURL);
}
const revisions = (await Promise.all(o.documents.map(row => ctx.input.api.get<DocumentRevision[]>(`/api/issues/${row.issueId}/documents/${encodeURIComponent(row.key!)}/revisions`)))).flat();
o.revisions = revisions.map(row => ({ id: row.id, documentId: row.documentId, createdByRunId: row.createdByRunId, createdByAgentId: row.createdByAgentId }));
state.noPublishedWorkProduct = !published; return o;
}
/** When Morgan's delegated task finishes inside the attempt, the product wakes the CEO on this chat with a
* completion follow-up. Let that admitted follow-up (graded by planDecisionSourceComplete) settle instead of
* leaving it running at final run custody. A worker still running at the deadline stays bounded active work. */
async function settleDelegatedCompletion(ctx: ChatCatalogContext, state: Record<string, unknown>, originalDeadline: number) {
const deadlineAt = Math.min(originalDeadline - 60_000, Date.now() + 300_000), worker = state.worker as Entity;
let quietSince: number | undefined;
try {
await pollUntil({ label: "Delegated work and its completion follow-up settled", deadlineAt, intervalMs: 1000,
load: async () => ({ observation: await observePlanReview(ctx, state), source: ctx.issue() }),
accept: ({ observation: o, source }) => {
const workerRuns = o.runs.filter(run => run.agentId === worker.id), ceos = o.runs.filter(run => run.agentId === o.leadId);
const settled = source?.conversationState === "waiting" && o.runs.every(run => run.status === "succeeded") && workerRuns.length === 1;
if (!settled) { quietSince = undefined; return false; }
if (ceos.length === 2) return planDecisionSourceComplete(o);
quietSince ??= Date.now();
return Date.now() - quietSince >= 30_000;
},
reject: ({ observation: o }) => o.runs.length > 3 || o.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Delegated plan work failed or admitted excess native work" : undefined });
} catch (error) {
if (error instanceof Error && /failed or admitted excess/.test(error.message)) throw error;
}
}
const sources = ["chat-catalog-domains/identity-plan-review.ts", "chat-catalog-domains/identity-support.ts", "chat-catalog-domains/internal-support.ts", "chat-scenarios/questions-and-approvals.yaml"];
export const planReviewIdentityCases: readonly ChatCatalogCase[] = ["questions-and-approvals.review-plan", "questions-and-approvals.reject-and-revise"].map(scenarioId => identityDefinition(scenarioId, async ctx => {
const source = await openStandingChat(ctx); const worker = await identityWorker(ctx); const session = await ctx.input.api.get<{ user: { id: string } }>("/api/auth/get-session");
if (!session.user?.id) throw new Error("Plan review requires its actual responsible human session"); const review = scenarioId.endsWith("review-plan");
const scopeMarker = `Acorn research launch ${ctx.input.nonce}`;
const plan = await putDocument(ctx, source.id, `# ${scopeMarker}\n${review ? "Create a local implementation checklist for a research notes website. Begin the assigned checklist work after the current plan revision is approved." : "Proposed action: publish the research notes introduction page. Its subject is a research notebook product for small science teams."}\nUse the exact project context ${scopeMarker}.`);
const original = await ctx.input.api.post<PlanInteraction>(`/api/issues/${source.id}/interactions`, createIssueThreadInteractionSchema.parse({ kind: "request_confirmation", title: review ? "Approve current research launch plan" : "Publish research launch introduction",
resolverPolicy: "anyone", continuationPolicy: "none", payload: { version: 1, prompt: review ? "Approve the current plan and start its linked ordinary work?" : "Publish the proposed introduction page?",
detailsMarkdown: `Review the actual attached plan revision ${plan.latestRevisionNumber}. ${review ? "Approval hands off one ordinary task to Morgan, not the conversation." : "A different requested draft scope must decline this publication proposal and create a local review draft instead. Publication requires a separate explicit accepted decision."}`,
supersedeOnUserComment: false, target: { type: "issue_document", issueId: source.id, documentId: plan.id, key: "plan", revisionId: plan.latestRevisionId, revisionNumber: plan.latestRevisionNumber } } }));
await ctx.input.page.reload({ waitUntil: "domcontentloaded" }); return { sourceId: source.id, personId: session.user.id, worker, plan, original, scopeMarker };
}, gradePlanReview, {
sourceFiles: [...sources, "../../server/src/services/chat-completion-delivery.ts", "chat-catalog-domains/turn-response-card.ts"], authentication: "human-session", oracleVersion: "paperclip.chat-catalog.plan-review.v7", expectedRunCount: 3, minimumRunCount: scenarioId.endsWith("review-plan") ? 2 : 1, attemptTimeoutMs: 600_000,
runPolicy: { kind: "source-settled-with-active-work", maximumActiveWorkerRuns: 1 },
async act(ctx, state) {
const originalDeadline = ctx.observationDeadlineAt;
if (!Number.isFinite(originalDeadline) || originalDeadline! <= Date.now()) throw new Error("Original plan-review observation budget exhausted or missing");
const deadlineAt = Math.min(chatCatalogNativePhaseDeadline(ctx, Date.now() + 180_000), originalDeadline!);
await pollUntil({ label: "Plan decision source settled", deadlineAt,
load: async () => ({ observation: await observePlanReview(ctx, state), source: ctx.issue() }),
accept: value => Date.now() < deadlineAt && chatCatalogNativePhaseIsTimely(ctx) && value.source?.conversationState === "waiting"
&& planDecisionSourceComplete(value.observation) && planDecisionWorkReady(value.observation),
reject: value => value.observation.runs.length > 3 || value.observation.runs.some(run => ["failed", "cancelled", "timed_out"].includes(run.status)) ? "Plan decision contains failed, cancelled or excess native work" : undefined });
const original = entity(state, "original");
if (scenarioId.endsWith("reject-and-revise")) {
// A rejected plan-target confirmation renders as requested changes in
// both the classic receipt ("Requested changes to Plan v1") and the
// Coordinator receipt ("Changes requested · v1"); the saved status is
// graded separately as rejected or superseded.
const card = ctx.input.page.locator(`#interaction-${original.id}`);
await expect(card).toContainText(/Declined|Superseded|Changes requested|Requested changes/i); await expect(card).not.toContainText(/Approved/i); state.rejectedReceiptVisible = true; return;
}
// A separate additional review opens before its actual public document edit.
// The first canonical approval's source plan is never rewritten by this check.
const target = await ctx.input.api.post<Entity>(`/api/companies/${ctx.input.fixtures.company.id}/issues`, { title: "Separate stale review fixture", status: "backlog" });
state.staleTaskId = target.id;
const old = await putDocument(ctx, target.id, "Old review: unrestricted publication.");
const stale = await ctx.input.api.post<Interaction>(`/api/issues/${target.id}/interactions`, createIssueThreadInteractionSchema.parse({ kind: "request_confirmation", title: "Review before edit", resolverPolicy: "human_only", continuationPolicy: "none",
payload: { version: 1, prompt: "Approve the currently opened older review?", supersedeOnUserComment: false, target: { type: "issue_document", issueId: target.id, documentId: old.id, key: "plan", revisionId: old.latestRevisionId, revisionNumber: old.latestRevisionNumber } } }));
const current = await putDocument(ctx, target.id, "Newer review: local draft only, do not publish.", old.latestRevisionId!);
const response = await ctx.input.page.context().request.post(`${ctx.input.api.baseURL}/api/issues/${target.id}/interactions/${stale.id}/accept`, { data: {}, headers: { Origin: ctx.input.api.baseURL } });
state.staleAttemptStatus = response.status(); const body = await response.json() as { code?: string; details?: { code?: string } }; state.staleErrorCode = body.details?.code ?? body.code;
state.staleRevisionId = old.latestRevisionId; state.newerRevisionId = current.latestRevisionId;
const interactions = await ctx.input.api.get<Interaction[]>(`/api/issues/${target.id}/interactions`); state.staleExpired = interactions.find(row => row.id === stale.id)?.status === "expired";
const source = ctx.input.page.url(); await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${target.identifier ?? target.id}`, { waitUntil: "domcontentloaded" });
// The supported plan deep link expands the real current document, not text fabricated by the harness.
await ctx.input.page.goto(`/${ctx.input.fixtures.company.issuePrefix}/issues/${target.identifier ?? target.id}#document-plan&viewer=full`, { waitUntil: "domcontentloaded" });
await expect(ctx.input.page.getByText("Newer review: local draft only, do not publish.", { exact: false }).first()).toBeVisible(); state.newerRevisionVisible = true;
await ctx.input.page.goto(source, { waitUntil: "domcontentloaded" });
await ctx.input.evidence("identity-stale-plan-review.json", { oldRevisionId: old.latestRevisionId, newRevisionId: current.latestRevisionId, staleAttemptStatus: state.staleAttemptStatus, staleErrorCode: state.staleErrorCode, newerRevisionVisible: true });
await settleDelegatedCompletion(ctx, state, originalDeadline!);
},
observe: observePlanReview,
async verifyResult(ctx, state, value) {
const o = identityObservation(value);
if (scenarioId.endsWith("review-plan") || o?.tasks.length) { await verifyInternalResult(ctx, state, value); return; }
const plan = state.plan as Entity | undefined;
const saved = (row: Entity) => row.id !== plan?.id && !!row.body?.trim() && !!o?.revisions.some(revision => revision.id === row.latestRevisionId && revision.documentId === row.id && revision.createdByRunId);
const doc = o?.documents.find(row => saved(row) && o.links.some(link => link.includes(`#document-${encodeURIComponent(row.key!)}`)));
const card = !doc && o ? o.documents.filter(saved).map(row => ({ row, card: draftReviewCard(o, row) })).find(entry => !!entry.card) : undefined;
if (doc) {
const href = await ctx.input.page.locator('[id^="comment-"] a[href]').evaluateAll(links => links.map(link => link.getAttribute("href")!));
const reviewLink = href.find(link => link.includes(`#document-${encodeURIComponent(doc.key!)}`));
if (!reviewLink) throw new Error("Actual draft review link missing from reply");
await ctx.input.page.locator(`[id^="comment-"] a[href=${JSON.stringify(reviewLink)}]`).first().click();
} else if (card) {
// The person opens the pending review request and follows its document link, as in the product.
const takeover = ctx.input.page.getByTestId("task-chat-composer-takeover");
if (!await takeover.isVisible()) await ctx.input.page.locator(`#interaction-${card.card!.id}`).first().click();
await takeover.locator(`a[href*=${JSON.stringify(`#document-${encodeURIComponent(card.row.key!)}`)}]`).first().click();
} else throw new Error("Actual local review draft is missing");
const opened = doc ?? card!.row;
// The opened view must show the saved draft itself: its first line of text.
const firstLine = markdownFirstLine(opened.body!);
await expect(ctx.input.page.getByText(firstLine, { exact: false }).first()).toBeVisible();
},
}));