mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-12-04 12:50:37 +01:00
## Thinking Path > - Paperclip is the open source app people use to manage AI agents for work > - The restart chaos TTFT driver measures time to first token, but only with a tiny fixture workspace and only locally > - Dotta asked whether speed is good with a workspace like the paperclip repository itself, and that had never been measured > - This pull request lets the driver run in a real repository workspace, measure the first follow-up after an idle restart, run on Daytona (per-turn or warm reusable sandboxes), and report each run's workspace operations > - The benefit is a repeatable large-workspace speed measurement; its first run found a full workspace re-upload on every remote turn ## Linked Issues or Issue Description **What happened?** The TTFT driver seeded only a tiny fixture repository, created tasks outside any project, ran only locally, and could not show workspace operation durations. So large-workspace speed (worktree creation, provision, remote upload) was never measured. **Steps to reproduce** 1. Run `ttft-baseline.ts` with any options. 2. Every task runs without a project workspace and on the local host. 3. Nothing in the report shows worktree, provision or sync cost. **Expected behavior** The driver can measure a real repository workspace, locally and on Daytona, and names the workspace operations each run waited on. ## What Changed - `--workspace-repo <path>`: the seed uses that repository as the project's primary workspace (git_worktree isolation), and tasks are created in the project. - A `postfault` phase: K1 while idle, then a follow-up on each task; reported in its own table. - `--env daytona`, `--daytona-image`, `--daytona-cpu`, `--daytona-warm` (the reusable warm Daytona fixture). The Daytona controller preparation moved to `daytona-controller.ts`, and every sandbox is cleaned up at the end; incomplete cleanup fails the run. - Each run's workspace operations (`/api/heartbeat-runs/:id/workspace-operations`) are saved, and printed ranked by duration. ## Verification - `tsc -p tests/restart-chaos`: no errors in harness files. - Used for the large-workspace measurement, a fresh paperclip clone on local and Daytona (per-turn and warm). First turn / follow-up: local 31–34 s / 7 s; Daytona per-turn 58–63 s / 30 s; Daytona warm 45–51 s / 8–10 s. Every Daytona sandbox was cleaned up (environment deleted, none remaining). ## Risks - Test harness only; no product code. ## Model Used - Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with tool use (shell, file editing, test execution, Daytona measurements). ## 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>
213 lines
13 KiB
TypeScript
213 lines
13 KiB
TypeScript
import { execFileSync } from "node:child_process";
|
|
import { existsSync } from "node:fs";
|
|
import { mkdtemp, rm } from "node:fs/promises";
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import type { ChaosApi } from "./api.js";
|
|
import { cloneWorkspaceRepository, createFixtureRepository, inheritingEnvironmentConfig, seedChaosLab, waitForAgentsReady } from "./seed.js";
|
|
import { Timeline } from "./timeline.js";
|
|
|
|
type Call = { method: string; route: string; body?: unknown };
|
|
|
|
/** Records the seed's board API calls; answers like a fresh local_trusted instance. */
|
|
function fakeApi(experimentalResponse: (body: Record<string, unknown>) => Record<string, unknown>) {
|
|
const calls: Call[] = [];
|
|
let ids = 0;
|
|
const api = {
|
|
get: async (route: string) => {
|
|
calls.push({ method: "GET", route });
|
|
if (route.includes("/environments")) return [{ id: "environment-1", driver: "local" }];
|
|
if (route.startsWith("/api/agents/")) return { id: route.split("/")[3], lifecycleState: "ready" };
|
|
throw new Error(`unexpected GET ${route}`);
|
|
},
|
|
post: async (route: string, body?: unknown) => {
|
|
calls.push({ method: "POST", route, body });
|
|
return { id: `id-${++ids}`, name: "x" };
|
|
},
|
|
patch: async (route: string, body?: unknown) => {
|
|
calls.push({ method: "PATCH", route, body });
|
|
if (route === "/api/instance/settings/experimental") return experimentalResponse(body as Record<string, unknown>);
|
|
throw new Error(`unexpected PATCH ${route}`);
|
|
},
|
|
};
|
|
return { api: api as unknown as ChaosApi, calls };
|
|
}
|
|
|
|
describe("seedChaosLab workspace isolation", () => {
|
|
let fixtureRoot: string;
|
|
beforeEach(async () => {
|
|
fixtureRoot = await mkdtemp(path.join(os.tmpdir(), "rc21-seed-"));
|
|
vi.stubEnv("OPENAI_API_KEY", "test-only-not-a-key");
|
|
});
|
|
afterEach(async () => {
|
|
vi.unstubAllEnvs();
|
|
await rm(fixtureRoot, { recursive: true, force: true });
|
|
});
|
|
|
|
const seed = (api: ChaosApi) => seedChaosLab({ api, env: "local", adapters: ["codex"], concurrency: 2,
|
|
budgetCents: 3_000, fixtureRoot, waveId: "w-test", timeline: new Timeline(null) });
|
|
|
|
it("waits for each seeded agent to reach lifecycleState ready only when the wave asks for it", async () => {
|
|
const waiting = fakeApi(body => ({ ...body }));
|
|
const timeline = new Timeline(null);
|
|
await seedChaosLab({ api: waiting.api, env: "local", adapters: ["codex"], concurrency: 2, budgetCents: 3_000,
|
|
fixtureRoot: path.join(fixtureRoot, "waiting"), waveId: "w-test", timeline, waitForReadyAgents: true });
|
|
expect(waiting.calls.some(call => call.method === "GET" && call.route.startsWith("/api/agents/"))).toBe(true);
|
|
expect(timeline.entries.filter(entry => entry.kind === "seed_agent_ready")).toEqual([expect.objectContaining({ adapter: "codex" })]);
|
|
const skipping = fakeApi(body => ({ ...body }));
|
|
await seed(skipping.api);
|
|
expect(skipping.calls.some(call => call.method === "GET" && call.route.startsWith("/api/agents/"))).toBe(false);
|
|
});
|
|
|
|
it("registers a remote git source, with no host folder, for a Daytona workspace repository", async () => {
|
|
const { api, calls } = fakeApi(body => ({ ...body }));
|
|
await seedChaosLab({ api, env: "local", adapters: ["codex"], concurrency: 2, budgetCents: 3_000, fixtureRoot: path.join(fixtureRoot, "remote"),
|
|
waveId: "w-test", timeline: new Timeline(null), workspaceGitUrl: "https://github.com/paperclipai/paperclip.git", workspaceCommit: "a".repeat(40) });
|
|
const project = calls.find(call => call.method === "POST" && call.route.endsWith("/projects"));
|
|
expect((project!.body as { workspace: unknown }).workspace).toEqual({ name: "Primary", sourceType: "git_repo",
|
|
repoUrl: "https://github.com/paperclipai/paperclip.git", repoRef: "a".repeat(40), isPrimary: true });
|
|
});
|
|
|
|
// RC-21: the project's git_worktree policy is gated behind the instance's
|
|
// isolated-workspaces setting. Without it every repo task ran in the shared
|
|
// primary checkout, so concurrent tasks wrote into one tree.
|
|
it("enables isolated workspaces before creating the git_worktree project", async () => {
|
|
const { api, calls } = fakeApi(body => ({ ...body }));
|
|
await seed(api);
|
|
const enable = calls.findIndex(call => call.method === "PATCH" && call.route === "/api/instance/settings/experimental"
|
|
&& (call.body as Record<string, unknown>).enableIsolatedWorkspaces === true);
|
|
const project = calls.findIndex(call => call.method === "POST" && call.route.endsWith("/projects"));
|
|
expect(enable).toBeGreaterThanOrEqual(0);
|
|
expect(project).toBeGreaterThan(enable);
|
|
expect((calls[project]!.body as { executionWorkspacePolicy: unknown }).executionWorkspacePolicy)
|
|
.toMatchObject({ enabled: true, defaultMode: "isolated_workspace", workspaceStrategy: { type: "git_worktree" } });
|
|
});
|
|
|
|
it("refuses to seed when the instance does not confirm isolated workspaces", async () => {
|
|
const { api, calls } = fakeApi(() => ({ enableIsolatedWorkspaces: false }));
|
|
await expect(seed(api)).rejects.toThrow(/isolated workspaces/i);
|
|
expect(calls.some(call => call.method === "POST" && call.route.endsWith("/projects"))).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("seedChaosLab RC-06 mask", () => {
|
|
let fixtureRoot: string;
|
|
beforeEach(async () => {
|
|
fixtureRoot = await mkdtemp(path.join(os.tmpdir(), "rc06-seed-"));
|
|
vi.stubEnv("OPENAI_API_KEY", "test-only-not-a-key");
|
|
});
|
|
afterEach(async () => {
|
|
vi.unstubAllEnvs();
|
|
await rm(fixtureRoot, { recursive: true, force: true });
|
|
});
|
|
|
|
const seed = (api: ChaosApi, timeline: Timeline, masks?: string[]) => seedChaosLab({ api, env: "local", adapters: ["codex"],
|
|
concurrency: 2, budgetCents: 3_000, fixtureRoot, waveId: "w-test", timeline, ...(masks ? { masks } : {}) });
|
|
const isPolicyCall = (call: Call) => call.method === "POST" && /^\/api\/companies\/[^/]+\/budgets\/policies$/.test(call.route);
|
|
|
|
it("keeps the budget amount and disables only the company hard stop", async () => {
|
|
const { api, calls } = fakeApi(body => ({ ...body }));
|
|
const timeline = new Timeline(null);
|
|
await seed(api, timeline, ["rc06"]);
|
|
const company = calls.find(call => call.method === "POST" && call.route === "/api/companies")!;
|
|
expect((company.body as { budgetMonthlyCents: number }).budgetMonthlyCents).toBe(3_000);
|
|
const policies = calls.filter(isPolicyCall);
|
|
expect(policies).toHaveLength(1);
|
|
expect(policies[0]!.route).toBe("/api/companies/id-1/budgets/policies");
|
|
expect(policies[0]!.body).toEqual({ scopeType: "company", scopeId: "id-1", amount: 3_000, hardStopEnabled: false });
|
|
expect(timeline.entries.filter(entry => entry.kind === "seed_mask_rc06"))
|
|
.toEqual([expect.objectContaining({ companyId: "id-1", budgetCents: 3_000, hardStopEnabled: false })]);
|
|
});
|
|
|
|
it("leaves the company hard stop on without the mask", async () => {
|
|
const { api, calls } = fakeApi(body => ({ ...body }));
|
|
const timeline = new Timeline(null);
|
|
await seed(api, timeline);
|
|
expect(calls.some(isPolicyCall)).toBe(false);
|
|
expect(timeline.entries.some(entry => entry.kind === "seed_mask_rc06")).toBe(false);
|
|
});
|
|
});
|
|
|
|
describe("inheritingEnvironmentConfig", () => {
|
|
it("drops the lifecycle and lease pins and keeps everything else", () => {
|
|
const fixture = { provider: "daytona", image: "img", runnerLifecycleMode: "per_turn", reuseLease: false };
|
|
expect(inheritingEnvironmentConfig(fixture)).toEqual({ provider: "daytona", image: "img" });
|
|
expect(fixture).toHaveProperty("runnerLifecycleMode", "per_turn");
|
|
});
|
|
});
|
|
|
|
describe("cloneWorkspaceRepository", () => {
|
|
it("clones a fresh, shallow working copy of the source repository", async () => {
|
|
const root = await mkdtemp(path.join(os.tmpdir(), "restart-chaos-clone-"));
|
|
try {
|
|
const source = await createFixtureRepository(path.join(root, "source"));
|
|
const clone = cloneWorkspaceRepository(source, path.join(root, "clone"));
|
|
expect(existsSync(path.join(clone, "chaoscli/cli.py"))).toBe(true);
|
|
expect(execFileSync("git", ["rev-parse", "--is-shallow-repository"], { cwd: clone, encoding: "utf8" }).trim()).toBe("true");
|
|
const first = execFileSync("git", ["rev-parse", "HEAD"], { cwd: source, encoding: "utf8" }).trim();
|
|
expect(execFileSync("git", ["rev-parse", "HEAD"], { cwd: clone, encoding: "utf8" }).trim()).toBe(first);
|
|
execFileSync("git", ["-c", "user.name=t", "-c", "user.email=t@t", "commit", "--quiet", "--allow-empty", "-m", "later"], { cwd: source });
|
|
const pinned = cloneWorkspaceRepository(source, path.join(root, "pinned"), first);
|
|
expect(execFileSync("git", ["rev-parse", "HEAD"], { cwd: pinned, encoding: "utf8" }).trim()).toBe(first);
|
|
expect(() => cloneWorkspaceRepository(source, path.join(root, "missing"), "0".repeat(40))).toThrow(/no longer has commit/);
|
|
for (const copy of [clone, pinned]) {
|
|
expect(execFileSync("git", ["remote"], { cwd: copy, encoding: "utf8" }).trim()).toBe("");
|
|
expect(() => execFileSync("git", ["push", "--quiet", "origin", "HEAD:refs/heads/agent-push"], { cwd: copy, stdio: "pipe" })).toThrow();
|
|
}
|
|
expect(execFileSync("git", ["branch", "--list", "agent-push"], { cwd: source, encoding: "utf8" }).trim()).toBe("");
|
|
} finally {
|
|
await rm(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
});
|
|
|
|
describe("waitForAgentsReady", () => {
|
|
it("waits for each new agent to finish lifecycle verification and records how long it took", async () => {
|
|
let reads = 0;
|
|
const api = { get: async () => ({ lifecycleState: ++reads >= 3 ? "ready" : "verifying" }) } as unknown as ChaosApi;
|
|
const timeline = new Timeline(null);
|
|
await waitForAgentsReady(api, { codex: { id: "a1" } }, timeline, 5_000, 1);
|
|
expect(reads).toBe(3);
|
|
expect(timeline.entries.find(entry => entry.kind === "seed_agent_ready")).toMatchObject({ adapter: "codex", agentId: "a1" });
|
|
});
|
|
|
|
it("measures each agent's verification from its own creation and stops waiting when the harness is interrupted", async () => {
|
|
const api = { get: async () => ({ lifecycleState: "ready" }) } as unknown as ChaosApi;
|
|
const timeline = new Timeline(null);
|
|
const now = Date.now();
|
|
await waitForAgentsReady(api, { codex: { id: "a1", createdAt: now - 9_000 }, claude: { id: "a2", createdAt: now - 1_000 } }, timeline, 5_000, 1);
|
|
const ready = Object.fromEntries(timeline.entries.filter(entry => entry.kind === "seed_agent_ready").map(entry => [entry.adapter, entry.readyAfterMs as number]));
|
|
expect(ready.codex).toBeGreaterThanOrEqual(9_000);
|
|
expect(ready.claude).toBeGreaterThanOrEqual(1_000);
|
|
expect(ready.claude).toBeLessThan(9_000);
|
|
const stuck = { get: async () => ({ lifecycleState: "verifying" }) } as unknown as ChaosApi;
|
|
let polls = 0;
|
|
await expect(waitForAgentsReady(stuck, { codex: { id: "a3" } }, new Timeline(null), 60_000, 1, () => ++polls > 2)).rejects.toThrow(/interrupted/);
|
|
});
|
|
|
|
it("keeps waiting through a deferred verification error and passes once the retry makes the agent ready", async () => {
|
|
let reads = 0;
|
|
const api = { get: async () => (++reads < 3 ? { lifecycleState: "verifying", lifecycleError: "host busy" } : { lifecycleState: "ready" }) } as unknown as ChaosApi;
|
|
const timeline = new Timeline(null);
|
|
await waitForAgentsReady(api, { codex: { id: "a1" } }, timeline, 5_000, 1);
|
|
expect(timeline.entries.filter(entry => entry.kind === "seed_agent_lifecycle_error")).toEqual([expect.objectContaining({ adapter: "codex", error: "host busy" })]);
|
|
});
|
|
|
|
it("names the last read error when an agent never becomes ready", async () => {
|
|
const broken = { get: async () => { throw new Error("401 unauthorized"); } } as unknown as ChaosApi;
|
|
await expect(waitForAgentsReady(broken, { codex: { id: "a1" } }, new Timeline(null), 20, 5)).rejects.toThrow(/codex \(last read error: 401 unauthorized\)/);
|
|
const deferred = { get: async () => ({ lifecycleState: "verifying", lifecycleError: "host busy" }) } as unknown as ChaosApi;
|
|
await expect(waitForAgentsReady(deferred, { codex: { id: "a1" } }, new Timeline(null), 20, 5)).rejects.toThrow(/codex \(last lifecycle error: host busy\)/);
|
|
});
|
|
|
|
it("fails the wave when an agent fails verification or never becomes ready", async () => {
|
|
const parked = { get: async () => ({ lifecycleState: "verifying", lifecycleError: "hello probe failed" }) } as unknown as ChaosApi;
|
|
await expect(waitForAgentsReady(parked, { claude: { id: "a2" } }, new Timeline(null), 20, 5)).rejects.toThrow(/claude \(last lifecycle error: hello probe failed\)/);
|
|
const rejected = { get: async () => ({ lifecycleState: "rejected", lifecycleError: "hire rejected" }) } as unknown as ChaosApi;
|
|
await expect(waitForAgentsReady(rejected, { claude: { id: "a2" } }, new Timeline(null), 5_000, 1)).rejects.toThrow(/hire rejected/);
|
|
const stuck = { get: async () => ({ lifecycleState: "verifying" }) } as unknown as ChaosApi;
|
|
await expect(waitForAgentsReady(stuck, { claude: { id: "a3" } }, new Timeline(null), 20, 5)).rejects.toThrow(/never reached lifecycleState ready/);
|
|
});
|
|
});
|