fix(dev): preserve empty instances through managed startup

Co-Authored-By: Paperclip <noreply@paperclip.ing>
This commit is contained in:
DottaandPaperclip committed 2026-10-06 22:02:17 -05:00
1 parent cd5d0f68af
commit b4f0ed180e
9 files changed
+95 -6

No files matched your search

+4
View File
@@ -1490,6 +1490,10 @@ describe("worktree helpers", () => {
expect(env).toContain("PAPERCLIP_AGENT_JWT_SECRET=");
expect(fs.existsSync(path.join(repoRoot, ".paperclip/seed-manifest.json"))).toBe(false);
expect(fs.existsSync(path.join(repoRoot, ".paperclip/seed-pending"))).toBe(false);
expect(fs.existsSync(path.join(repoRoot, ".paperclip/seed-empty"))).toBe(true);
await worktreeInitCommand({ seed: false, force: true, fromConfig: path.join(tempRoot, "missing.json"), home: path.join(tempRoot, "instances") });
expect(fs.existsSync(path.join(repoRoot, ".paperclip/seed-empty"))).toBe(false);
expect(readWorktreeSeedManifest(path.join(repoRoot, ".paperclip/config.json"))?.state).toBe("pending");
} finally {
process.chdir(originalCwd);
if (originalJwt === undefined) delete process.env.PAPERCLIP_AGENT_JWT_SECRET; else process.env.PAPERCLIP_AGENT_JWT_SECRET = originalJwt;
+3
View File
@@ -8,6 +8,7 @@ export const WORKTREE_SEED_MODES = ["minimal", "full"] as const;
export const WORKTREE_SEED_MANIFEST = "seed-manifest.json";
export const WORKTREE_SEED_PENDING_MARKER = "seed-pending";
export const WORKTREE_SEED_COMPLETE_MARKER = "seed-complete";
export const WORKTREE_SEED_EMPTY_MARKER = "seed-empty";
export const WORKTREE_SEED_LOCK_MARKER = "seed.lock";
export type WorktreeSeedMode = (typeof WORKTREE_SEED_MODES)[number];
@@ -98,6 +99,7 @@ export type WorktreeSeedMarkerPaths = {
manifest: string;
pending: string;
complete: string;
empty: string;
lock: string;
};
@@ -107,6 +109,7 @@ export function resolveWorktreeSeedMarkerPaths(configPath: string): WorktreeSeed
manifest: path.resolve(configDir, WORKTREE_SEED_MANIFEST),
pending: path.resolve(configDir, WORKTREE_SEED_PENDING_MARKER),
complete: path.resolve(configDir, WORKTREE_SEED_COMPLETE_MARKER),
empty: path.resolve(configDir, WORKTREE_SEED_EMPTY_MARKER),
lock: path.resolve(configDir, WORKTREE_SEED_LOCK_MARKER),
};
}
+19 -1
View File
@@ -246,6 +246,7 @@ export type EnsureWorktreeSeededResult = {
| "seeded"
| "verified_manifest"
| "complete_marker"
| "explicitly_empty"
| "legacy_unmarked"
| "legacy_database";
details?: SeedWorktreeDatabaseResult;
@@ -2222,6 +2223,9 @@ export async function ensureWorktreeSeeded(
): Promise<EnsureWorktreeSeededResult> {
const configPath = resolveConfigPath(opts.config);
const markers = resolveWorktreeSeedMarkerPaths(configPath);
if (existsSync(markers.empty)) {
return { seeded: false, reason: "explicitly_empty" };
}
const initialManifest = readWorktreeSeedManifest(configPath);
if (initialManifest?.state === "verified") {
return { seeded: false, reason: "verified_manifest" };
@@ -2283,6 +2287,9 @@ export async function ensureWorktreeSeeded(
mkdirSync(path.dirname(markers.lock), { recursive: true });
const releaseLock = await acquireWorktreeSeedLock(markers.lock);
try {
if (existsSync(markers.empty)) {
return { seeded: false, reason: "explicitly_empty" };
}
// These checks deliberately happen under the cross-process lock. A second
// service process waits for the first seed transaction, then observes the
// verified manifest instead of cloning the same database concurrently.
@@ -2438,6 +2445,7 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
rmSync(seedMarkers.manifest, { force: true });
rmSync(seedMarkers.pending, { force: true });
rmSync(seedMarkers.complete, { force: true });
rmSync(seedMarkers.empty, { force: true });
rmSync(paths.instanceRoot, { recursive: true, force: true });
}
@@ -2466,6 +2474,11 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
});
try {
// Persist the no-copy choice before the config becomes visible to managed startup.
if (opts.empty) {
mkdirSync(paths.repoConfigDir, { recursive: true });
writeFileSync(resolveWorktreeSeedMarkerPaths(paths.configPath).empty, "Explicitly empty instance; automatic database copying is disabled.\n", { mode: 0o600 });
}
writeConfig(selectedConfig, paths.configPath);
writeWorktreePortRegistry(paths.homeDir, [
...registeredConfigPaths,
@@ -2473,6 +2486,7 @@ async function runWorktreeInit(opts: WorktreeInitOptions): Promise<void> {
]);
} catch (error) {
rmSync(paths.configPath, { force: true });
if (opts.empty) rmSync(resolveWorktreeSeedMarkerPaths(paths.configPath).empty, { force: true });
throw error;
}
@@ -2605,6 +2619,8 @@ export async function worktreeEnsureSeededCommand(opts: WorktreeEnsureSeededOpti
spinner.stop("Seeded isolated worktree database (minimal).");
} else if (result.reason === "legacy_database") {
spinner.stop("Validated and adopted an existing legacy worktree database.");
} else if (result.reason === "explicitly_empty") {
spinner.stop("Explicitly empty instance; automatic database copying is disabled.");
} else {
spinner.stop("Worktree database already has a verified seed manifest.");
}
@@ -2622,7 +2638,7 @@ export async function worktreeEnsureSeededCommand(opts: WorktreeEnsureSeededOpti
);
}
}
p.outro(pc.green("Worktree database seed complete."));
p.outro(pc.green(result.reason === "explicitly_empty" ? "Empty worktree ready." : "Worktree database seed complete."));
} catch (error) {
spinner.stop(pc.red("Failed to seed worktree database."));
throw error;
@@ -4324,6 +4340,8 @@ async function runWorktreeReseed(opts: WorktreeReseedOptions): Promise<void> {
expectedCompanyId: nonEmpty(process.env.PAPERCLIP_SEED_EXPECTED_COMPANY_ID) ?? undefined,
seedDatabase: seedWorktreeDatabase,
});
// An operator-confirmed successful reseed replaces the earlier empty-instance choice.
rmSync(markers.empty, { force: true });
spinner.stop(`Reseeded ${targetEndpoint.label} (${seedMode}).`);
p.log.message(pc.dim(`Source: ${source.configPath}`));
p.log.message(pc.dim(`Target: ${targetEndpoint.configPath}`));
+9 -2
View File
@@ -888,6 +888,11 @@ Seed modes:
- `--no-seed` defers database copying until the worktree is first used
- `--empty` creates an empty isolated instance, with fresh signing secrets and no deferred copy; use this for synthetic test drives
`--empty` persists a `.paperclip/seed-empty` marker before writing the instance config.
The CLI and managed runtime provisioner honor it even when a registered source
instance is present. An explicit successful `worktree reseed`, or a replacement
`worktree init --force` without `--empty`, clears the choice.
Seeded worktree instances quarantine copied live execution by default for both `minimal` and `full` seeds. During restore, Paperclip disables copied agent timer heartbeats, resets copied `running` agents to `idle`, blocks and unassigns copied agent-owned `in_progress` issues, and unassigns copied agent-owned `todo`/`in_review` issues. This keeps a freshly booted worktree from starting agents for work already owned by the source instance. Pass `--preserve-live-work` only when you intentionally want the isolated worktree to resume copied assignments.
The same quarantine stops copied project/execution-workspace runtime desired states and clears copied runtime process claims. Without this reset, booting the cloned Paperclip database could restart a source workspace's dev service from the isolated instance, creating duplicate runners, port reassignment, and stale public URLs.
@@ -985,7 +990,8 @@ The workspace UI surfaces `Provisioning database`, `Validating clone`, `Ready`,
| `--server-port <port>` | Preferred server port |
| `--db-port <port>` | Preferred embedded Postgres port |
| `--seed-mode <mode>` | Seed profile: `minimal` or `full` (default: `minimal`) |
| `--no-seed` | Skip database seeding from the source instance |
| `--no-seed` | Defer database copying until first use |
| `--empty` | Create an empty instance with fresh signing secrets and disable automatic copying |
| `--force` | Replace existing repo-local config and isolated instance data |
Examples:
@@ -1086,7 +1092,8 @@ Managed workspace repair uses this same verified full-reseed contract through `P
| `--server-port <port>` | Preferred server port |
| `--db-port <port>` | Preferred embedded Postgres port |
| `--seed-mode <mode>` | Seed profile: `minimal` or `full` (default: `minimal`) |
| `--no-seed` | Skip database seeding from the source instance |
| `--no-seed` | Defer database copying until first use |
| `--empty` | Create an empty instance with fresh signing secrets and disable automatic copying |
| `--force` | Replace existing repo-local config and isolated instance data |
Examples:
Binary file not shown.

After

Width:  |  Height:  |  Size: 121 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

+6
View File
@@ -9,6 +9,7 @@ paperclip_instance_id="${PAPERCLIP_INSTANCE_ID:-default}"
paperclip_dir="$worktree_cwd/.paperclip"
worktree_config_path="$paperclip_dir/config.json"
seed_manifest_path="$paperclip_dir/seed-manifest.json"
seed_empty_path="$paperclip_dir/seed-empty"
if [[ ! -d "$base_cwd" ]]; then
echo "Base workspace does not exist: $base_cwd" >&2
@@ -20,6 +21,11 @@ if [[ ! -d "$worktree_cwd" ]]; then
exit 1
fi
if [[ -e "$seed_empty_path" ]]; then
echo "Worktree instance is explicitly empty; automatic database copying is disabled." >&2
exit 0
fi
if [[ -e "$seed_manifest_path" ]]; then
seed_manifest_state="$(SEED_MANIFEST_PATH="$seed_manifest_path" node <<'EOF'
const fs = require("node:fs");
@@ -4,12 +4,13 @@ import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { afterEach, describe, expect, it, vi } from "vitest";
import {
ensureWorktreeSeeded,
readWorktreeSeedManifest,
worktreeInitCommand,
} from "../../../cli/src/commands/worktree.ts";
import { realizeExecutionWorkspace } from "../services/workspace-runtime.ts";
import { realizeExecutionWorkspace, resolveRuntimeProvisionCommand } from "../services/workspace-runtime.ts";
const execFileAsync = promisify(execFile);
const cleanup: string[] = [];
@@ -90,8 +91,57 @@ afterEach(async () => {
});
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 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, 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.mkdtemp(path.join(os.tmpdir(), "paperclip-server-seed-source-"));
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");
+1
View File
@@ -5762,6 +5762,7 @@ export function resolveRuntimeProvisionCommand(input: {
if (input.workspace.strategy !== "git_worktree") return "";
const stateDir = path.join(input.workspace.cwd, ".paperclip");
if (existsSync(path.join(stateDir, "seed-empty"))) return "";
const manifestPath = path.join(stateDir, "seed-manifest.json");
const provisionScript = path.join(
input.workspace.baseCwd,