Files
PaperClipAI/tests/runner-e2e/history-publish.ts
T
DottaandPaperclip ebed7f5237 test(evals): protect Antigravity setup and two-turn delivery (#18190)
## Thinking Path

> - Paperclip manages agents and their work.
> - A provider integration must work through ordinary agent setup and
task controls.
> - The recorded Antigravity walkthrough exposed setup, delivery, and
continuation failures.
> - A repeatable check must verify real work and retain failed attempts.
> - This pull request converts all 47 recorded steps into one fixed
Product E2E journey.
> - Maintainers can rerun the case and inspect independent delivery,
cleanup, and accounting evidence.

## Linked Issues or Issue Description

Builds on merged #18187, #18188, and #18189, and consumes the shared
repairs from merged #18230 and the equivalent manual-policy declaration
from #18222. Refs #18214 for the CI task wrapper. Refs #12503 and #14938
for related legacy adapter work.

**Agent or provider**

Google Antigravity native Runner with a saved managed Google
subscription and the exact Low model.

**Why this adapter is useful**

A user must be able to add an agent, connect its account, and receive
real task results across a follow-up. Picker visibility alone is
insufficient.

**How the agent is invoked**

A fixed Playwright driver uses ordinary product controls. The agent runs
through native ACP. Independent checks use public APIs, actual
downloads, owned process observations, and native lifetime fences.

## What Changed

- Register one explicit-only case:
`antigravity-agent-journey.runner-antigravity.local.saved-subscription-two-turn`.
- Map all 47 source steps and declare saved-account prerequisites,
finite limits, and same-host macOS ARM64 scope.
- Create an agent through the ordinary picker, connect the saved
account, select Low, run Test, and wait for readiness. Save an
instruction marker, deliver a file, and update it through an ordinary
follow-up.
- Require each run's visible completed file activity, exact downloaded
bytes, committed Done result, same tagged conversation, distinct
physical owner birth, released lease, and free native fences. Verify
reload persistence.
- Stop failed native runs that still own a retry. Replay an existing
Stop with its durable request identity and wait for the matching audited
acknowledgement. A terminal reservation without a native intent remains
unconfirmed.
- Keep private evidence in the existing result, report, dashboard, and
accounting pipeline. Retain the paused QA agent and financial history
while preserving the shared account and budget policies.
- Journal only the ordinary wizard's future ID, target, name, intended
harness and expected creator before forwarding its POST unchanged. Bind
the response and interrupted recovery to exact identity reads; a pending
404 stays unconfirmed.
- Serialize private resource snapshots through temporary-file fsync,
atomic rename and directory fsync. Abort forwarding on storage failure
and preserve legacy receipts. If later journal or diagnostic writes
fail, retain the primary error, always close the browser, and attempt
the ordinary failed report.
- Add production-component browser controls and harden task-menu
readiness, alias selection, scroll restoration, failure packaging, and
one hermetic auth-test budget.
- Wait for the existing GitHub recovery fixture to register its next
deadline before asserting the original range; preserve its
nested-transaction and zero-request checks. In the decision-expiry
fixture, verify the exact saved expiry separately from the earlier
global wake of another queue.

## Verification

- Fresh registered acceptance passed on eval source
`9060f3cd01b7c3445ecdf703d72e9cf30fe42b59` and merged serving product
`61bd4ac6919c2309f766a25e62273b074cee3261`. It completed ordinary setup
and two turns with native `.5` and `gemini-3.8-flash-low`. All 16
matchers, 14 checkpoints, and cleanup passed in **165,613 ms**. Actual
downloads were **61 bytes** and **119 bytes**. Both turns passed their
own run-bound browser activity checks and reload persistence.
- Independent read-back confirms Done, a paused retained agent, the same
connected saved default account, and no active owned run. Both accepted
results have the same full tagged conversation and distinct primary
process births. All 21 observed processes retired; both leases released
and all three native fences were free after each turn. The selected `.5`
checkpoints also showed equal agent/backend session IDs; this is an
observed case requirement, not a generic ACP invariant.
- Receipts report 339,273 input tokens, 7,224 output tokens, and 202,846
cached input tokens. Subscription prices are unavailable. Billing
coverage remains incomplete, not free.
- The normal report CLI passed. All 310 files from nine original
attempts and two separate recoveries retained their hashes. The twelve
current screenshots are byte-identical, and 194 local report links are
contained and valid. The eight earlier reports were copied without
regeneration.
- Delivery source `1bf4fb04df04710b82844b3c9355767f46b5f68f` branches
from `d3f2a60e795fc60d64c8b19d1eed4d48657d5492` and merges cleanly with
current master `1d571de5f9f886d66e520800baec8fc2f67d0948`. All 41 prior
`c8b332` authored file blobs remain identical; the 42nd path is the
decision-expiry fixture contract correction. Creation ownership, the
strict durable writer, and the ordinary successful workflow remain
unchanged. Of 43 measured file blobs, 30 remain identical. The
Antigravity oracle, artifact, billing and report gates and its
suite-specific validation block remain unchanged. The actual retained
agent matches its original creator; its original request `setupId` was
not captured and is not reconstructed.
- Later master changes include model-visible workspace guidance and
rejected-terminal-report handling. Their bounded source assessment is
separate: the first actual finish failed, then a same-turn replacement
was accepted and committed. Later read-only results match both original
native-result hashes, and the complete event catalogs have no
`session.failed` event. Master #18228 also expands detection of explicit
JSON file requests. The measured create/update-and-attach `.txt` task
already required publication under both parsers; the publication
validation gate itself is unchanged. Master #18240 changes remote
workspace cache staging and adds an OpenCode index refresh. The selected
local lane returns before those paths. Master #18213 adds optional
numeric turn timing and trace boundaries. Its selected Antigravity
model, text, IDs, result and retirement semantics remain unchanged in
the bounded source review. Local diagnostic rows and awaits can change
event ordinals and latency; the oracle checks relative semantic order.
Collector coverage and latency improvement remain outside this proof.
This does not claim that the whole current runtime is byte-identical to
serving `61bd`, or relabel the measured result as a new run.
- The adopted upstream cache controls passed 3/3 with pinned real Turbo.
Forced work disables local and remote reads and writes; ordinary work
reuses local results. The original genuine-pnpm/Turbo controls remain
historical to `9060`'s earlier write-only policy. The duplicate cache
patch is superseded by #18230. Its qualification-only pnpm addition is
removed because the adopted upstream controls do not require it.
- The E2E typecheck, map checks and 277-control replay are carried from
the unchanged eval source paths. That replay passed, including the 183
Antigravity controls, catalog/connection checks and the separate
product-journey validator. The carried creation controls include 91
config/recovery cases. The final launcher suite passed 19/19, including
five real campaign finalization fault cases; the report suite passed
7/7. These final checks did not rerun the earlier 277-control group. The
canonical production-component browser spec passed in 27.4 s under its
unchanged 60 s limit before the replay. Four paused-composer cases and
the product base's build/typecheck plus 376 focused regressions were
verified earlier.
- The shipped wizard and actual API client cover persistence before
forwarding, lost response JSON, foreign/malformed requests, wrong
response identity/creator and cleanup-error preservation. Real
filesystem controls failed 5/5 before the writer repair and passed 5/5
afterward, preserving the old journal on partial-write, temporary-file
sync and rename faults. Three persistent-sync campaign controls failed
before the finalization repair and passed afterward. All five final
campaign fault cases preserve the primary failure, cleanup failure,
usage and failed report while attempting browser closure. The strict
journal still blocks the next mutation. These are provider-free
ownership controls; the Google task proof remains the original `9060` →
`61bd` acceptance.
- The decision restart check passed in the local 20-case fixture run. A
current-source real-PostgreSQL rollback control reproduced the exact
90,000 ms earlier global wake: the old equality rejected it, while the
exact durable expiry and new future-wake bound passed. The original 60 s
open-state, exact-timestamp, continuation and quiet checks remain. The
broader local run was **FAILED: 19 passed / 1 failed**, with a 15 s
timeout and a 30 s cleanup timeout in an unchanged timestamp-pagination
case. That case passed in canonical `c8b332` CI; the local timeout cause
remains inconclusive. An extra local server typecheck failed against
stale cached Runner declarations; it did not check this excluded test
file. Both limits remain recorded for fresh canonical CI.
- A broader local GitHub recovery group passed 21/22. Its unchanged
pagination case observed an unexpected config request; the log does not
establish the cause. That result remains retained, and fresh
current-head CI is the final broader gate.

- Exact delivery-head CI completed with 55 successes, two skips, and one
optional neutral review. Required `ci / verify` and `ci / e2e`, build,
typecheck, and Runner checks passed. Fresh Greptile is 5/5 with zero
unresolved threads. Optional Paperclip is neutral 4/5; its carried
recommendations are dispositioned against the public Stop contract and
selected live identity evidence.

Seven earlier converted attempts retain their failed grades and partial
evidence. Historical Paid8 and its later read-only per-run UI
observation remain separate from the fresh acceptance above. Unknown
prices and the older partial startup accounting remain explicit. Full
lineage and raw evidence remain private in the normal report bundle.

## Risks

- This case requires an authorized saved personal default Google
subscription and finite operator candidate admission. It does not test
fresh OAuth or establish global qualification.
- The physical observer supports a same-host loopback macOS ARM64
target. Cloud, Linux, and other models remain outside this case.
- A known-cost stop cannot cap missing prices or in-flight subscription
charges. Existing operator policies remain unchanged.
- Raw account/native identities stay private. Missing retirement proof
keeps resources retained. The selected cleanup mode does not test agent
purge.

## Model Used

OpenAI Codex (GPT-6). The host did not expose the exact model revision
or context limit. The model used tools for code edits, tests, browser
automation, and review.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-10-29 19:51:32 -05:00

781 lines
26 KiB
TypeScript

import { validateCampaignAccounting, validateRetainedRunnerResult } from "./result-validation.js";
import { validateEvalOperationsReport } from "./operations-report.js";
import { validateCampaignFeedbackReview } from "./feedback-dispositions.js";
import { createHash } from "node:crypto";
import { execFile } from "node:child_process";
import path from "node:path";
import { promisify } from "node:util";
import {
cp,
copyFile,
mkdtemp,
lstat,
mkdir,
readFile,
readdir,
realpath,
rm,
stat,
writeFile,
} from "node:fs/promises";
import os from "node:os";
import { writePublicCampaignSummaryImage } from "./public-summary-image.js";
import { regenerateRunnerDashboard } from "./dashboard-regenerate.js";
import { renderRunnerHistoryIndex } from "./history-index.js";
import { validateHistoryDestination } from "./history-destination.js";
import { PUBLIC_RUNNER_SCREENSHOT_MARKER } from "./screenshot-policy.js";
import { BoundedHistoryPublisher, checkHistoryPayload, HISTORY_LIMITS } from "./history-budget.js";
import {
campaignHistoryRecord,
emptyRunnerHistory,
mergeRunnerHistory,
} from "./history.js";
import type { RunnerE2ECampaign, RunnerE2EHistoryIndex } from "./types.js";
const execFileAsync = promisify(execFile);
const repositoryRoot = path.resolve(import.meta.dirname, "../..");
const MUTABLE_HISTORY_FILES = new Set([
"history.json",
"latest.json",
"latest-green.json",
]);
const PUBLISH_ROOT_FILES = new Set([
"dashboard.html",
"index.html",
"junit.xml",
"normalized-results.json",
"summary.md",
]);
const MAX_PUBLIC_RASTER_BYTES = 12 * 1024 * 1024;
const EMPTY_PUBLIC_SCREENSHOTS: ReadonlySet<string> = new Set();
const PRIVATE_EVIDENCE_DIRECTORIES = new Set([
"blob-report",
"html-report",
"playwright-output",
]);
function publicEvidencePath(
relative: string,
publicScreenshots: ReadonlySet<string> = EMPTY_PUBLIC_SCREENSHOTS,
) {
const match = relative.match(
/^evidence\/[A-Za-z0-9._-]+\/attempt-[1-9][0-9]*\/(.+)$/,
);
if (!match) return false;
const evidencePath = match[1]!;
const segments = evidencePath.split("/");
if (
segments.some(
(segment) =>
!segment ||
segment === "." ||
segment === ".." ||
PRIVATE_EVIDENCE_DIRECTORIES.has(segment),
)
) {
return false;
}
// A text extension and credential scan do not establish a public projection.
// API snapshots and process logs can still hold hidden reasoning and provider
// session identities. Keep those diagnostics in the retained Actions artifact;
// normalized-results.json already carries the graded result contract.
return (
path.posix.extname(evidencePath).toLowerCase() === ".png" &&
publicScreenshots.has(relative)
);
}
export function publicScreenshotPaths(campaign: RunnerE2ECampaign) {
assertPublicCampaign(campaign);
const screenshots = new Set<string>();
for (const result of campaign.results) {
const files =
result.screenshots
?.filter(
(screenshot) =>
screenshot.publication === PUBLIC_RUNNER_SCREENSHOT_MARKER,
)
.map((screenshot) => screenshot.file) ?? [];
if (files.length === 0) continue;
if (
!/^[A-Za-z0-9][A-Za-z0-9._-]{0,299}$/.test(result.executionId) ||
!Number.isSafeInteger(result.attempt) ||
result.attempt < 1
) {
throw new Error(
`Cannot publish screenshots for unsafe execution identity ${result.executionId}`,
);
}
for (const file of files) {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}\.png$/i.test(file)) {
throw new Error(
`Cannot publish unsafe screenshot path for ${result.executionId}: ${file}`,
);
}
screenshots.add(
`evidence/${result.executionId}/attempt-${result.attempt}/${file}`,
);
}
}
return screenshots;
}
export function assertPublicCampaign(campaign: Pick<RunnerE2ECampaign, "results">) {
if (campaign.results.some(result => result.productJourney?.privacy === "private" || result.antigravityJourney?.privacy === "private")) {
throw new Error("Private Product E2E campaigns cannot enter the public history publisher");
}
}
export function isHistoricalBundlePathAllowed(
relative: string,
allowPublicSummary = false,
publicScreenshots: ReadonlySet<string> = EMPTY_PUBLIC_SCREENSHOTS,
) {
if (
relative.includes("\\") ||
relative.startsWith("/") ||
relative.includes("..")
) {
return false;
}
if (PUBLISH_ROOT_FILES.has(relative)) return true;
if (allowPublicSummary && relative === "public-images/campaign-summary.png") {
return true;
}
if (
relative === "assets/favicon-32x32.png" ||
relative === "assets/InterVariable.woff2"
) {
return true;
}
return publicEvidencePath(relative, publicScreenshots);
}
function hasPublicPngMagic(content: Buffer) {
return (
content.length >= 24 &&
content
.subarray(0, 8)
.equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])) &&
content.subarray(12, 16).equals(Buffer.from("IHDR", "ascii"))
);
}
async function validatePublicRaster(absolute: string, relative: string) {
const metadata = await stat(absolute);
if (metadata.size === 0 || metadata.size > MAX_PUBLIC_RASTER_BYTES) {
throw new Error(
`Public screenshot ${relative} exceeds the per-file size boundary`,
);
}
const content = await readFile(absolute);
if (!hasPublicPngMagic(content)) {
throw new Error(
`Public screenshot ${relative} does not match its raster file type`,
);
}
}
async function pruneEvidenceDirectory(
root: string,
current: string,
publicScreenshots: ReadonlySet<string>,
) {
const entries = await readdir(current, { withFileTypes: true });
for (const entry of entries) {
const absolute = path.join(current, entry.name);
if (entry.isDirectory()) {
await pruneEvidenceDirectory(root, absolute, publicScreenshots);
if ((await readdir(absolute)).length === 0) {
await rm(absolute, { recursive: true });
}
continue;
}
const relative = path.relative(root, absolute).split(path.sep).join("/");
if (!entry.isFile() || !publicEvidencePath(relative, publicScreenshots)) {
await rm(absolute, { force: true });
}
}
}
export async function prunePrivateHistoryEvidence(
root: string,
publicScreenshots: ReadonlySet<string> = EMPTY_PUBLIC_SCREENSHOTS,
) {
const evidenceRoot = path.join(root, "evidence");
const metadata = await lstat(evidenceRoot).catch(() => null);
if (!metadata) return;
if (!metadata.isDirectory()) {
throw new Error("Historical evidence root must be a directory");
}
await pruneEvidenceDirectory(root, evidenceRoot, publicScreenshots);
}
export async function stageTrustedHistoryAssets(
root: string,
trustedRoot = repositoryRoot,
) {
const resolveTrustedAsset = async (segments: string[]) => {
const trustedRootReal = await realpath(trustedRoot);
let source = trustedRoot;
for (const [index, segment] of segments.entries()) {
source = path.join(source, segment);
const metadata = await lstat(source);
if (metadata.isSymbolicLink()) {
throw new Error(
`Refusing symbolic link in trusted publisher asset path ${segments.join("/")}`,
);
}
const final = index === segments.length - 1;
if (
(final && !metadata.isFile()) ||
(!final && !metadata.isDirectory())
) {
throw new Error(
`Trusted publisher asset path has an invalid file type: ${segments.join("/")}`,
);
}
}
const sourceReal = await realpath(source);
const relative = path.relative(trustedRootReal, sourceReal);
if (
!relative ||
relative === ".." ||
relative.startsWith(`..${path.sep}`)
) {
throw new Error(
`Trusted publisher asset escapes its checkout: ${segments.join("/")}`,
);
}
return sourceReal;
};
const [faviconSource, fontSource] = await Promise.all([
resolveTrustedAsset(["ui", "public", "favicon-32x32.png"]),
resolveTrustedAsset(["ui", "public", "fonts", "InterVariable.woff2"]),
]);
const assets = path.join(root, "assets");
await rm(assets, { recursive: true, force: true });
await mkdir(assets, { recursive: true });
await Promise.all([
copyFile(faviconSource, path.join(assets, "favicon-32x32.png")),
copyFile(fontSource, path.join(assets, "InterVariable.woff2")),
]);
}
interface BundleManifest {
schema: "paperclip.runner-e2e.bundle/v1";
campaignId: string;
bundleDigest: string;
files: Array<{ path: string; sha256: string; bytes: number }>;
}
function json(value: unknown) {
return `${JSON.stringify(value, null, 2)}\n`;
}
export { validateHistoryDestination };
async function relativeFiles(
root: string,
current = root,
allowPublicSummary = false,
publicScreenshots: ReadonlySet<string> = EMPTY_PUBLIC_SCREENSHOTS,
boundary?: { entries: number },
): Promise<string[]> {
const entries = await readdir(current, { withFileTypes: true });
const files: string[] = [];
for (const entry of entries) {
if (boundary && ++boundary.entries > 1024) throw new Error("Public bundle exceeds the directory-entry boundary");
const absolute = path.join(current, entry.name);
if (entry.isSymbolicLink()) {
throw new Error(`Refusing to publish symbolic link ${entry.name}`);
}
if (entry.isDirectory()) {
files.push(
...(await relativeFiles(
root,
absolute,
allowPublicSummary,
publicScreenshots,
boundary,
)),
);
} else if (entry.isFile()) {
const relative = path.relative(root, absolute).split(path.sep).join("/");
if (MUTABLE_HISTORY_FILES.has(relative)) continue;
if (
!isHistoricalBundlePathAllowed(
relative,
allowPublicSummary,
publicScreenshots,
)
) {
throw new Error(
`Refusing non-allowlisted historical bundle path ${relative}`,
);
}
files.push(relative);
}
}
return files;
}
export async function createBundleManifest(
root: string,
campaignId: string,
allowPublicSummary = false,
publicScreenshots: ReadonlySet<string> = EMPTY_PUBLIC_SCREENSHOTS,
bounded = false,
): Promise<BundleManifest> {
if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,199}$/.test(campaignId)) {
throw new Error("Campaign ID is unsafe for immutable object storage");
}
const retainedPaths = await relativeFiles(root, root, allowPublicSummary, publicScreenshots, bounded ? { entries: 0 } : undefined);
if (bounded) {
checkHistoryPayload(await Promise.all(retainedPaths.map(async file => ({
path: file, bytes: (await stat(path.join(root, file))).size,
}))), HISTORY_LIMITS.campaignBytes, HISTORY_LIMITS.campaignFiles, "Public campaign");
}
const retained = new Set(retainedPaths);
const missingScreenshots = [...publicScreenshots].filter((relative) => !retained.has(relative));
if (missingScreenshots.length > 0) {
throw new Error(`Declared public screenshots are missing from the historical bundle: ${missingScreenshots.sort().join(", ")}`);
}
const files = await Promise.all(
retainedPaths.sort().map(async (relative) => {
const absolute = path.join(root, ...relative.split("/"));
if (
relative === "public-images/campaign-summary.png" ||
publicScreenshots.has(relative)
) {
await validatePublicRaster(absolute, relative);
}
const [content, metadata] = await Promise.all([
readFile(absolute),
stat(absolute),
]);
return {
path: relative,
sha256: createHash("sha256").update(content).digest("hex"),
bytes: metadata.size,
};
}),
);
const bundleDigest = createHash("sha256")
.update(JSON.stringify(files))
.digest("hex");
return {
schema: "paperclip.runner-e2e.bundle/v1",
campaignId,
bundleDigest,
files,
};
}
export function buildHistoryPointers(history: RunnerE2EHistoryIndex) {
const byCampaign = new Map(
history.campaigns.map((campaign) => [campaign.campaignId, campaign]),
);
const pointer = (campaignId: string | null | undefined) => {
const campaign = campaignId ? byCampaign.get(campaignId) : undefined;
return campaign
? {
campaignId: campaign.campaignId,
generatedAt: campaign.generatedAt,
publicUrl: campaign.publicUrl,
sha: campaign.source.sha,
}
: null;
};
return {
latest: {
schema: "paperclip.runner-e2e.pointer/v1",
updatedAt: history.updatedAt,
overall: pointer(history.latestCampaignId),
suites: Object.fromEntries(
Object.entries(history.latestBySuite).map(([suiteId, campaignId]) => [
suiteId,
pointer(campaignId),
]),
),
},
latestGreen: {
schema: "paperclip.runner-e2e.pointer/v1",
updatedAt: history.updatedAt,
overall: pointer(history.latestGreenCampaignId),
suites: Object.fromEntries(
Object.entries(history.latestGreenBySuite).map(
([suiteId, campaignId]) => [suiteId, pointer(campaignId)],
),
),
},
};
}
function awsObject(bucket: string, key: string) {
return `s3://${bucket}/${key}`;
}
async function objectExists(bucket: string, key: string) {
try {
await execFileAsync("aws", [
"s3api",
"head-object",
"--bucket",
bucket,
"--key",
key,
]);
return true;
} catch (error) {
const detail = String(
(error as { stderr?: string }).stderr ??
(error instanceof Error ? error.message : error),
);
if (/\b(?:404|Not Found|NoSuchKey)\b/i.test(detail)) return false;
throw new Error(
`Unable to inspect historical object: ${detail.slice(0, 400)}`,
);
}
}
async function downloadJson<T>(
bucket: string,
key: string,
destination: string,
bounded?: BoundedHistoryPublisher,
) {
if (bounded) return bounded.downloadJson<T>(bucket, key, destination);
if (!(await objectExists(bucket, key))) return null;
await execFileAsync("aws", [
"s3",
"cp",
awsObject(bucket, key),
destination,
"--only-show-errors",
]);
return JSON.parse(await readFile(destination, "utf8")) as T;
}
async function uploadJson(
bucket: string,
key: string,
file: string,
cacheControl: string,
) {
await uploadFile(bucket, key, file, "application/json", cacheControl);
}
async function uploadFile(
bucket: string,
key: string,
file: string,
contentType: string,
cacheControl: string,
) {
await execFileAsync("aws", [
"s3",
"cp",
file,
awsObject(bucket, key),
"--only-show-errors",
"--content-type",
contentType,
"--cache-control",
cacheControl,
]);
}
export async function uploadImmutableBundle(
bucket: string,
key: string,
directory: string,
manifest?: BundleManifest,
bounded?: BoundedHistoryPublisher,
) {
if (bounded && manifest) {
for (const file of manifest.files) {
const extension = path.extname(file.path).toLowerCase();
const contentType = ({ ".png": "image/png", ".json": "application/json", ".html": "text/html; charset=utf-8",
".woff2": "font/woff2", ".xml": "application/xml", ".md": "text/plain; charset=utf-8" } as Record<string, string>)[extension];
if (!contentType) throw new Error(`Missing public content type for ${file.path}`);
await bounded.upload(bucket, `${key}/${file.path}`, path.join(directory, file.path), contentType,
"public,max-age=2592000,immutable", true);
}
return;
}
const common = [
"--recursive",
"--only-show-errors",
"--cache-control",
"public,max-age=31536000,immutable",
];
await execFileAsync("aws", [
"s3",
"cp",
directory,
awsObject(bucket, key),
...common,
"--exclude",
"history.json",
"--exclude",
"latest.json",
"--exclude",
"latest-green.json",
"--exclude",
"*.png",
]);
await execFileAsync("aws", [
"s3",
"cp",
directory,
awsObject(bucket, key),
...common,
"--exclude",
"*",
"--include",
"*.png",
"--content-type",
"image/png",
]);
}
async function main() {
const reportRoot = path.resolve(
process.env.PAPERCLIP_RUNNER_E2E_REPORT_DIR ??
"runner-e2e-merged-report/normalized",
);
const bucket = process.env.RUNNER_E2E_HISTORY_S3_BUCKET ?? "";
const destination = validateHistoryDestination({
bucket,
prefix: process.env.RUNNER_E2E_HISTORY_PREFIX ?? "runner-e2e",
publicBaseUrl: process.env.RUNNER_E2E_HISTORY_PUBLIC_BASE_URL ?? "",
});
const bounded = process.env.PAPERCLIP_E2E_BOUNDED_HISTORY === "true";
if (bounded && process.env.GITHUB_ACTIONS === "true" && process.env.GITHUB_RUN_ATTEMPT !== "1") {
throw new Error("Bounded history publication requires the original workflow attempt; retain failed publication evidence");
}
const publisher = bounded ? new BoundedHistoryPublisher(path.join(path.dirname(reportRoot), "history-publication-receipt.json")) : undefined;
if (publisher) await publisher.verifyRetention(bucket, destination.prefix);
const campaign = JSON.parse(
await readFile(path.join(reportRoot, "normalized-results.json"), "utf8"),
) as RunnerE2ECampaign;
for (const result of campaign.results ?? []) validateRetainedRunnerResult(result);
if (campaign.accounting) validateCampaignAccounting(campaign.accounting);
if (campaign.operations) validateEvalOperationsReport(campaign.operations);
if (campaign.feedbackReview) validateCampaignFeedbackReview(campaign, campaign.feedbackReview);
assertPublicCampaign(campaign);
if (campaign.schema !== "paperclip.runner-e2e.campaign/v2") {
throw new Error("Historical publishing requires a v2 normalized campaign");
}
const temporary = await mkdtemp(
path.join(os.tmpdir(), "runner-e2e-history-"),
);
const historyKey = `${destination.prefix}/history.json`;
const current =
(await downloadJson<RunnerE2EHistoryIndex>(
bucket,
historyKey,
path.join(temporary, "current-history.json"),
publisher,
)) ?? emptyRunnerHistory();
const history = mergeRunnerHistory(
current,
campaignHistoryRecord(
campaign,
`${destination.publicBaseUrl}/${destination.prefix}`,
),
bounded ? { now: Date.now(), maxAgeMs: HISTORY_LIMITS.indexDays * 86_400_000, maxCampaigns: HISTORY_LIMITS.indexCampaigns } : undefined,
);
if (bounded && !history.campaigns.some(entry => entry.campaignId === campaign.campaignId)) {
throw new Error("Bounded campaign is outside the retained history window");
}
const publicScreenshots = publicScreenshotPaths(campaign);
// Campaign bundles are immutable and must not capture a mutable history
// file left in a reused local directory. The root landing page below is the
// only dashboard that embeds navigation across campaigns. S3 gets its own
// staged copy. Only screenshots declared by normalized results (plus the
// fixed failure screenshot for failed executions) cross the public evidence
// boundary. Raw per-attempt text stays in the retained Actions artifact.
const s3ReportRoot = path.join(temporary, "s3-campaign");
await cp(reportRoot, s3ReportRoot, { recursive: true, errorOnExist: true });
await prunePrivateHistoryEvidence(s3ReportRoot, publicScreenshots);
await stageTrustedHistoryAssets(s3ReportRoot);
await rm(path.join(s3ReportRoot, "public-images"), {
recursive: true,
force: true,
});
const summaryImage = path.join(
s3ReportRoot,
"public-images",
"campaign-summary.png",
);
await writePublicCampaignSummaryImage(campaign, summaryImage);
await regenerateRunnerDashboard({
bundle: s3ReportRoot,
historyFile: null,
});
const manifest = await createBundleManifest(
s3ReportRoot,
campaign.campaignId,
true,
publicScreenshots,
bounded,
);
const campaignPrefix = `${destination.prefix}/campaigns/${campaign.campaignId}`;
const manifestKey = `${campaignPrefix}/bundle-manifest.json`;
const existingManifest = await downloadJson<BundleManifest>(
bucket,
manifestKey,
path.join(temporary, "existing-manifest.json"),
publisher,
);
if (
existingManifest &&
existingManifest.bundleDigest !== manifest.bundleDigest
) {
throw new Error(
`Immutable campaign ${campaign.campaignId} already exists with a different digest`,
);
}
const manifestFile = path.join(temporary, "bundle-manifest.json");
await writeFile(manifestFile, json(manifest), "utf8");
// Pages uses the same declared-screenshot boundary in a sibling stage. The
// downloaded access-controlled report stays intact for this whole job.
const pagesRoot = path.join(path.dirname(reportRoot), "pages");
await rm(pagesRoot, { recursive: true, force: true });
await cp(reportRoot, pagesRoot, { recursive: true, errorOnExist: true });
await prunePrivateHistoryEvidence(pagesRoot, publicScreenshots);
await stageTrustedHistoryAssets(pagesRoot);
await rm(path.join(pagesRoot, "public-images"), {
recursive: true,
force: true,
});
const pointers = buildHistoryPointers(history);
const historyFile = path.join(pagesRoot, "history.json");
const latestFile = path.join(pagesRoot, "latest.json");
const latestGreenFile = path.join(pagesRoot, "latest-green.json");
await Promise.all([
writeFile(historyFile, json(history), "utf8"),
writeFile(latestFile, json(pointers.latest), "utf8"),
writeFile(latestGreenFile, json(pointers.latestGreen), "utf8"),
]);
await regenerateRunnerDashboard({ bundle: pagesRoot, historyFile });
const pagesManifest = await createBundleManifest(
pagesRoot,
campaign.campaignId,
false,
publicScreenshots,
bounded,
);
const landingDirectory = path.join(temporary, "landing");
await regenerateRunnerDashboard({
bundle: s3ReportRoot,
historyFile,
outputDirectory: landingDirectory,
evidenceHrefPrefix: `campaigns/${campaign.campaignId}`,
});
await writeFile(
path.join(landingDirectory, "index.html"),
renderRunnerHistoryIndex(history),
"utf8",
);
if (publisher) {
const mutableFiles = [
{ key: historyKey, file: historyFile, contentType: "application/json" },
{ key: `${destination.prefix}/latest.json`, file: latestFile, contentType: "application/json" },
{ key: `${destination.prefix}/latest-green.json`, file: latestGreenFile, contentType: "application/json" },
...["index.html", "dashboard.html", "normalized-results.json"].map(file => ({ key: `${destination.prefix}/${file}`,
file: path.join(landingDirectory, file), contentType: file.endsWith("json") ? "application/json" : "text/html; charset=utf-8" })),
...["favicon-32x32.png", "InterVariable.woff2"].map(file => ({ key: `${destination.prefix}/assets/${file}`,
file: path.join(s3ReportRoot, "assets", file), contentType: file.endsWith("png") ? "image/png" : "font/woff2" })),
];
const metadata = async (file: string) => ({ path: file, bytes: (await stat(file)).size });
const campaignSize = checkHistoryPayload([...manifest.files, await metadata(manifestFile)],
HISTORY_LIMITS.campaignBytes, HISTORY_LIMITS.campaignFiles, "Public campaign with manifest");
const mutableMetadata = await Promise.all(mutableFiles.map(file => metadata(file.file)));
const mutableSize = checkHistoryPayload(mutableMetadata, HISTORY_LIMITS.mutableBytes, 8, "Mutable history");
const pointerMetadata = await Promise.all([historyFile, latestFile, latestGreenFile].map(metadata));
checkHistoryPayload(pointerMetadata, HISTORY_LIMITS.jsonBytes, 3, "History JSON");
const pagesSize = checkHistoryPayload([...pagesManifest.files, ...pointerMetadata],
HISTORY_LIMITS.pagesBytes, HISTORY_LIMITS.campaignFiles + 3, "Pages bundle");
if (!existingManifest) {
await uploadImmutableBundle(bucket, campaignPrefix, s3ReportRoot, manifest, publisher);
await publisher.upload(bucket, manifestKey, manifestFile, "application/json", "public,max-age=2592000,immutable", true);
}
for (const file of mutableFiles) await publisher.upload(bucket, file.key, file.file, file.contentType, "no-cache");
console.log(JSON.stringify({ campaign: campaignSize, mutable: mutableSize, pages: pagesSize, billedUsd: null }));
return;
}
if (!existingManifest) {
await uploadImmutableBundle(bucket, campaignPrefix, s3ReportRoot);
await uploadJson(bucket, manifestKey, manifestFile, "public,max-age=31536000,immutable");
}
await Promise.all([
uploadJson(bucket, historyKey, historyFile, "no-cache"),
uploadJson(
bucket,
`${destination.prefix}/latest.json`,
latestFile,
"no-cache",
),
uploadJson(
bucket,
`${destination.prefix}/latest-green.json`,
latestGreenFile,
"no-cache",
),
uploadFile(
bucket,
`${destination.prefix}/index.html`,
path.join(landingDirectory, "index.html"),
"text/html; charset=utf-8",
"no-cache",
),
uploadFile(
bucket,
`${destination.prefix}/dashboard.html`,
path.join(landingDirectory, "dashboard.html"),
"text/html; charset=utf-8",
"no-cache",
),
uploadFile(
bucket,
`${destination.prefix}/normalized-results.json`,
path.join(landingDirectory, "normalized-results.json"),
"application/json",
"no-cache",
),
uploadFile(
bucket,
`${destination.prefix}/assets/favicon-32x32.png`,
path.join(s3ReportRoot, "assets", "favicon-32x32.png"),
"image/png",
"public,max-age=86400",
),
uploadFile(
bucket,
`${destination.prefix}/assets/InterVariable.woff2`,
path.join(s3ReportRoot, "assets", "InterVariable.woff2"),
"font/woff2",
"public,max-age=86400",
),
]);
console.log(
`Published immutable campaign ${campaign.campaignId} (${manifest.bundleDigest}) and ${history.campaigns.length} history record(s)`,
);
}
if (
process.argv[1] &&
path.resolve(process.argv[1]) === path.resolve(import.meta.filename)
) {
await main().catch((error) => {
console.error(error instanceof Error ? error.message : String(error));
process.exitCode = 1;
});
}