mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-10-24 10:13:11 +02:00
## Thinking Path > - Paperclip manages agents and the work they perform. > - Product E2E tests exercise real agents, tools, setup and cleanup. > - Repeated runs need retained costs and traces, including failed attempts. > - A passing retry must not hide earlier spending or feedback. > - Recurring work also needs admission limits, private reports and failure detection. > - This change supplies those controls while keeping paid activation behind existing gates. ## Linked Issues or Issue Description Refs #16996 and #17158. This is the consolidated landing of the reviewed eval operations stack: #17019, #17024, #17025, #17027, #17030, #17033, #17035, #17038, #17043, #17044, #17048, #17050, #17051, #17092, #17096, #17100, #17107, #17109, #17112, #17115, #17117, #17121, #17123, #17127, #17130, #17133, #17134, #17137, #17140, #17143, #17154. The repository permits squash merges only. A local rehearsal showed that squashing each slice into master causes repeated conflicts in dependent slices. This PR preserves their commits and lands their combined implementation in one reviewed integration. Superseded slices will close after this merge. ## What Changed - Retain every attempt's cost receipt, including setup, failures, interruptions and retries. Separate reported amounts, estimates, missing costs and reserved capacity in reports and dashboards. - Add bounded request admission, exact model pricecards, gateway error accounting, cache policy and reconciliation evidence. Refuse unsupported routes and requests that cannot fit the allowance. - Integrate Braintrust gateway traces and OTLP correlation, with secret filtering and experiment imports. Record phase timing, including setup, feedback capture and cleanup. - Collect complaint and suggestion evidence after each attempt, including recovery after failures. Retain explicit review dispositions independently from the product grade. - Add gated daily and weekly selections, measured forecasts, setup/readiness checks, wall-time limits and retained monitor notifications. Include declared non-model overhead in admission while reporting the existing subscription separately. - Keep recurring history private, bound uploads and retention, and use isolated archive environments. Keep public publication an explicit operation. Report and publication jobs install only the committed lockfile, with scripts disabled and isolated stores; stale pins fail closed. - Integrate current master, preserve its Product E2E journey billing and privacy checks, and test that shared setup receipts do not double-count estimated agent usage. Preserve upstream fixture repairs. ## Verification - Complete integration baseline `0649a5ce7544ab20825c2183d2f421157db49f24` includes master `a3e1d915a7110a4e115b46396a3f79e6dfb4d05e` and every original stack head as ancestors. - On that integration baseline, `pnpm test:e2e:runner:unit`: 4,012 Vitest tests passed, two skipped, across 193 files; all 137 Node source-contract tests passed. - Focused billing and Product E2E journey contract checks: 24 tests passed. They cover estimates, unknown receipts, single-owner setup costs, browser-only execution and private publication guards. - Monitor and workflow wiring: all 96 Node tests passed. `node scripts/check-token-gates.mjs`: all gates clean. - `pnpm test:e2e:runner:typecheck` passes after the standard Runner TypeScript build refreshed local declarations. The first attempt rejected the new master `runner_prepared_launch` union member because this checkout retained an older generated declaration; the source union already contained that member. - Current head `492b0708a1c531a023d9ac10f0f3dc6383cc1754` removes dependency re-resolution from archive-authorized reporting jobs after the security scan flagged it. All 15 workflow-security tests pass after updating the old two-install assertion. - Hosted [CI run 39965460180](https://github.com/paperclipai/paperclip/actions/runs/39965460180) passes on the current repaired head, including typecheck, build, general tests, Runner checks, browser shards and canary dry run. Greptile is 5/5 on this exact head with no unresolved threads. The security scan passes after the fixed lockfile-resolution thread was resolved. - Paperclip Review returned a terminal neutral check but an incomplete 0-file assessment on the repaired head: its platform blocked both diff responses as prompt-injection content. This is not a successful code review. No bypass or fabricated pass was attempted; current-head Greptile, security and hosted CI are independent gates. - No paid test, reservation release or recurring-run activation accompanies this landing. Live route qualification and invoice reconciliation remain separate evidence. <details> <summary>Retained earlier validation failures</summary> Earlier broad local runs had two 15-second test timeouts (CLI poll cadence and Retry validation), one embedded-database setup timeout, and later PostgreSQL semaphore exhaustion. The exact timed-out tests passed separately without larger timeouts; the broad-run causes were not established. Those local failures remain distinct from subsequent hosted CI results. The independent #17158 fix records its Muse fixture collision, its UUID correction and hosted verification. Local Muse execution was also blocked by macOS embedded-PostgreSQL startup. No historical failure is treated as a successful paid qualification. </details> ## Risks - Admission is a local control, not a provider invoice cap. Missing provider receipts or resource charges retain unknown amounts and holds; estimates do not become billed dollars. - The bounded path admits only documented local suites and provider routes. Ordinary legacy or separate Runner protocol campaigns have different controls. Merging this code does not qualify additional routes. - Recurrence still needs the existing enable gates and current qualification/allowance evidence. Archive permissions and resources must match the documented private-environment contract. - Legacy reports may lack complete attempt or phase evidence. Reports preserve that limitation and do not infer zero usage from missing data. ## Model Used OpenAI GPT-6 through Codex, with reasoning, repository tools and code execution. The exact deployment variant and context-window size are not exposed by this session. ## 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 (targeted checks; full-suite host limitation disclosed above) - [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>
217 lines
14 KiB
TypeScript
217 lines
14 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { mkdir, mkdtemp, readFile, readdir, rm, stat, writeFile } from "node:fs/promises";
|
|
import * as fs from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { expect, it, vi } from "vitest";
|
|
import { openEvalCostLedger, readEvalCostLedger } from "./cost-ledger.js";
|
|
import { EVAL_OVERHEAD_COMPONENTS, type EvalOperatingOverhead } from "./operating-overhead.js";
|
|
import { importOperatingReceipt, operatingReceiptObservation, type EvalOperatingReceipt } from "./operating-receipts.js";
|
|
|
|
vi.mock("node:fs/promises", async (importOriginal) => {
|
|
const actual = await importOriginal<typeof fs>();
|
|
return { ...actual, open: vi.fn(actual.open) };
|
|
});
|
|
|
|
const evidence = Buffer.from("fixture-only infrastructure receipt");
|
|
const overhead: EvalOperatingOverhead = { version: 1, runner: "github-hosted", reference: "fixture-allowance",
|
|
verifiedAt: "2026-10-01T00:00:00Z", expiresAt: "2026-11-01T00:00:00Z",
|
|
components: EVAL_OVERHEAD_COMPONENTS.map(component => ({ component, maxUsd: "1", reference: `fixture-${component}` })) };
|
|
const receipt = (fields: Partial<EvalOperatingReceipt> = {}): EvalOperatingReceipt => ({ version: 2, costBasis: "component_cumulative", campaignId: "fixture",
|
|
allowanceReference: overhead.reference, component: "artifact_storage", evidenceSha256: createHash("sha256").update(evidence).digest("hex"),
|
|
windowStartedAt: "2026-10-01T00:00:00Z", windowEndedAt: "2026-10-02T00:00:00Z", coverage: "partial",
|
|
source: "infrastructure", provider: "fixture", classification: "estimated", costUsd: "0.2", pricingVersion: "fixture-pricing", ...fields });
|
|
const now = Date.parse("2026-10-03T00:00:00Z");
|
|
|
|
it("binds operating observations to the campaign, allowance, evidence and closed observation window", () => {
|
|
expect(operatingReceiptObservation(receipt(), "fixture", overhead, evidence, now)).toMatchObject({ requestId: "overhead:artifact_storage", final: false });
|
|
for (const changed of [receipt({ campaignId: "other" }), receipt({ allowanceReference: "other" }), receipt({ evidenceSha256: "0".repeat(64) }),
|
|
receipt({ windowEndedAt: "2026-10-04T00:00:00Z" }), receipt({ windowStartedAt: "2026-10-03T00:00:00Z" }),
|
|
receipt({ component: "model" as never }), receipt({ version: 1 as never }), receipt({ costBasis: undefined }),
|
|
receipt({ costBasis: "window_charge" as never }), { ...receipt(), apiKey: "disallowed" }]) {
|
|
expect(() => operatingReceiptObservation(changed, "fixture", overhead, evidence, now)).toThrow();
|
|
}
|
|
expect(() => operatingReceiptObservation(receipt(), "fixture", overhead, Buffer.from("different"), now)).toThrow();
|
|
});
|
|
|
|
it("does not upgrade missing or partial evidence to an invoice or completed receipt", () => {
|
|
for (const changed of [receipt({ classification: "reconciled" }), receipt({ classification: "unknown" }),
|
|
receipt({ classification: "unknown", costUsd: undefined, coverage: "complete" }), receipt({ pricingVersion: undefined }), receipt({ costUsd: "-1" })]) {
|
|
expect(() => operatingReceiptObservation(changed, "fixture", overhead, evidence, now)).toThrow();
|
|
}
|
|
expect(operatingReceiptObservation(receipt({ classification: "unknown", costUsd: undefined }), "fixture", overhead, evidence, now))
|
|
.toMatchObject({ classification: "unknown", final: false });
|
|
expect(operatingReceiptObservation(receipt({ component: "shared_subscription", classification: "allocated", coverage: "complete" }), "fixture", overhead, evidence, now))
|
|
.toMatchObject({ classification: "allocated", route: "subscription", final: true });
|
|
});
|
|
|
|
async function fixture(maxUsd = "20") {
|
|
const directory = await mkdtemp(path.join(tmpdir(), "operating-receipts-"));
|
|
const ledgerPath = path.join(directory, "ledger.jsonl");
|
|
const ledger = await openEvalCostLedger(ledgerPath, { campaignId: "fixture", maxUsd, deadlineAt: "2099-01-01T00:00:00Z",
|
|
maxRequests: 10, maxConcurrent: 1, maxAttemptsPerExecution: 1, overhead });
|
|
await ledger.close();
|
|
return { directory, ledgerPath };
|
|
}
|
|
|
|
it("retains private source evidence, imports idempotently and keeps partial holds until invoice reconciliation", async () => {
|
|
const { directory, ledgerPath } = await fixture();
|
|
try {
|
|
expect(await importOperatingReceipt(ledgerPath, receipt(), evidence)).toMatchObject({ knownUsd: "0.200000000", heldUsd: "3.800000000", unknownRequests: 4 });
|
|
const before = await readFile(ledgerPath, "utf8");
|
|
await importOperatingReceipt(ledgerPath, Object.fromEntries(Object.entries(receipt()).reverse()) as unknown as EvalOperatingReceipt, evidence);
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
const retained = path.join(`${ledgerPath}.overhead`, `${receipt().evidenceSha256}.evidence`);
|
|
expect(await readFile(retained)).toEqual(evidence);
|
|
expect((await stat(retained)).mode & 0o777).toBe(0o600);
|
|
expect(await readdir(`${ledgerPath}.overhead`)).toHaveLength(2);
|
|
expect(await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "0.3", coverage: "complete" }), evidence))
|
|
.toMatchObject({ knownUsd: "0.300000000", heldUsd: "3.000000000", unknownRequests: 3 });
|
|
expect(await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "0.4", coverage: "complete" }), evidence))
|
|
.toMatchObject({ knownUsd: "0.400000000", heldUsd: "3.600000000", conflictingRequests: 1 });
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it("fails before ledger mutation when retained evidence is corrupt or another writer owns the journal", async () => {
|
|
const { directory, ledgerPath } = await fixture();
|
|
try {
|
|
await importOperatingReceipt(ledgerPath, receipt(), evidence);
|
|
const before = await readFile(ledgerPath, "utf8");
|
|
await writeFile(path.join(`${ledgerPath}.overhead`, `${receipt().evidenceSha256}.evidence`), "corrupted");
|
|
await expect(importOperatingReceipt(ledgerPath, receipt({ costUsd: "0.5" }), evidence)).rejects.toThrow("conflicts");
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
const loaded = await readEvalCostLedger(ledgerPath), writer = await openEvalCostLedger(ledgerPath, loaded.state.limits);
|
|
try { await expect(importOperatingReceipt(ledgerPath, receipt(), evidence)).rejects.toThrow("writer lock"); }
|
|
finally { await writer.close(); }
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it("rejects separate partial windows and accounts for their cumulative total before admitting more work", async () => {
|
|
const { directory, ledgerPath } = await fixture("4.5");
|
|
try {
|
|
await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "0.8" }), evidence);
|
|
const before = await readFile(ledgerPath, "utf8");
|
|
await expect(importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "0.8",
|
|
windowStartedAt: "2026-10-02T00:00:00Z", windowEndedAt: "2026-10-03T00:00:00Z" }), evidence)).rejects.toThrow("cumulative component window");
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
expect(await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "1.6",
|
|
windowEndedAt: "2026-10-03T00:00:00Z" }), evidence)).toMatchObject({ knownUsd: "1.600000000", heldUsd: "3.000000000", committedUsd: "4.600000000", overBudget: true });
|
|
const loaded = await readEvalCostLedger(ledgerPath), writer = await openEvalCostLedger(ledgerPath, loaded.state.limits);
|
|
try {
|
|
await writer.admitAttempt("fixture-cell", "next");
|
|
await expect(writer.reserve("next", { executionId: "fixture-cell", attemptId: "next", phase: "agent" }, "0.01"))
|
|
.rejects.toThrow("spending cap reached");
|
|
} finally { await writer.close(); }
|
|
await expect(importOperatingReceipt(ledgerPath, receipt({ costUsd: "0.9" }), evidence)).rejects.toThrow("cumulative component window");
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it.each(["partial", "complete"] as const)("rejects a larger cumulative estimate hidden by an earlier %s invoice", async coverage => {
|
|
const { directory, ledgerPath } = await fixture("4.5");
|
|
try {
|
|
await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "0.8", coverage }), evidence);
|
|
const before = await readFile(ledgerPath, "utf8"), retained = await readdir(`${ledgerPath}.overhead`);
|
|
await expect(importOperatingReceipt(ledgerPath, receipt({ costUsd: "1.6", coverage,
|
|
windowEndedAt: "2026-10-03T00:00:00Z" }), evidence)).rejects.toThrow("would understate the cumulative total");
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
expect(await readdir(`${ledgerPath}.overhead`)).toEqual(retained);
|
|
const updated = await importOperatingReceipt(ledgerPath, receipt({ source: "invoice", classification: "reconciled", costUsd: "1.6", coverage,
|
|
windowEndedAt: "2026-10-03T00:00:00Z" }), evidence);
|
|
expect(updated).toMatchObject({ knownUsd: "1.600000000", committedUsd: "4.600000000", overBudget: true });
|
|
const loaded = await readEvalCostLedger(ledgerPath), writer = await openEvalCostLedger(ledgerPath, loaded.state.limits);
|
|
try {
|
|
await writer.admitAttempt("fixture-cell", "next");
|
|
await expect(writer.reserve("next", { executionId: "fixture-cell", attemptId: "next", phase: "agent" }, "0.01"))
|
|
.rejects.toThrow(coverage === "complete" ? "receipts conflict" : "spending cap reached");
|
|
} finally { await writer.close(); }
|
|
} finally { await rm(directory, { recursive: true, force: true }); }
|
|
});
|
|
|
|
it.each(["evidence", "receipt.json"])("retries must persist the existing %s file before recording its charge", async suffix => {
|
|
const { directory, ledgerPath } = await fixture();
|
|
const before = await readFile(ledgerPath, "utf8"), originalOpen = (await vi.importActual<typeof fs>("node:fs/promises")).open;
|
|
const value = receipt(), canonical = Object.fromEntries(Object.entries(value).sort(([a], [b]) => a.localeCompare(b)));
|
|
const observation = operatingReceiptObservation(value, "fixture", overhead, evidence, now);
|
|
await mkdir(`${ledgerPath}.overhead`, { mode: 0o700 });
|
|
await writeFile(path.join(`${ledgerPath}.overhead`, suffix === "evidence" ? `${value.evidenceSha256}.evidence`
|
|
: `${observation.observationId.split(":")[1]}.receipt.json`), suffix === "evidence" ? evidence : `${JSON.stringify(canonical, null, 2)}\n`, { mode: 0o600 });
|
|
let syncs = 0;
|
|
const opened = vi.mocked(fs.open).mockImplementation(async (...args) => {
|
|
const handle = await originalOpen(...args);
|
|
if (String(args[0]).endsWith(`.${suffix}`)) {
|
|
const originalSync = handle.sync.bind(handle);
|
|
vi.spyOn(handle, "sync").mockImplementation(async () => {
|
|
if (++syncs <= 2) throw new Error("fixture file sync failure");
|
|
await originalSync();
|
|
});
|
|
}
|
|
return handle;
|
|
});
|
|
try {
|
|
for (let attempt = 0; attempt < 2; attempt++) {
|
|
await expect(importOperatingReceipt(ledgerPath, receipt(), evidence)).rejects.toThrow("file sync failure");
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
}
|
|
expect(await importOperatingReceipt(ledgerPath, receipt(), evidence)).toMatchObject({ knownUsd: "0.200000000", heldUsd: "3.800000000" });
|
|
expect(syncs).toBe(3);
|
|
} finally {
|
|
opened.mockImplementation(originalOpen);
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it.each(["evidence", "receipt.json"])("recovers an incomplete %s write without publishing corrupt evidence or requiring manual deletion", async suffix => {
|
|
const { directory, ledgerPath } = await fixture();
|
|
const before = await readFile(ledgerPath, "utf8"), originalOpen = (await vi.importActual<typeof fs>("node:fs/promises")).open;
|
|
let injected = false;
|
|
const opened = vi.mocked(fs.open).mockImplementation(async (...args) => {
|
|
const handle = await originalOpen(...args);
|
|
if (!injected && String(args[0]).includes(`.${suffix}.`) && String(args[0]).endsWith(".tmp")) {
|
|
const originalWrite = handle.writeFile.bind(handle);
|
|
vi.spyOn(handle, "writeFile").mockImplementation(async () => {
|
|
injected = true;
|
|
await originalWrite("partial");
|
|
throw new Error("fixture partial write");
|
|
});
|
|
}
|
|
return handle;
|
|
});
|
|
try {
|
|
await expect(importOperatingReceipt(ledgerPath, receipt(), evidence)).rejects.toThrow("partial write");
|
|
expect(injected).toBe(true);
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
expect((await readdir(`${ledgerPath}.overhead`)).some(name => name.endsWith(`.${suffix}`) || name.endsWith(".tmp"))).toBe(false);
|
|
expect(await importOperatingReceipt(ledgerPath, receipt(), evidence)).toMatchObject({ knownUsd: "0.200000000", heldUsd: "3.800000000" });
|
|
expect(await readdir(`${ledgerPath}.overhead`)).toHaveLength(2);
|
|
} finally {
|
|
opened.mockImplementation(originalOpen);
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
it("retains the hold when the first evidence directory cannot be persisted in its parent", async () => {
|
|
const { directory, ledgerPath } = await fixture();
|
|
const before = await readFile(ledgerPath, "utf8"), originalOpen = (await vi.importActual<typeof fs>("node:fs/promises")).open;
|
|
let parentSyncs = 0;
|
|
const opened = vi.mocked(fs.open).mockImplementation(async (...args) => {
|
|
const handle = await originalOpen(...args);
|
|
if (args[0] === directory && args[1] === "r") {
|
|
vi.spyOn(handle, "sync").mockImplementation(async () => {
|
|
parentSyncs++;
|
|
throw new Error("fixture parent directory sync failure");
|
|
});
|
|
}
|
|
return handle;
|
|
});
|
|
try {
|
|
await expect(importOperatingReceipt(ledgerPath, receipt(), evidence)).rejects.toThrow("parent directory sync failure");
|
|
expect(parentSyncs).toBe(1);
|
|
expect(await readFile(ledgerPath, "utf8")).toBe(before);
|
|
expect((await readEvalCostLedger(ledgerPath)).state.snapshot()).toMatchObject({ knownUsd: "0.000000000", heldUsd: "4.000000000" });
|
|
} finally {
|
|
opened.mockImplementation(originalOpen);
|
|
await rm(directory, { recursive: true, force: true });
|
|
}
|
|
});
|