Files
PaperClipAI/server/src/__tests__/worktree-seed-server-spawn.test.ts
T
DottaandPaperclip a3a25ce6c9 fix(workspaces): stop running Paperclip's worktree setup before every agent turn (#20269)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Before an agent turn starts, the harness prepares the task's git
worktree
> - The harness runs a repository's `scripts/provision-worktree.sh` when
the project sets no `provisionCommand` and the file exists
> - The harness runs it on every turn, both when it creates the worktree
and when it reuses it
> - In the Paperclip repository, that script writes the worktree's
isolated instance config and runs `pnpm install`
> - Its "install needed" check compares against every `node_modules`
directory in the base checkout, including other worktrees, so it
reinstalls on every turn
> - This pull request renames the Paperclip script so that the harness
default does not find it in this repository
> - The benefit is that Paperclip agent turns no longer wait on a 6–9
second install. Other repositories keep the harness feature.

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Time to first token for agent turns in managed worktrees of the
Paperclip repository.

**Subsystem affected**
Execution workspace provisioning
(`server/src/services/workspace-runtime.ts`) and the repository script
`scripts/provision-worktree.sh`.

**Current behavior**
Every agent turn in a Paperclip worktree first runs `bash
./scripts/provision-worktree.sh`. In a local test, a `pnpm install
--frozen-lockfile` with nothing to change took 6.1 s and 6.3 s, and a
full install from a warm store took 9.0 s. The script's fingerprint skip
does not prevent this, because the script also requires every
base-checkout `node_modules` path (up to depth 4) to exist in the
worktree. On a developer machine that list had 1,735 entries, including
other worktrees under `.claude/worktrees/` and `.worktrees/` and pnpm's
internal `node_modules/.pnpm/*/node_modules`. A managed worktree never
contains the other worktrees' paths, so the script always decides to
reinstall.

**Proposed behavior**
The Paperclip repository does not ship a file at
`scripts/provision-worktree.sh`. The setup script becomes
`scripts/setup-paperclip-worktree.sh`. People can run it by hand or set
it as the project `provisionCommand` to opt in. The harness default
stays for other repositories.

**Reason and benefit**
Agents install dependencies when they need them (`node
scripts/agent-preflight.mjs`, as `AGENTS.md` says). Many turns never run
code. Instance setup stays available on demand:
`scripts/provision-worktree-runtime.sh` runs the setup script when a dev
server starts in a worktree that has no config. Database seeding was
already deferred.

**Breaking changes**
A project that explicitly sets `provisionCommand` to `bash
./scripts/provision-worktree.sh` for this repository will fail with
"file not found". Change it to `bash
./scripts/setup-paperclip-worktree.sh` or clear it.

## What Changed

- Rename `scripts/provision-worktree.sh` to
`scripts/setup-paperclip-worktree.sh`. The content is unchanged.
- `scripts/provision-worktree-runtime.sh` calls the new name when the
worktree has no config.
- Tests read the real script from its new path
(`provision-worktree-self-heal`, `workspace-runtime`,
`worktree-seed-server-spawn`). Server fixtures still copy it into their
test repositories as `scripts/provision-worktree.sh`, so the harness
default stays covered.
- `doc/DEVELOPING.md` says that the Paperclip repository deliberately
has no `provision-worktree.sh`, and tells people how to opt in.

## Verification

- `node --test scripts/__tests__/provision-worktree-self-heal.test.mjs`:
33 passed, 1 skipped (the skip already existed).
- `cd server && npx vitest run src/__tests__/workspace-runtime.test.ts
src/__tests__/heartbeat-workspace-source-trust.test.ts
src/__tests__/execution-workspace-reopen.test.ts`: 242 passed on the
rebased head.
- `cd server && npx vitest run
src/__tests__/worktree-seed-server-spawn.test.ts`: 2 passed.
- Manual: in a Paperclip worktree, start an agent turn. The run log does
not show a `workspace_provision` operation for the script.

## Risks

