Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/external-assistant-scoped.ts
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

70 lines
15 KiB
TypeScript

import { randomUUID } from "node:crypto";
import { expect } from "@playwright/test";
import type { ChatCatalogContext, ChatCompanionResult } from "../chat-catalog-contract.js";
import type { McpConnection } from "../../../packages/shared/src/public-mcp.js";
import { connect,mcp,type Tokens,type ToolResult } from "../public-mcp-client.js";
import { prepareAssistantSetup } from "./external-assistant-connections.js";
import { runScopedCompanion,companionBounds } from "./external-assistant-model.js";
import { definition,root,checks,externalObservation,observeExternal } from "./external-support.js";
import { identityWorker } from "./identity-support.js";
interface Fixture {tokens:Tokens;client:Awaited<ReturnType<typeof mcp>>;grantId:string;controlId?:string;otherCompanyId?:string}
const fixtures=new WeakMap<ChatCatalogContext,Fixture>();
function deniedAuthority(result:ToolResult){return result.isError===true&&result.content.some(row=>row.type==="text"&&/HTTP 403|paperclip:write permission is required/.test(row.text??""));}
function sourceTaskId(result:ToolResult){return (result.structuredContent?.task as {id?:string}|undefined)?.id;}
async function dispose(ctx:ChatCatalogContext){const fixture=fixtures.get(ctx);fixtures.delete(ctx);if(!fixture)return;try{await fixture.client.close();await ctx.input.api.delete(`/api/mcp/connections/${fixture.grantId}`,{allowNotFound:true});if(fixture.controlId)await ctx.input.api.delete(`/api/issues/${fixture.controlId}`,{allowNotFound:true});if(fixture.otherCompanyId)await ctx.input.api.delete(`/api/companies/${fixture.otherCompanyId}`,{allowNotFound:true});}finally{/* Whole disposable company cleanup owns a legitimately created target task. */}}
export function gradeScopedAssistant(value:unknown){
const c=checks(),o=externalObservation(value);c.add("complete-real-external-assistant-evidence",!!o,"The exact external-model query, actual model-selected MCP mutation, independent task/actor evidence and scope controls are required.");if(!o)return c.result();
const result=o.state.companionSurfaceResult as ChatCompanionResult|undefined;
c.add("real-model-canonical-surface",!!result&&result.query==="Create a website task for Morgan in Acorn."&&result.model===companionBounds.model&&result.providerResponseIds.length>0&&result.providerResponseIds.length<=6&&result.usage.inputTokens>0&&result.usage.outputTokens>0&&result.usage.outputTokens<=2048&&result.messages.filter(row=>row.role==="user").length===1&&result.messages.find(row=>row.role==="user")?.content===result.query&&o.runs.length===0,"A real bounded external model receives the original query as its sole human input; no Agent Chat or native run substitutes.");
c.add("effective-task-creation-only-prerequisite",o.state.createCapabilityListed===true&&o.state.commentDenied===true&&o.state.updateDenied===true&&o.state.controlUnchanged===true&&o.state.directRestStatus===401&&o.state.crossCompanyDenied===true&&o.state.otherCompanyTaskCount===0&&o.state.morganPaused===true,"Supported catalog and actual denied control operations prove scope before model dispatch; a broad write grant is never labelled creation-only.");
const created=o.state.createdTasks as Array<{id:string;companyId:string;title:string;assigneeAgentId:string;identifier?:string}>|undefined,task=created?.[0],calls=result?.toolCalls.filter(row=>row.name==="paperclip_create_task")??[];
c.add("actual-model-created-one-intended-task",created?.length===1&&!!task&&task.companyId===o.companyId&&task.assigneeAgentId===o.state.morganId&&/website/i.test(task.title)&&calls.length>=1&&calls.length<=4&&new Set(calls.map(row=>(row.arguments as {requestId?:string})?.requestId)).size===1&&calls.every(row=>/^[a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[89ab][a-f0-9]{3}-[a-f0-9]{12}$/i.test(String((row.arguments as {requestId?:string})?.requestId)))&&calls.every(row=>{const args=row.arguments as {companyId?:string;assigneeAgentId?:string};return args.companyId===o.companyId&&args.assigneeAgentId===o.state.morganId&&sourceTaskId(row.result as ToolResult)===task.id;}),"The model-selected tool call creates exactly one real Website task for the actual Morgan in Acorn, preserving idempotent uncertainty semantics.");
c.add("connected-human-mutation-attribution",!!task&&o.activity.some(row=>row.entityId===task.id&&row.actorType==="user"&&row.actorId===o.state.connectedUserId&&row.action==="issue.created")&&o.activity.some(row=>row.entityId===o.state.grantId&&row.action==="mcp.tool_called"&&row.actorType==="user"&&row.actorId===o.state.connectedUserId),"Independent durable product activity attributes creation to the connected person and selected MCP grant.");
c.add("actual-task-link-and-honest-queue",!!task&&!!result&&result.links.some(link=>{try{const url=new URL(link,o.origin);return url.origin===o.origin&&url.pathname.startsWith(`/${o.state.companyPrefix}/issues/`)&&url.pathname.split("/").some((part,i,parts)=>part==="issues"&&[task.id,task.identifier].includes(parts[i+1]));}catch{return false;}})&&!/\b(?:Morgan|the agent)\s+(?:is|has)\s+(?:already\s+)?(?:running|started|working|building)\b/i.test(result.reply),"The actual model returns its durable task link without claiming paused Morgan has begun execution.");
c.add("private-grant-and-provider-bytes-absent",o.state.privateScanComplete===true&&o.state.privateLeaked===false,"Owning raw transcript and tool observations are scanned against selected credential values before evidence redaction.");return c.result();
}
export const scopedAssistantExternalCases=[definition("assistant-connections.use-scoped-client",async ctx=>{
await prepareAssistantSetup(ctx);if(!ctx.input.privateInputs?.credentials.OPENAI_API_KEY)throw new Error("Setup blocker: selected OPENAI_API_KEY reference is missing for the real companion model");
await ctx.input.api.patch(root(ctx),{name:"Acorn"});const morgan=await identityWorker(ctx);await ctx.input.api.post(`/api/agents/${morgan.id}/pause`);
const paused=await ctx.input.api.get<{id:string;status:string}>(`/api/agents/${morgan.id}`);if(paused.status!=="paused")throw new Error("Setup blocker: exact disposable Morgan pause was not retained");
const source=ctx.input.page.url(),authorized=await connect(ctx.input.page.context(),{...ctx.input.fixtures.company,name:"Acorn",issuePrefix:ctx.input.fixtures.company.issuePrefix??"ACORN"},true,ctx.input.page,ctx.input.privateSecrets!);
const client=await mcp(authorized.tokens);let fixture:Fixture|undefined;
try{
const identity=await client.call("paperclip_connection"),grantId=identity.structuredContent?.connectionId,connectedUserId=(identity.structuredContent?.user as {id?:string}|undefined)?.id;if(typeof grantId!=="string"||!connectedUserId||identity.structuredContent?.companyId!==ctx.input.fixtures.company.id)throw new Error("Setup blocker: real consent did not bind this person and Acorn");
fixture={tokens:authorized.tokens,client,grantId};fixtures.set(ctx,fixture);
const metadata=await fetch(new URL("/.well-known/oauth-authorization-server",ctx.input.api.baseURL),{redirect:"error",signal:AbortSignal.timeout(15000)});if(!metadata.ok)throw new Error("Setup blocker: current public capability metadata is unavailable");const supported=await metadata.json() as {scopes_supported?:string[]};
const catalog=await client.list(),createCapabilityListed=catalog.tools.some(tool=>tool.name==="paperclip_create_task");
const control=await ctx.input.api.post<{id:string;title:string;description:string}>(`${root(ctx)}/issues`,{title:"Immutable external scope control",description:"Disposable scope control; no canonical task is pre-created.",status:"backlog"});fixture.controlId=control.id;
const visible=await client.call("paperclip_read_task",{companyId:ctx.input.fixtures.company.id,taskId:control.id});if(visible.isError||sourceTaskId(visible)!==control.id)throw new Error("Setup blocker: scope control is not readable by the connected identity");
const beforeComments=await ctx.input.api.get<Array<{id:string}>>(`/api/issues/${control.id}/comments?order=asc`);
const update=await client.call("paperclip_update_task",{companyId:ctx.input.fixtures.company.id,taskId:control.id,requestId:randomUUID(),changes:{title:control.title}}),comment=await client.call("paperclip_add_comment",{companyId:ctx.input.fixtures.company.id,taskId:control.id,requestId:randomUUID(),body:"Scope denial control; this must not be accepted by a task-creation-only grant."});
const current=await ctx.input.api.get<{title:string;description:string}>(`/api/issues/${control.id}`),afterComments=await ctx.input.api.get<Array<{id:string}>>(`/api/issues/${control.id}/comments?order=asc`);
const commentDenied=deniedAuthority(comment),updateDenied=deniedAuthority(update),controlUnchanged=current.title===control.title&&current.description===control.description&&JSON.stringify(beforeComments.map(row=>row.id))===JSON.stringify(afterComments.map(row=>row.id));
await ctx.input.evidence("chat-catalog-companion-capability-prerequisite.json",{supportedScopeNames:supported.scopes_supported,createCapabilityListed,commentDenied,updateDenied,controlUnchanged,modelDispatched:false,canonicalTaskCreated:false});
if(!createCapabilityListed||!commentDenied||!updateDenied||!controlUnchanged)throw new Error("Setup blocker: supported task-creation-only effective authority is unavailable; extra comment/update controls were not denied. No companion model was dispatched and the requested Website task was not created.");
const other=await ctx.input.api.post<{id:string}>("/api/companies",{name:`External scope control ${ctx.input.nonce}`});fixture.otherCompanyId=other.id;
const cross=await client.call("paperclip_create_task",{companyId:other.id,requestId:randomUUID(),title:"Unauthorized cross-company control",description:"Must not create",assigneeAgentId:morgan.id});const crossCompanyDenied=cross.isError===true&&cross.content.some(row=>/Company does not match the authorized connection/.test(row.text??""));
const direct=await fetch(new URL(`${root(ctx)}/issues`,ctx.input.api.baseURL),{headers:{authorization:`Bearer ${authorized.tokens.access_token}`},redirect:"error",signal:AbortSignal.timeout(15000)}),directRestStatus=direct.status;await direct.body?.cancel();
const beforeTaskIds=(await ctx.input.api.get<Array<{id:string}>>(`${root(ctx)}/issues?limit=1000`)).map(row=>row.id);await ctx.input.page.goto(source,{waitUntil:"domcontentloaded"});
return {morganId:morgan.id,morganPaused:true,companyPrefix:ctx.input.fixtures.company.issuePrefix,grantId,connectedUserId,createCapabilityListed,commentDenied,updateDenied,controlUnchanged,crossCompanyDenied,directRestStatus,beforeTaskIds,otherCompanyId:other.id};
}catch(error){if(fixture)await dispose(ctx);else await client.close();throw error;}
},gradeScopedAssistant,{
setupPolicy:{readiness:"preserve-scenario",invariantCheckIds:["paused-morgan-creation-fixture","effective-creation-only-grant"]},
authentication:"human-session",journeyKind:"scoped-external-assistant",companionSurface:companionBounds,requiredCredentials:["OPENAI_API_KEY"],expectedRunCount:0,expectedHumanMessageCount:0,turnTimeoutMs:180000,attemptTimeoutMs:600000,
sourceFiles:["chat-catalog-domains/external-assistant-scoped.ts","chat-catalog-domains/external-assistant-model.ts","chat-catalog-domains/external-assistant-connections.ts","chat-catalog-domains/external-support.ts","chat-catalog-domains/internal-support.ts","chat-catalog-domains/identity-support.ts","public-mcp-client.ts","public-mcp-model.ts","public-mcp-cases.ts","../../integrations/assistant-plugins/shared/skills/review-my-team/SKILL.md","../../integrations/assistant-plugins/shared/skills/delegate-work/SKILL.md","../../integrations/assistant-plugins/shared/skills/follow-up-results/SKILL.md","chat-scenarios/assistant-connections.yaml"],
async verifySetup(ctx,state){
const c=checks(),fixture=fixtures.get(ctx);if(!fixture)throw new Error("Private scoped-client fixture missing");
const agent=await ctx.input.api.get<{id:string;status:string;lifecycleState:string}>(`/api/agents/${state.morganId}`);
c.add("paused-morgan-creation-fixture",agent.id===state.morganId&&agent.status==="paused"&&agent.lifecycleState==="ready","The exact eligible Morgan is paused for this creation-only measurement; no runtime execution is claimed.");
const control=await ctx.input.api.get<{id:string;title:string}>(`/api/issues/${fixture.controlId}`);
const update=await fixture.client.call("paperclip_update_task",{companyId:ctx.input.fixtures.company.id,taskId:control.id,requestId:randomUUID(),changes:{title:control.title}}),comment=await fixture.client.call("paperclip_add_comment",{companyId:ctx.input.fixtures.company.id,taskId:control.id,requestId:randomUUID(),body:"Repeat scope denial control; no comment is authorized."});
c.add("effective-creation-only-grant",state.createCapabilityListed===true&&deniedAuthority(update)&&deniedAuthority(comment),"Fresh valid control operations remain denied before the real model can choose the positive task creation.");return c.result();
},
async runCompanionSurface(ctx,state,{query,signal}){const fixture=fixtures.get(ctx),credential=ctx.input.privateInputs?.credentials.OPENAI_API_KEY;if(!fixture||!credential||state.commentDenied!==true||state.updateDenied!==true)throw new Error("Creation-only scope prerequisite is not established; no model dispatch");
const tools=(await fixture.client.list({signal})).tools;return runScopedCompanion({query,credential,tools,signal,call:(name,args)=>fixture.client.call(name,args,{signal}),observe:async result=>{const raw=JSON.stringify(result);if((ctx.input.privateSecrets??[]).some(secret=>secret&&raw.includes(secret)))throw new Error("Private credential appeared in raw companion output; evidence withheld");state.privateScanComplete=true;state.privateLeaked=false;}});
},
async observe(ctx,state){const result=state.companionSurfaceResult as ChatCompanionResult;const o=await observeExternal(ctx,state);state.createdTasks=o.tasks.filter(task=>!(state.beforeTaskIds as string[]).includes(task.id));state.otherCompanyTaskCount=(await ctx.input.api.get<unknown[]>(`/api/companies/${state.otherCompanyId}/issues?limit=1000`)).length;const raw=JSON.stringify([result,o.tasks,o.activity]);state.privateLeaked=(ctx.input.privateSecrets??[]).some(secret=>secret&&raw.includes(secret));state.privateScanComplete=true;return {...o,reply:result.reply,links:result.links,humanQueries:[result.query],state};},
async verifyResult(ctx,state){const result=state.companionSurfaceResult as ChatCompanionResult,task=(state.createdTasks as Array<{id:string;identifier:string;title:string}>)[0];if(!task)throw new Error("Actual model-created task missing");const href=result.links.find(link=>{try{const url=new URL(link,ctx.input.api.baseURL);return url.origin===ctx.input.api.baseURL&&url.pathname.split("/").some((part,i,parts)=>part==="issues"&&[task.id,task.identifier].includes(parts[i+1]!));}catch{return false;}});if(!href)throw new Error("Actual model result omitted its durable task link");await ctx.input.page.goto(href,{waitUntil:"domcontentloaded"});await expect(ctx.input.page.getByRole("heading",{name:task.title,exact:true}).first()).toBeVisible();},
async cleanup(ctx){await dispose(ctx);},
})];