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

127 lines
10 KiB
TypeScript

import type { ChatCatalogContext } from "../chat-catalog-contract.js";
import { selectedExternalBinding, selectedExternalCredential, type ProviderBinding } from "./external-fixtures.js";
import { root } from "./external-support.js";
import { notionFactSpan, parseNotionFact, type NotionFact } from "./external-notion-semantics.js";
export interface NotionPageOracle { id: string; url: string; editedAt: string; marker: string; title: string; fact: NotionFact }
interface Page { object: string; id: string; url: string; last_edited_time: string; parent?: { type?: string; page_id?: string; workspace?: boolean }; properties?: Record<string, { type?: string; title?: Array<{ plain_text?: string }> }> }
interface Block { id: string; type: string; has_children: boolean; [key: string]: unknown }
const normalized = (id: string) => id.replaceAll("-", "").toLowerCase();
/** Only the selected disposable resource allowlist is accepted. This does not
* enumerate an account, search workspaces, or infer permission from a token. */
export function assertNotionConnection(binding: ProviderBinding) {
const p = binding.prerequisites, id = p.workspaceId;
if (!id || !/^[a-f0-9-]{32,36}$/i.test(id) || !binding.resourceIds.some(resource => normalized(resource) === normalized(id))) throw new Error("Setup blocker: Notion workspaceId must be an explicitly allowlisted disposable UUID");
const url = new URL(p.mcpUrl!);
if (url.protocol !== "https:" || url.hostname !== "mcp.notion.com" || url.pathname !== "/mcp" || url.username || url.password || url.search || url.hash) throw new Error("Setup blocker: named Notion proof requires the actual official Notion MCP resource");
if (!/^\d{4}-\d{2}-\d{2}$/.test(p.apiVersion ?? "")) throw new Error("Setup blocker: Notion API version reference is missing");
}
export function assertNotionFixture(binding: ProviderBinding) {
assertNotionConnection(binding); const p = binding.prerequisites;
for (const field of ["recentPageId", "olderPageId"]) { const id = p[field]; if (!id || !/^[a-f0-9-]{32,36}$/i.test(id) || !binding.resourceIds.some(resource => normalized(resource) === normalized(id))) throw new Error(`Setup blocker: Notion ${field} must be an explicitly allowlisted disposable UUID`); }
if (!p.recentMarker || !p.olderMarker || p.recentMarker === p.olderMarker) throw new Error("Setup blocker: distinct synthetic recent/background Notion marker references are required");
parseNotionFact(p.recentFactJson); parseNotionFact(p.olderFactJson);
}
async function notionJson<T>(token: string, version: string, pathname: string): Promise<T> {
const url = new URL(pathname, "https://api.notion.com");
if (url.origin !== "https://api.notion.com" || !/^\/v1\/(?:users\/me|pages\/[a-f0-9-]+|blocks\/[a-f0-9-]+\/children)$/.test(url.pathname)) throw new Error("Notion oracle escaped its read-only fixture resource");
const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(20_000), headers: { Authorization: `Bearer ${token}`, "Notion-Version": version, "content-type": "application/json" } });
if (!response.ok) { await response.body?.cancel(); throw new Error(`Setup blocker: authorized disposable Notion resource read returned HTTP ${response.status}; contents withheld`); }
const bytes = Buffer.from(await response.arrayBuffer()); if (bytes.length > 2 * 1024 * 1024) throw new Error("Setup blocker: Notion oracle response exceeds bounded fixture size");
try { return JSON.parse(bytes.toString("utf8")) as T; } catch { throw new Error("Notion oracle returned invalid JSON; contents withheld"); }
}
function richText(value: unknown): string {
if (!value || typeof value !== "object") return "";
if (Array.isArray(value)) return value.map(richText).join(" ");
const row = value as Record<string, unknown>;
if (typeof row.plain_text === "string") return row.plain_text;
return Object.values(row).filter(value => value && typeof value === "object").map(richText).join(" ");
}
async function blocksText(token: string, version: string, pageId: string, maxChildren = 100) {
let blocks = 0; const visited = new Set<string>();
async function children(id: string, depth: number): Promise<string> {
if (depth > 3 || visited.has(id)) throw new Error("Setup blocker: Notion page exceeds bounded fixture tree"); visited.add(id);
const page = await notionJson<{ results: Block[]; has_more: boolean }>(token, version, `/v1/blocks/${id}/children?page_size=100`);
if (!Array.isArray(page.results) || page.has_more || (blocks += page.results.length) > maxChildren) throw new Error("Setup blocker: Notion fixture page exceeds bounded child count");
const contents: string[] = [];
for (const block of page.results) { contents.push(richText(block[block.type])); if (block.has_children) contents.push(await children(block.id, depth + 1)); }
return contents.join("\n");
}
return children(pageId, 0);
}
export async function verifyNotionWorkspace(ctx: ChatCatalogContext, binding: ProviderBinding) {
assertNotionConnection(binding); const p = binding.prerequisites, token = selectedExternalCredential(ctx, binding, "apiTokenEnv");
const self = await notionJson<{ object: string; type: string; bot?: { workspace_id?: string } }>(token, p.apiVersion!, "/v1/users/me");
if (self.object !== "user" || self.type !== "bot" || !self.bot?.workspace_id || normalized(self.bot.workspace_id) !== normalized(p.workspaceId!)) throw new Error("Setup blocker: actual Notion token workspace differs from its authorized disposable workspace reference");
return { provider: "notion" as const, workspaceMatched: true };
}
export async function readNotionFixturePages(ctx: ChatCatalogContext, binding = selectedExternalBinding(ctx)) {
assertNotionFixture(binding); const p = binding.prerequisites;
const token = selectedExternalCredential(ctx, binding, "apiTokenEnv");
// Provider identity is checked privately; names, email and the raw account
// receipt never enter state/evidence. Provider contract:
// https://developers.notion.com/reference/user#bots
await verifyNotionWorkspace(ctx, binding);
const result: NotionPageOracle[] = [];
for (const [idField, markerField] of [["recentPageId", "recentMarker"], ["olderPageId", "olderMarker"]] as const) {
const id = p[idField]!, marker = p[markerField]!;
const page = await notionJson<Page>(token, p.apiVersion!, `/v1/pages/${id}`);
if (page.object !== "page" || normalized(page.id) !== normalized(id) || !Number.isFinite(Date.parse(page.last_edited_time))) throw new Error("Setup blocker: independent Notion page identity/date differs from its allowlisted fixture");
const url = new URL(page.url); if (url.protocol !== "https:" || !/(^|\.)notion\.(?:so|site)$/.test(url.hostname)) throw new Error("Setup blocker: Notion page returned an unexpected source host");
const body = await blocksText(token, p.apiVersion!, id);
if (!body.includes(marker)) throw new Error(`Setup blocker: ${idField} no longer contains its authorized synthetic marker`);
const fact = parseNotionFact(p[idField === "recentPageId" ? "recentFactJson" : "olderFactJson"]);
if (!notionFactSpan(body, fact)) throw new Error(`Setup blocker: ${idField} body does not substantiate its bounded approved fact`);
result.push({ id, url: page.url, editedAt: page.last_edited_time, marker, fact, title: Object.values(page.properties ?? {}).flatMap(row => row.title ?? []).map(row => row.plain_text ?? "").join("") });
}
if (Date.parse(result[0]!.editedAt) <= Date.parse(result[1]!.editedAt)) throw new Error("Setup blocker: recent Notion fixture must actually be newer than the background page");
return result;
}
export async function connectNamedNotion(ctx: ChatCatalogContext, binding: ProviderBinding, agentIds: string[]) {
assertNotionConnection(binding);
const token = selectedExternalCredential(ctx, binding, "mcpTokenEnv");
const result = await ctx.input.api.postSensitive<{ connectionId: string; actions: { readOnly: Array<{ catalogEntryId: string }>; canMakeChanges: Array<{ catalogEntryId: string }> } }>(`${root(ctx)}/tools/apps/connect`, {
link: binding.prerequisites.mcpUrl, name: "Launch Notion", authMode: "bearer", credentialValues: { "credentials.authorization": token }, grantKind: "organization",
});
const read = result.actions.readOnly.map(row => row.catalogEntryId);
if (!read.length) throw new Error("Setup blocker: actual Notion MCP connection did not expose any classified read actions");
try {
await ctx.input.api.post(`${root(ctx)}/tools/apps/${result.connectionId}/finish`, { enabledCatalogEntryIds: read, askFirstCatalogEntryIds: [], access: { agentIds } });
await ctx.input.api.putSensitive(`/api/tool-connections/${result.connectionId}/installs`, { installs: agentIds.map(targetId => ({ targetType: "agent", targetId })) });
return { connectionId: result.connectionId, readEntryIds: read };
} catch (error) { await ctx.input.api.delete(`/api/tool-connections/${result.connectionId}`, { allowNotFound: true }); throw error; }
}
/** A known-existing personal fixture page must really be inaccessible under the
* independently healthy shared workspace credential; never infer mismatch only
* from a display name. No discovery or non-allowlisted page is attempted. */
export async function verifyNotionPersonalPageDenied(
ctx: ChatCatalogContext,
shared: ProviderBinding,
pageId: string,
) {
assertNotionConnection(shared);
if (
!/^[a-f0-9-]{32,36}$/i.test(pageId) ||
!shared.resourceIds.some((id) => normalized(id) === normalized(pageId))
)
throw new Error(
"Setup blocker: personal Notion page is outside explicit disposable resource allowlist",
);
const token = selectedExternalCredential(ctx, shared, "apiTokenEnv");
const response = await fetch(`https://api.notion.com/v1/pages/${pageId}`, {
method: "GET",
redirect: "error",
signal: AbortSignal.timeout(20000),
headers: {
Authorization: `Bearer ${token}`,
"Notion-Version": shared.prerequisites.apiVersion!,
},
});
await response.body?.cancel();
if (![403, 404].includes(response.status))
throw new Error(
"Setup blocker: healthy shared Notion credential did not prove the selected personal page inaccessible",
);
return true;
}