mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-10 01:50:13 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart chaos harness (`tests/restart-chaos/`) restarts the control plane during real agent tasks and grades each task on rules R1–R6 > - One known product bug (RC-06) leaves a completed run "awaiting accounting". The company hard stop then refuses all new work, so one stuck row fails every later task in the wave > - That masks every other restart bug in the wave. Waves also had no record of what they spent > - This pull request adds an opt-in RC-06 mask, records wave spend, and lets a replay keep or add the mask > - The benefit is that chaos waves can find new restart bugs while RC-06 is open, and stay inside a known spend ## Linked Issues or Issue Description Refs #19477 (the Phase 1 harness this extends). **What existing behavior does this improve?** Restart chaos waves. One stuck accounting row (RC-06) hard-stops the isolated Chaos Lab company. All later tasks then rest blocked "over budget", and a Retry is refused with "Company cannot start work while completed runs await accounting". Two waves went 2/6 and 0/6 for this one reason. **Subsystem affected** Test harness only: `tests/restart-chaos/` (config, seed, scheduler, ledger, supervisor, main, README). **Current behavior** - No way to see past RC-06 without disabling the budget. - Wave spend is not recorded. - `--replay` rejected any mask flag, and it was not documented that the saved plan carries the mask. **Proposed behavior** - `--rc06-masked` keeps the budget amount and turns off only the hard stop on the isolated company. Masked tasks are labeled in the ledger and summary. - Each wave records its spend. - A replay keeps the source plan's masks and may add the RC-06 mask. ## What Changed - `--rc06-masked` (wave mode): after the company is created, the seed upserts the company budget policy with the same amount and `hardStopEnabled: false`. It writes `seed_mask_rc06` to the timeline. The plan stores `options.masks = ["rc06"]`. - The accounting gate in `budgets.ts` (`observedBlocks`) applies only when `hardStopEnabled` is true, so the mask lifts it. No product code changes. - Ledger lines carry `masks`. `SUMMARY.md` labels the cell and the latest-wave row `rc06-masked`. - Wave spend: before the sweep, `main.ts` reads `/api/companies/:id/costs/summary?period=all` (each wave owns its company), writes `wave_spend` to the timeline and prints it. If the wave stops early, cleanup records it once, best effort, before the server stops. - Load: #19513 already records `loadAvg1m` on each fault receipt. This branch first added the same value under another name, and the rebase removed it. The README now documents `loadAvg1m` and the load-suspect threshold. - Replay: `--replay <wave>/<task>` keeps the masks saved in the source `plan.json`. `--replay … --rc06-masked` adds the RC-06 mask. A replay never drops a mask. - README documents the flag, spend, load and the replay rule. - New unit tests: replay keeps saved masks and the replay flag adds the mask; the masked seed posts the company policy with the same amount and `hardStopEnabled: false` and records `seed_mask_rc06`, and an unmasked seed makes no policy call. ## Verification - `pnpm exec vitest run --config tests/restart-chaos/vitest.config.ts`: 71/71 pass (after rebase onto master with #19513). - `node scripts/typecheck-test-projects.mjs tests/restart-chaos`: pass. - Live: 4 masked local waves ran with this code (seeds 3307, 4409, 5501, 6619; Codex, ACPX Claude and OpenCode). - `seed_mask_rc06` appeared and no task was blocked by the accounting gate, even though `pendingRunCount` was 1–8 at wave end. - `wave_spend` was recorded each time (38¢–127¢ per wave). - The 1-minute load average was recorded on every fault (15–58). - Before the mask, the same harness gave 2/6 and 0/6, every failure RC-06. With the mask, the waves found other restart failures, all since fixed on master: RC-14, RC-16, RC-20 and RC-21. ## Risks - Low risk. Test harness only, and the mask is opt-in. - A masked wave has no product hard stop. The harness still records spend for each wave, and the operator must watch it. The mask applies only to the isolated, temporary Chaos Lab company. It never touches another instance. - Masked results do not count as RC-06 coverage. The ledger labels them so they are not mixed with unmasked cells. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file edit). Extended reasoning on. ## 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 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
145 lines
7.4 KiB
TypeScript
145 lines
7.4 KiB
TypeScript
import { parseArgs } from "node:util";
|
||
import {
|
||
ADAPTER_IDS, ENVIRONMENT_KINDS, FAULT_KINDS, TRIGGER_IDS, WORKLOAD_IDS,
|
||
type AdapterId, type EnvironmentKind, type FaultKind, type TriggerId, type WaveOptions, type WorkloadId,
|
||
} from "./types.js";
|
||
|
||
export const CREDENTIAL_FOR_ADAPTER: Record<AdapterId, "OPENAI_API_KEY" | "ANTHROPIC_API_KEY" | "OPENROUTER_API_KEY"> = {
|
||
codex: "OPENAI_API_KEY",
|
||
claude: "ANTHROPIC_API_KEY",
|
||
opencode: "OPENROUTER_API_KEY",
|
||
};
|
||
|
||
/** Catalog profile reused from tests/runner-e2e/catalog.ts for each adapter. */
|
||
export const PROFILE_FOR_ADAPTER: Record<AdapterId, string> = {
|
||
codex: "runner-codex",
|
||
claude: "runner-acpx-claude",
|
||
opencode: "runner-opencode",
|
||
};
|
||
|
||
/**
|
||
* Chaos sandboxes run in the company Daytona org next to the live Cloud fleet.
|
||
* They use the runner-e2e fixture's 4 vCPU by default, and task sandboxes may
|
||
* use at most 40 vCPU in total, a small fraction of the fleet's capacity. Set
|
||
* RESTART_CHAOS_DAYTONA_VCPU_BUDGET lower for a smaller org (a 10 vCPU org
|
||
* fails creates with HTTP 400 "Total CPU limit exceeded"; use 8 there so
|
||
* verification probes still fit).
|
||
*/
|
||
export const DAYTONA_DEFAULT_CPU = 4;
|
||
export const DAYTONA_VCPU_BUDGET = 40;
|
||
|
||
export type ParsedCommand =
|
||
| { mode: "wave"; options: WaveOptions; keep: boolean }
|
||
| { mode: "replay"; ref: ReplayRef; keep: boolean; overrides: Partial<Pick<WaveOptions, "pollMs" | "budgetCents" | "masks">> };
|
||
|
||
export interface ReplayRef { waveId: string; taskId: string }
|
||
|
||
const WAVE_ID = /^w-[0-9]{8}T[0-9]{6}-s[0-9]+(?:-replay-t[0-9]{2,3}-[0-9]+)?$/;
|
||
const TASK_ID = /^t[0-9]{2,3}$/;
|
||
|
||
export function parseReplayRef(value: string): ReplayRef {
|
||
const trimmed = value.trim().replace(/\/+$/, "");
|
||
const parts = trimmed.split("/");
|
||
if (parts.length !== 2) throw new Error(`--replay expects <wave>/<task>, got "${value}"`);
|
||
const [waveId, taskId] = parts as [string, string];
|
||
if (!WAVE_ID.test(waveId)) throw new Error(`Invalid wave id "${waveId}"`);
|
||
if (!TASK_ID.test(taskId)) throw new Error(`Invalid task id "${taskId}"`);
|
||
return { waveId, taskId };
|
||
}
|
||
|
||
function list<T extends string>(raw: string | undefined, allowed: readonly T[], name: string, fallback: readonly T[]): T[] {
|
||
if (raw === undefined) return [...fallback];
|
||
const values = raw.split(",").map(value => value.trim()).filter(Boolean);
|
||
if (!values.length) throw new Error(`--${name} must not be empty`);
|
||
for (const value of values) if (!allowed.includes(value as T)) throw new Error(`Unknown ${name} "${value}"; allowed: ${allowed.join(", ")}`);
|
||
return [...new Set(values)] as T[];
|
||
}
|
||
|
||
function integer(raw: string | undefined, name: string, fallback: number, min: number, max: number): number {
|
||
if (raw === undefined) return fallback;
|
||
if (!/^[0-9]+$/.test(raw)) throw new Error(`--${name} must be a non-negative integer`);
|
||
const value = Number(raw);
|
||
if (!Number.isSafeInteger(value) || value < min || value > max) throw new Error(`--${name} must be between ${min} and ${max}`);
|
||
return value;
|
||
}
|
||
|
||
export function parseCommand(argv: readonly string[], now = Date.now()): ParsedCommand {
|
||
// Tolerate a forwarded literal `--` (for example from a package runner).
|
||
const args = argv[0] === "--" ? argv.slice(1) : [...argv];
|
||
const { values } = parseArgs({
|
||
args,
|
||
strict: true,
|
||
options: {
|
||
env: { type: "string" },
|
||
adapters: { type: "string" },
|
||
workloads: { type: "string" },
|
||
faults: { type: "string" },
|
||
triggers: { type: "string" },
|
||
concurrency: { type: "string" },
|
||
tasks: { type: "string" },
|
||
seed: { type: "string" },
|
||
"budget-cents": { type: "string" },
|
||
"poll-ms": { type: "string" },
|
||
replay: { type: "string" },
|
||
"daytona-image": { type: "string" },
|
||
"daytona-cpu": { type: "string" },
|
||
keep: { type: "boolean" },
|
||
"rc06-masked": { type: "boolean" },
|
||
},
|
||
});
|
||
const keep = values.keep === true;
|
||
const pollMs = integer(values["poll-ms"], "poll-ms", 3_000, 2_000, 5_000);
|
||
const budgetCents = integer(values["budget-cents"], "budget-cents", 3_000, 1, 100_000);
|
||
if (values.replay !== undefined) {
|
||
for (const key of ["env", "adapters", "workloads", "faults", "triggers", "concurrency", "tasks", "seed", "daytona-image", "daytona-cpu"] as const) {
|
||
if (values[key] !== undefined) throw new Error(`--replay reproduces the saved plan; do not combine it with --${key}`);
|
||
}
|
||
return { mode: "replay", ref: parseReplayRef(values.replay), keep,
|
||
overrides: { ...(values["poll-ms"] ? { pollMs } : {}), ...(values["budget-cents"] ? { budgetCents } : {}),
|
||
// The saved plan already carries its masks; this adds the RC-06 mask to a replay of an unmasked wave.
|
||
...(values["rc06-masked"] ? { masks: ["rc06"] } : {}) } };
|
||
}
|
||
const env = (values.env ?? "local") as EnvironmentKind;
|
||
if (!ENVIRONMENT_KINDS.includes(env)) throw new Error(`Unknown env "${env}"; allowed: ${ENVIRONMENT_KINDS.join(", ")}`);
|
||
const daytonaImage = values["daytona-image"] ?? (env === "daytona" ? process.env.PAPERCLIP_E2E_DAYTONA_IMAGE : undefined);
|
||
if (env === "daytona" && !/^.+@sha256:[0-9a-f]{64}$/.test(daytonaImage ?? "")) {
|
||
throw new Error("--env daytona needs an immutable runner image: --daytona-image <registry/repository@sha256:…> or PAPERCLIP_E2E_DAYTONA_IMAGE");
|
||
}
|
||
if (env !== "daytona" && values["daytona-image"] !== undefined) throw new Error("--daytona-image applies only to --env daytona");
|
||
// B5 grades bench.sh progress read from the live workspace while it runs. A
|
||
// Daytona run's live workspace is inside the sandbox, so B5 is local-only.
|
||
const workloadChoices = env === "daytona" ? WORKLOAD_IDS.filter(id => id !== "B5") : WORKLOAD_IDS;
|
||
const options: WaveOptions = {
|
||
env,
|
||
adapters: list<AdapterId>(values.adapters, ADAPTER_IDS, "adapters", ["codex", "claude"]),
|
||
workloads: list<WorkloadId>(values.workloads, workloadChoices, "workloads", workloadChoices),
|
||
faults: list<FaultKind>(values.faults, FAULT_KINDS, "faults", ["K1", "K2", "K4"]),
|
||
triggers: list<TriggerId>(values.triggers, TRIGGER_IDS, "triggers", ["time"]),
|
||
concurrency: integer(values.concurrency, "concurrency", 4, 1, 20),
|
||
tasks: integer(values.tasks, "tasks", 8, 1, 200),
|
||
seed: integer(values.seed, "seed", now % 2_147_483_647, 0, 2_147_483_647),
|
||
budgetCents,
|
||
pollMs,
|
||
...(env === "daytona" ? { daytonaImage, daytonaCpu: integer(values["daytona-cpu"], "daytona-cpu", DAYTONA_DEFAULT_CPU, 1, 4) } : {}),
|
||
...(values["rc06-masked"] ? { masks: ["rc06"] } : {}),
|
||
};
|
||
if (env !== "daytona" && values["daytona-cpu"] !== undefined) throw new Error("--daytona-cpu applies only to --env daytona");
|
||
if (options.daytonaCpu !== undefined) {
|
||
const budget = integer(process.env.RESTART_CHAOS_DAYTONA_VCPU_BUDGET, "RESTART_CHAOS_DAYTONA_VCPU_BUDGET", DAYTONA_VCPU_BUDGET, 1, 1_000);
|
||
if (options.concurrency * options.daytonaCpu > budget) {
|
||
throw new Error(`--concurrency ${options.concurrency} × --daytona-cpu ${options.daytonaCpu} vCPU exceeds the Daytona vCPU budget of ${budget} `
|
||
+ "for chaos tasks. Lower one of them (RESTART_CHAOS_DAYTONA_VCPU_BUDGET sets the budget).");
|
||
}
|
||
}
|
||
return { mode: "wave", options, keep };
|
||
}
|
||
|
||
export function waveIdFor(seed: number, at = new Date()): string {
|
||
const stamp = at.toISOString().replace(/[-:]/g, "").replace(/\.\d{3}Z$/, "");
|
||
return `w-${stamp}-s${seed}`;
|
||
}
|
||
|
||
export function replayCommand(waveId: string, taskId: string): string {
|
||
return `node cli/node_modules/tsx/dist/cli.mjs tests/restart-chaos/main.ts --replay ${waveId}/${taskId}`;
|
||
}
|