Files
PaperClipAI/tests/runner-e2e/chat-catalog-domains/external-secret-endpoint.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

342 lines
17 KiB
TypeScript

import { createServer } from "node:http";
import { randomBytes } from "node:crypto";
import { mkdir, realpath, writeFile, rm } from "node:fs/promises";
import path from "node:path";
import { resolveDefaultAgentWorkspaceDir } from "../../../server/src/home-paths.js";
import { createLocalAgentJwt } from "../../../server/src/agent-auth-jwt.js";
import { listenOnFetchAllowedPort } from "../../e2e/fetch-allowed-port.js";
import type { ChatCatalogContext } from "../chat-catalog-contract.js";
import {
bytesContainSecret,
scanReachableSecretOutputs,
} from "./external-secret-scan.js";
export interface SecretScopeProbe {
boundSecretId: string;
unrelatedCompanyKey: string;
instanceKey: "custody_probe";
}
export interface SecretScopeReceipt {
runId: string;
agentId: string;
companyId: string;
tokenRunMatched: boolean;
identityStatus: number;
catalogStatus: number;
catalogKeys: string[];
secretRefs: string[];
companyKey: string;
instanceKey: string;
companyDeniedStatus: number;
instanceDeniedStatus: number;
taskId?: string;
workspaceId?: string;
taskWorkspaceMatched?: boolean;
}
export function validSecretScopeReceipt(
value: unknown,
expected: {
runId: string;
agentId: string;
companyId: string;
boundSecretId: string;
boundKey: string;
taskId?: string;
workspaceId?: string;
},
) {
const receipt = value as Partial<SecretScopeReceipt> | undefined;
return (
!!receipt &&
receipt.runId === expected.runId &&
receipt.agentId === expected.agentId &&
receipt.companyId === expected.companyId &&
receipt.tokenRunMatched === true &&
receipt.identityStatus === 200 &&
receipt.catalogStatus === 200 &&
// The worker's catalog also lists its model-provider credential binding;
// the bound key must appear exactly once, by the bound secret, and neither
// probed key may appear.
Array.isArray(receipt.catalogKeys) &&
Array.isArray(receipt.secretRefs) &&
receipt.catalogKeys.length === receipt.secretRefs.length &&
receipt.catalogKeys.filter(key => key === expected.boundKey).length === 1 &&
receipt.secretRefs[receipt.catalogKeys.indexOf(expected.boundKey)] === expected.boundSecretId &&
!receipt.catalogKeys.includes("unrelated-company-key") &&
!receipt.catalogKeys.includes("custody_probe") &&
receipt.companyKey === "unrelated-company-key" &&
receipt.instanceKey === "custody_probe" &&
receipt.companyDeniedStatus === 403 &&
receipt.instanceDeniedStatus === 403 &&
(expected.taskId === undefined || receipt.taskId === expected.taskId && receipt.taskWorkspaceMatched === true && typeof receipt.workspaceId === "string" && receipt.workspaceId.length > 0 && receipt.workspaceId === expected.workspaceId)
);
}
/** Native runner shells carry no Paperclip run identity (PAPERCLIP_API_KEY,
* PAPERCLIP_AGENT_ID and PAPERCLIP_RUN_ID are reserved), so the consumer is
* identified from saved server state when the bound credential arrives: the
* agent's one running run, on a task it owns, created from this chat, with its
* own execution workspace inside the attempt root. Nothing here depends on
* what the model copied into the command. */
export async function readSecretEndpointConsumerRun(ctx: ChatCatalogContext, agentId: string) {
const run = await readSecretEndpointActiveRun(ctx, agentId);
return { run, ...(await readSecretEndpointTaskBinding(ctx, agentId, run.id, String(run.contextSnapshot?.issueId ?? ""))) };
}
/** The agent's one running run in this company, read from the server. */
export async function readSecretEndpointActiveRun(ctx: ChatCatalogContext, agentId: string) {
const companyId = ctx.input.fixtures.company.id;
const rows = await ctx.input.api.get<Array<{ id: string; agentId: string; status: string }>>(`/api/companies/${companyId}/heartbeat-runs?agentId=${encodeURIComponent(agentId)}&limit=20`, { timeout: 4000 });
const running = rows.filter(row => row.agentId === agentId && row.status === "running");
if (running.length !== 1) throw new Error("Secret consumer has no single active run");
const run = await ctx.input.api.get<{ id: string; companyId: string; agentId: string; status: string; startedAt: string | null; responsibleUserId?: string | null; contextSnapshot: { issueId?: string } | null }>(`/api/heartbeat-runs/${running[0]!.id}`, { timeout: 4000 });
if (run.id !== running[0]!.id || run.companyId !== companyId || run.agentId !== agentId || run.status !== "running")
throw new Error("Secret consumer is not the actual active run");
return run;
}
export async function readSecretEndpointTaskBinding(ctx: ChatCatalogContext, agentId: string, runId: string, taskId: string) {
const temporary = process.env.PAPERCLIP_RUNNER_E2E_TEMP_ROOT;
if (!temporary || !taskId || !ctx.issue()?.id) throw new Error("Actual secret consumer task context unavailable");
const run = await ctx.input.api.get<{ id: string; companyId: string; agentId: string; status: string; startedAt: string | null; contextSnapshot: { issueId?: string } | null }>(`/api/heartbeat-runs/${runId}`, { timeout: 4000 });
if (run.id !== runId || run.companyId !== ctx.input.fixtures.company.id || run.agentId !== agentId || run.status !== "running" || !run.startedAt || !Number.isFinite(Date.parse(run.startedAt)) || run.contextSnapshot?.issueId !== taskId)
throw new Error("Secret consumer is not the actual active assigned run");
const [task, view] = await Promise.all([
ctx.input.api.get<{ id: string; companyId: string; assigneeAgentId: string | null; originIssueId?: string | null; executionWorkspaceId: string | null }>(`/api/issues/${taskId}`, { timeout: 4000 }),
ctx.input.api.get<{ workspace: { id: string; companyId: string; cwd: string } }>(`/api/issues/${taskId}/workspace`, { timeout: 4000 }),
]);
if (task.id !== taskId || task.companyId !== run.companyId || task.assigneeAgentId !== agentId || task.originIssueId !== ctx.issue()!.id || !task.executionWorkspaceId || view.workspace.id !== task.executionWorkspaceId || view.workspace.companyId !== run.companyId)
throw new Error("Secret consumer task workspace binding mismatch");
const [owned, actual] = await Promise.all([realpath(temporary), realpath(view.workspace.cwd)]);
if (!actual.startsWith(owned + path.sep)) throw new Error("Secret consumer task workspace is outside the attempt root");
return { taskId: task.id, workspaceId: view.workspace.id, taskWorkspaceMatched: true as const };
}
/** Owned loopback publishing check. Credential bytes stay in the server closure;
* the task receives only a script path and sanitized result. */
export async function secretTestEndpoint(
ctx: ChatCatalogContext,
agentId: string,
value: string,
envKey: "PUBLISHING_API_KEY" | "DEPLOYMENT_API_KEY",
scopeProbe?: SecretScopeProbe,
options?: { forbidAwsRuntimeAuthority?: true; taskBound?: true; personalWorkerReceipt?: true; activeRunConsumer?: true },
) {
if (options?.personalWorkerReceipt && (ctx.scenario.id !== "secrets.personal-secret" || envKey !== "PUBLISHING_API_KEY" || scopeProbe || options.taskBound || options.forbidAwsRuntimeAuthority)) throw new Error("Personal worker receipts require the dedicated personal-secret endpoint");
if (ctx.input.execution.environment.id !== "local")
throw new Error(
"Setup blocker: controlled secret endpoint needs the actual local worker environment",
);
const temporary = process.env.PAPERCLIP_RUNNER_E2E_TEMP_ROOT;
if (!temporary)
throw new Error("Secret endpoint requires its isolated attempt root");
const root = await realpath(temporary);
let home: string | undefined;
if (options?.taskBound) {
if (ctx.scenario.id !== "secrets.least-scope-delivery" || !scopeProbe) throw new Error("Task-bound secret helper is restricted to the scoped delivery fixture");
} else {
const candidate = path.resolve(resolveDefaultAgentWorkspaceDir(agentId));
if (!candidate.startsWith(root + path.sep)) throw new Error("Secret endpoint worker workspace escaped the disposable root");
await mkdir(candidate, { recursive: true });
home = await realpath(candidate);
if (!home.startsWith(root + path.sep)) throw new Error("Secret endpoint worker path resolved outside the disposable root");
}
const calls: Array<{
authorized: boolean;
agentId: string;
runId: string;
method: string;
pathname: string;
awsAuthorityAbsent?: boolean;
receiptId?: string;
createdAt?: string;
status?: number;
}> = [];
const scopeReceipts: SecretScopeReceipt[] = [],
privateRuntimeValues = new Set<string>();
const server = createServer(async (request, response) => {
const authorized = request.headers.authorization === `Bearer ${value}`;
const record: (typeof calls)[number] = {
authorized,
agentId: String(request.headers["x-paperclip-agent"] ?? ""),
runId: String(request.headers["x-paperclip-run"] ?? ""),
method: request.method ?? "",
pathname: request.url ?? "",
...(options?.forbidAwsRuntimeAuthority
? {
awsAuthorityAbsent:
request.headers["x-paperclip-no-aws"] === "true",
}
: {}),
};
if (calls.length >= 8) {
response.writeHead(429);
response.end();
return;
}
calls.push(record);
let ok =
authorized &&
(options?.personalWorkerReceipt || options?.taskBound || options?.activeRunConsumer || (record.agentId === agentId && /^[a-f0-9-]{36}$/i.test(record.runId))) &&
record.method === "GET" &&
record.pathname === "/publishing-check";
if (options?.activeRunConsumer && ok) {
// Native runner shells carry no Paperclip run identity; attribute the
// call to the agent's one running run from saved server state.
try {
const run = await readSecretEndpointActiveRun(ctx, agentId);
record.agentId = run.agentId;
record.runId = run.id;
} catch {
ok = false;
}
}
if (options?.forbidAwsRuntimeAuthority)
ok = ok && record.awsAuthorityAbsent === true;
if (scopeProbe && ok) {
try {
if (!ctx.input.privateSecrets) throw new Error("Private run credential unavailable");
// The consumer is the agent's actual running run, read from the server.
const consumer = await readSecretEndpointConsumerRun(ctx, agentId),
actor = await ctx.input.api.get<{ id: string; companyId: string; adapterType: string }>(`/api/agents/${agentId}`, { timeout: 4000 });
record.runId = consumer.run.id;
// Probe with the same run-bound agent authority the native tool bridge
// mints for this run (createLocalAgentJwt), never a fixture identity.
const token = createLocalAgentJwt(agentId, ctx.input.fixtures.company.id, actor.adapterType, consumer.run.id, consumer.run.responsibleUserId ?? null) ?? "";
// Register before parsing, requests, exceptions or any parent diagnostics.
if (token && token.length <= 8192) {
ctx.input.privateSecrets.push(token);
privateRuntimeValues.add(token);
}
if (!token || token.length > 8192) throw new Error("Private run credential unavailable");
const claims = JSON.parse(
Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"),
) as { sub?: string; company_id?: string; run_id?: string };
const tokenRunMatched =
actor.id === agentId &&
actor.companyId === ctx.input.fixtures.company.id &&
claims.sub === agentId &&
claims.company_id === ctx.input.fixtures.company.id &&
claims.run_id === consumer.run.id;
if (!tokenRunMatched)
throw new Error("Run credential identity mismatch");
const call = (pathname: string, method = "GET") =>
fetch(new URL(pathname, ctx.input.api.baseURL), {
method,
redirect: "error",
signal: AbortSignal.timeout(4000),
headers: {
authorization: `Bearer ${token}`,
"content-type": "application/json",
},
...(method === "POST" ? { body: "{}" } : {}),
});
const [identity, catalog] = await Promise.all([
call("/api/agents/me"),
call("/api/agents/me/secrets"),
]);
const identityStatus = identity.status,
catalogStatus = catalog.status;
const who = identity.ok
? ((await identity.json()) as { id: string; companyId: string })
: undefined;
if (!identity.ok) await identity.body?.cancel();
const listed = catalog.ok
? ((await catalog.json()) as {
secrets: Array<{ key: string; secretRef: string }>;
})
: undefined;
if (!catalog.ok) await catalog.body?.cancel();
if (
who?.id !== agentId ||
who.companyId !== ctx.input.fixtures.company.id ||
!Array.isArray(listed?.secrets) ||
listed.secrets.length > 20
)
throw new Error("Scoped run authority could not be verified");
const taskBinding = options?.taskBound ? { taskId: consumer.taskId, workspaceId: consumer.workspaceId, taskWorkspaceMatched: consumer.taskWorkspaceMatched } : undefined;
const denied = await Promise.all(
[scopeProbe.unrelatedCompanyKey, scopeProbe.instanceKey].map((key) =>
call(
`/api/agents/me/secrets/${encodeURIComponent(key)}/value`,
"POST",
),
),
);
const receipt: SecretScopeReceipt = {
...taskBinding,
runId: record.runId,
agentId,
companyId: who.companyId,
tokenRunMatched,
identityStatus,
catalogStatus,
catalogKeys: listed.secrets.map((row) => row.key),
secretRefs: listed.secrets.map((row) => row.secretRef),
companyKey: scopeProbe.unrelatedCompanyKey,
instanceKey: scopeProbe.instanceKey,
companyDeniedStatus: denied[0]!.status,
instanceDeniedStatus: denied[1]!.status,
};
await Promise.all(denied.map((result) => result.body?.cancel()));
scopeReceipts.push(receipt);
ok = validSecretScopeReceipt(receipt, {
...taskBinding,
runId: record.runId,
agentId,
companyId: ctx.input.fixtures.company.id,
boundSecretId: scopeProbe.boundSecretId,
boundKey: "deployment-api-key",
...(taskBinding ? { taskId: taskBinding.taskId, workspaceId: taskBinding.workspaceId } : {}),
});
} catch {
ok = false;
}
}
if (options?.personalWorkerReceipt) {
record.createdAt = new Date().toISOString(); record.status = ok ? 200 : 403;
if (ok) record.receiptId = randomBytes(24).toString("hex");
}
response.writeHead(ok ? 200 : 403, { "content-type": "application/json" });
response.end(
JSON.stringify({
ok,
check: "publishing endpoint",
status: ok ? 200 : 403,
...(record.receiptId ? { receiptId: record.receiptId } : {}),
}),
);
});
const port = await listenOnFetchAllowedPort(server),
scriptPath = home ? path.join(home, `secret-endpoint-check-${ctx.input.nonce}.mjs`) : "",
url = `http://127.0.0.1:${port}/publishing-check`;
const script = `const credential=process.env[${JSON.stringify(envKey)}];if(!credential){process.stdout.write(JSON.stringify({ok:false,reason:'credential unavailable'}));process.exitCode=1;}else{try{const response=await fetch(${JSON.stringify(url)},{method:'GET',redirect:'error',signal:AbortSignal.timeout(20000),headers:{authorization:'Bearer '+credential${options?.personalWorkerReceipt || options?.taskBound || options?.activeRunConsumer ? "" : ",...{'x-paperclip-agent':process.env.PAPERCLIP_AGENT_ID??'','x-paperclip-run':process.env.PAPERCLIP_RUN_ID??''}"},...${options?.forbidAwsRuntimeAuthority ? "{'x-paperclip-no-aws':String(!Object.keys(process.env).some(key=>key.startsWith('AWS_')||key.startsWith('PAPERCLIP_SECRETS_AWS_')))}" : "{}"}}});const result=await response.json();process.stdout.write(JSON.stringify({ok:result.ok===true,status:response.status,check:'publishing endpoint',...${options?.personalWorkerReceipt ? "(/^[a-f0-9]{48}$/.test(result.receiptId??''))?{receiptId:result.receiptId}:{}" : "{}"}}));if(!response.ok)process.exitCode=1;}catch{process.stdout.write(JSON.stringify({ok:false,reason:'endpoint check failed'}));process.exitCode=1;}}\n`;
if (scriptPath) await writeFile(scriptPath, script, { mode: 0o600 });
const command = scriptPath ? `node ${JSON.stringify(scriptPath)}` : `node --input-type=module -e '${script.replace(/'/g, "'\\''")}'`;
return {
url,
scriptPath,
command,
calls,
scopeReceipts,
async scanPrivateRuntimeOutputs(issueIds: string[], raw: unknown) {
let complete = scopeProbe ? privateRuntimeValues.size === 1 : true,
leaked = false;
const bytes = Buffer.from(JSON.stringify(raw));
for (const token of privateRuntimeValues) {
const scan = await scanReachableSecretOutputs(ctx, issueIds, token);
complete = complete && scan.complete;
leaked = leaked || scan.leaked || bytesContainSecret(bytes, token);
}
return { complete, leaked };
},
async close() {
try {
if (scriptPath) await rm(scriptPath, { force: true });
} finally {
privateRuntimeValues.clear();
await new Promise<void>((resolve) => server.close(() => resolve()));
}
},
};
}