feat(workspaces): defer isolated setup until runtime start (#10653)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - Isolated workspaces give each task a safe and reproducible checkout.
> - The existing setup cloned the development database before an agent
needed to run the app.
> - This made worktree creation slower and heavier for tasks that never
start a service.
> - Runtime services already use one server start path for heartbeat,
operator, and startup recovery flows.
> - This pull request moves heavy setup to that start path and keeps
worktree creation lean.
> - The benefit is faster isolated workspace creation with the same
reliable runtime setup when a service starts.

## Linked Issues or Issue Description

Related pull request: #10652 covers the initial deferred
database-seeding slice. This pull request supersedes it with end-to-end
runtime provisioning and safe cleanup.

**What existing behavior does this improve?**

This improves isolated worktree creation, runtime service startup, and
isolated instance cleanup.

**Subsystem affected**

Cross-cutting: CLI worktree setup, server runtime orchestration, shared
workspace contracts, and development scripts.

**Current behavior**

Paperclip seeds an isolated development database during worktree
creation. It can also leave an isolated instance directory after
workspace teardown. This work happens even when no runtime service
starts.

**Proposed behavior**

Paperclip creates the worktree with a lean eager setup. It runs an
idempotent runtime provision command before the first managed service
spawn. Concurrent starts share one provision attempt. Teardown removes
the isolated instance safely.

**Reason and benefit**

Many agent tasks only edit and test code. They do not need a running
Paperclip instance. Deferring the database seed reduces workspace
startup cost while preserving automatic setup for tasks that start the
app.

**Breaking changes**

None. The new runtime provision command is optional. Existing workspace
behavior is unchanged when it is absent.

## What Changed

- Split Paperclip worktree setup into a lean eager script and an
idempotent runtime provision script.
- Added `runtimeProvisionCommand` to project, issue, realized workspace,
and persisted workspace contracts.
- Added a per-workspace provision mutex before local service spawn for
heartbeat, operator, and startup recovery flows.
- Added a persisted `provisioning` service state and the
`workspace_runtime_provision` operation phase.
- Kept provision time outside the service readiness timeout and made
failed attempts visible and retryable.
- Reclaimed isolated instance data during safe workspace teardown.
- Serialized deferred database seeding across processes and bound
teardown to the instance root captured in persisted workspace metadata.
- Added tests for config flow, concurrency, retry, no-op behavior,
readiness timing, scripts, CLI commands, and cleanup.
- Documented the eager and runtime provisioning contracts.

## Verification

- `pnpm -r typecheck`
- `pnpm build`
- `pnpm test:run` (server: 3,201 passed; UI: 3,345 passed; the CLI phase
exposed one environment-sensitive AWS doctor assertion because the agent
runtime injects static AWS credentials)
- `env -u AWS_ACCESS_KEY_ID -u AWS_SECRET_ACCESS_KEY pnpm exec vitest
run cli/src/__tests__/secrets.test.ts -t 'passes AWS doctor checks when
non-secret provider config is present'`
- Focused runtime tests cover serialized provisioning, retry after
stderr failure, absent-command no-op behavior, operation logging,
persisted state order, and readiness timeout exclusion.
- Focused CLI and cleanup tests cover concurrent seed serialization,
stale-lock fail-closed behavior, persisted instance ownership, and
rewritten sibling pointers.

## Risks

- A faulty runtime provision script blocks service startup. Paperclip
records stderr, marks the service failed, and retries on the next start.
- Concurrent service requests share an in-process provision attempt,
while the seed command uses an atomic filesystem lock across processes.
A stale lock fails closed and requires an operator to verify no seed is
running before removing it.
- Isolated instance cleanup is destructive. The cleanup service
validates ownership and path containment before removal.

> 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

- OpenAI Codex, `gpt-5.6-sol`, with agentic reasoning, tool use, and
code execution. The service 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>
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
authored and GitHub committed 2026-08-02 10:37:10 -05:00
1 parent 8540ce2973
commit dcac49a4fd
47 files changed
+2167 -95

No files matched your search

@@ -6,6 +6,7 @@ import os from "node:os";
import path from "node:path";
const script = new URL("../provision-worktree.sh", import.meta.url).pathname;
const runtimeScript = new URL("../provision-worktree-runtime.sh", import.meta.url).pathname;
// Keep the PATH minimal so the fallback ladder is deterministic: node must be
// reachable, but a globally installed `paperclipai` must not shadow the paths
@@ -34,7 +35,7 @@ test.after(() => {
* initExit: exit code for `... index.ts worktree init ...`; on 0 the fake CLI
* writes a marker config so tests can tell CLI init from fallback.
*/
function makeBaseWorkspace({ helpExit, initExit }) {
function makeBaseWorkspace({ helpExit, initExit, ensureExit = 0 }) {
const baseCwd = makeTempDir("paperclip-provision-base-");
const runnerPath = path.join(baseCwd, "cli", "node_modules", "tsx", "dist", "cli.mjs");
const entryPath = path.join(baseCwd, "cli", "src", "index.ts");
@@ -46,6 +47,7 @@ function makeBaseWorkspace({ helpExit, initExit }) {
`
import fs from "node:fs";
const cliArgs = process.argv.slice(3);
fs.appendFileSync(${JSON.stringify(path.join(baseCwd, "cli-invocations.log"))}, JSON.stringify(cliArgs) + "\\n");
if (cliArgs.includes("--help")) {
if (${helpExit} !== 0) console.error("ERR_MODULE_NOT_FOUND: drizzle-orm");
process.exit(${helpExit});
@@ -60,6 +62,15 @@ if (cliArgs[0] === "worktree" && cliArgs[1] === "init") {
fs.writeFileSync(".paperclip/.env", "PAPERCLIP_IN_WORKTREE=true\\n");
process.exit(0);
}
if (cliArgs[0] === "worktree" && cliArgs[1] === "ensure-seeded") {
if (${ensureExit} !== 0) {
console.error("fake worktree ensure-seeded failure");
process.exit(${ensureExit});
}
fs.rmSync(".paperclip/seed-pending", { force: true });
fs.writeFileSync(".paperclip/seed-complete", "{}\\n");
process.exit(0);
}
process.exit(0);
`,
);
@@ -85,6 +96,34 @@ function runProvision(baseCwd, { pathPrefix } = {}) {
return { result, worktreeCwd, worktreesHome };
}
function runRuntimeProvision(baseCwd, worktreeCwd) {
const worktreesHome = makeTempDir("paperclip-provision-runtime-home-");
return spawnSync("bash", [runtimeScript], {
cwd: worktreeCwd,
encoding: "utf8",
env: {
PATH: testPath,
HOME: os.homedir(),
PAPERCLIP_WORKSPACE_BASE_CWD: baseCwd,
PAPERCLIP_WORKSPACE_CWD: worktreeCwd,
PAPERCLIP_WORKSPACE_BRANCH: "feature/provision-runtime-test",
PAPERCLIP_WORKTREES_DIR: worktreesHome,
PAPERCLIP_HOME: path.join(worktreesHome, "no-such-instance-home"),
},
});
}
function readCliInvocations(baseCwd) {
const logPath = path.join(baseCwd, "cli-invocations.log");
if (!fs.existsSync(logPath)) return [];
return fs
.readFileSync(logPath, "utf8")
.trim()
.split("\n")
.filter(Boolean)
.map((line) => JSON.parse(line));
}
function readWorktreeConfig(worktreeCwd) {
const configPath = path.join(worktreeCwd, ".paperclip", "config.json");
assert.ok(fs.existsSync(configPath), `expected ${configPath} to exist`);
@@ -98,6 +137,14 @@ test("uses the base CLI when its import graph boots", () => {
assert.equal(result.status, 0, result.stderr);
const config = readWorktreeConfig(worktreeCwd);
assert.equal(config.$meta.source, "fake-cli");
assert.ok(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-pending")));
const initInvocation = readCliInvocations(baseCwd).find(
(args) => args[0] === "worktree" && args[1] === "init",
);
assert.ok(
initInvocation?.includes("--no-seed"),
`expected --no-seed in ${JSON.stringify(initInvocation)}`,
);
});
test("falls back to an isolated config when the base CLI cannot boot", () => {
@@ -119,6 +166,7 @@ test("falls back to an isolated config when the base CLI cannot boot", () => {
);
const env = fs.readFileSync(path.join(worktreeCwd, ".paperclip", ".env"), "utf8");
assert.match(env, /PAPERCLIP_IN_WORKTREE=true/);
assert.ok(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-pending")));
});
test("repairs an unhealthy base install under the lock and then uses the CLI", (t) => {
@@ -202,3 +250,43 @@ test("a failed CLI init fails provisioning instead of being masked as success",
assert.match(result.stderr, /fake worktree init failure/);
assert.ok(!fs.existsSync(path.join(worktreeCwd, ".paperclip", "config.json")));
});
test("runtime provisioning invokes ensure-seeded once and fast-exits after success", () => {
const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0 });
const worktreeCwd = makeTempDir("paperclip-provision-runtime-worktree-");
fs.mkdirSync(path.join(worktreeCwd, ".paperclip"), { recursive: true });
fs.writeFileSync(path.join(worktreeCwd, ".paperclip", "config.json"), "{}\n");
fs.writeFileSync(path.join(worktreeCwd, ".paperclip", "seed-pending"), "{}\n");
const first = runRuntimeProvision(baseCwd, worktreeCwd);
assert.equal(first.status, 0, first.stderr);
assert.ok(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-complete")));
assert.ok(!fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-pending")));
const ensureCallsAfterFirst = readCliInvocations(baseCwd)
.filter((args) => args[0] === "worktree" && args[1] === "ensure-seeded");
assert.equal(ensureCallsAfterFirst.length, 1);
assert.ok(ensureCallsAfterFirst[0].includes("--config"));
assert.ok(ensureCallsAfterFirst[0].includes("--from-config"));
const second = runRuntimeProvision(baseCwd, worktreeCwd);
assert.equal(second.status, 0, second.stderr);
assert.match(second.stderr, /already seeded; skipping/);
const ensureCallsAfterSecond = readCliInvocations(baseCwd)
.filter((args) => args[0] === "worktree" && args[1] === "ensure-seeded");
assert.equal(ensureCallsAfterSecond.length, 1);
});
test("runtime provisioning leaves seed-pending in place when ensure-seeded fails", () => {
const baseCwd = makeBaseWorkspace({ helpExit: 0, initExit: 0, ensureExit: 4 });
const worktreeCwd = makeTempDir("paperclip-provision-runtime-failure-");
fs.mkdirSync(path.join(worktreeCwd, ".paperclip"), { recursive: true });
fs.writeFileSync(path.join(worktreeCwd, ".paperclip", "config.json"), "{}\n");
fs.writeFileSync(path.join(worktreeCwd, ".paperclip", "seed-pending"), "{}\n");
const result = runRuntimeProvision(baseCwd, worktreeCwd);
assert.equal(result.status, 4, result.stderr);
assert.match(result.stderr, /fake worktree ensure-seeded failure/);
assert.ok(fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-pending")));
assert.ok(!fs.existsSync(path.join(worktreeCwd, ".paperclip", "seed-complete")));
});
+7 -1
View File
@@ -8,7 +8,7 @@ import { stdin, stdout } from "node:process";
import { createCapturedOutputBuffer, parseJsonResponseWithLimit } from "./dev-runner-output.ts";
import { collectWatchedSnapshot as collectDevServerWatchedSnapshot, diffSnapshots } from "./dev-runner-snapshot.mjs";
import { createDevServiceIdentity, repoRoot } from "./dev-service-profile.ts";
import { bootstrapDevRunnerWorktreeEnv } from "../server/src/dev-runner-worktree.ts";
import { bootstrapDevRunnerWorktreeEnv, isWorktreeSeedPending } from "../server/src/dev-runner-worktree.ts";
import {
findAdoptableLocalService,
removeLocalServiceRegistryRecord,
@@ -28,6 +28,12 @@ if (worktreeEnvBootstrap.missingEnv) {
);
process.exit(1);
}
if (isWorktreeSeedPending(repoRoot)) {
console.error(
"[paperclip] this worktree database is seed-pending. Run `pnpm paperclipai worktree ensure-seeded` before `pnpm dev`.",
);
process.exit(1);
}
const mode = process.argv[2] === "watch" ? "watch" : "dev";
const cliArgs = process.argv.slice(3);
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env bash
set -euo pipefail
base_cwd="${PAPERCLIP_WORKSPACE_BASE_CWD:?PAPERCLIP_WORKSPACE_BASE_CWD is required}"
worktree_cwd="${PAPERCLIP_WORKSPACE_CWD:?PAPERCLIP_WORKSPACE_CWD is required}"
paperclip_home="${PAPERCLIP_HOME:-$HOME/.paperclip}"
paperclip_instance_id="${PAPERCLIP_INSTANCE_ID:-default}"
paperclip_dir="$worktree_cwd/.paperclip"
worktree_config_path="$paperclip_dir/config.json"
seed_pending_marker_path="$paperclip_dir/seed-pending"
seed_complete_marker_path="$paperclip_dir/seed-complete"
if [[ ! -d "$base_cwd" ]]; then
echo "Base workspace does not exist: $base_cwd" >&2
exit 1
fi
if [[ ! -d "$worktree_cwd" ]]; then
echo "Derived worktree does not exist: $worktree_cwd" >&2
exit 1
fi
if [[ -e "$seed_complete_marker_path" || ! -e "$seed_pending_marker_path" ]]; then
echo "Worktree database is already seeded; skipping runtime provisioning." >&2
exit 0
fi
if [[ ! -f "$worktree_config_path" ]]; then
echo "Worktree config does not exist: $worktree_config_path" >&2
exit 1
fi
source_config_path="${PAPERCLIP_CONFIG:-}"
if [[ -z "$source_config_path" && ( -e "$base_cwd/.paperclip/config.json" || -L "$base_cwd/.paperclip/config.json" ) ]]; then
source_config_path="$base_cwd/.paperclip/config.json"
fi
if [[ -z "$source_config_path" ]]; then
source_config_path="$paperclip_home/instances/$paperclip_instance_id/config.json"
fi
source_config_args=(--from-config "$source_config_path")
if [[ "$source_config_path" == "$worktree_config_path" ]]; then
# A human may invoke this after sourcing `worktree env`, which points
# PAPERCLIP_CONFIG at the target. In that case the CLI reads the original
# source config from the seed-pending marker instead.
source_config_args=()
fi
base_cli_runner_path="$base_cwd/cli/node_modules/tsx/dist/cli.mjs"
base_cli_entry_path="$base_cwd/cli/src/index.ts"
base_cli_files_present() {
[[ -f "$base_cli_runner_path" && -f "$base_cli_entry_path" ]]
}
base_cli_healthy() {
base_cli_files_present || return 1
(cd "$base_cwd" && node "$base_cli_runner_path" "$base_cli_entry_path" --help >/dev/null 2>&1)
}
repair_base_workspace_install() {
command -v pnpm >/dev/null 2>&1 || return 1
[[ -f "$base_cwd/package.json" && -f "$base_cwd/pnpm-lock.yaml" ]] || return 1
echo "Base workspace CLI at $base_cli_entry_path failed its health check (typically dangling pnpm symlinks after a partial install); repairing with pnpm install in $base_cwd." >&2
local repair_cmd=(pnpm install --prod=false --force --frozen-lockfile --config.confirmModulesPurge=false)
local repair_lock_dir=""
if command -v git >/dev/null 2>&1; then
repair_lock_dir="$(git -C "$base_cwd" rev-parse --absolute-git-dir 2>/dev/null || true)"
fi
if [[ ! -d "$repair_lock_dir" && -d "$base_cwd/.git" ]]; then
repair_lock_dir="$base_cwd/.git"
fi
if command -v flock >/dev/null 2>&1 && [[ -d "$repair_lock_dir" ]]; then
(
cd "$base_cwd" || exit 1
exec 9>"$repair_lock_dir/paperclip-provision-repair.lock"
flock 9
if base_cli_healthy; then
echo "Base workspace CLI became healthy while waiting for the repair lock; skipping reinstall." >&2
exit 0
fi
env -u NODE_ENV CI=true "${repair_cmd[@]}" >&2 || exit 1
base_cli_healthy
)
else
(cd "$base_cwd" && env -u NODE_ENV CI=true "${repair_cmd[@]}" >&2 && base_cli_healthy)
fi
}
ensure_base_cli_healthy() {
base_cli_files_present || return 1
base_cli_healthy && return 0
repair_base_workspace_install
}
run_ensure_seeded() {
if ensure_base_cli_healthy; then
(
cd "$worktree_cwd" &&
node "$base_cli_runner_path" "$base_cli_entry_path" worktree ensure-seeded --config "$worktree_config_path" "${source_config_args[@]}"
)
return
fi
if command -v pnpm >/dev/null 2>&1 && pnpm paperclipai --help >/dev/null 2>&1; then
(
cd "$worktree_cwd" &&
pnpm paperclipai worktree ensure-seeded --config "$worktree_config_path" "${source_config_args[@]}"
)
return
fi
if command -v paperclipai >/dev/null 2>&1; then
(
cd "$worktree_cwd" &&
paperclipai worktree ensure-seeded --config "$worktree_config_path" "${source_config_args[@]}"
)
return
fi
return 127
}
if run_ensure_seeded; then
exit 0
else
exit_code=$?
if [[ "$exit_code" -eq 127 ]]; then
echo "No usable paperclipai CLI found; cannot seed the worktree database." >&2
fi
exit "$exit_code"
fi
+36 -3
View File
@@ -8,7 +8,10 @@ paperclip_instance_id="${PAPERCLIP_INSTANCE_ID:-default}"
paperclip_dir="$worktree_cwd/.paperclip"
worktree_config_path="$paperclip_dir/config.json"
worktree_env_path="$paperclip_dir/.env"
seed_pending_marker_path="$paperclip_dir/seed-pending"
seed_complete_marker_path="$paperclip_dir/seed-complete"
worktree_name="${PAPERCLIP_WORKSPACE_BRANCH:-$(basename "$worktree_cwd")}"
created_worktree_config=0
worktree_instance_id="$(WORKTREE_CWD="$worktree_cwd" node <<'EOF'
const crypto = require("node:crypto");
const path = require("node:path");
@@ -111,7 +114,7 @@ run_isolated_worktree_init() {
if ensure_base_cli_healthy; then
(
cd "$worktree_cwd" &&
node "$base_cli_runner_path" "$base_cli_entry_path" worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
node "$base_cli_runner_path" "$base_cli_entry_path" worktree init --force --no-seed --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
)
return
fi
@@ -119,7 +122,7 @@ run_isolated_worktree_init() {
if command -v pnpm >/dev/null 2>&1 && pnpm paperclipai --help >/dev/null 2>&1; then
(
cd "$worktree_cwd" &&
pnpm paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
pnpm paperclipai worktree init --force --no-seed --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
)
return
fi
@@ -127,7 +130,7 @@ run_isolated_worktree_init() {
if command -v paperclipai >/dev/null 2>&1; then
(
cd "$worktree_cwd" &&
paperclipai worktree init --force --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
paperclipai worktree init --force --no-seed --seed-mode minimal --name "$worktree_name" --instance "$worktree_instance_id" --from-config "$source_config_path"
)
return
fi
@@ -234,6 +237,31 @@ for (const rawValue of runtimePaths) {
EOF
}
write_seed_pending_marker() {
SEED_PENDING_MARKER_PATH="$seed_pending_marker_path" \
SEED_COMPLETE_MARKER_PATH="$seed_complete_marker_path" \
SOURCE_CONFIG_PATH="$source_config_path" \
node <<'EOF'
const fs = require("node:fs");
const path = require("node:path");
const pendingPath = process.env.SEED_PENDING_MARKER_PATH;
const completePath = process.env.SEED_COMPLETE_MARKER_PATH;
fs.rmSync(completePath, { force: true });
fs.writeFileSync(
pendingPath,
`${JSON.stringify({
version: 1,
state: "pending",
sourceConfigPath: path.resolve(process.env.SOURCE_CONFIG_PATH),
seedMode: "minimal",
createdAt: new Date().toISOString(),
}, null, 2)}\n`,
{ mode: 0o600 },
);
EOF
}
write_fallback_worktree_config() {
WORKTREE_NAME="$worktree_name" \
BASE_CWD="$base_cwd" \
@@ -520,6 +548,11 @@ else
echo "paperclipai worktree init unavailable; writing isolated fallback config without DB seeding." >&2
write_fallback_worktree_config
fi
created_worktree_config=1
fi
if [[ "$created_worktree_config" -eq 1 && ! -e "$seed_pending_marker_path" && ! -e "$seed_complete_marker_path" ]]; then
write_seed_pending_marker
fi
list_base_node_modules_paths() {