mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-05 14:35:17 +01:00
## 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>
187 lines
21 KiB
TypeScript
187 lines
21 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { readFile } from "node:fs/promises";
|
|
import { expect } from "@playwright/test";
|
|
import { stringify } from "yaml";
|
|
import type { IssueAttachment } from "../../../packages/shared/src/types/issue.js";
|
|
import type { CompanyPortabilityFileEntry } from "../../../packages/shared/src/types/company-portability.js";
|
|
import type { ChatCatalogCase, ChatCatalogContext } from "../chat-catalog-contract.js";
|
|
import { makeDefinition } from "./internal-definition.js";
|
|
import { mainPerson } from "./internal-privacy.js";
|
|
import { readSearchProbeResponse } from "./internal-search-response.js";
|
|
import { checks, entity, hasLink, observation, observeInternal, project, sameTask, type Entity, type InternalObservation } from "./internal-support.js";
|
|
const sha = (body: string | Buffer) => createHash("sha256").update(body).digest("hex");
|
|
interface HistoricalTask extends Entity { completedAt?: string | null }
|
|
interface ReturnedFile { attachment: IssueAttachment; downloadedHash: string; byteSize: number }
|
|
interface SourceHistory { issueId: string; comments: Entity[]; attachments: IssueAttachment[] }
|
|
interface SearchObservation extends InternalObservation { chatIssueId: string; returnedFiles: ReturnedFile[]; sourceHistory: SourceHistory[]; finalAttachment: IssueAttachment; downloadedHash: string; deliveryComments: Entity[]; searchStatus: number; searchResults: unknown[]; privateFileStatus: number; currentSource: HistoricalTask }
|
|
export function buildHistoricalWebsiteImport(deliveryAt: string, nonce: string) {
|
|
const specs = [
|
|
{ slug: "final-website", title: "Final launch website delivery", status: "done", at: deliveryAt, filename: "final-website.html", label: "Final approved website delivered" },
|
|
{ slug: "old-final", title: "Earlier final website delivery", status: "done", at: new Date(Date.parse(deliveryAt) - 21 * 86400000).toISOString(), filename: "old-final.html", label: "Previous final website delivered" },
|
|
{ slug: "website-draft", title: "Latest launch website draft", status: "backlog", at: new Date().toISOString(), filename: "website-draft.html", label: "Unapproved draft only, never delivered" },
|
|
{ slug: "restricted-final", title: `Restricted final website ${nonce}`, status: "done", at: deliveryAt, filename: "restricted-final.html", label: "Restricted final website delivered" },
|
|
];
|
|
const files: Record<string, CompanyPortabilityFileEntry> = { "COMPANY.md": '---\nschema: "agentcompanies/v1"\nname: "Historical website fixture"\n---\nSynthetic migration fixture; source task and comment timestamps are preserved by the supported import contract.\n' };
|
|
const tasks: Record<string, unknown> = {};
|
|
const receipts = specs.map(spec => {
|
|
const body = `<!doctype html><html><body><h1>${spec.title}</h1><p>${nonce}-${spec.slug}</p></body></html>\n`; const digest = sha(body);
|
|
files[`tasks/${spec.slug}/TASK.md`] = `---\nname: ${JSON.stringify(spec.title)}\nkind: task\n---\nImported synthetic historical source. ${spec.label} on ${spec.at}. The source delivery time is preserved; importing the attachment again today does not change that original delivery date.\n`;
|
|
files[`blobs/${digest}`] = { encoding: "base64", data: Buffer.from(body).toString("base64"), contentType: "application/octet-stream" };
|
|
tasks[spec.slug] = { status: spec.status, priority: "medium", createdAt: new Date(Date.parse(spec.at) - 3600000).toISOString(), updatedAt: spec.at,
|
|
...(spec.status === "done" ? { completedAt: spec.at } : {}),
|
|
comments: [{ body: `${spec.label}: ${spec.filename}. Original delivery timestamp: ${spec.at}. Source bytes SHA256 ${digest}.`, authorType: "user", createdAt: spec.at }],
|
|
attachments: [{ sha256: digest, contentType: "text/html", originalFilename: spec.filename, byteSize: Buffer.byteLength(body), commentIndex: 0 }] };
|
|
return { ...spec, body, sha256: digest };
|
|
});
|
|
// The production portability reader implements block YAML, not a generic
|
|
// JSON/YAML parser. Keep keys plain and values JSON-compatible quoted scalars.
|
|
files[".paperclip.yaml"] = stringify({ schemaVersion: 7, tasks }, { defaultKeyType: "PLAIN", defaultStringType: "QUOTE_DOUBLE", lineWidth: 0, indentSeq: true });
|
|
return { files, receipts };
|
|
}
|
|
export function historicalWebsitePreviewMatches(value: unknown, bundle: ReturnType<typeof buildHistoricalWebsiteImport>): boolean {
|
|
const preview = value as { errors?: unknown[]; manifest?: { schemaVersion?: number; issues?: Array<{
|
|
slug: string; status?: string; completedAt?: string | null; comments?: Array<{ body: string; createdAt?: string | null }>;
|
|
attachments?: Array<{ sha256: string; originalFilename?: string | null; byteSize: number; commentIndex?: number | null }>;
|
|
}> } } | undefined;
|
|
const issues = preview?.manifest?.issues;
|
|
return Array.isArray(preview?.errors) && preview.errors.length === 0 && preview?.manifest?.schemaVersion === 7
|
|
&& Array.isArray(issues) && issues.length === bundle.receipts.length && bundle.receipts.every(expected => {
|
|
const matching = issues.filter(row => row.slug === expected.slug); const row = matching[0];
|
|
return matching.length === 1 && row?.status === expected.status && (expected.status !== "done" || row.completedAt === expected.at)
|
|
&& row.comments?.length === 1 && row.comments[0]?.createdAt === expected.at && row.comments[0].body.includes(expected.sha256)
|
|
&& row.attachments?.length === 1 && row.attachments[0]?.sha256 === expected.sha256
|
|
&& row.attachments[0].originalFilename === expected.filename && row.attachments[0].byteSize === Buffer.byteLength(expected.body)
|
|
&& row.attachments[0].commentIndex === 0;
|
|
});
|
|
}
|
|
function fileLink(o: InternalObservation, file: IssueAttachment) {
|
|
return o.links.find(href => { try { const url = new URL(href, o.origin); return url.origin === o.origin && !url.username && !url.password && !url.hash && url.pathname === file.contentPath; } catch { return false; } });
|
|
}
|
|
|
|
/** Read only actually rendered, same-origin attachment links through the current human's API actor. */
|
|
export async function readReturnedWebsiteFiles(ctx: ChatCatalogContext, o: InternalObservation): Promise<ReturnedFile[]> {
|
|
const chat = ctx.issue(); if (!chat) throw new Error("Artifact response has no actual chat");
|
|
const source = entity(o.state, "task");
|
|
const attachments = [...await ctx.input.api.get<IssueAttachment[]>(`/api/issues/${source.id}/attachments`),
|
|
...await ctx.input.api.get<IssueAttachment[]>(`/api/issues/${chat.id}/attachments`)];
|
|
const returned: ReturnedFile[] = [];
|
|
for (const attachment of attachments) {
|
|
if (!fileLink(o, attachment) || attachment.companyId !== o.companyId || attachment.sha256 !== o.state.finalHash
|
|
|| attachment.byteSize !== (o.state.finalAttachment as IssueAttachment).byteSize) continue;
|
|
const bytes = await ctx.input.api.getAttachmentContent(attachment.id);
|
|
returned.push({ attachment, downloadedHash: sha(bytes), byteSize: bytes.byteLength });
|
|
}
|
|
return returned;
|
|
}
|
|
function historySignature(history: SourceHistory) {
|
|
return JSON.stringify({ issueId: history.issueId,
|
|
comments: history.comments.map(row => [row.id, row.issueId, row.body, row.createdAt, row.authorAgentId, row.authorUserId]).sort(),
|
|
attachments: history.attachments.map(row => [row.id, row.issueId, row.issueCommentId, row.sha256, row.byteSize, row.originalFilename, row.createdAt]).sort() });
|
|
}
|
|
function verifiedReturnedFile(o: SearchObservation, target: Entity, original: IssueAttachment) {
|
|
return o.returnedFiles?.find(({ attachment: a, downloadedHash, byteSize }) => !!fileLink(o, a)
|
|
&& a.companyId === o.companyId && a.sha256 === o.state.finalHash && downloadedHash === o.state.finalHash
|
|
&& a.byteSize === original.byteSize && byteSize === original.byteSize && a.originalFilename === original.originalFilename
|
|
&& (a.id === original.id && a.issueId === target.id || a.issueId === o.chatIssueId && a.createdByAgentId === o.leadId
|
|
&& o.runs.some(run => run.id === a.originatingRunId && run.status === "succeeded")));
|
|
}
|
|
|
|
export function gradeArtifactSearch(value: unknown) {
|
|
const c = checks(); const o = observation(value) as SearchObservation | undefined;
|
|
c.add("real-imported-artifact-history", !!o && !!o.finalAttachment && Array.isArray(o.deliveryComments) && Array.isArray(o.searchResults) && !!o.currentSource, "Public migration receipts, original source dates and actual imported attachment/download evidence are required.");
|
|
if (!o || !o.finalAttachment || !Array.isArray(o.deliveryComments) || !Array.isArray(o.searchResults) || !o.currentSource) return c.result();
|
|
const target = entity(o.state, "task"); const file = o.state.finalAttachment as IssueAttachment; const hidden = entity(o.state, "privateTask");
|
|
c.add("original-last-week-delivery-not-import-time", o.currentSource.id === target.id && o.currentSource.completedAt === o.state.deliveryAt
|
|
&& Date.parse(String(o.state.deliveryAt)) >= Number(o.state.weekStart) && Date.parse(String(o.state.deliveryAt)) < Number(o.state.weekEnd)
|
|
&& o.deliveryComments.some(row => row.id === file.issueCommentId && row.createdAt === o.state.deliveryAt && (row.body ?? "").includes(file.sha256) && /Final approved website delivered/.test(row.body ?? ""))
|
|
&& o.activity.some(row => row.action === "company.imported" && Date.parse(row.createdAt ?? "") >= Date.parse(String(o.finalAttachment.createdAt))
|
|
&& Date.parse(row.createdAt ?? "") - Date.parse(String(o.finalAttachment.createdAt)) < 300000)
|
|
&& Date.parse(String(o.finalAttachment.createdAt)) > Date.parse(String(o.state.deliveryAt)),
|
|
"The final belongs to the requested prior week through preserved completion and attachment-bound source-comment dates; the actual attachment import happened later.");
|
|
c.add("exact-accessible-final-and-download", o.finalAttachment.id === file.id && o.finalAttachment.issueId === target.id && o.finalAttachment.sha256 === o.state.finalHash
|
|
&& o.downloadedHash === o.state.finalHash && hasLink(o, "issues", target) && !!verifiedReturnedFile(o, target, file),
|
|
"The answer selects the actual final from the requested source time, with both exact source and usable verified download links. How the reply words the delivery and its date is left to a human reader.");
|
|
const distractors = o.state.distractors as Entity[] | undefined;
|
|
// Other sources may be linked as context; their files must not be returned as the delivery.
|
|
// Whether the reply qualifies a linked draft or older final is left to a human reader.
|
|
const distractorFiles = ((o.state.originalHistory as SourceHistory[] | undefined) ?? []).filter(row => distractors?.some(task => task.id === row.issueId)).flatMap(row => row.attachments);
|
|
c.add("draft-older-final-and-private-snippets-excluded", !!distractors && !hasLink(o, "issues", hidden) && distractorFiles.every(attachment => !fileLink(o, attachment))
|
|
&& [403, 404].includes(o.privateFileStatus) && o.searchStatus === 200 && !JSON.stringify(o.searchResults).includes(hidden.id)
|
|
&& !JSON.stringify(o.searchResults).includes(String(o.state.privateMarker)) && !o.reply.includes(String(o.state.privateMarker)) && !o.reply.includes(hidden.title ?? String(o.state.privateMarker))
|
|
&& !o.links.some(href => href.includes((o.state.privateAttachment as IssueAttachment).id) || href.includes((o.state.privateAttachment as IssueAttachment).assetId)),
|
|
"No draft, older-final or private file is returned as the delivery, the private task is not linked, and independently denied private artifacts and previews remain outside results.");
|
|
const originals = o.state.originalTasks as HistoricalTask[] | undefined;
|
|
c.add("history-not-rewritten-by-search", !!originals && originals.every(row => sameTask(row, o.tasks.find(now => now.id === row.id)))
|
|
&& originals.every(row => (o.tasks.find(now => now.id === row.id) as HistoricalTask | undefined)?.completedAt === row.completedAt)
|
|
&& Array.isArray(o.state.originalHistory) && o.state.originalHistory.length === originals.length
|
|
&& originals.every(original => (o.state.originalHistory as SourceHistory[]).filter(row => row.issueId === original.id).length === 1)
|
|
&& (o.state.originalHistory as SourceHistory[]).every(before => {
|
|
const after = o.sourceHistory?.find(row => row.issueId === before.issueId); return !!after && historySignature(before) === historySignature(after);
|
|
})
|
|
&& !o.activity.some(row => row.agentId === o.leadId && originals.some(source => source.id === row.entityId)
|
|
&& /issue\.(?:attachment_|work_product_|updated|document_|deleted|comment_)/.test(row.action ?? "")),
|
|
"Searching preserves the migrated tasks, delivery state and source history.");
|
|
return c.result();
|
|
}
|
|
function findArtifact(): ChatCatalogCase {
|
|
let key: { id: string; token: string } | undefined;
|
|
const base = makeDefinition("documents-artifacts.find-artifact", async ctx => {
|
|
await mainPerson(ctx);
|
|
const timezone = await ctx.input.page.evaluate(() => Intl.DateTimeFormat().resolvedOptions().timeZone);
|
|
const parts = new Intl.DateTimeFormat("en-US", { timeZone: timezone, year: "numeric", month: "numeric", day: "numeric" }).formatToParts(new Date());
|
|
const number = (name: string) => Number(parts.find(part => part.type === name)?.value); const localDate = new Date(Date.UTC(number("year"), number("month") - 1, number("day")));
|
|
const weekEnd = localDate.getTime() - ((localDate.getUTCDay() + 6) % 7) * 86400000; const weekStart = weekEnd - 7 * 86400000;
|
|
const deliveryAt = new Date(weekStart + 2 * 86400000 + 12 * 3600000).toISOString();
|
|
const bundle = buildHistoricalWebsiteImport(deliveryAt, ctx.input.nonce); const root = `/api/companies/${ctx.input.fixtures.company.id}`;
|
|
const request = { source: { type: "inline", files: bundle.files, expectedFileCount: Object.keys(bundle.files).length }, include: { company: false, agents: false, projects: false, issues: true }, target: { mode: "existing_company", companyId: ctx.input.fixtures.company.id }, collisionStrategy: "rename", pauseAutomations: true };
|
|
const preview = await ctx.input.api.post(`${root}/imports/preview`, request);
|
|
await ctx.input.evidence("chat-catalog-historical-import-preview.json", preview);
|
|
if (!historicalWebsitePreviewMatches(preview, bundle)) throw new Error("Public historical preview omitted the original task dates, source comments or SHA-bound attachment linkage");
|
|
const imported = await ctx.input.api.post(`${root}/imports/apply`, request);
|
|
await ctx.input.evidence("chat-catalog-historical-import-apply.json", imported);
|
|
const p = await project(ctx); const oldProject = await project(ctx, "Earlier launch experiments"); const hiddenProject = await project(ctx, "Restricted launch history", { visibility: "private" });
|
|
const all = await ctx.input.api.get<HistoricalTask[]>(`${root}/issues?limit=1000&includeAgentCreatedTasks=true`); const records: HistoricalTask[] = [];
|
|
const files: IssueAttachment[] = [];
|
|
for (const receipt of bundle.receipts) {
|
|
const matching = all.filter(row => row.title === receipt.title); if (matching.length !== 1) throw new Error("Public historical import did not produce one exact source task");
|
|
const current = await ctx.input.api.patch<HistoricalTask>(`/api/issues/${matching[0]!.id}`, { projectId: receipt.slug === "restricted-final" ? hiddenProject.id : receipt.slug === "old-final" ? oldProject.id : p.id }); records.push(current);
|
|
const attached = (await ctx.input.api.get<IssueAttachment[]>(`/api/issues/${current.id}/attachments`)).filter(file => file.originalFilename === receipt.filename && file.sha256 === receipt.sha256);
|
|
if (attached.length !== 1 || sha(await ctx.input.api.getAttachmentContent(attached[0]!.id)) !== receipt.sha256) throw new Error("Imported attachment bytes or preserved source-comment linkage are missing"); files.push(attached[0]!);
|
|
}
|
|
if (!ctx.input.privateSecrets) throw new Error("Historical search requires private probe credential redaction");
|
|
key = await ctx.input.api.postSensitive(`/api/agents/${ctx.input.fixtures.agent.id}/keys`, { name: `historical-search-${ctx.input.nonce}` }); ctx.input.privateSecrets.push(key!.token);
|
|
const originalHistory = await Promise.all(records.map(async row => ({ issueId: row.id, comments: await ctx.input.api.get<Entity[]>(`/api/issues/${row.id}/comments?order=asc`), attachments: await ctx.input.api.get<IssueAttachment[]>(`/api/issues/${row.id}/attachments`) })));
|
|
const state = { originalHistory, project: p, task: records[0], finalAttachment: files[0], finalHash: bundle.receipts[0]!.sha256, deliveryAt, weekStart, weekEnd, timezone,
|
|
originalTasks: records, distractors: records.slice(1), privateTask: records[3], privateAttachment: files[3], privateMarker: `${ctx.input.nonce}-restricted-final` };
|
|
await ctx.input.evidence("chat-catalog-public-historical-delivery-import.json", { preview, imported, state, provenance: "Synthetic historical migration through supported public company import. Original source completion/comment dates are preserved; attachments are re-uploaded at import time, not falsely backdated." }); return state;
|
|
}, gradeArtifactSearch);
|
|
return { ...base, oracleVersion: "paperclip.chat-catalog.find-artifact.v2", authentication: "human-session", sourceFiles: [...base.sourceFiles, "chat-catalog-domains/internal-artifact-search.ts", "chat-catalog-domains/internal-privacy.ts", "chat-catalog-domains/identity-auth.ts"],
|
|
async observe(ctx, state): Promise<SearchObservation> {
|
|
if (!key) throw new Error("Historical search probe was not created during setup"); const o = await observeInternal(ctx, state); const file = state.finalAttachment as IssueAttachment;
|
|
const read = async (path: string) => { const url = new URL(path, ctx.input.api.baseURL); if (url.origin !== ctx.input.api.baseURL || !url.pathname.startsWith("/api/")) throw new Error("Historical probe escaped fixture API");
|
|
const response = await fetch(url, { redirect: "error", signal: AbortSignal.timeout(15000), headers: { Authorization: `Bearer ${key!.token}` } }); return readSearchProbeResponse(response); };
|
|
const [currentSource, attachments, deliveryComments, bytes, search] = await Promise.all([
|
|
ctx.input.api.get<HistoricalTask>(`/api/issues/${entity(state, "task").id}`), ctx.input.api.get<IssueAttachment[]>(`/api/issues/${entity(state, "task").id}/attachments`),
|
|
ctx.input.api.get<Entity[]>(`/api/issues/${entity(state, "task").id}/comments?order=asc`), ctx.input.api.getAttachmentContent(file.id), read(`/api/companies/${o.companyId}/search?q=website`),
|
|
]);
|
|
const hiddenUrl = new URL((state.privateAttachment as IssueAttachment).contentPath, ctx.input.api.baseURL);
|
|
const denied = await fetch(hiddenUrl, { redirect: "error", signal: AbortSignal.timeout(15000), headers: { Authorization: `Bearer ${key.token}` } }); await denied.body?.cancel();
|
|
const results = search.body as { results?: unknown[] } | undefined; if (search.status === 200 && !Array.isArray(results?.results)) throw new Error("Search omitted its production result collection");
|
|
const sourceHistory = await Promise.all((state.originalTasks as Entity[]).map(async row => ({ issueId: row.id, comments: await ctx.input.api.get<Entity[]>(`/api/issues/${row.id}/comments?order=asc`), attachments: await ctx.input.api.get<IssueAttachment[]>(`/api/issues/${row.id}/attachments`) })));
|
|
const returnedFiles = await readReturnedWebsiteFiles(ctx, o);
|
|
return { ...o, chatIssueId: ctx.issue()!.id, returnedFiles, sourceHistory, currentSource, finalAttachment: attachments.find(row => row.id === file.id)!, downloadedHash: sha(bytes), deliveryComments, searchStatus: search.status, searchResults: results?.results ?? [], privateFileStatus: denied.status };
|
|
},
|
|
async verifyResult(ctx, state, value) {
|
|
const o = value as SearchObservation; await base.verifyResult(ctx, state, value); const returned = verifiedReturnedFile(o, entity(state, "task"), state.finalAttachment as IssueAttachment); const href = returned && fileLink(o, returned.attachment); if (!href) throw new Error("Missing exact historical file link");
|
|
const page = await ctx.input.page.context().newPage(); try { const waiting = page.waitForEvent("download", { timeout: 5000 }).catch(() => undefined);
|
|
await page.goto(new URL(href, o.origin).href).catch(error => { if (!/download|ERR_ABORTED/i.test(String(error))) throw error; }); const download = await waiting;
|
|
if (download) { const path = await download.path(); if (!path || sha(await readFile(path)) !== state.finalHash) throw new Error("Historical browser download differs from preserved source bytes"); }
|
|
else await expect(page.getByRole("heading", { name: "Final launch website delivery", exact: true })).toBeVisible();
|
|
await ctx.input.evidence("chat-catalog-historical-file-opened.json", { attachmentId: returned!.attachment.id, sourceAttachmentId: o.finalAttachment.id, deliveryAt: state.deliveryAt, importedAt: o.finalAttachment.createdAt, sha256: returned!.downloadedHash });
|
|
} finally { await page.close(); }
|
|
},
|
|
async cleanup(ctx) { if (key) { await ctx.input.api.delete(`/api/agents/${ctx.input.fixtures.agent.id}/keys/${key.id}`, { allowNotFound: true }); key = undefined; } },
|
|
};
|
|
}
|
|
export const artifactSearchCases: readonly ChatCatalogCase[] = [findArtifact()];
|