- Explicit `provisionCommand` settings that name the old path will fail.
See "Breaking changes".
- Open pull requests that edit `scripts/provision-worktree.sh` (for
example #16213, #11335, #11733, #19764) will conflict on the rename. Git
rename detection should carry most edits over.
- An agent that runs tests in a new worktree without first running
preflight will see a missing-module error. `AGENTS.md` already tells
agents to run `node scripts/agent-preflight.mjs`.
- The script's install check still has the bug described above. It now
runs only on demand. A separate fix can address it.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, through Claude Code
with tool use (shell, file edits). Standard context window.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-11-09 14:03:24 +00:00

298 lines
14 KiB
TypeScript

import { execFile } from "node:child_process";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { promisify } from "node:util";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
ensureWorktreeSeeded,
readWorktreeSeedManifest,
worktreeInitCommand,
} from "../../../cli/src/commands/worktree.ts";
import { realizeExecutionWorkspace, resolveRuntimeProvisionCommand } from "../services/workspace-runtime.ts";
const execFileAsync = promisify(execFile);
const cleanup: string[] = [];
const originalConfig = process.env.PAPERCLIP_CONFIG;
const originalWorktreesDir = process.env.PAPERCLIP_WORKTREES_DIR;
async function runGit(cwd: string, args: string[]) {
await execFileAsync("git", args, { cwd });
}
async function writeConfig(configPath: string, instanceId: string) {
const instanceRoot = path.dirname(configPath);
await fs.mkdir(path.dirname(configPath), { recursive: true });
await fs.writeFile(configPath, `${JSON.stringify({
$meta: { version: 1, updatedAt: "2026-08-19T00:00:00.000Z", source: "configure" },
database: {
mode: "embedded-postgres",
embeddedPostgresDataDir: path.join(instanceRoot, "db"),
embeddedPostgresPort: 54329,
backup: { enabled: false, intervalMinutes: 60, retentionDays: 30, dir: path.join(instanceRoot, "backups") },
},
logging: { mode: "file", logDir: path.join(instanceRoot, "logs") },
server: {
deploymentMode: "local_trusted",
exposure: "private",
host: "127.0.0.1",
port: 3100,
allowedHostnames: [],
serveUi: true,
},
}, null, 2)}\n`, "utf8");
await fs.writeFile(
path.join(path.dirname(configPath), ".env"),
`PAPERCLIP_INSTANCE_ID=${instanceId}\n`,
"utf8",
);
}
function verifiedSeedResult() {
return {
backupSummary: "snapshot.sql",
snapshotAt: "2026-08-19T00:00:00.000Z",
migrationRevision: "0223_test.sql",
pausedScheduledRoutines: 0,
executionQuarantine: {
disabledTimerHeartbeats: 0,
resetRunningAgents: 0,
quarantinedInProgressIssues: 0,
unassignedTodoIssues: 0,
unassignedReviewIssues: 0,
stoppedProjectWorkspaceRuntimes: 0,
stoppedExecutionWorkspaceRuntimes: 0,
stoppedRuntimeServices: 0,
},
reboundWorkspaces: [],
validation: {
authUserCount: 1,
credentialAccountCount: 1,
instanceAdminCount: 1,
activeMembershipCount: 1,
companyCount: 1,
issueCount: 1,
representativeCompanyId: "00000000-0000-4000-8000-000000000001",
representativeIssueId: "00000000-0000-4000-8000-000000000002",
migrationRevision: "0223_test.sql",
},
};
}
afterEach(async () => {
if (originalConfig === undefined) delete process.env.PAPERCLIP_CONFIG;
else process.env.PAPERCLIP_CONFIG = originalConfig;
if (originalWorktreesDir === undefined) delete process.env.PAPERCLIP_WORKTREES_DIR;
else process.env.PAPERCLIP_WORKTREES_DIR = originalWorktreesDir;
for (const dir of cleanup.splice(0)) {
await fs.rm(dir, { recursive: true, force: true });
}
});
describe("managed worktree seed source through the server spawn path", () => {
it("preserves an explicitly empty instance during managed startup before its first database boot", async () => {
const tempRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-server-empty-worktree-")));
cleanup.push(tempRoot);
const baseCwd = path.join(tempRoot, "source");
const cwd = path.join(tempRoot, "empty");
const sourceConfigPath = path.join(baseCwd, ".paperclip", "config.json");
await writeConfig(sourceConfigPath, "registered-source");
await fs.mkdir(cwd, { recursive: true });
await fs.mkdir(path.join(baseCwd, "scripts"), { recursive: true });
await fs.writeFile(path.join(baseCwd, "scripts", "provision-worktree-runtime.sh"), "#!/usr/bin/env bash\n");
const originalCwd = process.cwd();
const originalEnv = { ...process.env };
try {
process.chdir(cwd);
await worktreeInitCommand({ empty: true, fromConfig: sourceConfigPath, home: path.join(tempRoot, "instances") });
const configPath = path.join(cwd, ".paperclip", "config.json");
const repoRoot = fileURLToPath(new URL("../../../", import.meta.url));
const startup = await execFileAsync(process.execPath, [path.join(repoRoot, "cli/node_modules/tsx/dist/cli.mjs"), "--eval", `
void (async () => {
const fs = await import('node:fs');
const dotenv = (await import(${JSON.stringify(pathToFileURL(path.join(repoRoot, "server/node_modules/dotenv/lib/main.js")).href)})).default;
const envPath = ${JSON.stringify(path.join(cwd, ".paperclip", ".env"))};
const saved = dotenv.parse(fs.readFileSync(envPath));
await import(${JSON.stringify(pathToFileURL(path.join(repoRoot, "server/src/config.ts")).href)});
const repaired = dotenv.parse(fs.readFileSync(envPath));
console.log(JSON.stringify({
jwt: process.env.PAPERCLIP_AGENT_JWT_SECRET === saved.PAPERCLIP_AGENT_JWT_SECRET,
actions: process.env.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET === saved.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET,
auth: process.env.BETTER_AUTH_SECRET === saved.PAPERCLIP_AGENT_JWT_SECRET,
savedActions: repaired.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET === saved.PAPERCLIP_TOOL_ACTION_SIGNING_SECRET
}));
})();
`], { cwd, env: { ...process.env, PAPERCLIP_CONFIG: configPath, PAPERCLIP_AGENT_JWT_SECRET: "source-jwt", PAPERCLIP_TOOL_ACTION_SIGNING_SECRET: "source-actions", BETTER_AUTH_SECRET: "source-auth" } });
expect(JSON.parse(startup.stdout.trim().split("\n").at(-1)!)).toEqual({ jwt: true, actions: true, auth: true, savedActions: true });
const workspace = {
baseCwd, cwd, source: "project_primary" as const, projectId: "project-1",
workspaceId: "project-workspace-1", repoUrl: null, repoRef: "HEAD",
strategy: "git_worktree" as const, branchName: null, branchCreatedByRuntime: false, worktreePath: cwd,
warnings: [], created: false,
};
expect(resolveRuntimeProvisionCommand({ config: {}, workspace })).toBe("");
expect(resolveRuntimeProvisionCommand({ config: { runtimeProvisionCommand: "./install-dependencies.sh" }, workspace }))
.toBe("./install-dependencies.sh");
process.env.PAPERCLIP_WORKSPACE_BASE_CWD = baseCwd;
process.env.PAPERCLIP_PROJECT_WORKSPACE_ID = "project-workspace-1";
process.env.PAPERCLIP_SEED_EXPECTED_COMPANY_ID = "company-1";
const seedDatabase = vi.fn(async () => verifiedSeedResult());
const inspectLegacyDatabase = vi.fn(async () => null);
await expect(ensureWorktreeSeeded({ config: configPath }, { seedDatabase, inspectLegacyDatabase }))
.resolves.toEqual({ seeded: false, reason: "explicitly_empty" });
expect(seedDatabase).not.toHaveBeenCalled();
expect(inspectLegacyDatabase).not.toHaveBeenCalled();
const provisionScript = fileURLToPath(new URL("../../../scripts/provision-worktree-runtime.sh", import.meta.url));
const provision = await execFileAsync("bash", [provisionScript], {
cwd,
env: { ...process.env, PAPERCLIP_WORKSPACE_CWD: cwd },
});
expect(provision.stderr).toContain("explicitly empty");
expect(readWorktreeSeedManifest(configPath)).toBeNull();
await expect(fs.stat(path.join(cwd, ".paperclip", "seed-pending"))).rejects.toMatchObject({ code: "ENOENT" });
} finally {
process.chdir(originalCwd);
for (const key of Object.keys(process.env)) if (!(key in originalEnv)) delete process.env[key];
Object.assign(process.env, originalEnv);
}
});
it("re-derives an ambient-instance manifest written before provisioning", async () => {
const tempRoot = await fs.realpath(await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-server-seed-source-")));
cleanup.push(tempRoot);
const repoRoot = path.join(tempRoot, "repo");
const hooksDir = path.join(tempRoot, "hooks");
const ambientConfigPath = path.join(tempRoot, "ambient", "config.json");
const registeredConfigPath = path.join(repoRoot, ".paperclip", "config.json");
const worktreeHome = path.join(tempRoot, "worktree-home");
await fs.mkdir(repoRoot, { recursive: true });
await runGit(repoRoot, ["init", "-q"]);
await runGit(repoRoot, ["config", "user.email", "paperclip@example.com"]);
await runGit(repoRoot, ["config", "user.name", "Paperclip Test"]);
await fs.mkdir(path.join(repoRoot, "scripts"), { recursive: true });
await fs.writeFile(path.join(repoRoot, "README.md"), "server spawn regression\n", "utf8");
await fs.copyFile(
fileURLToPath(new URL("../../../scripts/setup-paperclip-worktree.sh", import.meta.url)),
path.join(repoRoot, "scripts", "provision-worktree.sh"),
);
await fs.chmod(path.join(repoRoot, "scripts", "provision-worktree.sh"), 0o755);
await runGit(repoRoot, ["add", "README.md", "scripts/provision-worktree.sh"]);
await runGit(repoRoot, ["commit", "-qm", "Add managed provision script"]);
await writeConfig(registeredConfigPath, "registered-source");
await writeConfig(ambientConfigPath, "ambient-instance");
await fs.mkdir(worktreeHome, { recursive: true });
// Reproduce the integrated lane's ordering with a checkout hook: an earlier
// worktree-init-style writer inherits the server environment and leaves a valid
// target config whose manifest diagnostic points at the ambient instance.
await fs.mkdir(hooksDir, { recursive: true });
const hookPath = path.join(hooksDir, "post-checkout");
await fs.writeFile(
hookPath,
`#!/usr/bin/env node
const crypto = require("node:crypto");
const fs = require("node:fs");
const path = require("node:path");
const cwd = process.cwd();
if (cwd === ${JSON.stringify(repoRoot)}) process.exit(0);
const stateDir = path.join(cwd, ".paperclip");
const normalized = path.basename(cwd).trim().toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/-+/g, "-").replace(/^[-_]+|[-_]+$/g, "");
const instanceId = \`${"${(normalized || \"worktree\").slice(0, 48)}"}-\${crypto.createHash("sha256").update(path.resolve(cwd)).digest("hex").slice(0, 12)}\`;
const targetConfigPath = path.join(stateDir, "config.json");
const instanceRoot = path.join(process.env.PAPERCLIP_WORKTREES_DIR, "instances", instanceId);
fs.mkdirSync(stateDir, { recursive: true });
fs.mkdirSync(instanceRoot, { recursive: true });
fs.writeFileSync(targetConfigPath, JSON.stringify({
$meta: { version: 1, updatedAt: "2026-08-19T00:00:00.000Z", source: "configure" },
database: {
mode: "embedded-postgres",
embeddedPostgresDataDir: path.join(instanceRoot, "db"),
embeddedPostgresPort: 54330,
backup: { enabled: false, intervalMinutes: 60, retentionDays: 30, dir: path.join(instanceRoot, "backups") },
},
logging: { mode: "file", logDir: path.join(instanceRoot, "logs") },
server: {
deploymentMode: "local_trusted",
exposure: "private",
host: "127.0.0.1",
port: 3101,
allowedHostnames: [],
serveUi: true,
},
}, null, 2) + "\\n");
fs.writeFileSync(path.join(stateDir, ".env"), [
"PAPERCLIP_HOME=" + JSON.stringify(process.env.PAPERCLIP_WORKTREES_DIR),
"PAPERCLIP_INSTANCE_ID=" + JSON.stringify(instanceId),
"PAPERCLIP_CONFIG=" + JSON.stringify(targetConfigPath),
"",
].join("\\n"));
fs.writeFileSync(path.join(stateDir, "seed-manifest.json"), JSON.stringify({
version: 2,
source: { instanceId: "ambient-instance", configPath: process.env.PAPERCLIP_CONFIG },
snapshotAt: null,
seedMode: "minimal",
migrationRevision: null,
targetInstanceId: instanceId,
phase: "pending",
state: "pending",
attemptId: "ambient-writer",
startedAt: null,
finishedAt: null,
diagnostics: [{ phase: "pending", status: "succeeded", at: new Date().toISOString() }],
}, null, 2) + "\\n");
`,
"utf8",
);
await fs.chmod(hookPath, 0o755);
await runGit(repoRoot, ["config", "core.hooksPath", hooksDir]);
process.env.PAPERCLIP_CONFIG = ambientConfigPath;
process.env.PAPERCLIP_WORKTREES_DIR = worktreeHome;
const workspace = await realizeExecutionWorkspace({
base: {
baseCwd: repoRoot,
source: "project_primary",
projectId: "project-1",
workspaceId: "project-workspace-1",
repoUrl: null,
repoRef: "HEAD",
},
config: {
workspaceStrategy: {
type: "git_worktree",
branchTemplate: "{{issue.identifier}}-{{slug}}",
provisionCommand: "bash ./scripts/provision-worktree.sh",
},
},
issue: {
id: "issue-1",
identifier: "PAP-17681",
title: "Recover ambient seed source",
},
agent: { id: "agent-1", name: "Coder", companyId: "company-1" },
});
expect(readWorktreeSeedManifest(path.join(workspace.cwd, ".paperclip", "config.json"))).toMatchObject({
source: { instanceId: "ambient-instance", configPath: ambientConfigPath },
state: "pending",
});
await expect(ensureWorktreeSeeded({
config: path.join(workspace.cwd, ".paperclip", "config.json"),
registeredBaseWorkspaceCwd: repoRoot,
registeredProjectWorkspaceId: "project-workspace-1",
expectedCompanyId: "company-1",
}, {
seedDatabase: async () => verifiedSeedResult(),
})).resolves.toMatchObject({ seeded: true, reason: "seeded" });
expect(readWorktreeSeedManifest(path.join(workspace.cwd, ".paperclip", "config.json"))).toMatchObject({
source: { instanceId: "registered-source", configPath: registeredConfigPath },
state: "verified",
phase: "complete",
});
}, 20_000);
});