mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-28 21:46:15 +01:00
## Thinking Path
> - Paperclip manages AI agents and their execution state.
> - Remote workspace admission must preserve files before execution
starts.
> - Admission saved the entire workspace once per registered repository
on every run.
> - Existing snapshot receipts can prove that validated repositories are
already saved.
> - This change uses those receipts and saves new repositories once per
admission batch.
> - It also preserves fresh configuration metadata and reports actual
workspace reuse.
## Linked Issues or Issue Description
**What happened**
Remote follow-up runs uploaded an unchanged workspace for each
registered repository before starting the provider. Configuration
persistence also overwrote new evaluation metadata, and freshness logs
could claim replacement when the same workspace was reused.
**Expected behavior**
Validate existing repositories without uploads when a committed snapshot
covers their descriptors. Save acquired repositories before publishing
ready receipts. Retain current evaluation metadata and report the actual
workspace outcome.
**Steps to reproduce**
Use a remote workspace with two registered repositories. Prepare it,
then admit a follow-up run. Observe repository snapshot operations
despite unchanged repositories. The regression tests exercise this with
real Postgres, Git, and separate sandbox directories.
**Environment**
Server remote workspace admission at commit
c0214826b3. Related work: #19374 handles
interrupted clone staging; this change handles snapshot admission cost.
## What Changed
- Skip repository saves when the committed snapshot covers the validated
descriptor.
- Save all repositories in one admission snapshot before publishing
ready receipts.
- Retain descriptor coverage only when the new archive contains the
checkout. Drop deleted checkout coverage so admission can acquire it
again.
- Restore `needs_repair` status for failed batch saves and retry failed
uploads.
- Let fresh preparation metadata override stale reserved metadata while
preserving storage authority.
- Report actual reuse when freshness policy requested replacement.
- Add regression coverage and fix an existing routine user fixture
missing its membership role.
## Verification
- Red: original code fails unnecessary-snapshot, evaluation-metadata,
and reuse-message regressions.
- Green: 517 affected tests across six suites before the final coverage
correction. After that correction, all 102 remote workspace/concurrency
tests and 96 archive tests pass. Imported-repository, deleted-checkout,
and upload-retry cases pass.
- Additional red/green: deleted checkout coverage fails before the fix
and passes after it. All 96 archive tests pass, including manifest
digest and size bounds.
- `pnpm -r typecheck`, `pnpm build`, and `pnpm check:token-gates` pass
locally.
- All final-head CI verification jobs pass, including the aggregate `ci
/ verify` check. Greptile gives the final head 5/5.
- The monolithic local `pnpm test:run` passed all six chat shards and
continued through general server tests. It was stopped after final-head
CI passed; it did not complete locally. The targeted local regressions,
affected suites, typecheck, and build completed successfully.
## Risks
Snapshot receipts must refer to committed bytes. Legacy receipts require
one conservative save. Failed uploads must not publish repository
readiness. Replacement-class drift still retains the original
configuration for an explicitly reused workspace.
Existing directories with damaged or missing Git metadata still require
repair. Master and this PR both validate those directories without
cloning over them, preserving any surviving user files. Clearing a
snapshot descriptor would not change that path. Complete directory
deletion is different: this PR clears coverage so normal acquisition can
clone it again.
## Model Used
OpenAI gpt-6.1-sol through Codex. Used reasoning, repository inspection,
code editing, and local execution. The host does not expose 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
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
---------
Co-authored-by: Paperclip <noreply@paperclip.ing>
393 lines
33 KiB
TypeScript
393 lines
33 KiB
TypeScript
import { applyPendingMigrations, closeRegisteredClients, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS } from "@paperclipai/db";
|
|
import { execFile as execFileCallback } from "node:child_process";
|
|
import { promisify } from "node:util";
|
|
import { randomUUID } from "node:crypto";
|
|
import { mkdtemp, rm, mkdir, writeFile, readFile, realpath, open, lstat, symlink, readdir } from "node:fs/promises";
|
|
import { tmpdir } from "node:os";
|
|
import path from "node:path";
|
|
import { constants as fsConstants } from "node:fs";
|
|
import { afterAll, beforeAll, describe, expect, it, vi } from "vitest";
|
|
import { and, eq, sql } from "drizzle-orm";
|
|
import { agents, companies, createDb, executionWorkspaces, executionWorkspaceRepositories, heartbeatRuns, issues } from "@paperclipai/db";
|
|
import { executionWorkspaceService } from "../services/execution-workspaces.js";
|
|
import { executionWorkspaceRepositoryService } from "../services/execution-workspace-repositories.js";
|
|
import * as remoteWorkspaces from "../services/remote-workspaces.js";
|
|
import type { EnvironmentLease } from "@paperclipai/shared";
|
|
import { listLocalProjectRepositories } from "@paperclipai/adapter-utils/ssh";
|
|
import { readManagedWorkspaceRepositories, disposeGitWorkspaceSnapshot } from "@paperclipai/adapter-utils/git-workspace-sync";
|
|
import { captureDirectorySnapshot, disposeDirectorySnapshot, withDirectoryPublicationLock } from "@paperclipai/adapter-utils/workspace-restore-merge";
|
|
import { getEmbeddedPostgresTestSupport, startEmbeddedPostgresTestDatabase } from "./helpers/embedded-postgres.js";
|
|
|
|
const catalog = vi.hoisted(() => ({ available: true }));
|
|
vi.mock("../services/tool-access.js", () => ({ toolAccessService: () => ({ listProjectRepositories: async () => ({ repositories: catalog.available ? [{ id: "123", fullName: "team/source", url: "https://github.com/team/source", connections: [] }] : [] }) }) }));
|
|
const externalDatabaseUrl = process.env.PAPERCLIP_TASK_REPOSITORIES_TEST_DATABASE_URL;
|
|
if (externalDatabaseUrl && new URL(externalDatabaseUrl).pathname !== "/remote_workspace_repositories_test") {
|
|
throw new Error("Remote repository tests require the disposable remote_workspace_repositories_test database");
|
|
}
|
|
const support = externalDatabaseUrl ? { supported: true } : await getEmbeddedPostgresTestSupport();
|
|
(support.supported ? describe : describe.skip)("durable task repository receipts", () => {
|
|
let temporary: Awaited<ReturnType<typeof startEmbeddedPostgresTestDatabase>>;
|
|
let db: ReturnType<typeof createDb>;
|
|
let companyId: string, issueId: string, workspaceId: string, agentId: string, cwd: string;
|
|
const actor = { type: "board" as const, source: "local_implicit" as const, userId: "local-board" };
|
|
beforeAll(async () => {
|
|
vi.stubEnv("PAPERCLIP_ISSUE_PRIVACY_MODE", "enforce");
|
|
if (externalDatabaseUrl) await applyPendingMigrations(externalDatabaseUrl);
|
|
temporary = externalDatabaseUrl ? { connectionString: externalDatabaseUrl,
|
|
cleanup: () => closeRegisteredClients(externalDatabaseUrl) }
|
|
: await startEmbeddedPostgresTestDatabase("paperclip-task-repositories-");
|
|
db = createDb(temporary.connectionString);
|
|
await db.execute(sql`set client_min_messages = warning`);
|
|
if (externalDatabaseUrl) await db.execute(sql`truncate table companies restart identity cascade`);
|
|
cwd = await mkdtemp(path.join(tmpdir(), "paperclip-task-repositories-files-"));
|
|
[companyId] = (await db.insert(companies).values({ name: "Task repositories", issuePrefix: "TREPO" }).returning()).map(row => row.id);
|
|
[agentId] = (await db.insert(agents).values({ companyId, name: "Repository worker", adapterType: "process", status: "idle" }).returning()).map(row => row.id);
|
|
[workspaceId] = (await db.insert(executionWorkspaces).values({ companyId, projectId: null, name: "Task files", cwd, mode: "shared_workspace", strategyType: "task_directory" }).returning()).map(row => row.id);
|
|
[issueId] = (await db.insert(issues).values({ companyId, title: "Projectless task", executionWorkspaceId: workspaceId }).returning()).map(row => row.id);
|
|
}, EMBEDDED_POSTGRES_TEST_TIMEOUT_MS);
|
|
afterAll(async () => { vi.unstubAllEnvs(); await temporary?.cleanup(); if (cwd) await rm(cwd, { recursive: true, force: true }); });
|
|
const prepareForAdmission = async (input: Parameters<ReturnType<typeof executionWorkspaceRepositoryService>["prepareForAdmission"]>[0]) => {
|
|
await db.insert(heartbeatRuns).values({ id: input.runId, companyId: input.companyId, agentId: input.agentId,
|
|
status: "running", responsibleUserId: input.responsibleUserId, contextSnapshot: { issueId: input.issueId } }).onConflictDoNothing();
|
|
return executionWorkspaceRepositoryService(db).prepareForAdmission(input);
|
|
};
|
|
const request = (requestKey: string, ref?: string) => executionWorkspaceRepositoryService(db).request({ companyId, issueId, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey, ...(ref ? { ref } : {}) } });
|
|
it("prepares a remote task repository through its current writer without opening a controller path", async () => {
|
|
const runId = randomUUID(), taskId = randomUUID(), remoteWorkspaceId = randomUUID(), leaseId = randomUUID(), environmentId = randomUUID();
|
|
const remoteCwd = `/workspaces/${remoteWorkspaceId}`;
|
|
await db.insert(issues).values({ id: taskId, companyId, title: "Remote repositories" });
|
|
await db.insert(executionWorkspaces).values({ id: remoteWorkspaceId, companyId, sourceIssueId: taskId,
|
|
name: "Remote task", cwd: remoteCwd, mode: "isolated_workspace", strategyType: "project_primary", providerType: "cloud_sandbox",
|
|
metadata: { remoteWorkspace: { schema: "paperclip.remote-workspace.v1", epoch: 1, snapshotId: null,
|
|
source: { kind: "empty" }, writerRunId: runId, dirty: true,
|
|
location: { leaseId, environmentId, providerLeaseId: "remote-allocation", remoteCwd } } } });
|
|
await db.update(issues).set({ executionWorkspaceId: remoteWorkspaceId }).where(eq(issues.id, taskId));
|
|
const intent = await executionWorkspaceRepositoryService(db).request({ companyId, issueId: taskId, actor,
|
|
request: { repository: { kind: "catalog", id: "123" }, requestKey: "remote-repository" } });
|
|
const pin = "a".repeat(40);
|
|
const prepare = vi.spyOn(remoteWorkspaces, "prepareRemoteWorkspaceRepository").mockResolvedValue({
|
|
cwd: `${remoteCwd}/${intent.repository.relativePath}`, pinnedCommit: pin, branchName: "main", requiresSave: false });
|
|
try {
|
|
const prepared = await prepareForAdmission({ companyId, issueId: taskId, workspaceId: remoteWorkspaceId,
|
|
cwd: remoteCwd, agentId, runId, responsibleUserId: "local-board",
|
|
remoteTarget: { kind: "remote", transport: "sandbox", remoteCwd } as never,
|
|
remoteLease: { id: leaseId, environmentId, companyId, providerLeaseId: "remote-allocation" } as EnvironmentLease });
|
|
expect(prepare).toHaveBeenCalledWith(expect.objectContaining({ runId,
|
|
repository: expect.objectContaining({ id: intent.repository.id, relativePath: intent.repository.relativePath }) }));
|
|
expect(prepared).toMatchObject([{ id: intent.repository.id, pinnedCommit: pin }]);
|
|
const [receipt] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, intent.repository.id));
|
|
expect(receipt).toMatchObject({ state: "ready", pinnedCommit: pin, branchName: "main" });
|
|
expect(await lstat(remoteCwd).catch(() => null)).toBeNull();
|
|
await expect(prepareForAdmission({ companyId, issueId: taskId, workspaceId: remoteWorkspaceId,
|
|
cwd: remoteCwd, agentId, runId: randomUUID(), responsibleUserId: "local-board",
|
|
remoteTarget: { kind: "remote", transport: "sandbox", remoteCwd } as never,
|
|
remoteLease: { id: leaseId } as EnvironmentLease })).rejects.toThrow("publication binding");
|
|
expect(prepare).toHaveBeenCalledTimes(1);
|
|
} finally { prepare.mockRestore(); }
|
|
});
|
|
it("publishes a requested repository from an absent path through real admission locking and cloning", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "paperclip-fresh-repository-"));
|
|
const previousPath = process.env.PATH;
|
|
const exec = promisify(execFileCallback);
|
|
try {
|
|
const realGit = (await exec("which", ["git"])).stdout.trim();
|
|
const source = path.join(root, "source"), taskRoot = path.join(root, "task"), bin = path.join(root, "bin");
|
|
await Promise.all([mkdir(source), mkdir(taskRoot), mkdir(bin)]);
|
|
await exec(realGit, ["init", "--initial-branch=main", taskRoot]);
|
|
await writeFile(path.join(taskRoot, "report.txt"), "Task-owned report\n");
|
|
const git = async (...args: string[]) => (await exec(realGit, ["-C", source, ...args])).stdout.trim();
|
|
await git("init", "--initial-branch=main");
|
|
await writeFile(path.join(source, "source.txt"), "original source\n");
|
|
await git("add", ".");
|
|
await git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source");
|
|
const pin = await git("rev-parse", "HEAD");
|
|
const cloneStarted = path.join(root, "clone-started"), cloneReleased = path.join(root, "clone-released");
|
|
await writeFile(path.join(bin, "git"), `#!${process.execPath}\n` +
|
|
`const { spawnSync } = require('node:child_process'); const fs = require('node:fs'); const args = process.argv.slice(2);\n` +
|
|
`const remote = args.includes('clone') ? args.at(-2) : null;\n` +
|
|
`if (remote && remote !== 'https://github.com/team/source') process.exit(97);\n` +
|
|
`if (remote) { fs.writeFileSync(${JSON.stringify(cloneStarted)}, 'started'); const deadline = Date.now() + 10000; while (!fs.existsSync(${JSON.stringify(cloneReleased)})) { if (Date.now() > deadline) process.exit(96); Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 20); } }\n` +
|
|
`if (remote) args[args.length - 2] = ${JSON.stringify(source)};\n` +
|
|
`const result = spawnSync(${JSON.stringify(realGit)}, args, { stdio: 'inherit' });\n` +
|
|
`if (result.status) process.exit(result.status);\n` +
|
|
`if (remote) process.exit(spawnSync(${JSON.stringify(realGit)}, ['-C', args.at(-1), 'remote', 'set-url', 'origin', remote], { stdio: 'inherit' }).status ?? 98);\n` +
|
|
`process.exit(result.status ?? 99);\n`, { mode: 0o755 });
|
|
process.env.PATH = `${bin}${path.delimiter}${previousPath ?? ""}`;
|
|
const [workspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Fresh task root", cwd: taskRoot,
|
|
mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
|
const [task] = await db.insert(issues).values({ companyId, title: "Fresh repository", executionWorkspaceId: workspace.id }).returning();
|
|
const intent = await executionWorkspaceRepositoryService(db).request({ companyId, issueId: task.id, actor,
|
|
request: { repository: { kind: "catalog", id: "123" }, requestKey: "fresh-repository" } });
|
|
const checkout = path.join(taskRoot, intent.repository.relativePath);
|
|
expect(await lstat(checkout).catch(() => null)).toBeNull();
|
|
const admission = { companyId, issueId: task.id, workspaceId: workspace.id, cwd: taskRoot,
|
|
agentId, runId: randomUUID(), responsibleUserId: "local-board" };
|
|
const [readyWorkspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Shared physical root", cwd: taskRoot,
|
|
mode: "shared_workspace", strategyType: "operator_directory" }).returning();
|
|
const [readyTask] = await db.insert(issues).values({ companyId, title: "Reuse another repository", executionWorkspaceId: readyWorkspace.id }).returning();
|
|
const readyIntent = await executionWorkspaceRepositoryService(db).request({ companyId, issueId: readyTask.id, actor,
|
|
request: { repository: { kind: "url", url: "https://github.com/team/ready" }, requestKey: "ready-repository" } });
|
|
const readyCheckout = path.join(taskRoot, readyIntent.repository.relativePath);
|
|
await mkdir(path.dirname(readyCheckout), { recursive: true });
|
|
await exec(realGit, ["clone", "--no-hardlinks", source, readyCheckout]);
|
|
await exec(realGit, ["-C", readyCheckout, "remote", "set-url", "origin", readyIntent.repository.repoUrl]);
|
|
await db.update(executionWorkspaceRepositories).set({ state: "ready", pinnedCommit: pin })
|
|
.where(eq(executionWorkspaceRepositories.id, readyIntent.operationId));
|
|
const pending = Promise.all([1, 2].map(() => prepareForAdmission(admission)));
|
|
let results: Awaited<typeof pending>;
|
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
await vi.waitFor(async () => expect(await lstat(cloneStarted).catch(() => null)).not.toBeNull());
|
|
const ready = await Promise.race([
|
|
prepareForAdmission({ ...admission, workspaceId: readyWorkspace.id, issueId: readyTask.id, runId: randomUUID() }),
|
|
new Promise<never>((_, reject) => { timeout = setTimeout(() => reject(new Error("Unrelated repository reuse waited for a blocked clone")), 2000); }),
|
|
]);
|
|
expect(ready[0]).toMatchObject({ id: readyIntent.operationId, pinnedCommit: pin });
|
|
expect(await listLocalProjectRepositories(taskRoot)).toEqual([readyIntent.repository.relativePath]);
|
|
const snapshots = await readManagedWorkspaceRepositories(taskRoot);
|
|
try { expect(snapshots.map(repo => repo.path)).toEqual([readyIntent.repository.relativePath]); }
|
|
finally { await Promise.all(snapshots.map(repo => disposeGitWorkspaceSnapshot(repo.snapshot))); }
|
|
expect((await readdir(path.join(taskRoot, ".paperclip-runtime", "repository-staging"))).filter(name => name.includes(".clone-")).length).toBe(1);
|
|
expect((await exec(realGit, ["-C", taskRoot, "status", "--porcelain", "--untracked-files=all"])).stdout.trim()).toBe("?? report.txt");
|
|
await exec(realGit, ["-C", taskRoot, "add", "."]);
|
|
expect((await exec(realGit, ["-C", taskRoot, "diff", "--cached", "--name-only"])).stdout.trim()).toBe("report.txt");
|
|
const baseline = await captureDirectorySnapshot(taskRoot, { exclude: [".paperclip-runtime"] });
|
|
try { expect([...baseline.entries].some(([entry]) => entry.includes("repository-staging") || entry.includes(".clone-"))).toBe(false); }
|
|
finally { await disposeDirectorySnapshot(baseline); }
|
|
} finally {
|
|
clearTimeout(timeout);
|
|
await writeFile(cloneReleased, "released");
|
|
results = await pending;
|
|
}
|
|
for (const prepared of results) expect(prepared).toEqual([expect.objectContaining({ id: intent.operationId, pinnedCommit: pin })]);
|
|
expect(await readFile(path.join(checkout, "source.txt"), "utf8")).toBe("original source\n");
|
|
expect(JSON.parse(await readFile(path.join(checkout, ".git", "paperclip-workspace-owner.json"), "utf8")))
|
|
.toMatchObject({ repositoryId: intent.operationId, pinnedCommit: pin });
|
|
expect((await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, intent.operationId)))[0])
|
|
.toMatchObject({ state: "ready", pinnedCommit: pin, failureCode: null });
|
|
await writeFile(path.join(checkout, "source.txt"), "retained dirty work\n");
|
|
await prepareForAdmission(admission);
|
|
expect(await readFile(path.join(checkout, "source.txt"), "utf8")).toBe("retained dirty work\n");
|
|
} finally {
|
|
if (previousPath === undefined) delete process.env.PATH; else process.env.PATH = previousPath;
|
|
await rm(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
it("lets a missing requested ref be corrected before any checkout is published", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "paperclip-missing-ref-repository-"));
|
|
const previousPath = process.env.PATH;
|
|
const exec = promisify(execFileCallback);
|
|
try {
|
|
const realGit = (await exec("which", ["git"])).stdout.trim();
|
|
const source = path.join(root, "source"), taskRoot = path.join(root, "task"), bin = path.join(root, "bin");
|
|
await Promise.all([mkdir(source), mkdir(taskRoot), mkdir(bin)]);
|
|
const git = async (...args: string[]) => (await exec(realGit, ["-C", source, ...args])).stdout.trim();
|
|
// The repository's default branch is master; an agent asks for "main".
|
|
await git("init", "--initial-branch=master");
|
|
await writeFile(path.join(source, "source.txt"), "master source\n");
|
|
await git("add", ".");
|
|
await git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "source");
|
|
const pin = await git("rev-parse", "HEAD");
|
|
await writeFile(path.join(bin, "git"), `#!${process.execPath}\n` +
|
|
`const { spawnSync } = require('node:child_process'); const args = process.argv.slice(2);\n` +
|
|
`const remote = args.includes('clone') ? args.at(-2) : null;\n` +
|
|
`if (remote && remote !== 'https://github.com/team/source') process.exit(97);\n` +
|
|
`if (remote) args[args.length - 2] = ${JSON.stringify(source)};\n` +
|
|
`const result = spawnSync(${JSON.stringify(realGit)}, args, { stdio: 'inherit' });\n` +
|
|
`if (result.status) process.exit(result.status);\n` +
|
|
`if (remote) process.exit(spawnSync(${JSON.stringify(realGit)}, ['-C', args.at(-1), 'remote', 'set-url', 'origin', remote], { stdio: 'inherit' }).status ?? 98);\n` +
|
|
`process.exit(result.status ?? 99);\n`, { mode: 0o755 });
|
|
process.env.PATH = `${bin}${path.delimiter}${previousPath ?? ""}`;
|
|
const service = executionWorkspaceRepositoryService(db);
|
|
const [workspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Missing ref root", cwd: taskRoot,
|
|
mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
|
const [task] = await db.insert(issues).values({ companyId, title: "Missing ref", executionWorkspaceId: workspace.id }).returning();
|
|
const repository = { kind: "catalog" as const, id: "123" };
|
|
const intent = await service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "main", requestKey: "missing-ref" } });
|
|
const checkout = path.join(taskRoot, intent.repository.relativePath);
|
|
const admission = () => prepareForAdmission({ companyId, issueId: task.id, workspaceId: workspace.id, cwd: taskRoot,
|
|
agentId, runId: randomUUID(), responsibleUserId: "local-board" });
|
|
const receipt = async () => (await db.select().from(executionWorkspaceRepositories)
|
|
.where(eq(executionWorkspaceRepositories.id, intent.operationId)))[0];
|
|
|
|
await expect(admission()).rejects.toThrow(/ref "main" does not exist/);
|
|
expect(await receipt()).toMatchObject({ state: "needs_repair", failureCode: "repository_ref_not_found", pinnedCommit: null });
|
|
expect(await lstat(checkout).catch(() => null)).toBeNull();
|
|
|
|
// Retrying with the same missing ref keeps the receipt; a corrected ref replaces it.
|
|
await expect(service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "main", requestKey: "missing-ref" } }))
|
|
.resolves.toMatchObject({ operationId: intent.operationId });
|
|
// An admission that listed the receipt before the correction must use the corrected ref.
|
|
const stagingIgnore = path.join(taskRoot, ".paperclip-runtime", "repository-staging", ".gitignore");
|
|
await rm(stagingIgnore, { force: true });
|
|
let releaseLock!: () => void;
|
|
const lockHeld = new Promise<void>(resolve => { releaseLock = resolve; });
|
|
let lockAcquired!: () => void;
|
|
const acquired = new Promise<void>(resolve => { lockAcquired = resolve; });
|
|
const holder = withDirectoryPublicationLock(checkout, async () => { lockAcquired(); await lockHeld; });
|
|
await acquired;
|
|
const pending = admission();
|
|
try {
|
|
await vi.waitFor(async () => expect(await lstat(stagingIgnore).catch(() => null)).not.toBeNull());
|
|
const corrected = await service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "master", requestKey: "corrected-ref" } });
|
|
expect(corrected.operationId).toBe(intent.operationId);
|
|
expect(await receipt()).toMatchObject({ requestedRef: "master", state: "pending", failureCode: null, pinnedCommit: null });
|
|
expect((await receipt()).requestKeys.sort()).toEqual(["corrected-ref", "missing-ref"]);
|
|
} finally { releaseLock(); await holder; }
|
|
|
|
await expect(pending).resolves.toEqual([expect.objectContaining({ id: intent.operationId, pinnedCommit: pin })]);
|
|
expect(await readFile(path.join(checkout, "source.txt"), "utf8")).toBe("master source\n");
|
|
expect(await receipt()).toMatchObject({ state: "ready", requestedRef: "master", pinnedCommit: pin, failureCode: null });
|
|
// Published files are never switched to another ref.
|
|
await expect(service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "main", requestKey: "after-ready" } }))
|
|
.rejects.toThrow(/conflicts/);
|
|
} finally {
|
|
if (previousPath === undefined) delete process.env.PATH; else process.env.PATH = previousPath;
|
|
await rm(root, { recursive: true, force: true });
|
|
}
|
|
});
|
|
it("keeps a missing-ref receipt immutable when files exist at its checkout path", async () => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "paperclip-missing-ref-occupied-"));
|
|
try {
|
|
const service = executionWorkspaceRepositoryService(db);
|
|
const [workspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Occupied checkout root", cwd: root,
|
|
mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
|
const [task] = await db.insert(issues).values({ companyId, title: "Occupied checkout", executionWorkspaceId: workspace.id }).returning();
|
|
const repository = { kind: "catalog" as const, id: "123" };
|
|
const intent = await service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "main", requestKey: "occupied" } });
|
|
await db.update(executionWorkspaceRepositories).set({ state: "needs_repair", failureCode: "repository_ref_not_found" })
|
|
.where(eq(executionWorkspaceRepositories.id, intent.operationId));
|
|
await mkdir(path.join(root, intent.repository.relativePath), { recursive: true });
|
|
await expect(service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "master", requestKey: "occupied-fix" } }))
|
|
.rejects.toThrow(/conflicts/);
|
|
// A failure that was not a missing ref also keeps the receipt.
|
|
await rm(path.join(root, intent.repository.relativePath), { recursive: true, force: true });
|
|
await db.update(executionWorkspaceRepositories).set({ failureCode: "repository_preparation_failed" })
|
|
.where(eq(executionWorkspaceRepositories.id, intent.operationId));
|
|
await expect(service.request({ companyId, issueId: task.id, actor, request: { repository, ref: "master", requestKey: "generic-fix" } }))
|
|
.rejects.toThrow(/conflicts/);
|
|
expect((await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.id, intent.operationId)))[0])
|
|
.toMatchObject({ requestedRef: "main" });
|
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
});
|
|
it.skipIf(process.platform === "win32").each(["parent", "ignore_file"])("rejects a symlinked runtime staging %s before cloning", async (unsafeEntry) => {
|
|
const root = await mkdtemp(path.join(tmpdir(), "paperclip-unsafe-repository-staging-"));
|
|
try {
|
|
const taskRoot = path.join(root, "task"), outside = path.join(root, "outside");
|
|
await mkdir(taskRoot); await mkdir(outside);
|
|
if (unsafeEntry === "parent") await symlink(outside, path.join(taskRoot, ".paperclip-runtime"));
|
|
else {
|
|
const staging = path.join(taskRoot, ".paperclip-runtime", "repository-staging");
|
|
await mkdir(staging, { recursive: true });
|
|
await symlink(outside, path.join(staging, ".gitignore"));
|
|
}
|
|
const [workspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Unsafe staging", cwd: taskRoot,
|
|
mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
|
const [task] = await db.insert(issues).values({ companyId, title: "Unsafe staging", executionWorkspaceId: workspace.id }).returning();
|
|
await executionWorkspaceRepositoryService(db).request({ companyId, issueId: task.id, actor,
|
|
request: { repository: { kind: "catalog", id: "123" }, requestKey: "unsafe-staging" } });
|
|
await expect(prepareForAdmission({ companyId, issueId: task.id,
|
|
workspaceId: workspace.id, cwd: taskRoot, agentId, runId: randomUUID(), responsibleUserId: "local-board" }))
|
|
.rejects.toThrow(unsafeEntry === "parent" ? "staging directory escapes" : "ignore file is not a regular file");
|
|
expect(await readdir(outside)).toEqual([]);
|
|
} finally { await rm(root, { recursive: true, force: true }); }
|
|
});
|
|
it("converges concurrent requests and persists each retry key without creating a project", async () => {
|
|
const [peerIssue] = await db.insert(issues).values({ companyId, title: "Peer task sharing the root", executionWorkspaceId: workspaceId }).returning();
|
|
await db.update(executionWorkspaces).set({ sourceIssueId: issueId }).where(eq(executionWorkspaces.id, workspaceId));
|
|
const [first, second] = await Promise.all([
|
|
request("one"),
|
|
executionWorkspaceRepositoryService(db).request({ companyId, issueId: peerIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "two" } }),
|
|
]);
|
|
expect(first.operationId).toBe(second.operationId);
|
|
expect(first).toMatchObject({ kind: "requires_next_admission", applies: "next_normal_admission" });
|
|
const rows = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
|
expect(rows).toHaveLength(1);
|
|
expect(rows[0].requestKeys.sort()).toEqual(["one", "two"]);
|
|
expect((await db.select().from(issues).where(eq(issues.id, issueId)))[0]).toMatchObject({ projectId: null, executionWorkspaceId: workspaceId });
|
|
await expect(request("two", "different-ref")).rejects.toThrow(/conflicts/);
|
|
await expect(executionWorkspaceRepositoryService(db).request({ companyId, issueId, actor, request: { repository: { kind: "url", url: "https://github.com/other/source" }, requestKey: "two" } })).rejects.toThrow(/conflicts/);
|
|
});
|
|
it("rejects cross-company task IDs and revoked catalog permission even with a saved receipt", async () => {
|
|
const [other] = await db.insert(companies).values({ name: "Foreign", issuePrefix: "FOREIGN" }).returning();
|
|
await expect(executionWorkspaceRepositoryService(db).request({ companyId: other.id, issueId, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "foreign" } })).rejects.toThrow(/not found/);
|
|
catalog.available = false;
|
|
try {
|
|
await expect(request("one")).rejects.toThrow(/no longer available/);
|
|
await expect(prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId, runId: randomUUID(), responsibleUserId: "local-board" })).rejects.toThrow(/no longer available/);
|
|
} finally { catalog.available = true; }
|
|
});
|
|
it("retains durable ownership when Git bundle restoration omits the temporary receipt", async () => {
|
|
const [inventory] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
|
const checkout = path.join(cwd, inventory.relativePath);
|
|
await mkdir(checkout, { recursive: true });
|
|
const git = async (...args: string[]) => (await promisify(execFileCallback)("git", ["-C", checkout, ...args])).stdout.trim();
|
|
await git("init", "--initial-branch=main");
|
|
await git("remote", "add", "origin", inventory.repoUrl);
|
|
await writeFile(path.join(checkout, "source.txt"), "restored repository\n");
|
|
await git("add", ".");
|
|
await git("-c", "user.name=Fixture", "-c", "user.email=fixture@example.test", "commit", "-m", "restored");
|
|
const commit = await git("rev-parse", "HEAD");
|
|
await db.update(executionWorkspaceRepositories).set({ pinnedCommit: commit, state: "ready" }).where(eq(executionWorkspaceRepositories.id, inventory.id));
|
|
await writeFile(path.join(checkout, "source.txt"), "uncommitted work\n");
|
|
const prepared = await prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId, runId: randomUUID(), responsibleUserId: "local-board" });
|
|
expect(prepared).toHaveLength(1);
|
|
expect(prepared[0].pinnedCommit).toBe(commit);
|
|
expect(await readFile(path.join(checkout, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
|
if (process.platform !== "win32") {
|
|
const receiptPath = path.join(checkout, ".git", "paperclip-workspace-owner.json");
|
|
await rm(receiptPath, { force: true });
|
|
await promisify(execFileCallback)("mkfifo", [receiptPath]);
|
|
let deadline: ReturnType<typeof setTimeout> | undefined;
|
|
try {
|
|
await Promise.race([
|
|
prepareForAdmission({ companyId, issueId, workspaceId, cwd, agentId, runId: randomUUID(), responsibleUserId: "local-board" }),
|
|
new Promise((_, reject) => { deadline = setTimeout(() => reject(new Error("FIFO receipt blocked admission")), 3000); }),
|
|
]);
|
|
} finally {
|
|
clearTimeout(deadline);
|
|
const writer = await open(receiptPath, fsConstants.O_WRONLY | fsConstants.O_NONBLOCK).catch(() => null);
|
|
await writer?.close();
|
|
await rm(receiptPath, { force: true });
|
|
}
|
|
}
|
|
});
|
|
it("reuses the exact published checkout across logical workspaces without applying historical task privacy", async () => {
|
|
const [secondAgent] = await db.insert(agents).values({ companyId, name: "Second agent", adapterType: "process" }).returning();
|
|
const [secondWorkspace] = await db.insert(executionWorkspaces).values({ companyId, projectId: null, name: "Same configured folder", cwd, mode: "shared_workspace", strategyType: "operator_directory" }).returning();
|
|
const [secondIssue] = await db.insert(issues).values({ companyId, title: "Second task", assigneeAgentId: secondAgent.id, executionWorkspaceId: secondWorkspace.id }).returning();
|
|
const service = executionWorkspaceRepositoryService(db);
|
|
const intent = await service.request({ companyId, issueId: secondIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, requestKey: "shared-second" } });
|
|
const admission = { companyId, issueId: secondIssue.id, workspaceId: secondWorkspace.id, cwd, agentId: secondAgent.id, runId: randomUUID(), responsibleUserId: null };
|
|
const [original] = await db.select().from(executionWorkspaceRepositories).where(eq(executionWorkspaceRepositories.executionWorkspaceId, workspaceId));
|
|
await writeFile(path.join(cwd, original.relativePath, ".git", "paperclip-workspace-owner.json"),
|
|
JSON.stringify({ version: 1, repositoryId: original.id, pinnedCommit: original.pinnedCommit }));
|
|
const prepared = await prepareForAdmission(admission);
|
|
expect(prepared[0]).toMatchObject({ id: intent.operationId, cwd: path.join(await realpath(cwd), original.relativePath), pinnedCommit: original.pinnedCommit });
|
|
expect(await readFile(path.join(prepared[0].cwd, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
|
expect(JSON.parse(await readFile(path.join(prepared[0].cwd, ".git", "paperclip-workspace-owner.json"), "utf8")))
|
|
.toMatchObject({ repositoryId: intent.operationId, pinnedCommit: original.pinnedCommit });
|
|
const [differentRefWorkspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Conflicting ref", cwd, mode: "shared_workspace", strategyType: "operator_directory" }).returning();
|
|
const [differentRefIssue] = await db.insert(issues).values({ companyId, title: "Different ref", executionWorkspaceId: differentRefWorkspace.id }).returning();
|
|
await service.request({ companyId, issueId: differentRefIssue.id, actor, request: { repository: { kind: "catalog", id: "123" }, ref: "release", requestKey: "conflicting-ref" } });
|
|
await expect(prepareForAdmission({ ...admission, issueId: differentRefIssue.id, workspaceId: differentRefWorkspace.id, runId: randomUUID() })).rejects.toThrow(/different ref/);
|
|
const [privateSource] = await db.insert(issues).values({ companyId, title: "Retained private source", visibility: "private" }).returning();
|
|
const owner = executionWorkspaceService(db);
|
|
await owner.bindTaskWorkspace(companyId, privateSource.id, workspaceId);
|
|
const [movedWorkspace] = await db.insert(executionWorkspaces).values({ companyId, name: "Private task moved away", cwd: path.join(cwd, "moved-private-task"), mode: "shared_workspace", strategyType: "task_directory" }).returning();
|
|
await owner.bindTaskWorkspace(companyId, privateSource.id, movedWorkspace.id);
|
|
const [retainedWorkspace] = await db.select().from(executionWorkspaces).where(eq(executionWorkspaces.id, workspaceId));
|
|
expect(retainedWorkspace.metadata?._issuePrivacySources).toMatchObject({ [privateSource.id]: true });
|
|
await expect(prepareForAdmission(admission)).resolves.toHaveLength(1);
|
|
expect(await readFile(path.join(prepared[0].cwd, "source.txt"), "utf8")).toBe("uncommitted work\n");
|
|
});
|
|
it("stages a root change without replacing active files or adding a wake", async () => {
|
|
const owner = executionWorkspaceService(db);
|
|
await expect(owner.selectTaskWorkspace({ companyId, issueId, actor, selection: { kind: "task_directory" }, expectedBindingRevision: 0, requestKey: "move" })).resolves.toMatchObject({ kind: "scheduled", applies: "next_normal_admission" });
|
|
const [issue] = await db.select().from(issues).where(and(eq(issues.companyId, companyId), eq(issues.id, issueId)));
|
|
expect(issue.executionWorkspaceId).toBe(workspaceId);
|
|
expect(issue.workspacePendingSelection?.requestKey).toBe("move");
|
|
expect(issue.workspaceBindingRevision).toBe(1);
|
|
});
|
|
});
|