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 server has about 1,100 test and helper files in `server/src/__tests__` > - `server/tsconfig.json` excludes that directory, Vitest does not check types, and no script runs the tsconfig in that directory > - So a test can call a function with the wrong arguments and still pass, and no tool reports it > - This gap hid 2,168 real type errors, and some of them hid tests that did not test what they claim > - This pull request fixes all of these errors and adds the directory to the server layers from paperclipai/paperclip#18737 > - The benefit is that a type error in a server test now fails the typecheck, with no baseline and no backlog ## Linked Issues or Issue Description Refs paperclipai/paperclip#18737, which is merged and added the server layers. Refs paperclipai/paperclip#18738, which is merged and checks the test projects outside `pnpm -r`, so it is not a duplicate. Refs paperclipai/paperclip#18137, which records that this directory has no check. **What happened?** No tool checked the types of 1,074 of the 1,101 files in `server/src/__tests__`. I searched `package.json`, the workflows, and all tsconfig files. 27 files are in the program of another tsconfig, and these 27 have 0 errors. 11 of the 27 are in `helpers/maintenance/tsconfig.json`. No script ran that project when I measured this. paperclipai/paperclip#18738 now runs it. **Expected behavior** The server typecheck checks these files, and a type error fails the check. **Steps to reproduce** 1. On the base commit, run `tsc -p server/src/__tests__/tsconfig.json --noEmit`. It reports 6,536 errors and needs 12.3 GiB. 2. Add a type error to any file in `server/src/__tests__`. 3. Run `pnpm --filter @paperclipai/server typecheck`. It passes. **Paperclip version or commit** I measured the error breakdown below on commit `8dfd632452`, with TypeScript 7.0.2. The branch now includes master up to paperclipai/paperclip#18865. **Deployment mode** Not applicable. This issue applies to development and CI. No production source file in the server changes. ### Error breakdown Each row adds one change to the row above. | Step | Total errors | Change | Cause | | --- | --- | --- | --- | | Config as committed | 6,536 | | | | Add `src/types/*.d.ts` | 4,447 | -2,089 | Config. The Express request types were missing. | | Set `rootDir` to the repository root | 2,436 | -2,011 | Config. | | Set `allowImportingTsExtensions` | 2,181 | -255 | Config. Vitest accepts `.ts` imports. | | Add `ES2024.Promise` to `lib` | 2,138 | -43 | Config. Node 24 has `Promise.withResolvers`. | | Set `allowJs` for `.mjs` imports | 2,148 | +10 | Config. It removes 8 `TS7016` errors and shows new real errors. | | Set `declaration` to false | 2,142 | -6 | Config. Tests emit nothing. | | Count only files in `server/src` | 2,058 | -84 | Other packages: 53 Daytona, 29 Runner test, 2 UI. | So 4,478 of the 6,536 errors (69%) came from config or scope, and 2,058 are real type errors in 314 files. The 29 Runner test errors are also real, which gives 2,087 errors. Tests that master added after this measurement had 81 more errors, so this pull request fixes 2,168 errors. This table classifies the first 2,058 errors. | Kind of real error | Errors | | --- | --- | | Wrong argument or assignment type | 1,023 | | Stale or partial fixture objects | 525 | | Property that the type does not have | 317 | | Missing narrowing of null or unknown | 101 | | Implicit any | 60 | | Missing name or module | 16 | | Other | 16 | ### What the type errors hid Most errors were stale fixtures and loose mocks. These errors hid real test problems, and this pull request fixes them: - **A test that never ran.** `instrumentation.test.ts` required `sdk-trace-base`, which is not installed. So 3 span tests were skipped. They now run and pass. - **Assertions that could not fail.** - `issue-thread-interactions-service` used a company ID as an issue ID. - `status-card-evaluation-work` compared `[]` with `[]` in a rollback check. - `slack-conversation-lifecycle` read `item.issueId`, which does not exist. - `email-channels` used a permission key that does not exist. - `heartbeat-project-env` imported `LOW_TRUST_REVIEW_PRESET`, which is not exported. The value was undefined. - **Postgres processes that did not stop.** 11 test files called `stop` on the test database helper. That method does not exist, and the helper method is `cleanup`. - **Arguments that the service ignored.** - `methodKey` is now `connectionMethodKey` in the Daytona, Unikraft, 1Password, and Railway tests. - 108 calls passed `"owner-user"` to a parameter that expects an options object. - 9 chat wizard fixtures passed `managementContext` as `source`, so they ran `existing_app` and not `manifest`. - 2 tests passed a `{ userId }` actor that the function ignores. - Inserts into `environments` passed a `companyId` column that the table does not have. - **Problems in tests that master added during this work.** - `sandbox-creation-operations` read `database.connectionString` when an external test database was set. In that mode `database` is undefined, so the fixture would stop with a TypeError. It now uses the external URL. - `idle-completed-history` set a Dot operation to `dispatched`. That is a Muse status, and the Dot type does not have it. The fixture now uses `admitted`, which is a real in-flight Dot status. ### Possible product problems, not changed These may be real problems in production code or types. I did not change them, because this pull request does not change production behavior: - `decisions-service` `service.create` does not validate the lenient `cancel_issue_tree` input. - `createConnection` ignores `input.connectionPurpose`. - The `createConnection` route schema default stores `{}` for `transportConfig`. - `prepareManagedAiRuntime` accepted the invalid value `mode: "connection"`. - `createBinding` accepts invalid `projectionClass` strings outside class 3. - `ensureManagedProjectWorkspace` forwards an untyped `repoRef` by spread. - `routineVariableSchema.label` is optional, but `RoutineVariable.label` is required. - `ToolRunContext.projectId` may be too strict. - `withdrawInteraction` reads `issue.status`, which its type omits. - `issueService.list` and `reconcileNativeFinalizations` omit fields that they return at runtime. - `createGitHubExternalObjectProvider` handles `tokenProvider: null`, but its type forbids this value. ## What Changed - Fixed the 2,168 type errors. The diff changes 322 test and helper files. - Corrected `server/src/__tests__/tsconfig.json`. Editors and the typecheck now read the same options and report the same errors. - Added three `test-tree` layers to `server/scripts/typecheck-layers.mjs`. They read the server layers as declarations, and any error fails them. A hash of the path selects the shard, so a new file does not move other files. - Added `server/scripts/typecheck-stubs/daytona-sdk.d.ts`. Server tests reach Daytona plugin source, and the root install does not have `@daytonaio/sdk`. - Changed two imports in `ui/src/lib/issue-execution-policy.ts` to use `.js` extensions, because server tests import this file. - Made `declarationsConfig` and `--declarations-only` skip the `test-tree` layers, because these layers emit nothing. Other projects read only the source layers. Added a test for this. - Updated `doc/DEVELOPING.md`. ## Verification Run these commands: ```sh pnpm --filter @paperclipai/server typecheck pnpm exec vitest run server/scripts/typecheck-layers.test.mjs ``` Results on macOS (arm64), Node 24, 16 cores. Each check ran after the merge of paperclipai/paperclip#18738 unless the row says otherwise: | Check | Commit | Result | | --- | --- | --- | | Server typecheck, `PAPERCLIP_TYPECHECK_LOW_MEMORY=1`, all 7 layers | `6e45a08573` | Exit 0, 0 errors, 62 seconds, peak 3.52 GiB | | `node scripts/typecheck-test-projects.mjs --low-memory` | `a3306bd13e` | Exit 0, 0 errors, 42 seconds, peak 3.25 GiB | | The same script with `--reuse-declarations` | `1b878aabc0` | Exit 0, 0 errors | | `typecheck-layers.test.mjs` and `live-recovery-work.test.ts` | `01db5634e4` | 90 passed. These include real compiler runs for a pass, a type error, and an invalid tsconfig. | | `tsconfig.declarations.json` after a full server typecheck | `0fb1e4fb0a` | It references only `below`, `cycle`, and `above`. No generated config names a `tsconfig.layers.json` file. | | Owned runtime test in `idle-completed-history` | `e8f2f448ac` | Passed, with the fix that master later replaced | | `idle-incoming-wake`, `plugin-idle-manager`, and the changed `chat-channels` test | `6e45a08573` | 30 passed | | Runner `native-execution.test.ts` | `eab4dcc1f4` | 114 passed | | The 19 server test files that changed since `eab4dcc1f4`, and `typecheck-layers.test.mjs` | `259737b700` | 4,275 of 4,277 passed. The 2 failures are in `chat-channels` and are in the list of 7 below. | The peak is the largest single process, from `/usr/bin/time -l`. Peaks for the server typecheck were between 3.42 GiB and 3.56 GiB across 8 runs. Peaks for the test projects were 3.25 GiB and 3.37 GiB across 2 runs. I did not measure a cgroup. **Runtime check of the fixes.** Types do not prove that a test still works. So I ran all 309 changed server test files, 11,929 tests, before the rebase onto paperclipai/paperclip#18737: | Result | Tests | Detail | | --- | --- | --- | | Passed | 11,913 | Includes the 2 tests and the 54 `dot-runner` tests that passed in a later run, as described below. | | Failed | 7 | The same 7 tests also fail on the commit before the fixes. | | Skipped | 9 | These tests have their own skip conditions: `sentry` 5, and 1 each in `bundled-plugin-registration`, `customer-success-cloud`, `onepassword-connection`, and `workspace-runtime-https-live-exercise`. | The 7 tests that fail with and without this change, on my machine: - 3 tests in `chat-channels` and `email-channels` stop with `ENOENT` on a `SKILL.md` file. The path is in the parent checkout, above the git worktree that I used, so I expect that the worktree is the cause. I did not prove this. - `workspace-instance-cleanup` compares `/private/var/...` with `/var/...`. This is a macOS symlink difference. - 2 tests in `git-reproducible-managed-checkouts` get `unknown_base_git_files` and expect `unpushed_managed_checkout`. I did not find the cause. - 1 more test in `chat-channels`, `materializes direct external-chat finals once`, gets `undefined`. I did not find the cause. CI is the check for these 7 tests. `ci / verify` passed on `eab4dcc1f4`. Failures during this work: - My fix to `agent-runtime-connector-access` changed an invalid permission key in the setup, but not in the assertion. The runtime check found this. I corrected the assertion, and the file passes. - `heartbeat-plugin-environment` failed one wait in the full run. It passed three times alone, so I think that load caused the failure. It can fail again under load. - `dot-runner` skipped all 54 tests in the full run because `cargo` was not on my `PATH`. It then passed 54 of 54 with the toolchain on the `PATH`. - My first `lib` value removed the default DOM types, and the error count went up by 375. I added the DOM libraries. - My Daytona stub with bare `any` left 48 errors, because generic helpers then inferred `unknown`. I added shapes that return promises. - One fix to `agent-secrets-routes` used `class_3_static_lease`, and the test failed. That class allows only specific paths. I reverted to `unclassified`. - `ci / General tests (server (8/12))` failed on `259737b700` because of the flaky port in `idle-completed-history`. paperclipai/paperclip#18853 fixed this test on master, so this pull request keeps that fix. **Audit of the diff.** I counted these patterns in added and removed lines, to find fixes that only hide an error: | Pattern | Added | Removed | | --- | --- | --- | | `@ts-ignore` | 0 | 0 | | `@ts-expect-error` | 0 | 1 | | `.skip` | 0 | 0 | | `as any` | 9 | 9 | | `: any` | 11 | 2 | | `as never` | 8 | 2 | | `as unknown as` | 35 | 4 | | `Promise<unknown>` | 16 | 5 | | `expect(` | 128 | 113 | No hunk removes more `expect(` calls than it adds. Three removals of test content were intentional, and I checked each one: - `muse-control` removed `signalToken`. Line 1012 already asserts that it is absent. - `merged-pr-confirmation-sweep` removed legacy aliases. Other tests cover them. - `heartbeat-workspace-branch-containment` removed a `finalize` branch that no test row can reach. Some partial fixtures stay unchecked through `as unknown as` and `Promise<unknown>`, mostly in `issue-agent-mutation-ownership-routes` and `issue-comment-reopen-routes`. **Accuracy of the check.** One program over the tree and the three shards reported the same errors at the same positions. Memory, as the peak of the largest process on one thread, was 3.93 GiB for one program and 2.43 GiB for the largest shard. I measured these two values before the fixes. Not run or not proven: - I did not run the full `pnpm test:run`, or a root `pnpm build`. I expect CI to run the full suites. - I did not run the 4 GiB container check, or the full `scripts/typecheck-low-memory.mjs`. The peaks above come from macOS, so they are not a Linux cgroup measurement. - I did not run the UI typecheck after the merges. - `workspace-runtime-https-live-exercise` is skipped, so its `cleanup` fix did not run. ## Risks - **A large diff in test files.** 328 files change. A pull request that edits the same tests can get merge conflicts. New tests on master can also add type errors before this merges. Any such error fails this check and needs a fix here. - **A higher cost for changes to source types.** A change to a type can add errors in test files that the author did not touch. The author must then fix them. This is the purpose of the check, but it is new work. - **Changed test behavior.** Some tests now run paths that they did not run before, such as the 9 chat wizard fixtures and the 3 span tests. They pass here, but they can be more sensitive to timing or to the environment. - **The Daytona stub can go stale.** The stub is written by hand. If the plugin uses a new SDK member, the typecheck reports an error until someone updates the stub. - **The release path.** `release-verify.yml` and `scripts/release.sh` run `pnpm -r typecheck`, so they now run this check. - **The tsconfig change.** The test transform reads `server/src/__tests__/tsconfig.json`. The options that I changed are for type checks, and the runs above passed. - **A gap that remains.** Tsconfigs in `packages/paperclip-runner` and in most sandbox provider plugins exclude `*.test.ts`. This check does not read most of those test files, so they can still drift. That work is separate from this pull request. > For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and discuss it in `#dev` before opening the PR. Feature PRs that overlap with planned core work may need to be redirected — check the roadmap first. See `CONTRIBUTING.md`. ## Model Used Anthropic Claude Opus 5.5 (`claude-opus-5-5`) through Claude Code, with reasoning, tool use, code execution, and subagents. The runtime does not show the context window size. ## 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 - [ ] I have run tests locally and they pass (7 tests fail locally, with and without this change. See Verification.) - [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>
1762 lines
124 KiB
TypeScript
1762 lines
124 KiB
TypeScript
import { heartbeatService } from "../services/heartbeat.js";
|
|
import { instanceSettingsService } from "../services/instance-settings.js";
|
|
import { createDeliveryWorkCoordinator } from "../services/delivery-work-coordinator.js";
|
|
import { notifyDirectoryCleanup } from "../services/directory-cleanup-notifications.js";
|
|
import { idleWorkSnapshot } from "../services/task-admission.js";
|
|
import { resolveExternalTestDatabaseUrl } from "./helpers/external-test-database.js";
|
|
import fs from "node:fs/promises";
|
|
import { execFile as execFileCallback } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import * as executionTargetTools from "@paperclipai/adapter-utils/execution-target";
|
|
import * as ssh from "@paperclipai/adapter-utils/ssh";
|
|
const execFile = promisify(execFileCallback);
|
|
import os from "node:os";
|
|
import path from "node:path";
|
|
import { createHash, randomUUID } from "node:crypto";
|
|
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
|
|
import { eq, sql } from "drizzle-orm";
|
|
import { agentFileStore, fileHash, inspectAgentFile, inspectAgentDirectory, snapshotAgentFiles, MAX_AGENT_FILE_BYTES, MAX_AGENT_DIRECTORY_BYTES, MAX_AGENT_DIRECTORY_ENTRIES } from "../services/agent-file-store.js";
|
|
import { agents, companies, issues, authUsers, companyMemberships, principalPermissionGrants, heartbeatRuns, environmentLeases, environments, agentInstructionWorkingCopies, agentInstructionRevisions, agentInstructionHeads, createDb, fileStorageDb } from "@paperclipai/db";
|
|
import { startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
import { agentInstructionRevisionService } from "../services/agent-instruction-revisions.js";
|
|
import { agentInstructionWorkingCopyService, instructionWorkingCopyGuidance } from "../services/agent-instruction-working-copies.js";
|
|
import { resolveManagedInstructionsRoot } from "../services/agent-instructions.js";
|
|
import { buildNativeRuntimeContext } from "../services/native-runtime/runtime-context.js";
|
|
import type { EnvironmentRuntimeService } from "../services/environment-runtime.js";
|
|
import { remoteTerminationReceipt } from "../services/remote-execution-termination.js";
|
|
import { createReusableLeaseHandoff } from "../services/environment-lease-handoff.js";
|
|
import { AgentDirectoryReuseInvalidatedError, agentDirectoryWorkingCopyService } from "../services/agent-directory-working-copies.js";
|
|
import { withDirectoryMergeLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
|
import { heartbeatRunEvents } from "@paperclipai/db";
|
|
import { logger } from "../middleware/logger.js";
|
|
|
|
const external = resolveExternalTestDatabaseUrl("PAPERCLIP_AGENT_DIRECTORY_TEST_DATABASE_URL");
|
|
|
|
describe("persistent agent directories", () => {
|
|
let database: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
let copies: ReturnType<typeof agentInstructionWorkingCopyService>;
|
|
let revisions: ReturnType<typeof agentInstructionRevisionService>;
|
|
const previousHome = process.env.PAPERCLIP_HOME;
|
|
let home: string;
|
|
let companyId: string, agentId: string, userId: string, root: string;
|
|
const entryFile = "policy/INSTRUCTIONS.txt";
|
|
const initial = "\uFEFF# Original\r\n☃\n";
|
|
const target = () => ({ companyId, agentId });
|
|
const board = () => ({ type: "board" as const, userId, source: "session" as const });
|
|
async function run(options: { warm?: boolean; reuseRunId?: string } = {}) {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
return (await copies.prepare({ ...target(), runId, cwd: home, ...options }))!;
|
|
}
|
|
beforeAll(async () => {
|
|
home = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "instruction-working-copies-")));
|
|
process.env.PAPERCLIP_HOME = home;
|
|
if (!external) database = await startEmbeddedPostgresTestDatabase("instruction-copies-db-");
|
|
db = createDb(external ?? database.connectionString);
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
revisions = agentInstructionRevisionService(db);
|
|
}, 90_000);
|
|
afterAll(async () => {
|
|
if (previousHome === undefined) delete process.env.PAPERCLIP_HOME; else process.env.PAPERCLIP_HOME = previousHome;
|
|
await db?.$client.end({ timeout: 1 });
|
|
await database?.cleanup();
|
|
if (home) {
|
|
const writable = async (dir: string) => {
|
|
await fs.chmod(dir, 0o700);
|
|
for (const entry of await fs.readdir(dir, { withFileTypes: true })) if (entry.isDirectory()) await writable(path.join(dir, entry.name));
|
|
};
|
|
await writable(home);
|
|
await fs.rm(home, { recursive: true, force: true });
|
|
}
|
|
});
|
|
beforeEach(async () => {
|
|
companyId = randomUUID(); agentId = randomUUID(); userId = randomUUID();
|
|
await db.insert(companies).values({ id: companyId, name: "Instruction tests", issuePrefix: randomUUID().slice(0, 8) });
|
|
await db.insert(authUsers).values({ id: userId, name: "Editor", email: `${userId}@example.test`, createdAt: new Date(), updatedAt: new Date() });
|
|
root = resolveManagedInstructionsRoot({ ...target(), id: agentId, name: "Target", adapterConfig: {} });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } });
|
|
await db.insert(companyMemberships).values([
|
|
{ companyId, principalType: "user", principalId: userId, membershipRole: "operator" },
|
|
{ companyId, principalType: "agent", principalId: agentId, membershipRole: "member" },
|
|
]);
|
|
await db.insert(principalPermissionGrants).values({ companyId, principalType: "user", principalId: userId, permissionKey: "agents:configure", scope: { agentIds: [agentId] } });
|
|
await fs.mkdir(path.dirname(path.join(root, entryFile)), { recursive: true });
|
|
await fs.writeFile(path.join(root, entryFile), initial);
|
|
});
|
|
|
|
describe("post-save directory cleanup worker", () => {
|
|
afterEach(async () => {
|
|
vi.useRealTimers(); vi.restoreAllMocks();
|
|
await db.update(agentInstructionWorkingCopies).set({ receipt: { schema: "paperclip.agent-files.v1", cleanupPending: false } })
|
|
.where(eq(agentInstructionWorkingCopies.companyId, companyId));
|
|
});
|
|
const clock = () => vi.useFakeTimers({ toFake: ["Date", "setTimeout", "clearTimeout"], shouldAdvanceTime: true });
|
|
const coordinator = (canRun = () => true, canReconcile = () => true, onError = (_error: unknown) => {}) =>
|
|
createDeliveryWorkCoordinator({ owner: db, canRun, canReconcile, onError });
|
|
async function stopped(copy: NonNullable<Awaited<ReturnType<typeof copies.get>>>, dueAt = new Date(), owner = db) {
|
|
await owner.transaction(async tx => {
|
|
await notifyDirectoryCleanup(tx, { companyId: copy.companyId, runId: copy.runId });
|
|
await tx.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(), nextAttemptAt: dueAt })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
});
|
|
}
|
|
async function released(runId: string) {
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect((await copies.get(companyId, runId))?.receipt?.cleanupPending).toBe(false);
|
|
}, { timeout: 5000 });
|
|
}
|
|
it("leaves active, transferred, and completed receipts quiet even with retained baselines", async () => {
|
|
const active = await run(), completed = await run(), transferred = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(),
|
|
receipt: { ...completed.receipt, cleanupPending: false } }).where(eq(agentInstructionWorkingCopies.runId, completed.runId));
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(),
|
|
receipt: { ...transferred.receipt, retainedByRunId: active.runId } }).where(eq(agentInstructionWorkingCopies.runId, transferred.runId));
|
|
clock(); const worker = coordinator();
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
const reads = vi.spyOn(db, "select"), removes = vi.spyOn(fs, "rm");
|
|
await vi.advanceTimersByTimeAsync(120_000);
|
|
expect(reads).not.toHaveBeenCalled(); expect(removes).not.toHaveBeenCalled();
|
|
expect(worker.nextWakeAt()).toBeNull();
|
|
for (const copy of [active, completed, transferred]) expect((await fs.stat(copy.localRoot)).isDirectory()).toBe(true);
|
|
} finally { await worker.stop(); }
|
|
});
|
|
it("retires a stale retry on an already cleaned receipt after restart without filesystem work", async () => {
|
|
const copy = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", processStoppedAt: new Date(),
|
|
nextAttemptAt: new Date(), receipt: { schema: "paperclip.agent-files.v1", cleanupPending: false } })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
clock(); const worker = coordinator(), removes = vi.spyOn(fs, "rm");
|
|
try {
|
|
await agentInstructionWorkingCopyService(db).registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect((await copies.get(companyId, copy.runId))?.nextAttemptAt).toBeNull();
|
|
});
|
|
await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
const reads = vi.spyOn(db, "select");
|
|
await vi.advanceTimersByTimeAsync(120_000);
|
|
expect(reads).not.toHaveBeenCalled(); expect(removes).not.toHaveBeenCalled();
|
|
expect(worker.nextWakeAt()).toBeNull();
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
} finally { await worker.stop(); }
|
|
});
|
|
it("honors a cleanup obligation published before stale-deadline settlement", async () => {
|
|
const copy = await run(), dueAt = new Date(Date.now() + 30_000);
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", processStoppedAt: new Date(),
|
|
nextAttemptAt: dueAt, receipt: { schema: "paperclip.agent-files.v1", cleanupPending: false } })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const transact = db.transaction.bind(db);
|
|
const race = vi.spyOn(db, "transaction").mockImplementationOnce(async (callback, config) => {
|
|
await db.update(agentInstructionWorkingCopies).set({ receipt: { ...copy.receipt, cleanupPending: true } })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
return transact(callback, config);
|
|
});
|
|
try {
|
|
await copies.release(companyId, copy.runId);
|
|
expect(await copies.get(companyId, copy.runId)).toMatchObject({ receipt: { cleanupPending: false }, nextAttemptAt: null });
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
} finally { race.mockRestore(); }
|
|
});
|
|
it("reactivates from real collection, preserves saved files, retries failed cleanup, and becomes quiet", async () => {
|
|
const copy = await run(); await fs.writeFile(path.join(copy.localRoot, "memory.txt"), "saved memory");
|
|
clock(); const worker = coordinator();
|
|
const remove = fs.rm.bind(fs);
|
|
let failing = true;
|
|
const removes = vi.spyOn(fs, "rm").mockImplementation(async (file, opts) => {
|
|
if (failing && file === path.dirname(copy.localRoot)) throw new Error("temporary cleanup failure");
|
|
return remove(file, opts);
|
|
});
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("saved");
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect((await copies.get(companyId, copy.runId))?.nextAttemptAt).toBeInstanceOf(Date);
|
|
});
|
|
const pending = (await copies.get(companyId, copy.runId))!;
|
|
expect(pending.receipt?.cleanupPending).toBe(true);
|
|
expect(await fs.readFile(path.join(root, "memory.txt"), "utf8")).toBe("saved memory");
|
|
await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
expect(worker.nextWakeAt()).toBe(pending.nextAttemptAt!.getTime());
|
|
failing = false;
|
|
await vi.advanceTimersByTimeAsync(30_000); await released(copy.runId);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await vi.advanceTimersByTimeAsync(1000); await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
const reads = vi.spyOn(db, "select"); removes.mockClear();
|
|
await vi.advanceTimersByTimeAsync(120_000);
|
|
expect(reads).not.toHaveBeenCalled(); expect(removes).not.toHaveBeenCalled();
|
|
expect(worker.nextWakeAt()).toBeNull();
|
|
} finally { removes.mockRestore(); await worker.stop(); }
|
|
});
|
|
it.each(["restart", "drain", "standby"] as const)("preserves cleanup across %s", async mode => {
|
|
const copy = await run();
|
|
if (mode === "restart") await stopped(copy);
|
|
let admitted = mode === "restart";
|
|
clock(); const worker = coordinator(() => admitted, () => mode !== "standby");
|
|
try {
|
|
await agentInstructionWorkingCopyService(db).registerDirectoryCleanupWork(worker, () => admitted, async () => true).ready;
|
|
if (mode !== "restart") {
|
|
await stopped(copy); await vi.advanceTimersByTimeAsync(1000);
|
|
if (mode === "drain") await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
const reads = vi.spyOn(db, "select");
|
|
await vi.advanceTimersByTimeAsync(60_000); expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
expect((await fs.stat(copy.localRoot)).isDirectory()).toBe(true);
|
|
admitted = true; await vi.advanceTimersByTimeAsync(30_000);
|
|
}
|
|
await released(copy.runId);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} finally { await worker.stop(); }
|
|
});
|
|
it("retains a future cleanup deadline across restart without early file operations", async () => {
|
|
const copy = await run(); clock(); const due = new Date(Date.now() + 90_000);
|
|
await stopped(copy, due); const worker = coordinator();
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
expect(worker.nextWakeAt()).toBe(due.getTime());
|
|
const removes = vi.spyOn(fs, "rm"); await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(removes).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(30_000); await released(copy.runId);
|
|
} finally { await worker.stop(); }
|
|
});
|
|
it("honors outer rollback and only releases after the outer commit", async () => {
|
|
const copy = await run(); clock(); const worker = coordinator();
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
await expect(db.transaction(async tx => {
|
|
await stopped(copy, new Date(), tx as unknown as typeof db);
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect((await fs.stat(copy.localRoot)).isDirectory()).toBe(true);
|
|
throw new Error("rollback cleanup");
|
|
})).rejects.toThrow("rollback cleanup");
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect((await copies.get(companyId, copy.runId))?.state).toBe("prepared");
|
|
await db.transaction(async tx => {
|
|
await stopped(copy, new Date(), tx as unknown as typeof db);
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
expect((await fs.stat(copy.localRoot)).isDirectory()).toBe(true);
|
|
});
|
|
await released(copy.runId);
|
|
} finally { await worker.stop(); }
|
|
});
|
|
it("joins destructive cleanup on shutdown and restores quiet after restart", async () => {
|
|
const copy = await run(); await stopped(copy); clock(); const worker = coordinator();
|
|
let release!: () => void, entered!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const entry = new Promise<void>(resolve => { entered = resolve; });
|
|
const remove = fs.rm.bind(fs);
|
|
const removes = vi.spyOn(fs, "rm").mockImplementation(async (file, opts) => {
|
|
if (file === path.dirname(copy.localRoot)) { entered(); await gate; }
|
|
return remove(file, opts);
|
|
});
|
|
let stopping: Promise<void> | undefined;
|
|
try {
|
|
const registration = copies.registerDirectoryCleanupWork(worker, () => true, async () => true);
|
|
await entry; let finished = false;
|
|
stopping = worker.stop().then(() => { finished = true; });
|
|
await vi.advanceTimersByTimeAsync(1000); expect(finished).toBe(false);
|
|
release(); await stopping; await registration.ready;
|
|
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(false);
|
|
const restarted = coordinator();
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(restarted, () => true, async () => true).ready;
|
|
expect(restarted.nextWakeAt()).toBeNull();
|
|
} finally { await restarted.stop(); }
|
|
} finally { release(); removes.mockRestore(); await stopping; await worker.stop(); }
|
|
});
|
|
it("drains more than one discovery page in bounded execution batches", async () => {
|
|
const rows = [];
|
|
for (let index = 0; index < 103; index++) rows.push(await run());
|
|
for (const copy of rows) await stopped(copy);
|
|
clock(); const worker = coordinator();
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
const first = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.companyId, companyId));
|
|
expect(first.filter(row => row.receipt?.cleanupPending === false)).toHaveLength(20);
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(1000);
|
|
const all = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.companyId, companyId));
|
|
expect(all.every(row => row.receipt?.cleanupPending === false)).toBe(true);
|
|
}, { timeout: 10_000 });
|
|
for (const row of rows) await expect(fs.stat(row.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} finally { await worker.stop(); }
|
|
}, 30_000);
|
|
it("honors a newer deadline committed before the cleanup claim", async () => {
|
|
const copy = await run(); await stopped(copy); clock(); const worker = coordinator();
|
|
const later = new Date(Date.now() + 60_000), transaction = db.transaction.bind(db);
|
|
let changed = false;
|
|
const transactions = vi.spyOn(db, "transaction").mockImplementation((async (callback, options) => {
|
|
if (!changed) {
|
|
changed = true;
|
|
await transaction(async tx => {
|
|
await notifyDirectoryCleanup(tx, { companyId, runId: copy.runId });
|
|
await tx.update(agentInstructionWorkingCopies).set({ nextAttemptAt: later })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
});
|
|
}
|
|
return transaction(callback, options);
|
|
}) as typeof db.transaction);
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
transactions.mockRestore();
|
|
expect(changed).toBe(true);
|
|
expect((await fs.stat(copy.localRoot)).isDirectory()).toBe(true);
|
|
expect((await copies.get(companyId, copy.runId))?.nextAttemptAt).toEqual(later);
|
|
await vi.advanceTimersByTimeAsync(1000); await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
expect(worker.nextWakeAt()).toBe(later.getTime());
|
|
await vi.advanceTimersByTimeAsync(60_000); await released(copy.runId);
|
|
} finally { transactions.mockRestore(); await worker.stop(); }
|
|
});
|
|
it("backs off a failed reservation without losing cleanup or blocking another owner", async () => {
|
|
const first = await run(), second = await run();
|
|
clock(); await stopped(first, new Date(Date.now() - 1000)); await stopped(second);
|
|
const errors: unknown[] = [], worker = coordinator(() => true, () => true, error => errors.push(error));
|
|
const transaction = vi.spyOn(db, "transaction").mockImplementationOnce(async () => { throw new Error("cleanup reservation unavailable"); });
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
transaction.mockRestore();
|
|
expect(errors).toHaveLength(1);
|
|
expect((await fs.stat(first.localRoot)).isDirectory()).toBe(true);
|
|
expect((await copies.get(companyId, second.runId))?.receipt?.cleanupPending).toBe(false);
|
|
await vi.advanceTimersByTimeAsync(1000); await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
const reads = vi.spyOn(db, "select"); await vi.advanceTimersByTimeAsync(15_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
await vi.advanceTimersByTimeAsync(30_000); await released(first.runId);
|
|
} finally { transaction.mockRestore(); await worker.stop(); }
|
|
});
|
|
it("shares the directory lock with foreground collection and deletes only once", async () => {
|
|
const copy = await run(); await fs.writeFile(path.join(copy.localRoot, "memory.txt"), "last save");
|
|
clock(); const worker = coordinator();
|
|
let release!: () => void, entered!: () => void;
|
|
const gate = new Promise<void>(resolve => { release = resolve; });
|
|
const entry = new Promise<void>(resolve => { entered = resolve; });
|
|
const remove = fs.rm.bind(fs); let removals = 0;
|
|
const removes = vi.spyOn(fs, "rm").mockImplementation(async (file, options) => {
|
|
if (file === path.dirname(copy.localRoot)) { removals += 1; entered(); await gate; }
|
|
return remove(file, options);
|
|
});
|
|
let foreground: ReturnType<typeof copies.collectStopped> | undefined;
|
|
try {
|
|
await copies.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
foreground = copies.collectStopped({ companyId, runId: copy.runId });
|
|
await entry;
|
|
await vi.waitFor(async () => {
|
|
await vi.advanceTimersByTimeAsync(100);
|
|
expect((await copies.get(companyId, copy.runId))?.nextAttemptAt).toBeInstanceOf(Date);
|
|
});
|
|
release(); await foreground; await released(copy.runId);
|
|
await vi.advanceTimersByTimeAsync(1000); await expect.poll(() => idleWorkSnapshot().active).toBe(0);
|
|
expect(removals).toBe(1);
|
|
expect(await fs.readFile(path.join(root, "memory.txt"), "utf8")).toBe("last save");
|
|
expect(worker.nextWakeAt()).toBeNull();
|
|
} finally { release(); await foreground; removes.mockRestore(); await worker.stop(); }
|
|
});
|
|
it("reactivates from the real worktree setting without polling disabled policy", async () => {
|
|
const copy = await run(); await stopped(copy);
|
|
const runtimeEnv = { PAPERCLIP_IN_WORKTREE: "true", PAPERCLIP_INSTANCE_ID: "sleep41-directory-activation" };
|
|
const settings = instanceSettingsService(db, { runtimeEnv });
|
|
await settings.updateExperimental({ enableWorktreeRunExecution: false });
|
|
const service = heartbeatService(db, { runtimeEnv });
|
|
clock(); const worker = coordinator();
|
|
try {
|
|
await service.registerInstructionDirectoryCleanupWork(worker, () => true).ready;
|
|
expect(worker.nextWakeAt()).toBeNull();
|
|
const reads = vi.spyOn(db, "select"); await vi.advanceTimersByTimeAsync(60_000);
|
|
expect(reads).not.toHaveBeenCalled(); reads.mockRestore();
|
|
await service.resolveSchedulingSuppression();
|
|
await settings.updateExperimental({ enableWorktreeRunExecution: true });
|
|
await released(copy.runId);
|
|
} finally { await worker.stop(); await settings.updateExperimental({ enableWorktreeRunExecution: false }); }
|
|
});
|
|
it("retains unknown remote cleanup without acquiring a replacement environment", async () => {
|
|
const copy = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ location: `remote:${randomUUID()}` })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
await stopped(copy); clock(); const worker = coordinator();
|
|
const execute = vi.fn();
|
|
const service = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
try {
|
|
await service.registerDirectoryCleanupWork(worker, () => true, async () => true).ready;
|
|
const pending = (await copies.get(companyId, copy.runId))!;
|
|
expect(pending.receipt?.cleanupPending).toBe(true); expect(pending.nextAttemptAt).toBeInstanceOf(Date);
|
|
expect(execute).not.toHaveBeenCalled();
|
|
await vi.advanceTimersByTimeAsync(30_000);
|
|
await expect.poll(async () => (await copies.get(companyId, copy.runId))!.nextAttemptAt!.getTime()).toBeGreaterThan(pending.nextAttemptAt!.getTime());
|
|
expect(execute).not.toHaveBeenCalled();
|
|
} finally { await worker.stop(); }
|
|
});
|
|
});
|
|
|
|
describe("warm directory ownership", () => {
|
|
async function nextRun() {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
return runId;
|
|
}
|
|
it("adopts one physical root and fences stale cleanup through final save", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
const second = await copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home });
|
|
expect(second).toMatchObject({ runId: secondId, localRoot: first.localRoot, executionRoot: first.executionRoot,
|
|
responsibleUserId: userId, receipt: { materializationRunId: first.runId } });
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBe(secondId);
|
|
await copies.release(companyId, first.runId);
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.processStoppedAt).toBeNull();
|
|
await copies.reportUnavailable(companyId, first.runId);
|
|
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
|
await copies.release(companyId, secondId);
|
|
expect(await copies.hasChanges({ companyId, runId: secondId })).toBe(false);
|
|
const thirdId = await nextRun();
|
|
const third = await copies.adopt({ companyId, agentId, runId: thirdId, previousRunId: secondId, cwd: home });
|
|
expect(third?.executionRoot).toBe(first.executionRoot);
|
|
await fs.writeFile(path.join(first.localRoot, "warm-memory.txt"), "third turn edit");
|
|
expect(await copies.hasChanges({ companyId, runId: thirdId })).toBe(true);
|
|
expect(await copies.collectStopped({ companyId, runId: thirdId })).toMatchObject({ state: "saved", receipt: { cleanupPending: false } });
|
|
expect(await fs.readFile(path.join(root, "warm-memory.txt"), "utf8")).toBe("third turn edit");
|
|
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await copies.release(companyId, first.runId);
|
|
});
|
|
it.each(["company", "agent", "workspace", "environment"])("rejects foreign %s adoption", async mismatch => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
expect(await copies.adopt({ companyId: mismatch === "company" ? randomUUID() : companyId,
|
|
agentId: mismatch === "agent" ? randomUUID() : agentId, runId: secondId, previousRunId: first.runId,
|
|
cwd: mismatch === "workspace" ? `${home}-other` : home,
|
|
...(mismatch === "environment" ? { target: { kind: "remote" as const, transport: "sandbox" as const, environmentId: randomUUID(), remoteCwd: "/workspace" } } : {}),
|
|
})).toBeNull();
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBeUndefined();
|
|
await copies.collectStopped({ companyId, runId: first.runId });
|
|
});
|
|
it("adopts unchanged ownership after collection retry metadata changes before claim", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native" }).where(eq(heartbeatRuns.id, first.runId));
|
|
const secondId = await nextRun();
|
|
const fileDb = fileStorageDb(db);
|
|
const transaction = fileDb.transaction.bind(fileDb);
|
|
let injected = false;
|
|
const spy = vi.spyOn(fileDb, "transaction").mockImplementation((async (callback, options) => {
|
|
if (!injected) {
|
|
injected = true;
|
|
const before = (await copies.get(companyId, first.runId))!;
|
|
vi.useFakeTimers({ toFake: ["Date"] });
|
|
vi.setSystemTime(new Date(before.updatedAt.getTime() + 1000));
|
|
try { await copies.recoverStopped(); } finally { vi.useRealTimers(); }
|
|
const after = (await copies.get(companyId, first.runId))!;
|
|
expect(after.updatedAt.getTime()).toBeGreaterThan(before.updatedAt.getTime());
|
|
expect(after.nextAttemptAt).toBeInstanceOf(Date);
|
|
for (const field of ["state", "baseHash", "localRoot", "executionRoot", "processStoppedAt", "receipt", "attempts"] as const)
|
|
expect(after[field]).toEqual(before[field]);
|
|
}
|
|
return transaction(callback, options);
|
|
}) as typeof db.transaction);
|
|
try {
|
|
const adopted = await copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home });
|
|
expect(injected).toBe(true);
|
|
expect(adopted).toMatchObject({ runId: secondId, localRoot: first.localRoot, executionRoot: first.executionRoot });
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBe(secondId);
|
|
} finally { spy.mockRestore(); vi.useRealTimers(); expect(injected).toBe(true); }
|
|
});
|
|
|
|
it.each(["materialization", "checkpoint", "stopped", "state"])("rejects changed %s authority with the same baseline before adoption", async change => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
const warning = vi.spyOn(logger, "warn");
|
|
const privateValue = "private-materialization-/tmp/untrusted-token-do-not-log";
|
|
const fileDb = fileStorageDb(db);
|
|
const transaction = fileDb.transaction.bind(fileDb);
|
|
let injected = false;
|
|
const spy = vi.spyOn(fileDb, "transaction").mockImplementation((async (callback, options) => {
|
|
if (!injected) {
|
|
injected = true;
|
|
const prior = (await copies.get(companyId, first.runId))!;
|
|
const values = change === "materialization" ? { receipt: { ...prior.receipt, materializationIdentity: privateValue } }
|
|
: change === "checkpoint" ? { receipt: { ...prior.receipt, checkpointState: "saved" } }
|
|
: change === "stopped" ? { processStoppedAt: new Date() } : { state: "pending_collection" };
|
|
await db.update(agentInstructionWorkingCopies).set({ ...values, updatedAt: new Date(Date.now() + 1000) })
|
|
.where(eq(agentInstructionWorkingCopies.runId, first.runId));
|
|
expect((await copies.get(companyId, first.runId))!.baseHash).toBe(prior.baseHash);
|
|
}
|
|
return transaction(callback, options);
|
|
}) as typeof db.transaction);
|
|
try {
|
|
await expect(copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home }))
|
|
.rejects.toMatchObject({ status: 409, details: { stage: "locked_adoption_authority", predecessorPresent: true,
|
|
observedAfterInitialRead: true, changedFields: expect.arrayContaining([change === "materialization" || change === "checkpoint" ? "receipt" : change === "stopped" ? "processStoppedAt" : "state"]) } });
|
|
expect(injected).toBe(true);
|
|
expect(warning).toHaveBeenCalledWith({ companyId, agentId, runId: secondId, previousRunId: first.runId,
|
|
adoptionConflict: { stage: "locked_adoption_authority", predecessorPresent: true, observedAfterInitialRead: true,
|
|
changedFields: [change === "materialization" || change === "checkpoint" ? "receipt" : change === "stopped" ? "processStoppedAt" : "state"] } },
|
|
"Agent directory adoption conflict");
|
|
expect(JSON.stringify(warning.mock.calls)).not.toContain(privateValue);
|
|
expect(await copies.get(companyId, secondId)).toBeNull();
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBeUndefined();
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
} finally { spy.mockRestore(); warning.mockRestore(); }
|
|
});
|
|
|
|
it("reports closed claim predicates when retirement wins before the final owner read", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
const warning = vi.spyOn(logger, "warn");
|
|
const transaction = db.transaction.bind(db);
|
|
let injected = false;
|
|
const spy = vi.spyOn(db, "transaction").mockImplementation((async (callback, options) => {
|
|
const result = await transaction(callback, options);
|
|
if (!injected) {
|
|
injected = true;
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "pending_collection" })
|
|
.where(eq(agentInstructionWorkingCopies.runId, first.runId));
|
|
}
|
|
return result;
|
|
}) as typeof db.transaction);
|
|
try {
|
|
await expect(copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home }))
|
|
.rejects.toMatchObject({ status: 409, details: { stage: "adoption_claim", observedAfterClaim: true,
|
|
predecessorPresent: true, conditions: { unchangedTurn: false, timestampMatches: true, baselineMatches: true,
|
|
localRootMatches: true, unstopped: true, successorAbsent: true, receiptMatches: true } } });
|
|
expect(warning).toHaveBeenCalledWith({ companyId, agentId, runId: secondId, previousRunId: first.runId,
|
|
adoptionConflict: { stage: "adoption_claim", observedAfterClaim: true, predecessorPresent: true,
|
|
conditions: { unchangedTurn: false, timestampMatches: true, baselineMatches: true, localRootMatches: true,
|
|
unstopped: true, successorAbsent: true, receiptMatches: true } } }, "Agent directory adoption conflict");
|
|
expect(await copies.get(companyId, secondId)).toBeNull();
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBeUndefined();
|
|
} finally { spy.mockRestore(); warning.mockRestore(); }
|
|
});
|
|
|
|
it("allows only one stale concurrent adoption with identical updatedAt timestamps", async () => {
|
|
const fixed = new Date("2030-01-01T00:00:00.000Z");
|
|
vi.useFakeTimers({ toFake: ["Date"] });
|
|
vi.setSystemTime(fixed);
|
|
try {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const next = await Promise.all([nextRun(), nextRun()]);
|
|
let reads = 0;
|
|
let releaseReads!: () => void;
|
|
const bothRead = new Promise<void>(resolve => { releaseReads = resolve; });
|
|
// Both claimants see the same unclaimed row before either can enter
|
|
// the agent-row transaction. Date precision cannot distinguish them.
|
|
const staleReader = async () => {
|
|
const captured = await copies.get(companyId, first.runId);
|
|
reads++;
|
|
if (reads >= 3) { if (reads === 4) releaseReads(); await bothRead; }
|
|
return captured;
|
|
};
|
|
const service = agentDirectoryWorkingCopyService(db, staleReader, async (row, values) => {
|
|
const [updated] = await db.update(agentInstructionWorkingCopies).set({ ...values, updatedAt: fixed })
|
|
.where(eq(agentInstructionWorkingCopies.runId, row.runId)).returning();
|
|
return updated;
|
|
});
|
|
const settled = await Promise.allSettled(next.map(runId => service.adopt({ companyId, agentId, runId, previousRunId: first.runId, cwd: home })));
|
|
const winners = settled.filter(result => result.status === "fulfilled" && result.value);
|
|
expect(winners).toHaveLength(1);
|
|
expect(settled.filter(result => result.status === "rejected")).toHaveLength(1);
|
|
const prior = await copies.get(companyId, first.runId);
|
|
expect(prior?.updatedAt).toEqual(fixed);
|
|
const winnerId = prior?.receipt?.retainedByRunId as string;
|
|
expect(next).toContain(winnerId);
|
|
expect(await copies.get(companyId, next.find(id => id !== winnerId)!)).toBeNull();
|
|
await copies.collectStopped({ companyId, runId: winnerId });
|
|
} finally { vi.useRealTimers(); }
|
|
});
|
|
it("fences a stale collector when adoption commits immediately before its stop CAS", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
const transaction = db.transaction.bind(db);
|
|
let injected = false;
|
|
const spy = vi.spyOn(db, "transaction").mockImplementation((async (callback, options) => {
|
|
if (!injected) {
|
|
injected = true;
|
|
expect(await copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home })).not.toBeNull();
|
|
}
|
|
return transaction(callback, options);
|
|
}) as typeof db.transaction);
|
|
try {
|
|
expect(await copies.collectStopped({ companyId, runId: first.runId })).toMatchObject({
|
|
receipt: { retainedByRunId: secondId }, processStoppedAt: null, attempts: 0,
|
|
});
|
|
expect(injected).toBe(true);
|
|
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
|
expect((await copies.get(companyId, secondId))?.processStoppedAt).toBeNull();
|
|
} finally { spy.mockRestore(); }
|
|
await copies.collectStopped({ companyId, runId: secondId });
|
|
});
|
|
it("requires current-run authorization before transferring collection authority", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
await db.update(heartbeatRuns).set({ responsibleUserId: null }).where(eq(heartbeatRuns.id, secondId));
|
|
await expect(copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home })).rejects.toMatchObject({ status: 403 });
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.retainedByRunId).toBeUndefined();
|
|
await copies.collectStopped({ companyId, runId: first.runId });
|
|
});
|
|
it.each(["owner-close", "restart-proof"])("durably preserves an adopted directory after retirement failure and final cleanup: %s", async recovery => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
const secondId = await nextRun();
|
|
await copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home });
|
|
await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "native" }).where(eq(heartbeatRuns.id, secondId));
|
|
expect(await copies.reportRetirementUnconfirmed(companyId, secondId)).toMatchObject({
|
|
state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", processStoppedAt: null,
|
|
});
|
|
await fs.writeFile(path.join(first.localRoot, "unsaved-memory.txt"), "Keep failed retirement edits");
|
|
// Mirror heartbeat's final cleanup after preparation throws. Neither the
|
|
// current pending owner nor the prior alias may become terminal loss.
|
|
await copies.reportUnavailable(companyId, secondId);
|
|
await copies.reportUnavailable(companyId, first.runId);
|
|
expect(await copies.get(companyId, secondId)).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_STOP_UNCONFIRMED", processStoppedAt: null });
|
|
await copies.reportRetirementUnconfirmed(companyId, first.runId);
|
|
await copies.release(companyId, first.runId);
|
|
await copies.release(companyId, secondId);
|
|
await copies.recoverStopped(); // A terminal run with no stop receipt grants no collection authority.
|
|
expect((await copies.get(companyId, secondId))?.processStoppedAt).toBeNull();
|
|
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
|
if (recovery === "owner-close") await copies.collectStopped({ companyId, runId: secondId }); // Explicit test owner retirement.
|
|
else {
|
|
const { appendHeartbeatRunEvent } = await import("../services/heartbeat-run-events.js");
|
|
const stop = (runId: string) => appendHeartbeatRunEvent(db, { companyId, runId, agentId,
|
|
eventType: "native.local_process_stopped", stream: "system", level: "info", message: "Test-owned process retirement proof", payload: {} });
|
|
await stop(first.runId);
|
|
copies = agentInstructionWorkingCopyService(db); // No in-memory owner or transport survives.
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, secondId))?.processStoppedAt).toBeNull();
|
|
await stop(secondId);
|
|
// Make the deferred maintenance retry due after the new owner stop proof.
|
|
await db.update(agentInstructionWorkingCopies).set({ nextAttemptAt: null }).where(eq(agentInstructionWorkingCopies.runId, secondId));
|
|
await copies.recoverStopped();
|
|
}
|
|
expect(await copies.get(companyId, secondId)).toMatchObject({ state: "saved", receipt: { cleanupPending: false } });
|
|
expect(await fs.readFile(path.join(root, "unsaved-memory.txt"), "utf8")).toBe("Keep failed retirement edits");
|
|
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
it("declines reuse after canonical instruction changes", async () => {
|
|
const first = await run();
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(false);
|
|
await fs.writeFile(path.join(root, entryFile), "Changed canonical instructions");
|
|
const secondId = await nextRun();
|
|
expect(await copies.adopt({ companyId, agentId, runId: secondId, previousRunId: first.runId, cwd: home })).toBeNull();
|
|
await copies.collectStopped({ companyId, runId: first.runId });
|
|
});
|
|
it("requires stop for matching bytes at a replaced materialized root", async () => {
|
|
const first = await run();
|
|
const replaced = `${first.localRoot}-old`;
|
|
await fs.rename(first.localRoot, replaced);
|
|
await fs.cp(replaced, first.localRoot, { recursive: true });
|
|
expect(await copies.hasChanges({ companyId, runId: first.runId })).toBe(true);
|
|
await copies.collectStopped({ companyId, runId: first.runId });
|
|
});
|
|
});
|
|
|
|
it.each([".paperclip-runtime/state", "notes/.paperclip-runtime/state", "promptTemplate.legacy.md"])("rejects reserved board path %s before mutation", async (reserved) => {
|
|
await expect(agentFileStore(db).write({ ...target(), path: reserved, bytes: Buffer.from("reserved"), baseHash: null }, board())).rejects.toMatchObject({ status: 422 });
|
|
await expect(fs.stat(path.join(root, reserved))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await run()).toBeTruthy();
|
|
});
|
|
|
|
it("round trips nested text, empty directories and binary bytes independently of task files", async () => {
|
|
const first = await run();
|
|
expect(first.localRoot.startsWith(path.join(home, ".paperclip-runtime"))).toBe(false);
|
|
await fs.mkdir(path.join(first.localRoot, "notes", "empty"), { recursive: true });
|
|
await fs.writeFile(path.join(first.localRoot, "notes", "fact.txt"), "remember me");
|
|
const bytes = Buffer.from([0, 255, 17, 128, 9]);
|
|
await fs.writeFile(path.join(first.localRoot, "image.bin"), bytes);
|
|
await fs.writeFile(path.join(home, "task-only.txt"), "not personal");
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.state).toBe("saved");
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
const next = await run();
|
|
expect(await fs.readFile(path.join(next.localRoot, "notes", "fact.txt"), "utf8")).toBe("remember me");
|
|
expect(await fs.readFile(path.join(next.localRoot, "image.bin"))).toEqual(bytes);
|
|
expect((await fs.stat(path.join(next.localRoot, "notes", "empty"))).isDirectory()).toBe(true);
|
|
await expect(fs.stat(path.join(next.localRoot, "task-only.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId))).toHaveLength(0);
|
|
});
|
|
|
|
async function sparseFile(filename: string, size: number) {
|
|
const handle = await fs.open(filename, "w");
|
|
try { await handle.truncate(size); } finally { await handle.close(); }
|
|
}
|
|
|
|
it("saves and restores files beyond the former file and folder limits, with streaming inspection and download", async () => {
|
|
const first = await run();
|
|
const size = 66 * 1024 * 1024;
|
|
await sparseFile(path.join(first.localRoot, "large.bin"), size);
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.state).toBe("saved");
|
|
await copies.release(companyId, first.runId);
|
|
const next = await run();
|
|
const restored = await inspectAgentFile(next.localRoot, "large.bin");
|
|
expect(restored).toMatchObject({ size, bytes: null });
|
|
const store = agentFileStore(db);
|
|
const download = (await store.download(companyId, agentId, "large.bin", board()))!;
|
|
expect(download.size).toBe(size);
|
|
// The lock is released before consuming the stream. An editor replacement
|
|
// must not change the already opened download's bytes.
|
|
await store.write({ ...target(), path: "large.bin", bytes: Buffer.from("replacement"), baseHash: restored!.hash }, board());
|
|
const hash = createHash("sha256");
|
|
let downloaded = 0;
|
|
for await (const chunk of download.stream) { downloaded += chunk.length; hash.update(chunk); }
|
|
expect(downloaded).toBe(size);
|
|
expect(hash.digest("hex")).toBe(restored!.hash);
|
|
expect(await fs.readFile(path.join(root, "large.bin"), "utf8")).toBe("replacement");
|
|
await store.write({ ...target(), path: "empty.bin", bytes: Buffer.alloc(0), baseHash: null }, board());
|
|
const empty = (await store.download(companyId, agentId, "empty.bin", board()))!;
|
|
expect(empty.size).toBe(0);
|
|
for await (const _chunk of empty.stream) throw new Error("Empty download must have no chunks");
|
|
}, 30_000);
|
|
|
|
it("accepts the exact 256 MiB file boundary without retaining a text buffer", async () => {
|
|
expect(MAX_AGENT_FILE_BYTES).toBe(256 * 1024 * 1024);
|
|
await sparseFile(path.join(root, "boundary.bin"), MAX_AGENT_FILE_BYTES);
|
|
expect(await inspectAgentFile(root, "boundary.bin")).toMatchObject({ size: MAX_AGENT_FILE_BYTES, bytes: null });
|
|
});
|
|
|
|
it("checks quota for a small editor save without reading unrelated file bytes", async () => {
|
|
const asset = path.join(root, "large.bin");
|
|
await sparseFile(asset, MAX_AGENT_FILE_BYTES);
|
|
const open = vi.spyOn(fs, "open");
|
|
try {
|
|
await agentFileStore(db).write({ ...target(), path: "note.txt", bytes: Buffer.from("small edit"), baseHash: null }, board());
|
|
expect(open.mock.calls.some(([filename]) => filename === asset)).toBe(false);
|
|
expect(await fs.readFile(path.join(root, "note.txt"), "utf8")).toBe("small edit");
|
|
} finally { open.mockRestore(); }
|
|
});
|
|
|
|
it("reports an oversized run file without a partial save and removes its temporary copy", async () => {
|
|
const copy = await run();
|
|
await sparseFile(path.join(copy.localRoot, "too-large.bin"), MAX_AGENT_FILE_BYTES + 1);
|
|
await fs.writeFile(path.join(copy.localRoot, entryFile), "changed instructions");
|
|
const failed = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(failed).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED", candidateHash: null, nextAttemptAt: null, attempts: 1 });
|
|
expect(failed?.receipt?.storageWarning).toContain("Runs can continue");
|
|
expect(failed?.errorMessage).toContain('"too-large.bin" exceeds the 256 MiB');
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
await expect(fs.stat(path.join(root, "too-large.bin"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect((await copies.reportUnavailable(companyId, copy.runId))?.errorCode).toBe("AGENT_FILES_LIMIT_EXCEEDED");
|
|
await copies.release(companyId, copy.runId);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect((await copies.get(companyId, copy.runId))?.receipt?.baseline).toBeUndefined();
|
|
const next = await run();
|
|
expect(await fs.readFile(path.join(next.localRoot, entryFile), "utf8")).toBe(initial);
|
|
await fs.writeFile(path.join(next.localRoot, "next-task.txt"), "still working");
|
|
expect((await copies.collectStopped({ companyId, runId: next.runId }))?.state).toBe("saved");
|
|
expect(await fs.readFile(path.join(root, "next-task.txt"), "utf8")).toBe("still working");
|
|
});
|
|
|
|
it.each([false, true])("warns on each run at the file limit and clears the warning after ordinary agent cleanup (warm=%s)", async (warm) => {
|
|
await sparseFile(path.join(root, "full.bin"), MAX_AGENT_FILE_BYTES);
|
|
const first = await run({ warm });
|
|
expect(first.receipt?.storageWarning).toContain("256 MiB");
|
|
expect(instructionWorkingCopyGuidance(first)).toContain("Runs can continue");
|
|
const unchanged = await copies[warm ? "checkpointWarm" : "collectStopped"]({ companyId, runId: first.runId });
|
|
expect(unchanged).toMatchObject({ state: warm ? "warm_saved" : "unchanged", errorCode: null });
|
|
if (warm) expect(unchanged?.receipt?.checkpointState).toBe("unchanged");
|
|
expect(unchanged?.receipt?.storageWarning).toContain("Agent storage is full");
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
const second = await run({ warm, ...(warm ? { reuseRunId: first.runId } : {}) });
|
|
if (warm) expect(second.localRoot).toBe(first.localRoot);
|
|
expect(second.receipt?.storageWarning).toContain("Agent storage is full");
|
|
await fs.unlink(path.join(second.localRoot, "full.bin"));
|
|
await fs.writeFile(path.join(second.localRoot, "task-output.txt"), "work continues");
|
|
expect(await copies.collectStopped({ companyId, runId: second.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
|
const next = await run();
|
|
expect(next.receipt?.storageWarning).toBeNull();
|
|
expect(await fs.readFile(path.join(next.localRoot, "task-output.txt"), "utf8")).toBe("work continues");
|
|
}, 30_000);
|
|
|
|
it("starts successive runs with an already oversized saved file and lets the agent remove it", async () => {
|
|
await sparseFile(path.join(root, "old-large.bin"), MAX_AGENT_FILE_BYTES + 1);
|
|
const first = await run();
|
|
expect(first.state).toBe("prepared");
|
|
expect(first.receipt?.storageWarning).toContain("256 MiB");
|
|
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
|
const stopped = await copies.collectStopped({ companyId, runId: first.runId });
|
|
expect(stopped).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED" });
|
|
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
const cleanup = await run();
|
|
expect(cleanup.state).toBe("prepared");
|
|
await fs.unlink(path.join(cleanup.localRoot, "old-large.bin"));
|
|
expect(await copies.collectStopped({ companyId, runId: cleanup.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
|
expect((await run()).receipt?.storageWarning).toBeNull();
|
|
}, 30_000);
|
|
|
|
it("starts when the existing folder exceeds its total quota and accepts agent cleanup", async () => {
|
|
for (let index = 0; index < 8; index++) await fs.writeFile(path.join(root, `quota-part-${index}.bin`), "fixture");
|
|
const lstat = fs.lstat.bind(fs);
|
|
// Keep this regression small on disk while exercising the real filesystem,
|
|
// snapshots, database receipts, restore, and merge with 2 GiB of metadata.
|
|
const sizes = vi.spyOn(fs, "lstat").mockImplementation(async (...args: Parameters<typeof fs.lstat>) => {
|
|
const stat = await lstat(...args);
|
|
if (path.basename(String(args[0])).startsWith("quota-part-")) Object.assign(stat, { size: MAX_AGENT_FILE_BYTES });
|
|
return stat;
|
|
});
|
|
try {
|
|
const first = await run();
|
|
expect(first.receipt?.storageWarning).toContain("2 GiB");
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.errorCode).toBe("AGENT_FILES_LIMIT_EXCEEDED");
|
|
const cleanup = await run();
|
|
for (let index = 0; index < 8; index++) await fs.unlink(path.join(cleanup.localRoot, `quota-part-${index}.bin`));
|
|
await fs.writeFile(path.join(cleanup.localRoot, "small.txt"), "recovered");
|
|
expect(await copies.collectStopped({ companyId, runId: cleanup.runId })).toMatchObject({ state: "saved", receipt: { storageWarning: null } });
|
|
expect((await run()).receipt?.storageWarning).toBeNull();
|
|
} finally { sizes.mockRestore(); }
|
|
});
|
|
|
|
it("rejects more than 2 GiB in aggregate before hashing or saving any file", async () => {
|
|
expect(MAX_AGENT_DIRECTORY_BYTES).toBe(2 * 1024 * 1024 * 1024);
|
|
const copy = await run();
|
|
for (let index = 0; index < 8; index++) await sparseFile(path.join(copy.localRoot, `part-${index}.bin`), MAX_AGENT_FILE_BYTES);
|
|
// The eight allowed files exactly fill the quota; the entry is additional.
|
|
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(result).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED" });
|
|
expect(result?.errorMessage).toContain("2 GiB total storage limit");
|
|
expect(await fs.readdir(root)).toEqual(["policy"]);
|
|
});
|
|
|
|
it("rejects excessive entry count before snapshotting", async () => {
|
|
const directory = path.join(home, "many-entries");
|
|
await fs.mkdir(directory);
|
|
await fs.writeFile(path.join(directory, "empty"), "");
|
|
const entries = await fs.readdir(directory, { withFileTypes: true });
|
|
// Exercise the walker bound without creating 100,001 physical files.
|
|
const readdir = vi.spyOn(fs, "readdir").mockResolvedValue(Array(MAX_AGENT_DIRECTORY_ENTRIES + 1).fill(entries[0]));
|
|
try {
|
|
await expect(snapshotAgentFiles(directory)).rejects.toMatchObject({ status: 422, message: expect.stringContaining("100,000-entry limit") });
|
|
} finally { readdir.mockRestore(); }
|
|
}, 30_000);
|
|
|
|
it("keeps the entry's 1 MiB limit and cleans up failed synchronization", async () => {
|
|
const copy = await run();
|
|
await fs.writeFile(path.join(copy.localRoot, entryFile), "a".repeat(1024 * 1024 + 1));
|
|
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(result?.state).toBe("unavailable");
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(result?.errorMessage).toContain("at most 1 MiB");
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
});
|
|
|
|
it("merges independent changes and uses the last synchronization for same-file edits", async () => {
|
|
const a = await run(), b = await run();
|
|
await fs.writeFile(path.join(a.localRoot, "a.txt"), "A");
|
|
await fs.writeFile(path.join(b.localRoot, "b.txt"), "B");
|
|
await Promise.all([a, b].map(copy => copies.collectStopped({ companyId, runId: copy.runId })));
|
|
expect(await fs.readFile(path.join(root, "a.txt"), "utf8")).toBe("A");
|
|
expect(await fs.readFile(path.join(root, "b.txt"), "utf8")).toBe("B");
|
|
const c = await run(), d = await run();
|
|
await fs.writeFile(path.join(c.localRoot, "a.txt"), "C");
|
|
await fs.writeFile(path.join(d.localRoot, "a.txt"), "D");
|
|
await fs.writeFile(path.join(c.localRoot, "b.txt"), "new B");
|
|
expect((await copies.collectStopped({ companyId, runId: c.runId }))?.state).toBe("saved");
|
|
expect((await copies.collectStopped({ companyId, runId: d.runId }))?.state).toBe("saved");
|
|
expect(await fs.readFile(path.join(root, "a.txt"), "utf8")).toBe("D");
|
|
expect(await fs.readFile(path.join(root, "b.txt"), "utf8")).toBe("new B");
|
|
expect(await copies.list(companyId, agentId, board())).toEqual([]);
|
|
for (const copy of [a, b, c, d]) await expect(fs.stat(path.dirname(copy.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await fs.readdir(path.join(path.dirname(root), "file-sync", "runs"))).toEqual([]);
|
|
});
|
|
|
|
it("makes concurrent edit/delete races last-sync-wins and preserves unrelated new files", async () => {
|
|
await fs.mkdir(path.join(root, "notes"));
|
|
await fs.writeFile(path.join(root, "notes", "old.txt"), "old");
|
|
const deleting = await run(), editing = await run();
|
|
await fs.rm(path.join(deleting.localRoot, "notes"), { recursive: true });
|
|
await fs.writeFile(path.join(editing.localRoot, "notes", "old.txt"), "edited");
|
|
await fs.writeFile(path.join(editing.localRoot, "notes", "new.txt"), "unrelated");
|
|
await copies.collectStopped({ companyId, runId: editing.runId });
|
|
expect((await copies.collectStopped({ companyId, runId: deleting.runId }))?.state).toBe("saved");
|
|
await expect(fs.stat(path.join(root, "notes", "old.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await fs.readFile(path.join(root, "notes", "new.txt"), "utf8")).toBe("unrelated");
|
|
const remove = await run(), change = await run();
|
|
await fs.unlink(path.join(remove.localRoot, "notes", "new.txt"));
|
|
await fs.writeFile(path.join(change.localRoot, "notes", "new.txt"), "restored by later edit");
|
|
await copies.collectStopped({ companyId, runId: remove.runId });
|
|
await copies.collectStopped({ companyId, runId: change.runId });
|
|
expect(await fs.readFile(path.join(root, "notes", "new.txt"), "utf8")).toBe("restored by later edit");
|
|
});
|
|
|
|
it("handles a concurrently replaced parent and keeps the later file change", async () => {
|
|
await fs.mkdir(path.join(root, "notes"));
|
|
await fs.writeFile(path.join(root, "notes", "fact.txt"), "old");
|
|
const replacing = await run(), editing = await run();
|
|
await fs.rm(path.join(replacing.localRoot, "notes"), { recursive: true });
|
|
await fs.writeFile(path.join(replacing.localRoot, "notes"), "now a file");
|
|
await fs.writeFile(path.join(editing.localRoot, "notes", "fact.txt"), "new fact");
|
|
await copies.collectStopped({ companyId, runId: replacing.runId });
|
|
expect(await fs.readFile(path.join(root, "notes"), "utf8")).toBe("now a file");
|
|
expect((await copies.collectStopped({ companyId, runId: editing.runId }))?.state).toBe("saved");
|
|
expect(await fs.readFile(path.join(root, "notes", "fact.txt"), "utf8")).toBe("new fact");
|
|
});
|
|
|
|
it("cleans stopped copies after a crash during cleanup without touching active copies", async () => {
|
|
const finished = await run(), active = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date() }).where(eq(agentInstructionWorkingCopies.runId, finished.runId));
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverCaptured();
|
|
await expect(fs.stat(finished.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect((await fs.stat(active.localRoot)).isDirectory()).toBe(true);
|
|
});
|
|
|
|
it("cleans up a staging failure before any provider starts", async () => {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 1, signal: null, timedOut: false, stdout: "", stderr: "fixture failure", pid: null, startedAt: null });
|
|
try {
|
|
await expect(copies.prepare({ ...target(), runId, cwd: home, target: { kind: "remote", transport: "ssh", environmentId: randomUUID(), remoteCwd: "/fixture/task",
|
|
spec: { host: "unused.invalid", port: 22, username: "test", remoteCwd: "/fixture/task", remoteWorkspacePath: "/fixture/task", privateKey: null, knownHosts: null, strictHostKeyChecking: true } } })).rejects.toThrow("Could not exclude");
|
|
const row = (await copies.get(companyId, runId))!;
|
|
expect(row.state).toBe("unavailable");
|
|
expect(row.receipt?.baseline).toBeUndefined();
|
|
await expect(fs.stat(path.dirname(row.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
|
} finally { shell.mockRestore(); }
|
|
});
|
|
|
|
it.each(["succeeded", "failed", "cancelled", "timed_out", "interrupted"])("registers staging ownership before copying and cleans preparation for a %s run after restart", async (status) => {
|
|
const original = fs.cp.bind(fs);
|
|
const copy = vi.spyOn(fs, "cp").mockImplementationOnce(async (source, destination, options) => {
|
|
const rows = await db.select().from(agentInstructionWorkingCopies).where(eq(agentInstructionWorkingCopies.agentId, agentId));
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0]).toMatchObject({ state: "preparing", localRoot: destination });
|
|
return original(source, destination, options);
|
|
});
|
|
const interrupted = await run();
|
|
copy.mockRestore();
|
|
const active = await run();
|
|
for (const row of [interrupted, active]) {
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "preparing", baseHash: "preparing", receipt: { schema: "paperclip.agent-files.v1" } }).where(eq(agentInstructionWorkingCopies.runId, row.runId));
|
|
}
|
|
await db.update(heartbeatRuns).set({ status }).where(eq(heartbeatRuns.id, interrupted.runId));
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, interrupted.runId))?.state).toBe("unavailable");
|
|
await expect(fs.stat(path.dirname(interrupted.localRoot))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect((await fs.stat(active.localRoot)).isDirectory()).toBe(true);
|
|
});
|
|
|
|
it.each(["new-home", "same-path-empty", "foreign-lease", "other-controller", "missing-collector", "over-quota"] as const)("recovers remote agent files after controller cache loss: %s", async scenario => {
|
|
const copy = await run({ warm: true });
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/retained-task";
|
|
const executionRoot = path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId);
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId,
|
|
provider: "daytona", providerLeaseId: "original-sandbox", status: "active", metadata: { remoteCwd } });
|
|
await db.update(agentInstructionWorkingCopies).set({ location: `remote:${environmentId}`, executionRoot,
|
|
receipt: { ...copy.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const saved = (await copies.get(companyId, copy.runId))!;
|
|
const replacementHome = path.join(home, `replacement-${randomUUID()}`);
|
|
const remoteFiles = await fs.mkdtemp(path.join(home, "remote-checkpoint-"));
|
|
await fs.mkdir(path.join(remoteFiles, "files", "policy"), { recursive: true });
|
|
await fs.writeFile(path.join(remoteFiles, "files", entryFile), "Remote instructions changed during the turn");
|
|
await fs.writeFile(path.join(remoteFiles, "files", "unsaved.txt"), "Only the running sandbox has this");
|
|
await fs.rm(path.dirname(copy.localRoot), { recursive: true, force: true });
|
|
if (scenario === "over-quota") {
|
|
const handle = await fs.open(path.join(remoteFiles, "files", "too-large.bin"), "w");
|
|
try { await handle.truncate(MAX_AGENT_FILE_BYTES + 1); } finally { await handle.close(); }
|
|
}
|
|
const transport = vi.spyOn(executionTargetTools, "prepareAdapterExecutionTargetRuntime").mockImplementation(async options => ({
|
|
target: options.target!, workspaceRemoteDir: options.workspaceRemoteDir!, runtimeRootDir: options.runtimeRootDir!,
|
|
assetDirs: {}, additionalSourceDirs: {}, additionalSourceFailures: [], workspaceSyncSnapshot: null,
|
|
restoreWorkspace: async () => { await fs.cp(path.join(remoteFiles, "files"), options.workspaceLocalDir, { recursive: true }); },
|
|
}));
|
|
const ephemeralBefore = process.env.PAPERCLIP_EPHEMERAL_SERVER;
|
|
process.env.PAPERCLIP_EPHEMERAL_SERVER = "true";
|
|
if (scenario === "new-home") process.env.PAPERCLIP_HOME = replacementHome;
|
|
const remote = { kind: "remote" as const, transport: "sandbox" as const, environmentId,
|
|
leaseId: scenario === "foreign-lease" ? randomUUID() : leaseId, remoteCwd, runner: { execute: vi.fn() } };
|
|
try {
|
|
if (scenario === "missing-collector") {
|
|
const retained = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(retained).toMatchObject({ state: "pending_collection", errorCode: "INSTRUCTION_REMOTE_COLLECTOR_UNAVAILABLE", baseHash: saved.baseHash });
|
|
expect(retained?.receipt?.baseline).toEqual(saved.receipt?.baseline);
|
|
expect(retained?.nextAttemptAt).toBeInstanceOf(Date);
|
|
expect(transport).not.toHaveBeenCalled();
|
|
return;
|
|
}
|
|
if (scenario === "other-controller") {
|
|
await db.transaction(async tx => {
|
|
await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${`agent-directory:${companyId}:${agentId}`}, 0))`);
|
|
await expect(copies.prepare({ ...target(), runId: copy.runId, cwd: remoteCwd, target: remote, warm: true }))
|
|
.rejects.toThrow("Agent directory operation is already active");
|
|
expect(transport).not.toHaveBeenCalled();
|
|
});
|
|
return;
|
|
}
|
|
const preparing = copies.prepare({ ...target(), runId: copy.runId, cwd: remoteCwd, target: remote, warm: true });
|
|
if (scenario === "foreign-lease") {
|
|
await expect(preparing).rejects.toThrow("Agent directory recovery lease changed");
|
|
expect(transport).not.toHaveBeenCalled();
|
|
return;
|
|
}
|
|
const recovered = (await preparing)!;
|
|
expect(recovered.executionRoot).toBe(executionRoot);
|
|
expect(recovered.baseHash).toBe(saved.baseHash);
|
|
expect(recovered.receipt).toEqual(saved.receipt);
|
|
if (scenario === "new-home") {
|
|
expect(recovered.localRoot.startsWith(replacementHome)).toBe(true);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} else expect(recovered.localRoot).toBe(copy.localRoot);
|
|
expect(await fs.readFile(path.join(recovered.localRoot, "unsaved.txt"), "utf8")).toBe("Only the running sandbox has this");
|
|
expect(await fs.readFile(path.join(recovered.localRoot, entryFile), "utf8")).toBe("Remote instructions changed during the turn");
|
|
expect(transport).toHaveBeenNthCalledWith(1, expect.objectContaining({ adapterKey: "agent-files-recovery", workspaceRemoteDir: executionRoot,
|
|
workspaceBaseline: { exclude: [".paperclip-runtime"], entries: new Map() }, workspaceInboundMode: "adopt_remote" }));
|
|
if (scenario === "over-quota") {
|
|
expect((await fs.stat(path.join(recovered.localRoot, "too-large.bin"))).size).toBe(MAX_AGENT_FILE_BYTES + 1);
|
|
await expect(inspectAgentDirectory(recovered.localRoot)).rejects.toThrow();
|
|
}
|
|
expect(transport).toHaveBeenCalledWith(expect.objectContaining({ workspaceLocalDir: recovered.localRoot, workspaceInboundMode: "adopt_remote" }));
|
|
await copies.prepare({ ...target(), runId: copy.runId, cwd: remoteCwd, target: remote, warm: true });
|
|
expect(transport).toHaveBeenCalledTimes(2);
|
|
} finally {
|
|
process.env.PAPERCLIP_HOME = home;
|
|
if (ephemeralBefore === undefined) delete process.env.PAPERCLIP_EPHEMERAL_SERVER;
|
|
else process.env.PAPERCLIP_EPHEMERAL_SERVER = ephemeralBefore;
|
|
transport.mockRestore();
|
|
}
|
|
});
|
|
|
|
it("retains remote cleanup across restart and failed retries until the original lease is cleaned", async () => {
|
|
const copy = await run();
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
|
const executionRoot = path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId);
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values({ id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "original-sandbox" });
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(), location: `remote:${environmentId}`, executionRoot,
|
|
receipt: { ...copy.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverCaptured();
|
|
const pending = (await copies.get(companyId, copy.runId))!;
|
|
expect(pending.receipt).toMatchObject({ cleanupPending: true, cleanup: { leaseId, remoteCwd } });
|
|
expect(pending.receipt?.baseline).toBeUndefined();
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
const execute = vi.fn().mockRejectedValueOnce(new Error("provider temporarily unavailable")).mockResolvedValue({ exitCode: 0, stdout: "", stderr: "" });
|
|
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
for (const expectedPending of [true, false]) {
|
|
await db.update(agentInstructionWorkingCopies).set({ nextAttemptAt: null }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
await copies.recoverCaptured();
|
|
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(expectedPending);
|
|
}
|
|
expect(execute).toHaveBeenCalledTimes(2);
|
|
expect(execute).toHaveBeenLastCalledWith(expect.objectContaining({ lease: expect.objectContaining({ id: leaseId, providerLeaseId: "original-sandbox" }),
|
|
command: "rm", args: ["-rf", "--", executionRoot,
|
|
path.posix.join(remoteCwd, ".paperclip-runtime", "paperclip-runner", "agent-file-transfers", agentId, copy.runId)], bypassSession: true }));
|
|
await copies.recoverCaptured();
|
|
expect(execute).toHaveBeenCalledTimes(2);
|
|
await copies.release(companyId, copy.runId);
|
|
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(false);
|
|
expect(execute).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it.each(["missing", "stopped", "destroyed"])("recovers a retained remote unchanged turn only with exact stop proof: %s", async stopped => {
|
|
const copy = await run();
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
|
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "retained-sandbox" };
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values({ ...lease, status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
|
metadata: stopped !== "missing" ? { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: stopped }) } : {} });
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native" }).where(eq(heartbeatRuns.id, copy.runId));
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unchanged_turn", location: `remote:${environmentId}`,
|
|
executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
|
receipt: { ...copy.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const execute = vi.fn();
|
|
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
expect((await copies.reportUnavailable(companyId, copy.runId))?.state).toBe("unchanged_turn");
|
|
await copies.recoverStopped();
|
|
const recovered = (await copies.get(companyId, copy.runId))!;
|
|
if (stopped === "destroyed") {
|
|
expect(recovered).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE", receipt: { cleanupPending: false } });
|
|
expect(recovered.processStoppedAt).toBeInstanceOf(Date);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, copy.runId))?.updatedAt).toEqual(recovered.updatedAt);
|
|
} else {
|
|
expect(recovered).toMatchObject({ state: stopped === "stopped" ? "pending_collection" : "unchanged_turn", processStoppedAt: null });
|
|
if (stopped === "stopped") {
|
|
expect(recovered.errorCode).toBe("INSTRUCTION_STOPPED_REMOTE_COLLECTION_PENDING");
|
|
expect(recovered.receipt?.baseline).toBeDefined();
|
|
await copies.release(companyId, copy.runId);
|
|
await copies.recoverCaptured();
|
|
}
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
}
|
|
expect(execute).not.toHaveBeenCalled(); // Never restart a remote provider to recover bytes.
|
|
});
|
|
|
|
it.each([0, 2])("preserves a legacy no-ID remote copy with %s matching leases", async count => {
|
|
const copy = await run();
|
|
const environmentId = randomUUID(), remoteCwd = "/fixture/task";
|
|
await db.insert(environments).values({ id: environmentId, name: `Legacy remote ${environmentId}`, driver: "sandbox" });
|
|
for (let index = 0; index < count; index++) await db.insert(environmentLeases).values({
|
|
companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: `allocation-${index}` });
|
|
await db.update(agentInstructionWorkingCopies).set({ location: `remote:${environmentId}`,
|
|
executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
|
receipt: { ...copy.receipt, cleanup: { remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const execute = vi.fn();
|
|
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
const pending = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(pending).toMatchObject({ state: "pending_collection", attempts: 0, processStoppedAt: null, errorCode: "INSTRUCTION_REMOTE_LEASE_UNVERIFIED" });
|
|
expect(pending!.receipt?.baseline).toBeDefined();
|
|
await copies.release(companyId, copy.runId);
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("finishes remote cleanup from a destruction receipt after the environment is deleted", async () => {
|
|
const copy = await run();
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
|
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "destroyed-sandbox" };
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values({ ...lease, status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
|
metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }) } });
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "saved", processStoppedAt: new Date(), location: `remote:${environmentId}`,
|
|
executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
|
receipt: { ...copy.receipt, cleanupPending: true, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
await db.delete(environments).where(eq(environments.id, environmentId));
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverCaptured();
|
|
expect((await copies.get(companyId, copy.runId))?.receipt?.cleanupPending).toBe(false);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it.each([false, true])("rejects symlinks without saving any part of the tree, preserving an existing full-storage warning: %s", async (full) => {
|
|
if (full) await sparseFile(path.join(root, "full.bin"), MAX_AGENT_FILE_BYTES);
|
|
const copy = await run();
|
|
await fs.writeFile(path.join(copy.localRoot, "innocent.txt"), "changed");
|
|
await fs.symlink(path.join(home, "outside"), path.join(copy.localRoot, "escape"));
|
|
const result = await copies.collectStopped({ companyId, runId: copy.runId });
|
|
expect(result?.state).toBe("unavailable");
|
|
expect(result?.errorCode).toBe("AGENT_FILES_SAVE_FAILED");
|
|
expect(result?.receipt?.storageWarning).toBe(copy.receipt?.storageWarning);
|
|
if (full) expect(result?.receipt?.storageWarning).toContain("Agent storage is full");
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await expect(fs.stat(path.join(root, "innocent.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
}, 30_000);
|
|
|
|
it("adopts the last deployed head once and bridges an old collector without appending history", async () => {
|
|
const id = randomUUID();
|
|
const content = "last deployed revision";
|
|
await db.insert(agentInstructionRevisions).values({ id, ...target(), entryFile, contentBase64: Buffer.from(content).toString("base64"), contentHash: fileHash(Buffer.from(content)), byteLength: content.length, source: "board" });
|
|
await db.insert(agentInstructionHeads).values({ ...target(), entryFile, revisionId: id });
|
|
const current = await revisions.readCurrent(target(), board());
|
|
expect(current?.content).toBe(content);
|
|
await revisions.commit({ ...target(), entryFile, content: "new directory contents", baseRevisionId: id, source: "cleanup" }, board());
|
|
await revisions.materializeCurrent(target());
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe("new directory contents");
|
|
await expect(revisions.commit({ ...target(), entryFile, content: "stale legacy run", baseRevisionId: id, source: "cleanup" }, board())).rejects.toMatchObject({ status: 409 });
|
|
expect(await db.select().from(agentInstructionRevisions).where(eq(agentInstructionRevisions.agentId, agentId))).toHaveLength(1);
|
|
});
|
|
|
|
it("ordinary file edits leave the loaded instruction digest unchanged", async () => {
|
|
const make = async () => {
|
|
const copy = await run();
|
|
const context = await buildNativeRuntimeContext({ db, agent: { id: agentId, companyId, name: "Target", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } },
|
|
runId: copy.runId, runtimeConfig: {}, runtimeSkillEntries: [], instructionWorkingCopy: { rootPath: copy.executionRoot, entryPath: entryFile, kind: "agent_files" } });
|
|
return { copy, context };
|
|
};
|
|
const before = await make();
|
|
await fs.writeFile(path.join(before.copy.localRoot, "notes.txt"), "new personal knowledge");
|
|
await copies.collectStopped({ companyId, runId: before.copy.runId });
|
|
const after = await make();
|
|
expect(after.context.aggregateDigest).toBe(before.context.aggregateDigest);
|
|
expect(after.context.instructions.bundle.fileCount).toBe(1);
|
|
});
|
|
it("checkpoints three managed turns into one live directory, fences old cleanup, and persists after retirement", async () => {
|
|
let copy = await run({ warm: true });
|
|
const original = copy;
|
|
for (let turn = 1; turn <= 3; turn++) {
|
|
await fs.appendFile(path.join(copy.localRoot, "memory.txt"), `turn ${turn}\n`);
|
|
const saved = (await copies.checkpointWarm({ companyId, runId: copy.runId }))!;
|
|
expect(saved.state).toBe("warm_saved");
|
|
expect(saved.processStoppedAt).toBeNull();
|
|
expect(await agentFileStore(db).read(companyId, agentId, "memory.txt", board())).toEqual(Buffer.from(Array.from({ length: turn }, (_, i) => `turn ${i + 1}\n`).join("")));
|
|
await copies.release(companyId, copy.runId);
|
|
expect(await fs.stat(copy.localRoot)).toBeTruthy();
|
|
if (turn < 3) {
|
|
expect(await copies.canReuseWarm(companyId, agentId, copy.runId)).toBe(true);
|
|
copy = await run({ warm: true, reuseRunId: copy.runId });
|
|
expect(copy.executionRoot).toBe(original.executionRoot);
|
|
await copies.collectStopped({ companyId, runId: original.runId });
|
|
await copies.release(companyId, original.runId);
|
|
expect(await fs.stat(copy.localRoot)).toBeTruthy();
|
|
}
|
|
}
|
|
// A child may write after the last turn's checkpoint; session retirement
|
|
// must collect this delta using the current owner, not the first run.
|
|
await fs.writeFile(path.join(copy.localRoot, "late.txt"), "after turn");
|
|
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("saved");
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
const fresh = await run();
|
|
expect(await fs.readFile(path.join(fresh.localRoot, "memory.txt"), "utf8")).toBe("turn 1\nturn 2\nturn 3\n");
|
|
expect(await fs.readFile(path.join(fresh.localRoot, "late.txt"), "utf8")).toBe("after turn");
|
|
});
|
|
|
|
it("rechecks canonical edits at handoff and releases the writer lock before retirement and fresh restore", async () => {
|
|
const first = await run({ warm: true });
|
|
await copies.checkpointWarm({ companyId, runId: first.runId });
|
|
expect(await copies.canReuseWarm(companyId, agentId, first.runId)).toBe(true);
|
|
await agentFileStore(db).write({ ...target(), path: "editor.txt", bytes: Buffer.from("new canonical content"), baseHash: null }, board());
|
|
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
await expect(copies.prepare({ ...target(), runId, cwd: home, warm: true, reuseRunId: first.runId })).rejects.toBeInstanceOf(AgentDirectoryReuseInvalidatedError);
|
|
expect(JSON.parse(await fs.readFile(path.join(path.dirname(first.localRoot), "owner.json"), "utf8")).runId).toBe(first.runId);
|
|
// Both paths need the canonical writer lock. A handoff failure must release
|
|
// it before orchestration stops the old session and restores a fresh copy.
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId }))?.state).toBe("unchanged");
|
|
const next = (await copies.prepare({ ...target(), runId, cwd: home, warm: true }))!;
|
|
expect(next.localRoot).not.toBe(first.localRoot);
|
|
expect(await fs.readFile(path.join(next.localRoot, "editor.txt"), "utf8")).toBe("new canonical content");
|
|
}, 10_000);
|
|
|
|
it("attaches the successor collector before fallible post-handoff bookkeeping", async () => {
|
|
const first = await run({ warm: true });
|
|
await copies.checkpointWarm({ companyId, runId: first.runId });
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
let collectorRunId = first.runId;
|
|
const handoff = vi.fn((copy: typeof first) => { collectorRunId = copy.runId; });
|
|
const directories = agentDirectoryWorkingCopyService(db, copies.get, async () => { throw new Error("injected post-handoff database failure"); });
|
|
|
|
await expect(directories.prepare({ ...target(), runId, cwd: home, warm: true, reuseRunId: first.runId, onWarmHandoff: handoff }))
|
|
.rejects.toThrow("injected post-handoff database failure");
|
|
expect(handoff).toHaveBeenCalledOnce();
|
|
expect(collectorRunId).toBe(runId);
|
|
await fs.writeFile(path.join(first.localRoot, "last-write.txt"), "saved after failed handoff");
|
|
// The stale collector cannot touch the successor; the attached collector
|
|
// still saves and cleans the actual owner after process retirement.
|
|
await copies.collectStopped({ companyId, runId: first.runId });
|
|
expect((await fs.stat(first.localRoot)).isDirectory()).toBe(true);
|
|
expect((await copies.collectStopped({ companyId, runId: collectorRunId }))?.state).toBe("saved");
|
|
expect(await fs.readFile(path.join(root, "last-write.txt"), "utf8")).toBe("saved after failed handoff");
|
|
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
}, 10_000);
|
|
it("retires loaded instruction edits while allowing ordinary personal-file edits to stay warm", async () => {
|
|
const copy = await run({ warm: true });
|
|
await fs.writeFile(path.join(copy.localRoot, entryFile), "# New loaded policy\n");
|
|
expect((await copies.checkpointWarm({ companyId, runId: copy.runId }))?.state).toBe("warm_saved");
|
|
expect(await copies.canReuseWarm(companyId, agentId, copy.runId)).toBe(false);
|
|
await copies.collectStopped({ companyId, runId: copy.runId });
|
|
const fresh = await run({ warm: true });
|
|
expect(fresh.executionRoot).not.toBe(copy.executionRoot);
|
|
expect(await fs.readFile(path.join(fresh.localRoot, entryFile), "utf8")).toBe("# New loaded policy\n");
|
|
});
|
|
it("refreshes after editor changes and preserves concurrent unrelated files", async () => {
|
|
const copy = await run({ warm: true });
|
|
await fs.writeFile(path.join(copy.localRoot, "mine.txt"), "from run");
|
|
await agentFileStore(db).write({ ...target(), path: "board.txt", bytes: Buffer.from("from board"), baseHash: null }, board());
|
|
expect((await copies.checkpointWarm({ companyId, runId: copy.runId }))?.state).toBe("warm_saved");
|
|
expect(await copies.canReuseWarm(companyId, agentId, copy.runId)).toBe(false);
|
|
expect(await fs.readFile(path.join(root, "board.txt"), "utf8")).toBe("from board");
|
|
expect(await fs.readFile(path.join(root, "mine.txt"), "utf8")).toBe("from run");
|
|
await copies.collectStopped({ companyId, runId: copy.runId });
|
|
});
|
|
it("keeps an invalid warm checkpoint unsaved and requests stopped collection", async () => {
|
|
const copy = await run({ warm: true });
|
|
await fs.symlink(root, path.join(copy.localRoot, "escape"));
|
|
const failed = await copies.checkpointWarm({ companyId, runId: copy.runId });
|
|
expect(failed?.state).toBe("prepared");
|
|
expect(failed?.errorCode).toBe("AGENT_FILES_CHECKPOINT_UNSTABLE");
|
|
expect(failed?.processStoppedAt).toBeNull();
|
|
expect(await copies.canReuseWarm(companyId, agentId, copy.runId)).toBe(false);
|
|
await fs.rm(path.join(copy.localRoot, "escape"));
|
|
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("unchanged");
|
|
});
|
|
it("rejects over-quota warm changes without replacing saved bytes, then permits a clean future run", async () => {
|
|
const copy = await run({ warm: true });
|
|
const handle = await fs.open(path.join(copy.localRoot, "too-large.bin"), "w");
|
|
await handle.truncate(MAX_AGENT_FILE_BYTES + 1); await handle.close();
|
|
expect((await copies.checkpointWarm({ companyId, runId: copy.runId }))?.errorCode).toBe("AGENT_FILES_CHECKPOINT_UNSTABLE");
|
|
const stopped = (await copies.collectStopped({ companyId, runId: copy.runId }))!;
|
|
expect(stopped).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_LIMIT_EXCEEDED" });
|
|
expect(stopped.receipt?.storageWarning).toContain("Agent storage is full");
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await run({ warm: true })).toBeTruthy();
|
|
});
|
|
it("rechecks authorization even for an unchanged warm checkpoint", async () => {
|
|
const copy = await run({ warm: true });
|
|
await copies.checkpointWarm({ companyId, runId: copy.runId });
|
|
await db.delete(principalPermissionGrants).where(eq(principalPermissionGrants.companyId, companyId));
|
|
await db.update(companyMemberships).set({ membershipRole: "member" }).where(eq(companyMemberships.companyId, companyId));
|
|
expect((await copies.checkpointWarm({ companyId, runId: copy.runId }))?.errorCode).toBe("AGENT_FILES_CHECKPOINT_UNSTABLE");
|
|
expect(await copies.canReuseWarm(companyId, agentId, copy.runId)).toBe(false);
|
|
expect((await copies.collectStopped({ companyId, runId: copy.runId }))?.state).toBe("unavailable");
|
|
});
|
|
it("reclaims a warm remote owner after verified sandbox destruction without claiming unsaved tail bytes", async () => {
|
|
const copy = await run({ warm: true });
|
|
await fs.writeFile(path.join(copy.localRoot, "saved.txt"), "checkpoint");
|
|
await copies.checkpointWarm({ companyId, runId: copy.runId });
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/task";
|
|
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "destroyed-warm" };
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values({ ...lease, status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
|
metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }) } });
|
|
await db.update(heartbeatRuns).set({ status: "succeeded", runtimeMode: "native" }).where(eq(heartbeatRuns.id, copy.runId));
|
|
const saved = (await copies.get(companyId, copy.runId))!;
|
|
await db.update(agentInstructionWorkingCopies).set({ location: `remote:${environmentId}`,
|
|
executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
|
receipt: { ...saved.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverStopped();
|
|
const recovered = (await copies.get(companyId, copy.runId))!;
|
|
expect(recovered).toMatchObject({ state: "unavailable", errorCode: "AGENT_FILES_FINAL_COLLECTION_UNAVAILABLE" });
|
|
expect(recovered.receipt?.cleanupPending).toBe(false);
|
|
expect(await fs.readFile(path.join(root, "saved.txt"), "utf8")).toBe("checkpoint");
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
it("uses the workspace transport to restore after destruction of the remote filesystem", async () => {
|
|
const remoteCwd = path.join(home, "remote-task");
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
await execFile("git", ["init", remoteCwd]);
|
|
const runner: import("@paperclipai/adapter-utils/command-managed-runtime").CommandManagedRuntimeRunner = {
|
|
execute: async input => {
|
|
const startedAt = new Date().toISOString();
|
|
const env = { ...process.env, ...input.env };
|
|
const args = [...(input.args ?? [])];
|
|
if (input.stdin != null && (args[0] === "-c" || args[0] === "-lc")) {
|
|
env.PAPERCLIP_TEST_STDIN = input.stdin;
|
|
args[1] = `printf '%s' "$PAPERCLIP_TEST_STDIN" | (${args[1]})`;
|
|
}
|
|
try {
|
|
const result = await execFile(input.command, args, { cwd: input.cwd, env, timeout: input.timeoutMs, maxBuffer: 32 * 1024 * 1024 });
|
|
return { exitCode: 0, signal: null, timedOut: false, stdout: result.stdout, stderr: result.stderr, pid: null, startedAt };
|
|
} catch (error) {
|
|
const e = error as { code?: number; signal?: NodeJS.Signals; stdout?: string; stderr?: string };
|
|
return { exitCode: typeof e.code === "number" ? e.code : 1, signal: e.signal ?? null, timedOut: false, stdout: e.stdout ?? "", stderr: e.stderr ?? "", pid: null, startedAt };
|
|
}
|
|
},
|
|
};
|
|
const executionTarget = { kind: "remote" as const, transport: "sandbox" as const, environmentId: randomUUID(), leaseId: "", remoteCwd, runner };
|
|
await db.insert(environments).values({ id: executionTarget.environmentId, name: "Fixture sandbox", driver: "sandbox" });
|
|
const prepare = async () => {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
executionTarget.leaseId = randomUUID();
|
|
await db.insert(environmentLeases).values({ id: executionTarget.leaseId, companyId, environmentId: executionTarget.environmentId,
|
|
heartbeatRunId: runId, provider: "daytona", providerLeaseId: "fixture-allocation" });
|
|
return (await copies.prepare({ ...target(), runId, cwd: home, target: executionTarget }))!;
|
|
};
|
|
await fs.mkdir(path.join(root, "build"));
|
|
await fs.writeFile(path.join(root, "build", "personal.txt"), "cache-like names are still agent files");
|
|
const first = await prepare();
|
|
const firstScratch = path.join(remoteCwd, ".paperclip-runtime", "paperclip-runner", "agent-file-transfers", agentId, first.runId);
|
|
expect(await fs.readdir(firstScratch)).toEqual([]);
|
|
await expect(fs.stat(path.join(first.executionRoot, ".paperclip-runtime"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await fs.readFile(path.join(first.executionRoot, "build", "personal.txt"), "utf8")).toBe("cache-like names are still agent files");
|
|
await fs.mkdir(path.join(first.executionRoot, "notes"));
|
|
await fs.writeFile(path.join(first.executionRoot, "notes", "bytes.bin"), Buffer.from([0, 128, 255]));
|
|
await fs.mkdir(path.join(first.executionRoot, "node_modules"));
|
|
await fs.writeFile(path.join(first.executionRoot, "node_modules", "personal.txt"), "retain this too");
|
|
await fs.writeFile(path.join(remoteCwd, "task-only.txt"), "task");
|
|
expect((await execFile("git", ["-C", remoteCwd, "status", "--porcelain", "--untracked-files=all"])).stdout).toBe("?? task-only.txt\n");
|
|
expect((await copies.collectStopped({ companyId, runId: first.runId, target: executionTarget }))?.state).toBe("saved");
|
|
await copies.release(companyId, first.runId);
|
|
await expect(fs.stat(firstScratch)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect((await copies.get(companyId, first.runId))?.receipt?.baseline).toBeUndefined();
|
|
await expect(fs.stat(first.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await fs.rm(remoteCwd, { recursive: true });
|
|
await fs.mkdir(remoteCwd);
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
const second = await prepare();
|
|
expect(await fs.readFile(path.join(second.executionRoot, "notes", "bytes.bin"))).toEqual(Buffer.from([0,128,255]));
|
|
expect(await fs.readFile(path.join(second.executionRoot, "node_modules", "personal.txt"), "utf8")).toBe("retain this too");
|
|
await expect(fs.stat(path.join(second.executionRoot, "task-only.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
await copies.collectStopped({ companyId, runId: second.runId, target: executionTarget });
|
|
await copies.release(companyId, second.runId);
|
|
});
|
|
|
|
it("checkpoints and reuses the remote directory through the real transport without copying unchanged bytes", async () => {
|
|
const remoteCwd = path.join(home, "warm-remote-task");
|
|
await fs.mkdir(remoteCwd, { recursive: true });
|
|
const runner: import("@paperclipai/adapter-utils/command-managed-runtime").CommandManagedRuntimeRunner = {
|
|
execute: async input => {
|
|
const startedAt = new Date().toISOString();
|
|
const env = { ...process.env, ...input.env };
|
|
const args = [...(input.args ?? [])];
|
|
if (input.stdin != null && (args[0] === "-c" || args[0] === "-lc")) {
|
|
env.PAPERCLIP_TEST_STDIN = input.stdin;
|
|
args[1] = `printf '%s' "$PAPERCLIP_TEST_STDIN" | (${args[1]})`;
|
|
}
|
|
try {
|
|
const result = await execFile(input.command, args, { cwd: input.cwd, env, timeout: input.timeoutMs, maxBuffer: 32 * 1024 * 1024 });
|
|
return { exitCode: 0, signal: null, timedOut: false, stdout: result.stdout, stderr: result.stderr, pid: null, startedAt };
|
|
} catch (error) {
|
|
const e = error as { code?: number; signal?: NodeJS.Signals; stdout?: string; stderr?: string };
|
|
return { exitCode: typeof e.code === "number" ? e.code : 1, signal: e.signal ?? null, timedOut: false, stdout: e.stdout ?? "", stderr: e.stderr ?? "", pid: null, startedAt };
|
|
}
|
|
},
|
|
};
|
|
const executionTarget = { kind: "remote" as const, transport: "sandbox" as const, environmentId: randomUUID(), leaseId: "", remoteCwd, runner };
|
|
await db.insert(environments).values({ id: executionTarget.environmentId, name: "Warm fixture sandbox", driver: "sandbox" });
|
|
const prepare = async (reuseRunId?: string) => {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
executionTarget.leaseId = randomUUID();
|
|
await db.insert(environmentLeases).values({ id: executionTarget.leaseId, companyId, environmentId: executionTarget.environmentId,
|
|
heartbeatRunId: runId, provider: "daytona", providerLeaseId: "warm-fixture-allocation" });
|
|
return (await copies.prepare({ ...target(), runId, cwd: home, target: executionTarget, warm: true, reuseRunId }))!;
|
|
};
|
|
let copy = await prepare();
|
|
const original = copy;
|
|
await fs.writeFile(path.join(copy.executionRoot, "image.bin"), Buffer.alloc(32768, 93));
|
|
for (let turn = 1; turn <= 3; turn++) {
|
|
await fs.appendFile(path.join(copy.executionRoot, "memory.txt"), `turn ${turn}\n`);
|
|
const saved = (await copies.checkpointWarm({ companyId, runId: copy.runId, target: executionTarget }))!;
|
|
expect(saved, JSON.stringify({ code: saved.errorCode, message: saved.errorMessage })).toMatchObject({ state: "warm_saved", errorCode: null });
|
|
if (turn > 1) expect(saved.receipt?.checkpointStats).toMatchObject({ copiedFiles: 1, copiedBytes: turn * 7, hashedBytes: turn * 7 });
|
|
expect(await fs.readFile(path.join(root, "memory.txt"), "utf8")).toBe(Array.from({ length: turn }, (_, i) => `turn ${i + 1}\n`).join(""));
|
|
expect((await fs.readdir(path.dirname(copy.localRoot))).filter(name => name.startsWith("checkpoint-"))).toEqual([]);
|
|
expect((await fs.readdir(path.join(copy.executionRoot, ".paperclip-runtime"))).filter(name => name.startsWith("checkpoint-"))).toEqual([]);
|
|
if (turn < 3) { copy = await prepare(copy.runId); expect(copy.executionRoot).toBe(original.executionRoot); }
|
|
}
|
|
await copies.collectStopped({ companyId, runId: original.runId, target: executionTarget });
|
|
expect(await fs.stat(copy.executionRoot)).toBeTruthy();
|
|
expect((await copies.collectStopped({ companyId, runId: copy.runId, target: executionTarget }))?.receipt).toMatchObject({ cleanupPending: false });
|
|
await expect(fs.stat(copy.executionRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it("stages SSH agent files at the registered root without a nested task workspace", async () => {
|
|
const remoteCwd = path.join(home, "ssh-task");
|
|
const exclude = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: null, startedAt: null });
|
|
const stage = vi.spyOn(ssh, "syncDirectoryToSsh").mockImplementation(async input => {
|
|
await fs.mkdir(path.dirname(input.remoteDir), { recursive: true });
|
|
await fs.cp(input.localDir, input.remoteDir, { recursive: true });
|
|
});
|
|
const restore = vi.spyOn(ssh, "restoreWorkspaceFromSshExecution").mockImplementation(async input => {
|
|
await fs.cp(input.remoteDir!, input.localDir, { recursive: true });
|
|
});
|
|
try {
|
|
const runId = randomUUID();
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
const target = { kind: "remote" as const, transport: "ssh" as const, environmentId: randomUUID(), remoteCwd,
|
|
spec: { host: "unused.invalid", port: 22, username: "test", remoteCwd, remoteWorkspacePath: remoteCwd, privateKey: null, knownHosts: null, strictHostKeyChecking: true } };
|
|
await db.insert(environments).values({ id: target.environmentId, name: "Fixture SSH", driver: "ssh" });
|
|
// Legacy no-ID receipt: only the unique run/environment lease authorizes retrieval.
|
|
await db.insert(environmentLeases).values({ companyId, environmentId: target.environmentId, heartbeatRunId: runId, provider: "ssh", providerLeaseId: "fixture-host" });
|
|
const copy = (await copies.prepare({ companyId, agentId, runId, cwd: home, target }))!;
|
|
expect(stage).toHaveBeenCalledWith(expect.objectContaining({ remoteDir: copy.executionRoot }));
|
|
expect(await fs.readFile(path.join(copy.executionRoot, entryFile), "utf8")).toBe(initial);
|
|
await fs.writeFile(path.join(copy.executionRoot, "ssh-note.txt"), "persistent SSH file");
|
|
expect((await copies.collectStopped({ companyId, runId, target }))?.state).toBe("saved");
|
|
expect(restore).toHaveBeenCalledWith(expect.objectContaining({ remoteDir: copy.executionRoot, restoreGitHistory: false }));
|
|
expect(await fs.readFile(path.join(root, "ssh-note.txt"), "utf8")).toBe("persistent SSH file");
|
|
} finally { stage.mockRestore(); restore.mockRestore(); exclude.mockRestore(); }
|
|
});
|
|
|
|
it("deduplicates concurrent stopped callbacks and discards completed operational snapshots", async () => {
|
|
const copy = await run();
|
|
await fs.writeFile(path.join(copy.localRoot, "note.txt"), "one write");
|
|
const results = await Promise.all([copies.collectStopped({ companyId, runId: copy.runId }), copies.collectStopped({ companyId, runId: copy.runId })]);
|
|
expect(results.every(result => result?.state === "saved")).toBe(true);
|
|
// Simulate a crash after save but before release. The restart sweeper must
|
|
// reclaim operational baselines without touching canonical files.
|
|
copies = agentInstructionWorkingCopyService(db);
|
|
await copies.recoverCaptured();
|
|
const row = await copies.get(companyId, copy.runId);
|
|
expect(row?.receipt?.schema).toBe("paperclip.agent-files.v1");
|
|
expect(row?.receipt?.baseline).toBeUndefined();
|
|
expect(await fs.readFile(path.join(root, "note.txt"), "utf8")).toBe("one write");
|
|
});
|
|
|
|
it.each(["prepared", "unavailable", "warm_saved", "superseded", "saved", "unchanged", "resolved"])(
|
|
"does not acquire a held directory lock for a no-op %s release", async state => {
|
|
const copy = await run();
|
|
const stopped = ["superseded", "saved", "unchanged", "resolved"].includes(state);
|
|
await db.update(agentInstructionWorkingCopies).set({ state, processStoppedAt: stopped ? new Date() : null,
|
|
receipt: { ...copy.receipt, ...(stopped ? { cleanupPending: false } : {}) } })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const before = await copies.get(companyId, copy.runId);
|
|
await withDirectoryMergeLock(path.resolve(copy.localRoot, "../../.."), async () => {
|
|
// Any attempted nested acquisition fails promptly instead of hanging the test.
|
|
let now = Date.now();
|
|
const clock = vi.spyOn(Date, "now").mockImplementation(() => now += 31_000);
|
|
try { await copies.release(companyId, copy.runId); } finally { clock.mockRestore(); }
|
|
expect(await copies.get(companyId, copy.runId)).toEqual(before);
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
});
|
|
});
|
|
|
|
async function unavailableRemote(options: { state?: "stopped" | "destroyed"; receiptMismatch?: string } = {}) {
|
|
const copy = await run();
|
|
const environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/cleanup-task";
|
|
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: copy.runId, provider: "daytona", providerLeaseId: "cleanup-fixture" };
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
const receipt = options.state ? remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: options.state })! : undefined;
|
|
if (receipt && options.receiptMismatch) (receipt as Record<string, unknown>)[options.receiptMismatch] = randomUUID();
|
|
await db.insert(environmentLeases).values({ ...lease, ...(receipt ? { status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
|
metadata: { remoteExecutionTermination: receipt } } : {}) });
|
|
await db.update(heartbeatRuns).set({ status: "succeeded" }).where(eq(heartbeatRuns.id, copy.runId));
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE",
|
|
errorMessage: "Fixture could not collect files", candidateHash: "preserved-candidate", candidateBase64: Buffer.from("preserved bytes").toString("base64"), attempts: 3,
|
|
location: `remote:${environmentId}`, executionRoot: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, copy.runId),
|
|
receipt: { ...copy.receipt, cleanup: { leaseId, remoteCwd } } }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
return { copy: (await copies.get(companyId, copy.runId))!, lease, environmentId };
|
|
}
|
|
|
|
it.each(["destroyed", "stopped", "broken_handoff", "extra_owner", "foreign_company"] as const)(
|
|
"recovers an earlier remote copy only from the exact destroyed successor chain (%s)", async scenario => {
|
|
const { copy, lease } = await unavailableRemote();
|
|
const issueId = randomUUID(), successorRunId = randomUUID(), successorId = randomUUID();
|
|
const acquiredAt = new Date(Date.now() - 2000), handoffAt = new Date(Date.now() - 1000);
|
|
await db.insert(issues).values({ id: issueId, companyId, title: "Completed retained workspace", status: "done" });
|
|
await db.insert(heartbeatRuns).values({ id: successorRunId, companyId, agentId, invocationSource: "on_demand", status: "succeeded" });
|
|
const [previous] = await db.update(environmentLeases).set({ status: "expired", leasePolicy: "reuse_by_environment",
|
|
issueId, acquiredAt, releasedAt: handoffAt, cleanupStatus: "success", metadata: { agentId } })
|
|
.where(eq(environmentLeases.id, lease.id)).returning();
|
|
const successor = { ...previous!, id: successorId, heartbeatRunId: successorRunId, acquiredAt: handoffAt,
|
|
releasedAt: new Date(), metadata: { agentId } };
|
|
if (scenario === "foreign_company") {
|
|
const foreignCompanyId = randomUUID();
|
|
await db.insert(companies).values({ id: foreignCompanyId, name: "Unrelated owner", issuePrefix: randomUUID().slice(0, 8) });
|
|
successor.companyId = foreignCompanyId;
|
|
}
|
|
const handoff = createReusableLeaseHandoff(previous!, successor);
|
|
const termination = remoteTerminationReceipt(successor, { providerLeaseId: lease.providerLeaseId,
|
|
state: scenario === "stopped" ? "stopped" : "destroyed" });
|
|
await db.update(environmentLeases).set({ metadata: { agentId, reusableLeaseSuccessor: handoff } })
|
|
.where(eq(environmentLeases.id, lease.id));
|
|
await db.insert(environmentLeases).values({ ...successor, metadata: { agentId, remoteExecutionTermination: termination,
|
|
reusableLeasePredecessor: scenario === "broken_handoff" ? { ...handoff, handoffId: randomUUID() } : handoff } });
|
|
if (scenario === "extra_owner") await db.insert(environmentLeases).values({ ...lease, id: randomUUID(), status: "active" });
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "pending_collection", attempts: 0, candidateHash: null, candidateBase64: null })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockRejectedValue(new Error("must not execute"));
|
|
try {
|
|
await copies.recoverStopped();
|
|
const recovered = (await copies.get(companyId, copy.runId))!;
|
|
if (scenario === "destroyed") {
|
|
expect(recovered).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE",
|
|
receipt: { cleanupPending: false }, nextAttemptAt: null });
|
|
expect(recovered.processStoppedAt).toBeInstanceOf(Date);
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
} else {
|
|
expect(recovered).toMatchObject({ state: "pending_collection", processStoppedAt: null });
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
}
|
|
expect(shell).not.toHaveBeenCalled();
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
const [historical] = await db.select().from(environmentLeases).where(eq(environmentLeases.id, lease.id));
|
|
expect(historical!.metadata).not.toHaveProperty("remoteExecutionTermination");
|
|
} finally { shell.mockRestore(); }
|
|
});
|
|
|
|
it.each([undefined, "stopped", "companyId", "runId", "leaseId", "provider", "providerLeaseId"])(
|
|
"defers unavailable cleanup without exact destruction proof (%s)", async proof => {
|
|
const { copy } = await unavailableRemote({ state: proof === undefined ? undefined : proof === "stopped" ? "stopped" : "destroyed",
|
|
receiptMismatch: proof && proof !== "stopped" ? proof : undefined });
|
|
const execute = vi.fn();
|
|
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
const before = Date.now();
|
|
await withDirectoryMergeLock(path.resolve(copy.localRoot, "../../.."), () => copies.recoverStopped());
|
|
const deferred = (await copies.get(companyId, copy.runId))!;
|
|
expect(deferred).toMatchObject({ state: "unavailable", processStoppedAt: null, attempts: 3,
|
|
candidateHash: copy.candidateHash, candidateBase64: copy.candidateBase64, errorCode: copy.errorCode, errorMessage: copy.errorMessage, receipt: copy.receipt });
|
|
expect(deferred.nextAttemptAt!.getTime()).toBeGreaterThanOrEqual(before + 30_000);
|
|
expect(await copies.recoverStopped()).toBe(0);
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
expect(execute).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("cleans an unavailable copy after exact destruction without claiming a save or executing remotely", async () => {
|
|
const { copy, environmentId } = await unavailableRemote({ state: "destroyed" });
|
|
await fs.writeFile(path.join(copy.localRoot, "unsaved.txt"), "unsaved edit");
|
|
await db.delete(environments).where(eq(environments.id, environmentId));
|
|
const execute = vi.fn();
|
|
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockRejectedValue(new Error("must not execute"));
|
|
copies = agentInstructionWorkingCopyService(db, { environmentRuntime: { execute } as unknown as EnvironmentRuntimeService });
|
|
try {
|
|
await copies.recoverStopped();
|
|
const recovered = (await copies.get(companyId, copy.runId))!;
|
|
expect(recovered).toMatchObject({ state: "unavailable", candidateHash: copy.candidateHash, candidateBase64: copy.candidateBase64, attempts: 3,
|
|
errorCode: copy.errorCode, errorMessage: copy.errorMessage, receipt: { cleanupPending: false } });
|
|
expect(recovered.processStoppedAt).toBeInstanceOf(Date);
|
|
expect(recovered.nextAttemptAt).toBeNull();
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
await expect(fs.stat(path.join(root, "unsaved.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(await fs.readFile(path.join(root, entryFile), "utf8")).toBe(initial);
|
|
expect(execute).not.toHaveBeenCalled(); expect(shell).not.toHaveBeenCalled();
|
|
} finally { shell.mockRestore(); }
|
|
});
|
|
|
|
it.each([false, true])("preserves uncollected local edits and their unavailable receipt even after local stop proof (%s)", async stopped => {
|
|
const copy = await run();
|
|
await fs.writeFile(path.join(copy.localRoot, "unsaved-local.txt"), "recoverable local edit");
|
|
await db.update(heartbeatRuns).set({ status: "failed", runtimeMode: "native" }).where(eq(heartbeatRuns.id, copy.runId));
|
|
await copies.reportUnavailable(companyId, copy.runId);
|
|
if (stopped) await db.insert(heartbeatRunEvents).values({ companyId, runId: copy.runId, agentId, seq: 1, eventType: "native.local_process_stopped", stream: "system", level: "info", message: "fixture stop" });
|
|
const before = (await copies.get(companyId, copy.runId))!;
|
|
expect(before).toMatchObject({ state: "unavailable", attempts: 0, processStoppedAt: null });
|
|
await copies.recoverStopped();
|
|
const patch = vi.fn(async () => { throw new Error("local copy must not be changed"); });
|
|
await agentDirectoryWorkingCopyService(db, copies.get, patch).recoverUnavailable(before);
|
|
expect(patch).not.toHaveBeenCalled();
|
|
expect(await copies.get(companyId, copy.runId)).toEqual(before);
|
|
expect(await fs.readFile(path.join(copy.localRoot, "unsaved-local.txt"), "utf8")).toBe("recoverable local edit");
|
|
await expect(fs.stat(path.join(root, "unsaved-local.txt"))).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it("serializes same-run preparation after recovery commits stop proof and before it removes bytes", async () => {
|
|
const { copy, lease } = await unavailableRemote({ state: "destroyed" });
|
|
const remoteCwd = "/fixture/cleanup-task";
|
|
const executionTarget = { kind: "remote" as const, transport: "ssh" as const, environmentId: lease.environmentId, leaseId: lease.id, remoteCwd,
|
|
spec: { host: "unused.invalid", port: 22, username: "test", remoteCwd, remoteWorkspacePath: remoteCwd, privateKey: null, knownHosts: null, strictHostKeyChecking: true } };
|
|
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: null, startedAt: null });
|
|
const stage = vi.spyOn(ssh, "syncDirectoryToSsh").mockResolvedValue(undefined);
|
|
let stopCommitted!: () => void, finishCleanup!: () => void;
|
|
const committed = new Promise<void>(resolve => { stopCommitted = resolve; });
|
|
const proceed = new Promise<void>(resolve => { finishCleanup = resolve; });
|
|
const directories = agentDirectoryWorkingCopyService(db, copies.get, async (row, values) => {
|
|
const [updated] = await db.update(agentInstructionWorkingCopies).set(values).where(eq(agentInstructionWorkingCopies.runId, row.runId)).returning();
|
|
if (values.processStoppedAt) { stopCommitted(); await proceed; }
|
|
return updated!;
|
|
});
|
|
const recovering = directories.recoverUnavailable(copy);
|
|
await committed;
|
|
let prepareSettled = false;
|
|
const preparing = copies.prepare({ ...target(), runId: copy.runId, cwd: home, target: executionTarget }).then(row => { prepareSettled = true; return row; });
|
|
try {
|
|
try {
|
|
await new Promise(resolve => setTimeout(resolve, 100));
|
|
expect(prepareSettled).toBe(false);
|
|
expect((await copies.get(companyId, copy.runId))?.state).toBe("unavailable");
|
|
} finally { finishCleanup(); await recovering; }
|
|
const prepared = await preparing;
|
|
expect(prepared).toMatchObject({ state: "prepared", processStoppedAt: null });
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
// A stale cleanup callback now observes the live lifecycle and does nothing.
|
|
await directories.release(copy);
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
} finally { shell.mockRestore(); stage.mockRestore(); }
|
|
});
|
|
|
|
it("keeps stopped pending cleanup behind a held lock and lets recovery proceed to other agents", async () => {
|
|
const blocked = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", processStoppedAt: new Date() }).where(eq(agentInstructionWorkingCopies.runId, blocked.runId));
|
|
// A distinct canonical agent has its own lifecycle lock.
|
|
const firstAgent = agentId, firstRoot = root;
|
|
agentId = randomUUID();
|
|
root = resolveManagedInstructionsRoot({ ...target(), id: agentId, name: "Other", adapterConfig: {} });
|
|
await db.insert(agents).values({ id: agentId, companyId, name: "Other", adapterConfig: { instructionsBundleMode: "managed", instructionsRootPath: root, instructionsEntryFile: entryFile } });
|
|
await db.insert(companyMemberships).values({ companyId, principalType: "agent", principalId: agentId, membershipRole: "member" });
|
|
await db.update(principalPermissionGrants).set({ scope: { agentIds: [firstAgent, agentId] } }).where(eq(principalPermissionGrants.companyId, companyId));
|
|
await fs.mkdir(path.dirname(path.join(root, entryFile)), { recursive: true }); await fs.writeFile(path.join(root, entryFile), initial);
|
|
const other = await run();
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", processStoppedAt: new Date() }).where(eq(agentInstructionWorkingCopies.runId, other.runId));
|
|
agentId = firstAgent; root = firstRoot;
|
|
await withDirectoryMergeLock(path.resolve(blocked.localRoot, "../../.."), async () => {
|
|
let now = Date.now();
|
|
const clock = vi.spyOn(Date, "now").mockImplementation(() => now += 31_000);
|
|
try {
|
|
await expect(copies.release(companyId, blocked.runId)).rejects.toMatchObject({ code: "ERR_WORKSPACE_RESTORE_LOCK_TIMEOUT" });
|
|
await copies.recoverCaptured();
|
|
} finally { clock.mockRestore(); }
|
|
expect((await copies.get(companyId, blocked.runId))?.nextAttemptAt).toBeInstanceOf(Date);
|
|
expect(await fs.readFile(path.join(blocked.localRoot, entryFile), "utf8")).toBe(initial);
|
|
await expect(fs.stat(other.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
// A fresh recovery worker retries after the holder releases the lock. It
|
|
// cleans the pending copy without changing the failed-save receipt.
|
|
const deferred = (await copies.get(companyId, blocked.runId))!;
|
|
await db.update(agentInstructionWorkingCopies).set({ nextAttemptAt: new Date(0) })
|
|
.where(eq(agentInstructionWorkingCopies.runId, blocked.runId));
|
|
await agentInstructionWorkingCopyService(db).recoverCaptured();
|
|
expect(await copies.get(companyId, blocked.runId)).toMatchObject({ state: deferred.state,
|
|
errorCode: deferred.errorCode, errorMessage: deferred.errorMessage,
|
|
candidateHash: deferred.candidateHash, receipt: { cleanupPending: false }, nextAttemptAt: null });
|
|
await expect(fs.stat(blocked.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it.each(["environment", "path", "lease-run"])("rejects destruction outside the registered copy binding (%s)", async mismatch => {
|
|
const { copy, lease } = await unavailableRemote({ state: "destroyed" });
|
|
if (mismatch === "environment") await db.update(agentInstructionWorkingCopies).set({ location: `remote:${randomUUID()}` }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
if (mismatch === "path") await db.update(agentInstructionWorkingCopies).set({ executionRoot: "/fixture/foreign" }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
if (mismatch === "lease-run") {
|
|
const other = await run();
|
|
const moved = { ...lease, heartbeatRunId: other.runId };
|
|
await db.update(environmentLeases).set({ heartbeatRunId: other.runId, metadata: { remoteExecutionTermination: remoteTerminationReceipt(moved, { providerLeaseId: moved.providerLeaseId, state: "destroyed" }) } }).where(eq(environmentLeases.id, lease.id));
|
|
}
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, copy.runId))?.processStoppedAt).toBeNull();
|
|
expect(await fs.readFile(path.join(copy.localRoot, entryFile), "utf8")).toBe(initial);
|
|
});
|
|
|
|
it("backs off an unproven batch so the next unavailable copy can be cleaned", async () => {
|
|
const deferred: string[] = [];
|
|
for (let i = 0; i < 20; i++) {
|
|
const { copy } = await unavailableRemote();
|
|
deferred.push(copy.runId);
|
|
await db.update(agentInstructionWorkingCopies).set({ updatedAt: new Date(i) }).where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
}
|
|
const { copy: ready } = await unavailableRemote({ state: "destroyed" });
|
|
await db.update(agentInstructionWorkingCopies).set({ updatedAt: new Date(20) }).where(eq(agentInstructionWorkingCopies.runId, ready.runId));
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, ready.runId))?.processStoppedAt).toBeNull();
|
|
await copies.recoverStopped();
|
|
expect((await copies.get(companyId, ready.runId))?.receipt?.cleanupPending).toBe(false);
|
|
for (const runId of deferred) expect(await copies.get(companyId, runId)).toMatchObject({ state: "unavailable", processStoppedAt: null, attempts: 3 });
|
|
});
|
|
|
|
it("continues cleanup when the retry reservation fails for the first copy", async () => {
|
|
const first = await run(), second = await run();
|
|
for (const [index, copy] of [first, second].entries()) {
|
|
await db.update(agentInstructionWorkingCopies).set({ state: "unavailable", processStoppedAt: new Date(), updatedAt: new Date(index),
|
|
errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE", candidateHash: "preserved", candidateBase64: Buffer.from("candidate").toString("base64") })
|
|
.where(eq(agentInstructionWorkingCopies.runId, copy.runId));
|
|
}
|
|
const before = await copies.get(companyId, first.runId);
|
|
const failReservation = () => { throw new Error("fixture retry-reservation write failure"); };
|
|
const update = vi.spyOn(db, "transaction").mockImplementationOnce(failReservation);
|
|
try { await copies.recoverCaptured(); } finally { update.mockRestore(); }
|
|
expect(await copies.get(companyId, first.runId)).toEqual(before);
|
|
expect(await fs.readFile(path.join(first.localRoot, entryFile), "utf8")).toBe(initial);
|
|
expect(await copies.get(companyId, second.runId)).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE", candidateHash: "preserved", receipt: { cleanupPending: false } });
|
|
await expect(fs.stat(second.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
});
|
|
|
|
it.each([false, true])("does not execute a cached transport after destruction, including an ambiguous stop-proof commit (%s)", async interrupted => {
|
|
const runId = randomUUID(), environmentId = randomUUID(), leaseId = randomUUID(), remoteCwd = "/fixture/cached-task";
|
|
const lease = { id: leaseId, companyId, environmentId, heartbeatRunId: runId, provider: "daytona", providerLeaseId: "cached-fixture" };
|
|
await db.insert(heartbeatRuns).values({ id: runId, companyId, agentId, invocationSource: "on_demand", responsibleUserId: userId });
|
|
await db.insert(environments).values({ id: environmentId, name: environmentId, driver: "sandbox" });
|
|
await db.insert(environmentLeases).values(lease);
|
|
const execute = vi.fn(), restoreWorkspace = vi.fn(), cleanupWorkspaceSnapshot = vi.fn().mockResolvedValue(undefined);
|
|
const executionTarget = { kind: "remote" as const, transport: "sandbox" as const, environmentId, leaseId, remoteCwd, runner: { execute } };
|
|
const shell = vi.spyOn(executionTargetTools, "runAdapterExecutionTargetShellCommand").mockResolvedValue({ exitCode: 0, signal: null, timedOut: false, stdout: "", stderr: "", pid: null, startedAt: null });
|
|
const stage = vi.spyOn(executionTargetTools, "prepareAdapterExecutionTargetRuntime").mockImplementation(async options => ({ target: executionTarget,
|
|
workspaceRemoteDir: path.posix.join(remoteCwd, ".paperclip-runtime", "agent-files", agentId, runId), runtimeRootDir: options.runtimeRootDir ?? null,
|
|
assetDirs: {}, additionalSourceDirs: {}, additionalSourceFailures: [], workspaceSyncSnapshot: null, restoreWorkspace, cleanupWorkspaceSnapshot }));
|
|
try {
|
|
const copy = (await copies.prepare({ ...target(), runId, cwd: home, target: executionTarget }))!;
|
|
await copies.reportUnavailable(companyId, runId);
|
|
await copies.release(companyId, runId);
|
|
expect(cleanupWorkspaceSnapshot).not.toHaveBeenCalled();
|
|
shell.mockClear(); stage.mockClear();
|
|
await db.update(heartbeatRuns).set({ status: "failed" }).where(eq(heartbeatRuns.id, runId));
|
|
await db.update(environmentLeases).set({ status: "released", releasedAt: new Date(), cleanupStatus: "success",
|
|
metadata: { remoteExecutionTermination: remoteTerminationReceipt(lease, { providerLeaseId: lease.providerLeaseId, state: "destroyed" }) } }).where(eq(environmentLeases.id, leaseId));
|
|
if (interrupted) {
|
|
const directories = agentDirectoryWorkingCopyService(db, copies.get, async (row, values) => {
|
|
const [updated] = await db.update(agentInstructionWorkingCopies).set(values).where(eq(agentInstructionWorkingCopies.runId, row.runId)).returning();
|
|
if (values.processStoppedAt) throw new Error("fixture lost update response after commit");
|
|
return updated!;
|
|
});
|
|
await expect(directories.recoverUnavailable((await copies.get(companyId, runId))!)).rejects.toThrow("lost update response");
|
|
expect((await copies.get(companyId, runId))?.receipt?.cleanupDestroyedOnly).toBe(true);
|
|
await copies.recoverCaptured();
|
|
} else await copies.recoverStopped();
|
|
expect(await copies.get(companyId, runId)).toMatchObject({ state: "unavailable", errorCode: "INSTRUCTION_COLLECTION_UNAVAILABLE", receipt: { cleanupPending: false } });
|
|
await expect(fs.stat(copy.localRoot)).rejects.toMatchObject({ code: "ENOENT" });
|
|
expect(cleanupWorkspaceSnapshot).toHaveBeenCalledOnce();
|
|
expect(execute).not.toHaveBeenCalled(); expect(restoreWorkspace).not.toHaveBeenCalled(); expect(shell).not.toHaveBeenCalled(); expect(stage).not.toHaveBeenCalled();
|
|
} finally { shell.mockRestore(); stage.mockRestore(); }
|
|
});
|
|
|
|
});
|