@xzzpig/pi-subagents 0.13.0 → 0.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +243 -0
- package/README.md +6 -5
- package/agents/evidence-auditor.md +34 -0
- package/agents/researcher.md +23 -13
- package/agents/reviewer.md +3 -2
- package/docs/agents.md +56 -15
- package/docs/configuration.md +93 -15
- package/docs/extension-api.md +132 -19
- package/docs/missions.md +10 -2
- package/docs/models.md +11 -22
- package/docs/observability.md +67 -11
- package/docs/standalone-background.md +59 -0
- package/docs/tool-reference.md +42 -23
- package/docs/watchdog.md +39 -10
- package/docs/workflows.md +58 -19
- package/index.ts +5 -2
- package/inspector-runner.mjs +2 -2
- package/node_modules/@xzzpig/pi-components/CHANGELOG.md +19 -0
- package/node_modules/@xzzpig/pi-components/README.md +28 -0
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +46 -4
- package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +65 -17
- package/node_modules/@xzzpig/pi-components/package.json +1 -1
- package/node_modules/@xzzpig/pi-components/src/transcript.ts +107 -14
- package/package.json +10 -5
- package/prompts/parallel-review.md +1 -1
- package/runner-peer-loader.mjs +24 -0
- package/runner-peer-preload.mjs +36 -0
- package/skills/pi-subagents/SKILL.md +34 -22
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
- package/skills/pi-subagents/references/execution-controls.md +27 -8
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
- package/skills/pi-subagents/references/review-and-validation.md +3 -3
- package/src/agents/advertised-agent-prompt.ts +94 -0
- package/src/agents/agent-management.ts +71 -59
- package/src/agents/agent-serializer.ts +6 -3
- package/src/agents/agents.ts +198 -72
- package/src/agents/builtin-names.ts +1 -0
- package/src/agents/chain-serializer.ts +5 -0
- package/src/agents/runtime-agent-registry.ts +7 -6
- package/src/api/delegation.ts +4 -0
- package/src/api/preflight.ts +110 -71
- package/src/api/required-child-extensions.ts +6 -0
- package/src/api/shared-types.ts +3 -1
- package/src/api/workflow-resources.ts +6 -0
- package/src/extension/config.ts +14 -37
- package/src/extension/fanout-child.ts +68 -5
- package/src/extension/herdr-pi-bridge.ts +164 -0
- package/src/extension/index.ts +141 -51
- package/src/extension/public-execution.ts +7 -6
- package/src/extension/rpc.ts +8 -21
- package/src/extension/schemas.ts +86 -84
- package/src/extension/tool-description.ts +32 -79
- package/src/inspectors/actions.ts +148 -0
- package/src/inspectors/ghostty/actions.ts +74 -0
- package/src/inspectors/ghostty/plugin.ts +17 -0
- package/src/inspectors/herdr/actions.ts +99 -179
- package/src/inspectors/herdr/plugin.ts +20 -0
- package/src/inspectors/herdr/project-panes.ts +4 -1
- package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
- package/src/inspectors/plugins.ts +8 -0
- package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
- package/src/inspectors/types.ts +51 -0
- package/src/integrations/pi-web-session-liveness.ts +73 -0
- package/src/intercom/intercom-bridge.ts +50 -8
- package/src/intercom/native-supervisor-channel.ts +142 -115
- package/src/intercom/supervisor-ui.ts +3 -2
- package/src/missions/workflow-state.ts +37 -16
- package/src/policy/authority.ts +4 -0
- package/src/profiles/profiles.ts +12 -6
- package/src/runs/background/active-async-capacity.ts +22 -18
- package/src/runs/background/active-run-index.ts +17 -1
- package/src/runs/background/async-execution.ts +359 -176
- package/src/runs/background/async-job-tracker.ts +41 -7
- package/src/runs/background/async-resume.ts +19 -12
- package/src/runs/background/async-retention.ts +20 -0
- package/src/runs/background/async-status-snapshot.ts +10 -12
- package/src/runs/background/async-status.ts +32 -13
- package/src/runs/background/auto-drain.ts +59 -35
- package/src/runs/background/binary-bootstrap.ts +38 -0
- package/src/runs/background/chain-append.ts +1 -1
- package/src/runs/background/chain-root-attachment.ts +22 -33
- package/src/runs/background/control-channel.ts +78 -44
- package/src/runs/background/fleet-view.ts +30 -2
- package/src/runs/background/notify.ts +193 -19
- package/src/runs/background/owned-process-tree.ts +35 -8
- package/src/runs/background/process-terminal.ts +23 -23
- package/src/runs/background/result-files.ts +8 -4
- package/src/runs/background/result-watcher.ts +19 -2
- package/src/runs/background/retained-nested-route-tracker.ts +96 -0
- package/src/runs/background/run-child-session.ts +118 -41
- package/src/runs/background/run-status.ts +78 -5
- package/src/runs/background/runner-aliases.ts +22 -5
- package/src/runs/background/runner-child-launch.ts +93 -0
- package/src/runs/background/runner-child-sessions.ts +5 -4
- package/src/runs/background/runner-http-dispatcher.ts +119 -0
- package/src/runs/background/scheduled-runs.ts +51 -18
- package/src/runs/background/stale-run-reconciler.ts +38 -12
- package/src/runs/background/steering.ts +20 -2
- package/src/runs/background/subagent-runner.ts +766 -432
- package/src/runs/background/subagent-wait.ts +179 -28
- package/src/runs/background/wait-completions.ts +79 -27
- package/src/runs/background/wait-subscriptions.ts +9 -3
- package/src/runs/background/wait-tool.ts +5 -3
- package/src/runs/foreground/async-steering-action.ts +37 -7
- package/src/runs/foreground/async-stop-action.ts +93 -3
- package/src/runs/foreground/execution.ts +174 -194
- package/src/runs/foreground/foreground-history.ts +5 -2
- package/src/runs/foreground/prompt-audit.ts +12 -6
- package/src/runs/foreground/subagent-executor.ts +896 -397
- package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
- package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
- package/src/runs/shared/acceptance.ts +54 -14
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +172 -78
- package/src/runs/shared/capability-ceiling.ts +2 -0
- package/src/runs/shared/child-hooks.ts +167 -3
- package/src/runs/shared/child-launch-plan.ts +15 -3
- package/src/runs/shared/child-launch.ts +44 -16
- package/src/runs/shared/child-lifecycle.ts +6 -3
- package/src/runs/shared/child-runtime-config.ts +8 -1
- package/src/runs/shared/child-session.ts +130 -24
- package/src/runs/shared/child-tool-plan.ts +145 -14
- package/src/runs/shared/completion-evidence.ts +2 -2
- package/src/runs/shared/completion-guard.ts +6 -3
- package/src/runs/shared/dynamic-fanout.ts +2 -2
- package/src/runs/shared/effective-system-prompt.ts +33 -0
- package/src/runs/shared/external-cli-contract.ts +11 -1
- package/src/runs/shared/external-cli-preflight.ts +6 -2
- package/src/runs/shared/external-cli-runner.ts +9 -7
- package/src/runs/shared/herdr-connection.ts +134 -0
- package/src/runs/shared/herdr-external-adapters.ts +169 -0
- package/src/runs/shared/herdr-machine.ts +279 -0
- package/src/runs/shared/herdr-pi-protocol.ts +59 -0
- package/src/runs/shared/herdr-placed-run.ts +263 -0
- package/src/runs/shared/host-step-status.ts +11 -11
- package/src/runs/shared/llm-intent-arbiter.ts +40 -21
- package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
- package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
- package/src/runs/shared/model-scope.ts +1 -1
- package/src/runs/shared/nested-events.ts +19 -10
- package/src/runs/shared/orca-progress-tabs.ts +7 -1
- package/src/runs/shared/parallel-handoff.ts +57 -12
- package/src/runs/shared/parallel-utils.ts +10 -4
- package/src/runs/shared/pi-spawn.ts +10 -0
- package/src/runs/shared/readonly-drain-observation.ts +42 -0
- package/src/runs/shared/run-fanout-budget.ts +8 -8
- package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
- package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
- package/src/runs/shared/task-intent.ts +46 -13
- package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
- package/src/runs/shared/worktree-setup-command.ts +213 -0
- package/src/runs/shared/worktree.ts +437 -214
- package/src/shared/child-cache-retention.ts +43 -0
- package/src/shared/fork-context.ts +15 -72
- package/src/shared/launch-contract.ts +70 -8
- package/src/shared/model-response-aliases.ts +13 -0
- package/src/shared/opencode-session-headers.ts +30 -0
- package/src/shared/pruned-fork.ts +1 -1
- package/src/shared/required-child-extensions.ts +81 -0
- package/src/shared/settings.ts +5 -2
- package/src/shared/shortcuts.ts +0 -4
- package/src/shared/types.ts +164 -90
- package/src/shared/utils.ts +10 -2
- package/src/shared/watch-strategy.ts +2 -0
- package/src/shared/workflow-child-permit.ts +18 -13
- package/src/slash/delegation-adapters.ts +3 -1
- package/src/slash/delegation-request.ts +14 -0
- package/src/slash/slash-commands.ts +2 -7
- package/src/slash/subagents-admin.ts +31 -14
- package/src/tui/fleet-native-transcript.ts +50 -6
- package/src/tui/fleet-status.ts +165 -20
- package/src/tui/fleet.ts +52 -21
- package/src/tui/render.ts +210 -50
- package/src/watchdog/child-status.ts +28 -28
- package/src/watchdog/lsp-diagnostics.ts +1 -1
- package/src/watchdog/model-selection.ts +21 -1
- package/src/watchdog/permission-arbiter.ts +5 -2
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/register-main.ts +39 -35
- package/src/watchdog/render.ts +1 -1
- package/src/watchdog/review.ts +122 -74
- package/src/watchdog/rules.ts +1 -1
- package/src/watchdog/runtime.ts +100 -27
- package/src/watchdog/scope.ts +1 -1
- package/src/watchdog/settings.ts +3 -0
- package/src/watchdog/tool-actions.ts +13 -12
- package/src/watchdog/turn-delta.ts +23 -0
- package/src/watchdog/types.ts +5 -3
- package/src/watchdog/warning-format.ts +1 -1
- package/src/workflows/chat-progress.ts +3 -3
- package/src/workflows/scripted-workflow.ts +349 -26
- package/src/workflows/workflow-checklist.ts +17 -20
- package/src/workflows/workflow-child-summary.ts +57 -8
- package/src/workflows/workflow-preflight.ts +19 -19
- package/src/workflows/workflow-receipt.ts +24 -6
- package/src/workflows/workflow-resources.ts +108 -22
- package/src/workflows/workflow-settlement.ts +3 -0
- package/src/runs/shared/model-exclusions.ts +0 -373
- /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
|
+
import { runSetupCommand, type SetupCommandOptions, type SetupCommandResult } from "./worktree-setup-command.ts";
|
|
3
4
|
import * as fs from "node:fs";
|
|
4
5
|
import * as os from "node:os";
|
|
5
6
|
import * as path from "node:path";
|
|
@@ -17,6 +18,11 @@ const WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
|
|
|
17
18
|
const WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
|
|
18
19
|
const WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
|
|
19
20
|
const WORKTREE_COMMAND_OUTPUT_MAX_BYTES = 128 * 1024;
|
|
21
|
+
const WORKTRUNK_COMMAND = process.platform === "win32" ? "git" : "wt";
|
|
22
|
+
const WORKTRUNK_ARG_PREFIX = process.platform === "win32" ? ["wt"] : [];
|
|
23
|
+
export const MACHINE_DIFF_OPTIONS = ["--no-color", "--no-ext-diff", "--no-textconv", "--default-prefix", "--line-prefix=", "--no-relative"] as const;
|
|
24
|
+
const MACHINE_PATCH_OPTIONS = [...MACHINE_DIFF_OPTIONS, "--binary"] as const;
|
|
25
|
+
const PATCH_VALIDATION_OPTIONS = ["apply", "--check", "--cached", "--reverse", "--binary", "--whitespace=nowarn"] as const;
|
|
20
26
|
|
|
21
27
|
export interface WorktreeNamingInput {
|
|
22
28
|
runId: string;
|
|
@@ -115,6 +121,10 @@ interface WorktreeSetupHookConfig {
|
|
|
115
121
|
}
|
|
116
122
|
|
|
117
123
|
export interface CreateWorktreesOptions {
|
|
124
|
+
signal?: AbortSignal;
|
|
125
|
+
/** Existing absolute run deadline only; setup does not start a child budget. */
|
|
126
|
+
deadlineAt?: number;
|
|
127
|
+
onProgress?: (snapshot: WorktreeSetupProgress) => void;
|
|
118
128
|
agents?: string[];
|
|
119
129
|
/** Optional stable labels used to make branch identity readable. */
|
|
120
130
|
labels?: Array<string | undefined>;
|
|
@@ -128,8 +138,6 @@ export interface CreateWorktreesOptions {
|
|
|
128
138
|
branchPrefix?: string;
|
|
129
139
|
setupHook?: WorktreeSetupHookConfig;
|
|
130
140
|
baseDir?: string;
|
|
131
|
-
/** Called with deterministic ownership metadata before setup hooks and child launch; native reports planned paths before allocation, while Worktrunk reports its returned paths after allocation. */
|
|
132
|
-
beforeCreate?: (setup: WorktreeSetup) => void;
|
|
133
141
|
}
|
|
134
142
|
|
|
135
143
|
interface ResolvedWorktreeSetupHook {
|
|
@@ -162,14 +170,112 @@ interface GitResult {
|
|
|
162
170
|
interface RepoState {
|
|
163
171
|
toplevel: string;
|
|
164
172
|
cwdRelative: string;
|
|
165
|
-
sourceCheckout: SourceCheckoutSnapshot;
|
|
166
173
|
baseCommit: string;
|
|
167
174
|
}
|
|
168
175
|
|
|
169
176
|
const DEFAULT_WORKTREE_SETUP_HOOK_TIMEOUT_MS = 30000;
|
|
170
177
|
|
|
171
|
-
|
|
172
|
-
|
|
178
|
+
/** In-memory evidence only. Callers project this into existing handoff diagnostics. */
|
|
179
|
+
export interface WorktreeSetupProgress {
|
|
180
|
+
setup: WorktreeSetup;
|
|
181
|
+
attempts: Array<{ index: number; branch: string; path?: string; validated: boolean; command?: WorktreeSetupProgress["command"]; hookCommand?: WorktreeSetupProgress["command"] }>;
|
|
182
|
+
phase: string;
|
|
183
|
+
command?: { command: string; args: string[]; pid?: number; processGroupId?: number; result?: Omit<SetupCommandResult, "stdout" | "stdoutBuffer" | "stderr"> };
|
|
184
|
+
unknown?: string;
|
|
185
|
+
cleanup?: WorktreeCleanupReport;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
export class WorktreeSetupError extends Error {
|
|
189
|
+
readonly snapshot: WorktreeSetupProgress;
|
|
190
|
+
constructor(error: unknown, snapshot: WorktreeSetupProgress) {
|
|
191
|
+
super(`${error instanceof Error ? error.message : String(error)}${snapshot.unknown ? `; setup settlement unknown: ${snapshot.unknown}; manual reconciliation required` : ""}`, { cause: error });
|
|
192
|
+
this.name = "WorktreeSetupError";
|
|
193
|
+
this.snapshot = snapshot;
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
let worktreeTurn: Promise<void> = Promise.resolve();
|
|
198
|
+
let setupActive = false;
|
|
199
|
+
let setupPoison: string | undefined;
|
|
200
|
+
|
|
201
|
+
function assertWorktreeMutationAllowed(): void {
|
|
202
|
+
if (setupPoison) throw new Error(`Worktree mutation blocked: ${setupPoison}`);
|
|
203
|
+
if (setupActive) throw new Error("Worktree setup is active; finalization must await withWorktreeTransaction");
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Later async finalization owners wrap their synchronous diff/cleanup as ONE turn. */
|
|
207
|
+
export async function withWorktreeTransaction<T>(action: () => T | Promise<T>): Promise<T> {
|
|
208
|
+
const previous = worktreeTurn;
|
|
209
|
+
let release!: () => void;
|
|
210
|
+
worktreeTurn = new Promise<void>((resolve) => { release = resolve; });
|
|
211
|
+
await previous;
|
|
212
|
+
try {
|
|
213
|
+
if (setupPoison) throw new Error(`Worktree mutation blocked: ${setupPoison}`);
|
|
214
|
+
return await action();
|
|
215
|
+
} finally { release(); }
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
class SetupTransaction {
|
|
219
|
+
readonly progress: WorktreeSetupProgress;
|
|
220
|
+
readonly options: CreateWorktreesOptions;
|
|
221
|
+
constructor(cwd: string, options: CreateWorktreesOptions) {
|
|
222
|
+
this.options = options;
|
|
223
|
+
this.progress = { setup: { cwd, baseCommit: "", worktrees: [] }, attempts: [], phase: "preflight" };
|
|
224
|
+
}
|
|
225
|
+
snapshot(): WorktreeSetupProgress {
|
|
226
|
+
return structuredClone(this.progress);
|
|
227
|
+
}
|
|
228
|
+
publish(): void { this.options.onProgress?.(this.snapshot()); }
|
|
229
|
+
check(): void {
|
|
230
|
+
if (setupPoison) throw new Error(setupPoison);
|
|
231
|
+
if (this.options.signal?.aborted) throw new Error("Worktree setup aborted");
|
|
232
|
+
if (this.options.deadlineAt !== undefined && Date.now() >= this.options.deadlineAt) throw new Error("Worktree setup deadline exceeded");
|
|
233
|
+
}
|
|
234
|
+
unknown(error: unknown): void {
|
|
235
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
236
|
+
this.progress.unknown ??= reason;
|
|
237
|
+
setupPoison ??= reason;
|
|
238
|
+
}
|
|
239
|
+
async command(command: string, args: string[], options: SetupCommandOptions = {}): Promise<SetupCommandResult> {
|
|
240
|
+
this.check();
|
|
241
|
+
this.progress.command = { command, args };
|
|
242
|
+
if (this.progress.phase === "allocation") this.progress.attempts.at(-1)!.command = this.progress.command;
|
|
243
|
+
if (this.progress.phase === "hook") this.progress.attempts.find((attempt) => attempt.path === options.cwd)!.hookCommand = this.progress.command;
|
|
244
|
+
const result = await runSetupCommand(command, args, {
|
|
245
|
+
...options, signal: this.options.signal, deadlineAt: this.options.deadlineAt,
|
|
246
|
+
onSpawn: (process) => { Object.assign(this.progress.command!, process); this.publish(); },
|
|
247
|
+
});
|
|
248
|
+
const { stdout: _stdout, stdoutBuffer: _stdoutBuffer, stderr: _stderr, ...metadata } = result;
|
|
249
|
+
this.progress.command.result = metadata;
|
|
250
|
+
if (result.processTree?.state === "unknown") this.unknown(result.error ?? "Command tree settlement unverified");
|
|
251
|
+
this.publish();
|
|
252
|
+
if (result.error) throw result.error;
|
|
253
|
+
return result;
|
|
254
|
+
}
|
|
255
|
+
async git(cwd: string, args: string[], acceptedExitCodes?: readonly number[]): Promise<SetupCommandResult> {
|
|
256
|
+
return this.command("git", ["-C", cwd, ...args], { acceptedExitCodes });
|
|
257
|
+
}
|
|
258
|
+
async gitChecked(cwd: string, args: string[]): Promise<string> {
|
|
259
|
+
const result = await this.git(cwd, args);
|
|
260
|
+
return result.stdout;
|
|
261
|
+
}
|
|
262
|
+
attempt(index: number, branch: string, worktreePath?: string): void {
|
|
263
|
+
this.check();
|
|
264
|
+
this.progress.phase = "allocation";
|
|
265
|
+
this.progress.command = undefined;
|
|
266
|
+
this.progress.attempts.push({ index, branch, path: worktreePath, validated: false });
|
|
267
|
+
this.publish();
|
|
268
|
+
}
|
|
269
|
+
validated(worktree: WorktreeInfo): void {
|
|
270
|
+
this.progress.phase = "validated";
|
|
271
|
+
Object.assign(this.progress.attempts.at(-1)!, { path: worktree.path, validated: true });
|
|
272
|
+
this.progress.setup.worktrees.push(worktree);
|
|
273
|
+
this.publish();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function runGit(cwd: string, args: string[], env?: NodeJS.ProcessEnv): GitResult {
|
|
278
|
+
const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true, shell: false, ...(env ? { env: { ...process.env, ...env } } : {}) });
|
|
173
279
|
return {
|
|
174
280
|
stdout: result.stdout ?? "",
|
|
175
281
|
stderr: result.stderr ?? "",
|
|
@@ -187,38 +293,97 @@ function runGitChecked(cwd: string, args: string[]): string {
|
|
|
187
293
|
return result.stdout;
|
|
188
294
|
}
|
|
189
295
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
296
|
+
/** Validate a captured patch against the worktree index without changing either. */
|
|
297
|
+
export function validateWorktreePatch(worktreePath: string, patchPath: string): string | undefined {
|
|
298
|
+
const result = runGit(worktreePath, [...PATCH_VALIDATION_OPTIONS, patchPath]);
|
|
299
|
+
if (result.status === 0) return undefined;
|
|
300
|
+
return result.stderr.trim() || result.stdout.trim() || `git -C ${worktreePath} apply --check failed`;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
function currentWorktreePatch(worktreePath: string, baseCommit: string): { patch: string } | { error: string } {
|
|
304
|
+
assertWorktreeMutationAllowed();
|
|
305
|
+
let tempDir: string;
|
|
306
|
+
try {
|
|
307
|
+
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-worktree-index-"));
|
|
308
|
+
} catch (error) {
|
|
309
|
+
return { error: error instanceof Error ? error.message : String(error) };
|
|
196
310
|
}
|
|
311
|
+
const env = { GIT_INDEX_FILE: path.join(tempDir, "index") };
|
|
312
|
+
try {
|
|
313
|
+
const readTree = runGit(worktreePath, ["read-tree", "HEAD"], env);
|
|
314
|
+
if (readTree.status !== 0) return { error: readTree.stderr.trim() || readTree.stdout.trim() || "git read-tree failed" };
|
|
315
|
+
const add = runGit(worktreePath, ["add", "-A"], env);
|
|
316
|
+
if (add.status !== 0) return { error: add.stderr.trim() || add.stdout.trim() || "git add failed" };
|
|
317
|
+
const diff = runGit(worktreePath, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, baseCommit], env);
|
|
318
|
+
if (diff.status !== 0) return { error: diff.stderr.trim() || diff.stdout.trim() || "git diff failed" };
|
|
319
|
+
return { patch: diff.stdout };
|
|
320
|
+
} finally {
|
|
321
|
+
try {
|
|
322
|
+
fs.rmSync(tempDir, { recursive: true, force: true });
|
|
323
|
+
} catch {
|
|
324
|
+
// Cleanup safety depends on preserving the worktree, not on best-effort temp-index deletion.
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
export function validateWorktreePatchRepresentsCurrentWorktree(worktreePath: string, baseCommit: string, patchPath: string): string | undefined {
|
|
330
|
+
const validationError = validateWorktreePatch(worktreePath, patchPath);
|
|
331
|
+
if (validationError) return validationError;
|
|
332
|
+
let capturedPatch: string;
|
|
333
|
+
try {
|
|
334
|
+
capturedPatch = fs.readFileSync(patchPath, "utf-8");
|
|
335
|
+
} catch (error) {
|
|
336
|
+
return error instanceof Error ? error.message : String(error);
|
|
337
|
+
}
|
|
338
|
+
const current = currentWorktreePatch(worktreePath, baseCommit);
|
|
339
|
+
if ("error" in current) return current.error || "failed to capture current worktree patch";
|
|
340
|
+
if (capturedPatch !== current.patch) return "captured handoff patch does not match current worktree changes";
|
|
197
341
|
return undefined;
|
|
198
342
|
}
|
|
199
343
|
|
|
200
|
-
function
|
|
201
|
-
const
|
|
202
|
-
|
|
344
|
+
async function probeWorktreeSource(tx: Pick<SetupTransaction, "git" | "gitChecked">, cwd: string): Promise<string> {
|
|
345
|
+
const repoCheck = await tx.git(cwd, ["rev-parse", "--is-inside-work-tree"], [0, 128]);
|
|
346
|
+
if (repoCheck.status !== 0 || repoCheck.stdout.trim() !== "true") throw new Error("worktree isolation requires a git repository");
|
|
347
|
+
const toplevel = (await tx.gitChecked(cwd, ["rev-parse", "--show-toplevel"])).trim();
|
|
203
348
|
|
|
204
349
|
// pi-subagents writes durable runtime state under .pi/subagents/ by default;
|
|
205
350
|
// that state must not make managed isolation unusable for later runs.
|
|
206
|
-
const status =
|
|
351
|
+
const status = await tx.gitChecked(toplevel, ["status", "--porcelain", "--", `:!${PROJECT_SUBAGENTS_RELATIVE_DIR}`]);
|
|
207
352
|
if (status.trim().length > 0) {
|
|
208
353
|
throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
|
|
209
354
|
}
|
|
355
|
+
return toplevel;
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
/** Read-only admission check; allocation repeats it because source state can change. */
|
|
359
|
+
export async function preflightWorktreeSource(cwd: string, options: Pick<SetupCommandOptions, "signal" | "deadlineAt"> = {}): Promise<void> {
|
|
360
|
+
const git = async (cwd: string, args: string[], acceptedExitCodes: readonly number[] = [0]): Promise<SetupCommandResult> => {
|
|
361
|
+
const result = await runSetupCommand("git", ["-C", cwd, ...args], { ...options, acceptedExitCodes });
|
|
362
|
+
if (result.error) throw result.error;
|
|
363
|
+
if (result.outputIncomplete || result.status === null || !acceptedExitCodes.includes(result.status)) {
|
|
364
|
+
throw new Error(result.stderr.trim().slice(0, 2000) || "Worktree source probe failed");
|
|
365
|
+
}
|
|
366
|
+
return result;
|
|
367
|
+
};
|
|
368
|
+
await probeWorktreeSource({ git, gitChecked: async (cwd, args) => (await git(cwd, args)).stdout }, cwd);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function resolveRepoState(tx: SetupTransaction, cwd: string, requestedBaseRef: string | undefined): Promise<RepoState> {
|
|
372
|
+
const toplevel = await probeWorktreeSource(tx, cwd);
|
|
373
|
+
const rawPrefix = (await tx.gitChecked(cwd, ["rev-parse", "--show-prefix"])).trim();
|
|
374
|
+
const cwdRelative = rawPrefix ? path.normalize(rawPrefix.replace(/[\\/]+$/, "")) : "";
|
|
210
375
|
|
|
211
|
-
const sourceHead = runGitChecked(toplevel, ["rev-parse", "HEAD"]).trim();
|
|
212
|
-
const sourceCheckout = snapshotSourceCheckout(toplevel, sourceHead);
|
|
213
376
|
const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
|
|
214
377
|
let baseCommit: string;
|
|
215
378
|
try {
|
|
216
|
-
|
|
379
|
+
const base = await tx.git(toplevel, ["rev-parse", "--verify", "--end-of-options", `${baseRef}^{commit}`], [0, 128]);
|
|
380
|
+
if (base.status !== 0) throw new Error(base.stderr.trim() || "ref not found");
|
|
381
|
+
baseCommit = base.stdout.trim();
|
|
217
382
|
} catch (error) {
|
|
218
383
|
throw new Error(`baseRef '${baseRef}' could not be resolved to a commit: ${error instanceof Error ? error.message : String(error)}`, { cause: error instanceof Error ? error : undefined });
|
|
219
384
|
}
|
|
220
385
|
if (!baseCommit) throw new Error(`baseRef '${baseRef}' could not be resolved to a commit`);
|
|
221
|
-
return { toplevel, cwdRelative,
|
|
386
|
+
return { toplevel, cwdRelative, baseCommit };
|
|
222
387
|
}
|
|
223
388
|
|
|
224
389
|
function normalizeComparableCwd(cwd: string): string {
|
|
@@ -307,7 +472,7 @@ function validGitRef(ref: string): boolean {
|
|
|
307
472
|
/** Normalize and validate a configured worktree base ref without resolving it. */
|
|
308
473
|
export function normalizeWorktreeBaseRef(value: unknown): string | undefined {
|
|
309
474
|
if (value === undefined) return undefined;
|
|
310
|
-
if (typeof value !== "string" || !validGitRef(value)) throw new Error("baseRef must be a valid Git ref");
|
|
475
|
+
if (typeof value !== "string" || !validGitRef(value)) throw new Error("baseRef must be a valid Git ref: use HEAD or a supported named ref (for example, refs/heads/main). Full 40/64-character commit IDs and revision expressions are unsupported.");
|
|
311
476
|
return value;
|
|
312
477
|
}
|
|
313
478
|
|
|
@@ -381,19 +546,19 @@ function hasConfiguredWorktreeBaseDir(baseDir: string | undefined): boolean {
|
|
|
381
546
|
: (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
|
|
382
547
|
}
|
|
383
548
|
|
|
549
|
+
function isInsidePiExtensionsDirectory(targetPath: string): boolean {
|
|
550
|
+
const extensionsDir = normalizeComparableCwd(path.join(getAgentDir(), "extensions"));
|
|
551
|
+
return isPathInside(extensionsDir, normalizeComparableCwd(targetPath));
|
|
552
|
+
}
|
|
553
|
+
|
|
384
554
|
interface WorktrunkCapability {
|
|
385
555
|
available: boolean;
|
|
386
556
|
reason?: string;
|
|
387
557
|
}
|
|
388
558
|
|
|
389
|
-
interface SourceCheckoutSnapshot {
|
|
390
|
-
head: string;
|
|
391
|
-
branch?: string;
|
|
392
|
-
}
|
|
393
|
-
|
|
394
559
|
function runWorktrunk(args: string[], cwd?: string): WorktreeCommandResult {
|
|
395
560
|
try {
|
|
396
|
-
const result = spawnSync(
|
|
561
|
+
const result = spawnSync(WORKTRUNK_COMMAND, [...WORKTRUNK_ARG_PREFIX, ...args], {
|
|
397
562
|
cwd,
|
|
398
563
|
encoding: "utf-8",
|
|
399
564
|
windowsHide: true,
|
|
@@ -423,18 +588,6 @@ function probeWorktrunk(): WorktrunkCapability {
|
|
|
423
588
|
return { available: true };
|
|
424
589
|
}
|
|
425
590
|
|
|
426
|
-
function snapshotSourceCheckout(toplevel: string, head: string): SourceCheckoutSnapshot {
|
|
427
|
-
const branch = runGit(toplevel, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
428
|
-
const branchName = branch.status === 0 ? branch.stdout.trim() : "";
|
|
429
|
-
return branchName ? { head, branch: branchName } : { head };
|
|
430
|
-
}
|
|
431
|
-
|
|
432
|
-
function restoreSourceCheckoutIfWorktrunkSwitchedIt(toplevel: string, createdBranch: string, sourceCheckout: SourceCheckoutSnapshot): void {
|
|
433
|
-
const current = runGit(toplevel, ["symbolic-ref", "--quiet", "--short", "HEAD"]);
|
|
434
|
-
if (current.status !== 0 || current.stdout.trim() !== createdBranch) return;
|
|
435
|
-
runGitChecked(toplevel, sourceCheckout.branch ? ["checkout", sourceCheckout.branch] : ["checkout", "--detach", sourceCheckout.head]);
|
|
436
|
-
}
|
|
437
|
-
|
|
438
591
|
/** Resolve a requested provider without silently switching after allocation starts. */
|
|
439
592
|
export function resolveWorktreeProvider(requested: WorktreeProvider | undefined, baseDir?: string): ManagedWorktreeProvider {
|
|
440
593
|
const selection = requested ?? DEFAULT_WORKTREE_PROVIDER;
|
|
@@ -450,6 +603,34 @@ export function resolveWorktreeProvider(requested: WorktreeProvider | undefined,
|
|
|
450
603
|
return "native";
|
|
451
604
|
}
|
|
452
605
|
|
|
606
|
+
async function resolveSetupProvider(tx: SetupTransaction, requested: WorktreeProvider | undefined, baseDir: string | undefined, repoRoot: string): Promise<ManagedWorktreeProvider> {
|
|
607
|
+
const selection = requested ?? DEFAULT_WORKTREE_PROVIDER;
|
|
608
|
+
if (selection !== "auto" && selection !== "native" && selection !== "worktrunk") throw new Error('worktree provider must be "auto", "native", or "worktrunk"');
|
|
609
|
+
if (selection === "native") return "native";
|
|
610
|
+
if (hasConfiguredWorktreeBaseDir(baseDir)) {
|
|
611
|
+
if (selection === "worktrunk") throw new Error("worktreeProvider='worktrunk' cannot be combined with worktreeBaseDir or PI_SUBAGENTS_WORKTREE_DIR");
|
|
612
|
+
return "native";
|
|
613
|
+
}
|
|
614
|
+
if (selection === "auto" && isInsidePiExtensionsDirectory(repoRoot)) return "native";
|
|
615
|
+
let reason: string | undefined;
|
|
616
|
+
try {
|
|
617
|
+
const probeExitCodes = Array.from({ length: 256 }, (_, code) => code);
|
|
618
|
+
const version = await tx.command(WORKTRUNK_COMMAND, [...WORKTRUNK_ARG_PREFIX, "--version"], { maxBuffer: WORKTREE_COMMAND_OUTPUT_MAX_BYTES, acceptedExitCodes: probeExitCodes });
|
|
619
|
+
if (version.status !== 0 || !/\b(?:wt\s+)?v?(\d+\.\d+(?:\.\d+)?)\b/i.test(version.stdout.trim())) reason = "Worktrunk is unavailable or returned an invalid version";
|
|
620
|
+
else {
|
|
621
|
+
const help = await tx.command(WORKTRUNK_COMMAND, [...WORKTRUNK_ARG_PREFIX, "switch", "--help"], { maxBuffer: WORKTREE_COMMAND_OUTPUT_MAX_BYTES, acceptedExitCodes: probeExitCodes });
|
|
622
|
+
const missing = ["--create", "--base", "--no-cd", "--no-hooks", "--format"].filter((flag) => !`${help.stdout}\n${help.stderr}`.includes(flag));
|
|
623
|
+
if (help.status !== 0 || missing.length) reason = `Worktrunk switch capability unavailable: ${missing.join(", ")}`;
|
|
624
|
+
}
|
|
625
|
+
} catch (error) {
|
|
626
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
627
|
+
reason = error.message;
|
|
628
|
+
}
|
|
629
|
+
if (!reason) return "worktrunk";
|
|
630
|
+
if (selection === "worktrunk") throw new Error(`Worktrunk provider is unavailable: ${reason}`);
|
|
631
|
+
return "native";
|
|
632
|
+
}
|
|
633
|
+
|
|
453
634
|
/** Whether a launch must bind its worktree-dependent paths after allocation. */
|
|
454
635
|
export function shouldDeferWorktreeCwd(requested: WorktreeProvider | undefined, baseDir?: string): boolean {
|
|
455
636
|
return (requested ?? DEFAULT_WORKTREE_PROVIDER) !== "native" && !hasConfiguredWorktreeBaseDir(baseDir);
|
|
@@ -461,11 +642,13 @@ export function shouldDeferWorktreeCwd(requested: WorktreeProvider | undefined,
|
|
|
461
642
|
* to the repository. Managed leaves always nest one level deeper under the
|
|
462
643
|
* project folder (`basename(repoRoot)`).
|
|
463
644
|
*/
|
|
464
|
-
function resolveWorktreeDedicatedRoot(configuredBaseDir: string | undefined, repoRoot: string): string {
|
|
645
|
+
function resolveWorktreeDedicatedRoot(configuredBaseDir: string | undefined, repoRoot: string, relocateExtensionRepo = true): string {
|
|
465
646
|
const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
|
|
466
647
|
let expanded: string;
|
|
467
648
|
if (rawBaseDir === undefined || (configuredBaseDir === undefined && !rawBaseDir.trim())) {
|
|
468
|
-
expanded =
|
|
649
|
+
expanded = relocateExtensionRepo && isInsidePiExtensionsDirectory(repoRoot)
|
|
650
|
+
? path.join(getAgentDir(), "worktrees")
|
|
651
|
+
: path.join(path.dirname(repoRoot), "worktrees");
|
|
469
652
|
} else {
|
|
470
653
|
const trimmed = rawBaseDir.trim();
|
|
471
654
|
if (!trimmed) throw new Error("worktree base directory cannot be empty");
|
|
@@ -627,11 +810,6 @@ function normalizeSyntheticPath(worktreePath: string, rawPath: string): string {
|
|
|
627
810
|
return path.normalize(relative);
|
|
628
811
|
}
|
|
629
812
|
|
|
630
|
-
function hasTrackedEntries(worktreePath: string, relativePath: string): boolean {
|
|
631
|
-
const result = runGit(worktreePath, ["ls-files", "--", relativePath]);
|
|
632
|
-
return result.status === 0 && result.stdout.trim().length > 0;
|
|
633
|
-
}
|
|
634
|
-
|
|
635
813
|
function parseWorktreeSetupHookOutput(rawStdout: string): WorktreeSetupHookOutput {
|
|
636
814
|
const trimmed = rawStdout.trim();
|
|
637
815
|
if (!trimmed) {
|
|
@@ -650,53 +828,49 @@ function parseWorktreeSetupHookOutput(rawStdout: string): WorktreeSetupHookOutpu
|
|
|
650
828
|
return parsed as WorktreeSetupHookOutput;
|
|
651
829
|
}
|
|
652
830
|
|
|
653
|
-
function runWorktreeSetupHook(
|
|
831
|
+
async function runWorktreeSetupHook(
|
|
832
|
+
tx: SetupTransaction,
|
|
654
833
|
hook: ResolvedWorktreeSetupHook,
|
|
655
834
|
input: WorktreeSetupHookInput,
|
|
656
|
-
): string[] {
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
const code = "code" in result.error ? result.error.code : undefined;
|
|
668
|
-
if (code === "ETIMEDOUT") {
|
|
669
|
-
throw new Error(`worktree setup hook timed out after ${hook.timeoutMs}ms`);
|
|
670
|
-
}
|
|
671
|
-
throw new Error(`worktree setup hook failed: ${result.error.message}`);
|
|
672
|
-
}
|
|
673
|
-
|
|
674
|
-
if (result.status !== 0) {
|
|
675
|
-
const details = result.stderr.trim() || result.stdout.trim() || "no output";
|
|
676
|
-
throw new Error(`worktree setup hook failed with exit code ${result.status}: ${details}`);
|
|
677
|
-
}
|
|
678
|
-
|
|
679
|
-
const output = parseWorktreeSetupHookOutput(result.stdout);
|
|
680
|
-
if (output.syntheticPaths === undefined) return [];
|
|
681
|
-
if (!Array.isArray(output.syntheticPaths)) {
|
|
682
|
-
throw new Error("worktree setup hook output field 'syntheticPaths' must be an array of relative paths");
|
|
835
|
+
): Promise<string[]> {
|
|
836
|
+
tx.progress.phase = "hook";
|
|
837
|
+
let result: SetupCommandResult;
|
|
838
|
+
try {
|
|
839
|
+
result = await tx.command(hook.hookPath, [], {
|
|
840
|
+
cwd: input.worktreePath,
|
|
841
|
+
input: JSON.stringify(input),
|
|
842
|
+
hookTimeoutMs: hook.timeoutMs,
|
|
843
|
+
});
|
|
844
|
+
} catch (error) {
|
|
845
|
+
throw new Error(`worktree setup hook failed: ${error instanceof Error ? error.message : String(error)}`, { cause: error });
|
|
683
846
|
}
|
|
847
|
+
tx.progress.phase = "hook-validation";
|
|
684
848
|
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
if (
|
|
688
|
-
|
|
849
|
+
try {
|
|
850
|
+
const output = parseWorktreeSetupHookOutput(result.stdout);
|
|
851
|
+
if (output.syntheticPaths === undefined) return [];
|
|
852
|
+
if (!Array.isArray(output.syntheticPaths)) {
|
|
853
|
+
throw new Error("worktree setup hook output field 'syntheticPaths' must be an array of relative paths");
|
|
689
854
|
}
|
|
690
|
-
const
|
|
691
|
-
|
|
692
|
-
throw new Error(
|
|
855
|
+
const uniquePaths = new Set<string>();
|
|
856
|
+
for (const candidate of output.syntheticPaths) {
|
|
857
|
+
if (typeof candidate !== "string") throw new Error("worktree setup hook output field 'syntheticPaths' must contain only strings");
|
|
858
|
+
const normalizedPath = normalizeSyntheticPath(input.worktreePath, candidate);
|
|
859
|
+
if ((await tx.gitChecked(input.worktreePath, ["ls-files", "--", normalizedPath])).trim()) {
|
|
860
|
+
throw new Error(`worktree setup hook cannot mark tracked paths as synthetic: ${normalizedPath}`);
|
|
861
|
+
}
|
|
862
|
+
uniquePaths.add(normalizedPath);
|
|
693
863
|
}
|
|
694
|
-
uniquePaths
|
|
864
|
+
return [...uniquePaths];
|
|
865
|
+
} catch (error) {
|
|
866
|
+
// Semantic rejection occurs after exit: retain uncertainty, never signal an old PID.
|
|
867
|
+
tx.unknown(error);
|
|
868
|
+
throw error;
|
|
695
869
|
}
|
|
696
|
-
return [...uniquePaths];
|
|
697
870
|
}
|
|
698
871
|
|
|
699
|
-
function finalizeCreatedWorktree(
|
|
872
|
+
async function finalizeCreatedWorktree(
|
|
873
|
+
tx: SetupTransaction,
|
|
700
874
|
toplevel: string,
|
|
701
875
|
cwdRelative: string,
|
|
702
876
|
runId: string,
|
|
@@ -704,38 +878,23 @@ function finalizeCreatedWorktree(
|
|
|
704
878
|
setupHook: ResolvedWorktreeSetupHook | undefined,
|
|
705
879
|
agent: string | undefined,
|
|
706
880
|
worktree: WorktreeInfo,
|
|
707
|
-
): WorktreeInfo {
|
|
881
|
+
): Promise<WorktreeInfo> {
|
|
708
882
|
const agentCwd = cwdRelative ? path.join(worktree.path, cwdRelative) : worktree.path;
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
branch: worktree.branch,
|
|
719
|
-
index: worktree.index,
|
|
720
|
-
runId,
|
|
721
|
-
baseCommit,
|
|
722
|
-
agent,
|
|
723
|
-
});
|
|
724
|
-
syntheticPaths.push(...hookSyntheticPaths);
|
|
725
|
-
}
|
|
726
|
-
return { ...worktree, agentCwd, nodeModulesLinked, syntheticPaths };
|
|
727
|
-
} catch (error) {
|
|
728
|
-
try { runGitChecked(toplevel, ["worktree", "remove", "--force", worktree.path]); } catch {
|
|
729
|
-
// Best-effort rollback; preserve the original setup failure.
|
|
730
|
-
}
|
|
731
|
-
try { runGitChecked(toplevel, ["branch", "-D", worktree.branch]); } catch {
|
|
732
|
-
// Best-effort rollback; preserve the original setup failure.
|
|
733
|
-
}
|
|
734
|
-
throw error;
|
|
883
|
+
tx.check();
|
|
884
|
+
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
|
|
885
|
+
const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
886
|
+
if (setupHook) {
|
|
887
|
+
const hookSyntheticPaths = await runWorktreeSetupHook(tx, setupHook, {
|
|
888
|
+
version: 1, repoRoot: toplevel, worktreePath: worktree.path, agentCwd,
|
|
889
|
+
branch: worktree.branch, index: worktree.index, runId, baseCommit, agent,
|
|
890
|
+
});
|
|
891
|
+
syntheticPaths.push(...hookSyntheticPaths);
|
|
735
892
|
}
|
|
893
|
+
return { ...worktree, agentCwd, nodeModulesLinked, syntheticPaths };
|
|
736
894
|
}
|
|
737
895
|
|
|
738
|
-
function createNativeWorktree(
|
|
896
|
+
async function createNativeWorktree(
|
|
897
|
+
tx: SetupTransaction,
|
|
739
898
|
toplevel: string,
|
|
740
899
|
cwdRelative: string,
|
|
741
900
|
runId: string,
|
|
@@ -747,17 +906,20 @@ function createNativeWorktree(
|
|
|
747
906
|
labels: Array<string | undefined> | undefined,
|
|
748
907
|
tasks: Array<string | undefined> | undefined,
|
|
749
908
|
branchPrefix: string | undefined,
|
|
750
|
-
): WorktreeInfo {
|
|
909
|
+
): Promise<WorktreeInfo> {
|
|
751
910
|
const naming = buildWorktreeNaming({ runId, index, agent, label: labels?.[index], task: tasks?.[index], branchPrefix });
|
|
752
911
|
const worktreePath = buildNativeWorktreePath(dedicatedRoot, toplevel, runId, index);
|
|
753
912
|
assertSafeWorktreeLocation(worktreePath, toplevel, dedicatedRoot);
|
|
913
|
+
// Absence is required before claiming any partial artifacts from this attempt.
|
|
914
|
+
const branch = await tx.git(toplevel, ["show-ref", "--verify", "--quiet", `refs/heads/${naming.requestedBranch}`], [0, 1]);
|
|
915
|
+
let pathExists = false;
|
|
916
|
+
try { fs.lstatSync(worktreePath); pathExists = true; }
|
|
917
|
+
catch (error) { if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error; }
|
|
918
|
+
if (branch.status !== 1 || pathExists) throw new Error(`worktree path or branch already exists: ${worktreePath}, ${naming.requestedBranch}`);
|
|
919
|
+
tx.attempt(index, naming.requestedBranch, worktreePath);
|
|
754
920
|
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
const message = add.stderr.trim() || add.stdout.trim() || `failed to create worktree ${worktreePath}`;
|
|
758
|
-
throw new Error(message);
|
|
759
|
-
}
|
|
760
|
-
return finalizeCreatedWorktree(toplevel, cwdRelative, runId, baseCommit, setupHook, agent, {
|
|
921
|
+
await tx.git(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
922
|
+
const worktree: WorktreeInfo = {
|
|
761
923
|
path: worktreePath,
|
|
762
924
|
agentCwd: worktreePath,
|
|
763
925
|
branch: naming.requestedBranch,
|
|
@@ -766,7 +928,9 @@ function createNativeWorktree(
|
|
|
766
928
|
syntheticPaths: [],
|
|
767
929
|
provider: "native",
|
|
768
930
|
naming,
|
|
769
|
-
}
|
|
931
|
+
};
|
|
932
|
+
tx.validated(worktree);
|
|
933
|
+
return finalizeCreatedWorktree(tx, toplevel, cwdRelative, runId, baseCommit, setupHook, agent, worktree);
|
|
770
934
|
}
|
|
771
935
|
|
|
772
936
|
interface WorktrunkSwitchOutput {
|
|
@@ -791,37 +955,30 @@ function parseWorktrunkSwitchOutput(rawStdout: string): WorktrunkSwitchOutput {
|
|
|
791
955
|
return parsed as WorktrunkSwitchOutput;
|
|
792
956
|
}
|
|
793
957
|
|
|
794
|
-
function createWorktrunkWorktree(
|
|
958
|
+
async function createWorktrunkWorktree(
|
|
959
|
+
tx: SetupTransaction,
|
|
795
960
|
toplevel: string,
|
|
796
961
|
cwdRelative: string,
|
|
797
962
|
runId: string,
|
|
798
963
|
index: number,
|
|
799
964
|
baseCommit: string,
|
|
800
|
-
sourceCheckout: SourceCheckoutSnapshot,
|
|
801
965
|
agents: string[] | undefined,
|
|
802
966
|
labels: Array<string | undefined> | undefined,
|
|
803
967
|
tasks: Array<string | undefined> | undefined,
|
|
804
968
|
branchPrefix: string | undefined,
|
|
805
|
-
): WorktreeInfo {
|
|
969
|
+
): Promise<WorktreeInfo> {
|
|
806
970
|
const naming = buildWorktreeNaming({ runId, index, agent: agents?.[index], label: labels?.[index], task: tasks?.[index], branchPrefix });
|
|
807
971
|
const args = ["-C", toplevel, "switch", "--create", naming.requestedBranch, "--base", baseCommit, "--no-cd", "--no-hooks", "--format", "json"];
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
throw new Error(`Worktrunk provisioning failed: ${message}`);
|
|
812
|
-
}
|
|
813
|
-
let createdAllocation = false;
|
|
814
|
-
let returnedPath: string | undefined;
|
|
972
|
+
tx.attempt(index, naming.requestedBranch);
|
|
973
|
+
const result = await tx.command(WORKTRUNK_COMMAND, [...WORKTRUNK_ARG_PREFIX, ...args], { cwd: toplevel, maxBuffer: WORKTREE_COMMAND_OUTPUT_MAX_BYTES });
|
|
974
|
+
tx.progress.phase = "validation";
|
|
815
975
|
try {
|
|
816
976
|
const output = parseWorktrunkSwitchOutput(result.stdout);
|
|
817
|
-
|
|
818
|
-
if (typeof output.path === "string" && path.isAbsolute(output.path)) returnedPath = path.resolve(output.path);
|
|
819
|
-
if (!createdAllocation || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
|
|
977
|
+
if (output.action !== "created" || output.created_branch !== true || output.branch !== naming.requestedBranch || output.base_branch !== baseCommit) {
|
|
820
978
|
throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
|
|
821
979
|
}
|
|
822
980
|
if (typeof output.path !== "string" || !path.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
823
|
-
const worktreePathCandidate =
|
|
824
|
-
if (!worktreePathCandidate) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
981
|
+
const worktreePathCandidate = path.resolve(output.path);
|
|
825
982
|
let stat: fs.Stats;
|
|
826
983
|
try {
|
|
827
984
|
stat = fs.lstatSync(worktreePathCandidate);
|
|
@@ -831,16 +988,16 @@ function createWorktrunkWorktree(
|
|
|
831
988
|
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Worktrunk provisioning returned a path that is not a real directory");
|
|
832
989
|
const worktreePath = normalizeComparableCwd(worktreePathCandidate);
|
|
833
990
|
if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
|
|
834
|
-
const sourceCommonDirRaw =
|
|
835
|
-
const returnedCommonDirRaw =
|
|
991
|
+
const sourceCommonDirRaw = (await tx.gitChecked(toplevel, ["rev-parse", "--git-common-dir"])).trim();
|
|
992
|
+
const returnedCommonDirRaw = (await tx.gitChecked(worktreePath, ["rev-parse", "--git-common-dir"])).trim();
|
|
836
993
|
const sourceCommonDir = normalizeComparableCwd(path.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path.resolve(toplevel, sourceCommonDirRaw));
|
|
837
994
|
const returnedCommonDir = normalizeComparableCwd(path.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path.resolve(worktreePath, returnedCommonDirRaw));
|
|
838
995
|
if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
|
|
839
|
-
const returnedBranch =
|
|
996
|
+
const returnedBranch = (await tx.gitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"])).trim();
|
|
840
997
|
if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
|
|
841
|
-
const returnedHead =
|
|
998
|
+
const returnedHead = (await tx.gitChecked(worktreePath, ["rev-parse", "HEAD"])).trim();
|
|
842
999
|
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
843
|
-
|
|
1000
|
+
const worktree: WorktreeInfo = {
|
|
844
1001
|
path: worktreePath,
|
|
845
1002
|
agentCwd: cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath,
|
|
846
1003
|
branch: naming.requestedBranch,
|
|
@@ -850,35 +1007,16 @@ function createWorktrunkWorktree(
|
|
|
850
1007
|
provider: "worktrunk",
|
|
851
1008
|
naming,
|
|
852
1009
|
};
|
|
1010
|
+
tx.validated(worktree);
|
|
1011
|
+
return worktree;
|
|
853
1012
|
} catch (error) {
|
|
854
|
-
|
|
855
|
-
try { restoreSourceCheckoutIfWorktrunkSwitchedIt(toplevel, naming.requestedBranch, sourceCheckout); } catch {
|
|
856
|
-
// Best-effort rollback; preserve the validation failure.
|
|
857
|
-
}
|
|
858
|
-
try {
|
|
859
|
-
const listedPath = findGitWorktreePath(toplevel, naming.requestedBranch);
|
|
860
|
-
const candidates = [listedPath, returnedPath].filter((candidate, candidateIndex, all): candidate is string => Boolean(candidate) && all.indexOf(candidate) === candidateIndex);
|
|
861
|
-
for (const candidate of candidates) {
|
|
862
|
-
if (normalizeComparableCwd(candidate) === normalizeComparableCwd(toplevel)) continue;
|
|
863
|
-
try {
|
|
864
|
-
runGitChecked(toplevel, ["worktree", "remove", "--force", candidate]);
|
|
865
|
-
break;
|
|
866
|
-
} catch {
|
|
867
|
-
// Try another provider-reported/listed path before giving up.
|
|
868
|
-
}
|
|
869
|
-
}
|
|
870
|
-
} catch {
|
|
871
|
-
// Best-effort rollback; preserve the validation failure.
|
|
872
|
-
}
|
|
873
|
-
try { runGitChecked(toplevel, ["branch", "-D", naming.requestedBranch]); } catch {
|
|
874
|
-
// Best-effort rollback; preserve the validation failure.
|
|
875
|
-
}
|
|
876
|
-
}
|
|
1013
|
+
tx.unknown(error);
|
|
877
1014
|
throw error;
|
|
878
1015
|
}
|
|
879
1016
|
}
|
|
880
1017
|
|
|
881
1018
|
function removeSyntheticPath(worktree: WorktreeInfo, syntheticPath: string): void {
|
|
1019
|
+
assertWorktreeMutationAllowed();
|
|
882
1020
|
const resolved = path.resolve(worktree.path, syntheticPath);
|
|
883
1021
|
const relative = path.relative(worktree.path, resolved);
|
|
884
1022
|
if (!relative || relative === "." || relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
@@ -957,15 +1095,18 @@ function captureWorktreeDiff(
|
|
|
957
1095
|
): WorktreeDiff {
|
|
958
1096
|
removeSyntheticPathsBeforeDiff(worktree);
|
|
959
1097
|
runGitChecked(worktree.path, ["add", "-A"]);
|
|
960
|
-
const diffStat = runGitChecked(worktree.path, ["diff", "--cached", "--stat", setup.baseCommit]).trim();
|
|
961
|
-
const patch = runGitChecked(worktree.path, ["diff", "--cached", setup.baseCommit]);
|
|
962
|
-
const numstat = runGitChecked(worktree.path, ["diff", "--cached", "--numstat", setup.baseCommit]);
|
|
1098
|
+
const diffStat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--stat", setup.baseCommit]).trim();
|
|
1099
|
+
const patch = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_PATCH_OPTIONS, setup.baseCommit]);
|
|
1100
|
+
const numstat = runGitChecked(worktree.path, ["diff", "--cached", ...MACHINE_DIFF_OPTIONS, "--numstat", setup.baseCommit]);
|
|
963
1101
|
fs.writeFileSync(patchPath, patch, "utf-8");
|
|
964
1102
|
|
|
965
1103
|
if (!patch.trim()) {
|
|
966
1104
|
return emptyDiff(worktree.index, agent, worktree.branch, patchPath);
|
|
967
1105
|
}
|
|
968
1106
|
|
|
1107
|
+
const validationError = validateWorktreePatch(worktree.path, patchPath);
|
|
1108
|
+
if (validationError) throw new Error(`captured worktree patch is not machine-applyable: ${validationError}`);
|
|
1109
|
+
|
|
969
1110
|
const parsed = parseNumstat(numstat);
|
|
970
1111
|
return {
|
|
971
1112
|
index: worktree.index,
|
|
@@ -1034,7 +1175,7 @@ function cleanupSingleWorktree(
|
|
|
1034
1175
|
errors.push(`synthetic path cleanup failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
1035
1176
|
}
|
|
1036
1177
|
const status = runGit(worktree.path, ["status", "--porcelain"]);
|
|
1037
|
-
const baseDiff = runGit(worktree.path, ["diff", "--quiet", setup.baseCommit, "--"]);
|
|
1178
|
+
const baseDiff = runGit(worktree.path, ["diff", "--quiet", ...MACHINE_DIFF_OPTIONS, setup.baseCommit, "--"]);
|
|
1038
1179
|
if (status.status !== 0 || (baseDiff.status !== 0 && baseDiff.status !== 1)) {
|
|
1039
1180
|
const reason = status.status !== 0
|
|
1040
1181
|
? status.stderr.trim() || status.stdout.trim() || "git status failed"
|
|
@@ -1055,13 +1196,25 @@ function cleanupSingleWorktree(
|
|
|
1055
1196
|
const hasWork = status.stdout.trim().length > 0 || baseDiff.status === 1;
|
|
1056
1197
|
if (hasWork && intent.kind === "preserve") {
|
|
1057
1198
|
const captured = (intent.capturedDiffs ?? setup.capturedDiffs)?.find((diff) => diff.index === worktree.index);
|
|
1058
|
-
|
|
1199
|
+
let patchValidationError: string | undefined;
|
|
1200
|
+
let patchCaptured = false;
|
|
1201
|
+
if (captured !== undefined
|
|
1059
1202
|
&& captured.error === undefined
|
|
1060
1203
|
&& fs.existsSync(captured.patchPath)
|
|
1061
|
-
&&
|
|
1062
|
-
|
|
1204
|
+
&& handoffRecordsPatch(intent.handoffManifestPath, captured.patchPath)) {
|
|
1205
|
+
try {
|
|
1206
|
+
if (fs.statSync(captured.patchPath).size > 0) {
|
|
1207
|
+
patchValidationError = validateWorktreePatchRepresentsCurrentWorktree(worktree.path, setup.baseCommit, captured.patchPath);
|
|
1208
|
+
patchCaptured = patchValidationError === undefined;
|
|
1209
|
+
}
|
|
1210
|
+
} catch (error) {
|
|
1211
|
+
patchValidationError = error instanceof Error ? error.message : String(error);
|
|
1212
|
+
}
|
|
1213
|
+
}
|
|
1063
1214
|
if (!patchCaptured) {
|
|
1064
|
-
const reason =
|
|
1215
|
+
const reason = patchValidationError
|
|
1216
|
+
? `captured handoff patch failed validation: ${patchValidationError}`
|
|
1217
|
+
: "worktree contains changes that are not represented by a captured handoff patch";
|
|
1065
1218
|
return {
|
|
1066
1219
|
index: worktree.index,
|
|
1067
1220
|
path: worktree.path,
|
|
@@ -1128,39 +1281,96 @@ function hasWorktreeChanges(diff: WorktreeDiff): boolean {
|
|
|
1128
1281
|
return diff.filesChanged > 0 || diff.insertions > 0 || diff.deletions > 0 || diff.diffStat.trim().length > 0;
|
|
1129
1282
|
}
|
|
1130
1283
|
|
|
1131
|
-
|
|
1284
|
+
async function compensateSetup(tx: SetupTransaction): Promise<WorktreeCleanupReport> {
|
|
1285
|
+
const { setup, attempts } = tx.progress;
|
|
1286
|
+
const report: WorktreeCleanupReport = { state: "partial", tasks: [], pruned: false, errors: [] };
|
|
1287
|
+
tx.progress.cleanup = report;
|
|
1288
|
+
tx.progress.phase = "rollback";
|
|
1289
|
+
// Cancellation stops allocation, not accounting. Compensation has ONLY the
|
|
1290
|
+
// remaining original absolute deadline; it does not reuse the launch signal.
|
|
1291
|
+
const git = async (args: string[], acceptedExitCodes: readonly number[] = [0]) => {
|
|
1292
|
+
if (setupPoison) throw new Error(setupPoison);
|
|
1293
|
+
tx.progress.command = { command: "git", args: ["-C", setup.cwd, ...args] };
|
|
1294
|
+
const result = await runSetupCommand("git", tx.progress.command.args, {
|
|
1295
|
+
deadlineAt: tx.options.deadlineAt, acceptedExitCodes,
|
|
1296
|
+
onSpawn: (process) => { Object.assign(tx.progress.command!, process); tx.publish(); },
|
|
1297
|
+
});
|
|
1298
|
+
const { stdout: _stdout, stdoutBuffer: _stdoutBuffer, stderr: _stderr, ...metadata } = result;
|
|
1299
|
+
tx.progress.command.result = metadata;
|
|
1300
|
+
if (result.processTree?.state === "unknown") tx.unknown(result.error ?? "Rollback command settlement unverified");
|
|
1301
|
+
tx.publish();
|
|
1302
|
+
if (result.error || result.status === null || !acceptedExitCodes.includes(result.status)) throw result.error ?? new Error(result.stderr.trim() || "Rollback command failed");
|
|
1303
|
+
return result;
|
|
1304
|
+
};
|
|
1305
|
+
for (const attempt of [...attempts].reverse()) {
|
|
1306
|
+
if (!attempt.path) {
|
|
1307
|
+
tx.unknown(`Allocation path unconfirmed for branch ${attempt.branch}`);
|
|
1308
|
+
report.errors!.push(tx.progress.unknown!);
|
|
1309
|
+
continue;
|
|
1310
|
+
}
|
|
1311
|
+
const known = setup.worktrees.find((worktree) => worktree.index === attempt.index);
|
|
1312
|
+
const task: WorktreeCleanupTask = { index: attempt.index, path: attempt.path, branch: attempt.branch,
|
|
1313
|
+
provider: known?.provider ?? "native", naming: known?.naming, worktreeRemoved: false, branchRemoved: false };
|
|
1314
|
+
report.tasks.push(task);
|
|
1315
|
+
try {
|
|
1316
|
+
if (normalizeComparableCwd(attempt.path) === normalizeComparableCwd(setup.cwd)) throw new Error("Refusing source-checkout removal");
|
|
1317
|
+
if (attempt.validated) {
|
|
1318
|
+
await git(["worktree", "remove", "--force", attempt.path]);
|
|
1319
|
+
task.worktreeRemoved = true;
|
|
1320
|
+
} else {
|
|
1321
|
+
// Native attempts were absent before mutation. Reconcile only exact
|
|
1322
|
+
// registered path/branch identity; never recursively delete a guessed leaf.
|
|
1323
|
+
const listed = (await git(["worktree", "list", "--porcelain"])).stdout;
|
|
1324
|
+
const entry = listed.split("\n\n").find((block) => block.split("\n").includes(`worktree ${attempt.path}`));
|
|
1325
|
+
if (entry) {
|
|
1326
|
+
if (!entry.split("\n").includes(`branch refs/heads/${attempt.branch}`)) {
|
|
1327
|
+
tx.unknown("Partial allocation ownership mismatch");
|
|
1328
|
+
throw new Error(tx.progress.unknown);
|
|
1329
|
+
}
|
|
1330
|
+
await git(["worktree", "remove", "--force", attempt.path]);
|
|
1331
|
+
} else if (fs.existsSync(attempt.path)) {
|
|
1332
|
+
tx.unknown("Unregistered partial allocation retained");
|
|
1333
|
+
throw new Error(tx.progress.unknown);
|
|
1334
|
+
}
|
|
1335
|
+
task.worktreeRemoved = true;
|
|
1336
|
+
}
|
|
1337
|
+
const branch = await git(["show-ref", "--verify", "--quiet", `refs/heads/${attempt.branch}`], [0, 1]);
|
|
1338
|
+
if (branch.status === 0) await git(["branch", "-D", attempt.branch]);
|
|
1339
|
+
task.branchRemoved = true;
|
|
1340
|
+
} catch (error) {
|
|
1341
|
+
task.preserved = true;
|
|
1342
|
+
task.errors = [error instanceof Error ? error.message : String(error)];
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
try {
|
|
1346
|
+
if (attempts.length > 0) { await git(["worktree", "prune"]); report.pruned = true; }
|
|
1347
|
+
} catch (error) { report.errors!.push(error instanceof Error ? error.message : String(error)); }
|
|
1348
|
+
if (tx.progress.unknown) report.errors!.push(tx.progress.unknown);
|
|
1349
|
+
report.tasks.sort((a, b) => a.index - b.index);
|
|
1350
|
+
if (!setupPoison && (report.pruned || attempts.length === 0) && report.tasks.every((task) => task.worktreeRemoved && task.branchRemoved) && !report.errors!.length) report.state = "complete";
|
|
1351
|
+
return report;
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
async function allocateWorktrees(tx: SetupTransaction, cwd: string, runId: string, count: number): Promise<WorktreeSetup> {
|
|
1355
|
+
const options = tx.options;
|
|
1356
|
+
tx.check();
|
|
1132
1357
|
if (!Number.isSafeInteger(count) || count < 0) throw new Error("worktree count must be a non-negative integer");
|
|
1133
|
-
const repo = resolveRepoState(cwd, options?.baseRef);
|
|
1358
|
+
const repo = await resolveRepoState(tx, cwd, options?.baseRef);
|
|
1359
|
+
tx.progress.setup.cwd = repo.toplevel;
|
|
1360
|
+
tx.progress.setup.baseCommit = repo.baseCommit;
|
|
1134
1361
|
const setupHook = resolveWorktreeSetupHook(repo.toplevel, options?.setupHook);
|
|
1135
|
-
const provider =
|
|
1362
|
+
const provider = await resolveSetupProvider(tx, options?.provider, options?.baseDir, repo.toplevel);
|
|
1136
1363
|
const branchPrefix = normalizeWorktreeBranchPrefix(options?.branchPrefix);
|
|
1137
|
-
const dedicatedRoot = provider === "native"
|
|
1138
|
-
|
|
1364
|
+
const dedicatedRoot = provider === "native"
|
|
1365
|
+
? resolveWorktreeDedicatedRoot(options?.baseDir, repo.toplevel, (options?.provider ?? DEFAULT_WORKTREE_PROVIDER) === "auto")
|
|
1366
|
+
: undefined;
|
|
1367
|
+
const worktrees = tx.progress.setup.worktrees;
|
|
1139
1368
|
|
|
1140
1369
|
try {
|
|
1141
1370
|
if (provider === "native") {
|
|
1142
|
-
const plannedSetup: WorktreeSetup = {
|
|
1143
|
-
cwd: repo.toplevel,
|
|
1144
|
-
baseCommit: repo.baseCommit,
|
|
1145
|
-
worktrees: Array.from({ length: count }, (_, index) => {
|
|
1146
|
-
const naming = buildWorktreeNaming({ runId, index, agent: options?.agents?.[index], label: options?.labels?.[index], task: options?.tasks?.[index], branchPrefix });
|
|
1147
|
-
const worktreePath = buildNativeWorktreePath(dedicatedRoot!, repo.toplevel, runId, index);
|
|
1148
|
-
assertSafeWorktreeLocation(worktreePath, repo.toplevel, dedicatedRoot!);
|
|
1149
|
-
return {
|
|
1150
|
-
path: worktreePath,
|
|
1151
|
-
agentCwd: repo.cwdRelative ? path.join(worktreePath, repo.cwdRelative) : worktreePath,
|
|
1152
|
-
branch: naming.requestedBranch,
|
|
1153
|
-
index,
|
|
1154
|
-
nodeModulesLinked: false,
|
|
1155
|
-
syntheticPaths: [],
|
|
1156
|
-
provider: "native",
|
|
1157
|
-
naming,
|
|
1158
|
-
};
|
|
1159
|
-
}),
|
|
1160
|
-
};
|
|
1161
|
-
options?.beforeCreate?.(plannedSetup);
|
|
1162
1371
|
for (let index = 0; index < count; index++) {
|
|
1163
|
-
worktrees
|
|
1372
|
+
worktrees[index] = await createNativeWorktree(
|
|
1373
|
+
tx,
|
|
1164
1374
|
repo.toplevel,
|
|
1165
1375
|
repo.cwdRelative,
|
|
1166
1376
|
runId,
|
|
@@ -1172,28 +1382,26 @@ export function createWorktrees(cwd: string, runId: string, count: number, optio
|
|
|
1172
1382
|
options?.labels,
|
|
1173
1383
|
options?.tasks,
|
|
1174
1384
|
branchPrefix,
|
|
1175
|
-
)
|
|
1385
|
+
);
|
|
1176
1386
|
}
|
|
1177
1387
|
} else {
|
|
1178
1388
|
for (let index = 0; index < count; index++) {
|
|
1179
|
-
|
|
1389
|
+
await createWorktrunkWorktree(
|
|
1390
|
+
tx,
|
|
1180
1391
|
repo.toplevel,
|
|
1181
1392
|
repo.cwdRelative,
|
|
1182
1393
|
runId,
|
|
1183
1394
|
index,
|
|
1184
1395
|
repo.baseCommit,
|
|
1185
|
-
repo.sourceCheckout,
|
|
1186
1396
|
options?.agents,
|
|
1187
1397
|
options?.labels,
|
|
1188
1398
|
options?.tasks,
|
|
1189
1399
|
branchPrefix,
|
|
1190
|
-
)
|
|
1400
|
+
);
|
|
1191
1401
|
}
|
|
1192
|
-
// Worktrunk determines its path only after creation. Journal the exact
|
|
1193
|
-
// returned ownership before Pi runs setup hooks or launches a child.
|
|
1194
|
-
options?.beforeCreate?.({ cwd: repo.toplevel, baseCommit: repo.baseCommit, worktrees: [...worktrees] });
|
|
1195
1402
|
for (let index = 0; index < worktrees.length; index++) {
|
|
1196
|
-
worktrees[index] = finalizeCreatedWorktree(
|
|
1403
|
+
worktrees[index] = await finalizeCreatedWorktree(
|
|
1404
|
+
tx,
|
|
1197
1405
|
repo.toplevel,
|
|
1198
1406
|
repo.cwdRelative,
|
|
1199
1407
|
runId,
|
|
@@ -1204,23 +1412,37 @@ export function createWorktrees(cwd: string, runId: string, count: number, optio
|
|
|
1204
1412
|
);
|
|
1205
1413
|
}
|
|
1206
1414
|
}
|
|
1415
|
+
tx.check();
|
|
1416
|
+
tx.progress.phase = "ready";
|
|
1417
|
+
tx.publish();
|
|
1418
|
+
tx.check();
|
|
1419
|
+
return tx.progress.setup;
|
|
1207
1420
|
} catch (error) {
|
|
1208
|
-
|
|
1209
|
-
cwd: repo.toplevel,
|
|
1210
|
-
worktrees,
|
|
1211
|
-
baseCommit: repo.baseCommit,
|
|
1212
|
-
}, { kind: "setup-rollback" });
|
|
1421
|
+
await compensateSetup(tx);
|
|
1213
1422
|
throw error;
|
|
1214
1423
|
}
|
|
1424
|
+
}
|
|
1215
1425
|
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1426
|
+
export async function createWorktrees(cwd: string, runId: string, count: number, options: CreateWorktreesOptions = {}): Promise<WorktreeSetup> {
|
|
1427
|
+
const tx = new SetupTransaction(cwd, options);
|
|
1428
|
+
try {
|
|
1429
|
+
return await withWorktreeTransaction(async () => {
|
|
1430
|
+
setupActive = true;
|
|
1431
|
+
try { return await allocateWorktrees(tx, cwd, runId, count); }
|
|
1432
|
+
finally { setupActive = false; }
|
|
1433
|
+
});
|
|
1434
|
+
} catch (error) {
|
|
1435
|
+
if (setupPoison) tx.progress.unknown ??= setupPoison;
|
|
1436
|
+
tx.progress.cleanup ??= { state: tx.progress.unknown ? "partial" : "complete", tasks: [], pruned: false, errors: tx.progress.unknown ? [tx.progress.unknown] : [] };
|
|
1437
|
+
try { tx.publish(); } catch (publicationError) {
|
|
1438
|
+
tx.progress.cleanup?.errors?.push(`Recovery publication failed: ${String(publicationError)}`);
|
|
1439
|
+
}
|
|
1440
|
+
throw new WorktreeSetupError(error, tx.snapshot());
|
|
1441
|
+
}
|
|
1221
1442
|
}
|
|
1222
1443
|
|
|
1223
1444
|
export function diffWorktrees(setup: WorktreeSetup, agents: string[], diffsDir: string): WorktreeDiff[] {
|
|
1445
|
+
assertWorktreeMutationAllowed();
|
|
1224
1446
|
try {
|
|
1225
1447
|
fs.mkdirSync(diffsDir, { recursive: true });
|
|
1226
1448
|
} catch {
|
|
@@ -1250,6 +1472,7 @@ export function cleanupWorktrees(
|
|
|
1250
1472
|
setup: WorktreeSetup,
|
|
1251
1473
|
intent: WorktreeCleanupIntent = { kind: "preserve", ...(setup.capturedDiffs ? { capturedDiffs: setup.capturedDiffs } : {}) },
|
|
1252
1474
|
): WorktreeCleanupReport {
|
|
1475
|
+
assertWorktreeMutationAllowed();
|
|
1253
1476
|
const tasks: WorktreeCleanupTask[] = [];
|
|
1254
1477
|
for (let index = setup.worktrees.length - 1; index >= 0; index--) {
|
|
1255
1478
|
tasks.push(cleanupSingleWorktree(setup, setup.worktrees[index]!, intent));
|