@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
1
2
|
import { spawnSync } from "node:child_process";
|
|
2
3
|
import * as fs from "node:fs";
|
|
3
4
|
import * as os from "node:os";
|
|
@@ -5,6 +6,42 @@ import * as path from "node:path";
|
|
|
5
6
|
import { resolveAuthorityDecision, type AuthorityPolicyConfig } from "../../policy/authority.ts";
|
|
6
7
|
import { PROJECT_SUBAGENTS_RELATIVE_DIR } from "../../shared/artifacts.ts";
|
|
7
8
|
import { getAgentDir } from "../../shared/utils.ts";
|
|
9
|
+
import type { ManagedWorktreeProvider, WorktreeNaming, WorktreeProvider } from "../../shared/types.ts";
|
|
10
|
+
|
|
11
|
+
export const DEFAULT_WORKTREE_PROVIDER: WorktreeProvider = "auto";
|
|
12
|
+
export const DEFAULT_WORKTREE_BASE_REF = "HEAD";
|
|
13
|
+
export const DEFAULT_WORKTREE_BRANCH_PREFIX = "pi-subagents/";
|
|
14
|
+
/** Internal marker used to defer Worktrunk-dependent instruction paths to launch time. */
|
|
15
|
+
export const WORKTREE_AGENT_CWD_PLACEHOLDER = path.join(path.parse(process.cwd()).root, "__pi_subagents_worktree_cwd__");
|
|
16
|
+
const WORKTREE_NAMING_COMPONENT_MAX_BYTES = 96;
|
|
17
|
+
const WORKTREE_NAMING_LABEL_MAX_BYTES = 256;
|
|
18
|
+
const WORKTREE_NAMING_BRANCH_MAX_BYTES = 256;
|
|
19
|
+
const WORKTREE_COMMAND_OUTPUT_MAX_BYTES = 128 * 1024;
|
|
20
|
+
|
|
21
|
+
export interface WorktreeNamingInput {
|
|
22
|
+
runId: string;
|
|
23
|
+
index: number;
|
|
24
|
+
/** Explicit step index; otherwise a trailing `-sN` in runId is used. */
|
|
25
|
+
stepIndex?: number;
|
|
26
|
+
/** Explicit task index; defaults to index. */
|
|
27
|
+
taskIndex?: number;
|
|
28
|
+
/** Label precedence is lane/workflow key, output/stable key, then this label. */
|
|
29
|
+
agent?: string;
|
|
30
|
+
label?: string;
|
|
31
|
+
laneKey?: string;
|
|
32
|
+
workflowKey?: string;
|
|
33
|
+
outputName?: string;
|
|
34
|
+
taskKey?: string;
|
|
35
|
+
task?: string;
|
|
36
|
+
branchPrefix?: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface WorktreeCommandResult {
|
|
40
|
+
stdout: string;
|
|
41
|
+
stderr: string;
|
|
42
|
+
status: number | null;
|
|
43
|
+
error?: Error;
|
|
44
|
+
}
|
|
8
45
|
|
|
9
46
|
export interface WorktreeSetup {
|
|
10
47
|
cwd: string;
|
|
@@ -20,6 +57,8 @@ export interface WorktreeInfo {
|
|
|
20
57
|
index: number;
|
|
21
58
|
nodeModulesLinked: boolean;
|
|
22
59
|
syntheticPaths: string[];
|
|
60
|
+
provider?: ManagedWorktreeProvider;
|
|
61
|
+
naming?: WorktreeNaming;
|
|
23
62
|
}
|
|
24
63
|
|
|
25
64
|
export interface WorktreeDiff {
|
|
@@ -38,6 +77,8 @@ export interface WorktreeCleanupTask {
|
|
|
38
77
|
index: number;
|
|
39
78
|
path: string;
|
|
40
79
|
branch: string;
|
|
80
|
+
provider?: ManagedWorktreeProvider;
|
|
81
|
+
naming?: WorktreeNaming;
|
|
41
82
|
worktreeRemoved: boolean;
|
|
42
83
|
branchRemoved: boolean;
|
|
43
84
|
preserved?: boolean;
|
|
@@ -73,10 +114,22 @@ interface WorktreeSetupHookConfig {
|
|
|
73
114
|
timeoutMs?: number;
|
|
74
115
|
}
|
|
75
116
|
|
|
76
|
-
interface CreateWorktreesOptions {
|
|
117
|
+
export interface CreateWorktreesOptions {
|
|
77
118
|
agents?: string[];
|
|
119
|
+
/** Optional stable labels used to make branch identity readable. */
|
|
120
|
+
labels?: Array<string | undefined>;
|
|
121
|
+
/** Original task text used for the agent-plus-slug naming fallback. */
|
|
122
|
+
tasks?: Array<string | undefined>;
|
|
123
|
+
/** Worktree allocator selection; auto prefers Worktrunk when available. */
|
|
124
|
+
provider?: WorktreeProvider;
|
|
125
|
+
/** Git ref used as the worktree base; defaults to `HEAD`. */
|
|
126
|
+
baseRef?: string;
|
|
127
|
+
/** Branch namespace; defaults to `pi-subagents/`. */
|
|
128
|
+
branchPrefix?: string;
|
|
78
129
|
setupHook?: WorktreeSetupHookConfig;
|
|
79
130
|
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;
|
|
80
133
|
}
|
|
81
134
|
|
|
82
135
|
interface ResolvedWorktreeSetupHook {
|
|
@@ -109,13 +162,14 @@ interface GitResult {
|
|
|
109
162
|
interface RepoState {
|
|
110
163
|
toplevel: string;
|
|
111
164
|
cwdRelative: string;
|
|
165
|
+
sourceCheckout: SourceCheckoutSnapshot;
|
|
112
166
|
baseCommit: string;
|
|
113
167
|
}
|
|
114
168
|
|
|
115
169
|
const DEFAULT_WORKTREE_SETUP_HOOK_TIMEOUT_MS = 30000;
|
|
116
170
|
|
|
117
171
|
function runGit(cwd: string, args: string[]): GitResult {
|
|
118
|
-
const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
|
|
172
|
+
const result = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true, shell: false });
|
|
119
173
|
return {
|
|
120
174
|
stdout: result.stdout ?? "",
|
|
121
175
|
stderr: result.stderr ?? "",
|
|
@@ -133,7 +187,17 @@ function runGitChecked(cwd: string, args: string[]): string {
|
|
|
133
187
|
return result.stdout;
|
|
134
188
|
}
|
|
135
189
|
|
|
136
|
-
function
|
|
190
|
+
function findGitWorktreePath(cwd: string, branch: string): string | undefined {
|
|
191
|
+
const targetBranch = `branch refs/heads/${branch}`;
|
|
192
|
+
let currentPath: string | undefined;
|
|
193
|
+
for (const line of runGitChecked(cwd, ["worktree", "list", "--porcelain"]).split("\n")) {
|
|
194
|
+
if (line.startsWith("worktree ")) currentPath = line.slice("worktree ".length).trim();
|
|
195
|
+
else if (line.trim() === targetBranch) return currentPath;
|
|
196
|
+
}
|
|
197
|
+
return undefined;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
function resolveRepoState(cwd: string, requestedBaseRef: string | undefined): RepoState {
|
|
137
201
|
const cwdRelative = resolveRepoCwdRelative(cwd);
|
|
138
202
|
const toplevel = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
|
|
139
203
|
|
|
@@ -144,8 +208,17 @@ function resolveRepoState(cwd: string): RepoState {
|
|
|
144
208
|
throw new Error("worktree isolation requires a clean git working tree. Commit or stash changes first.");
|
|
145
209
|
}
|
|
146
210
|
|
|
147
|
-
const
|
|
148
|
-
|
|
211
|
+
const sourceHead = runGitChecked(toplevel, ["rev-parse", "HEAD"]).trim();
|
|
212
|
+
const sourceCheckout = snapshotSourceCheckout(toplevel, sourceHead);
|
|
213
|
+
const baseRef = normalizeWorktreeBaseRef(requestedBaseRef) ?? DEFAULT_WORKTREE_BASE_REF;
|
|
214
|
+
let baseCommit: string;
|
|
215
|
+
try {
|
|
216
|
+
baseCommit = runGitChecked(toplevel, ["rev-parse", "--verify", "--end-of-options", `${baseRef}^{commit}`]).trim();
|
|
217
|
+
} catch (error) {
|
|
218
|
+
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
|
+
}
|
|
220
|
+
if (!baseCommit) throw new Error(`baseRef '${baseRef}' could not be resolved to a commit`);
|
|
221
|
+
return { toplevel, cwdRelative, sourceCheckout, baseCommit };
|
|
149
222
|
}
|
|
150
223
|
|
|
151
224
|
function normalizeComparableCwd(cwd: string): string {
|
|
@@ -154,7 +227,13 @@ function normalizeComparableCwd(cwd: string): string {
|
|
|
154
227
|
const missingSegments: string[] = [];
|
|
155
228
|
while (true) {
|
|
156
229
|
try {
|
|
157
|
-
|
|
230
|
+
let realpath: string;
|
|
231
|
+
try {
|
|
232
|
+
realpath = fs.realpathSync.native(existing);
|
|
233
|
+
} catch {
|
|
234
|
+
realpath = fs.realpathSync(existing);
|
|
235
|
+
}
|
|
236
|
+
return path.join(realpath, ...missingSegments.reverse());
|
|
158
237
|
} catch {
|
|
159
238
|
const parent = path.dirname(existing);
|
|
160
239
|
if (parent === existing) return resolved;
|
|
@@ -190,35 +269,271 @@ function safePatchAgentName(agent: string): string {
|
|
|
190
269
|
return agent.replace(/[^\w.-]/g, "_");
|
|
191
270
|
}
|
|
192
271
|
|
|
193
|
-
function
|
|
194
|
-
return
|
|
272
|
+
function shortWorktreeHash(value: string): string {
|
|
273
|
+
return createHash("sha256").update(value, "utf-8").digest("hex").slice(0, 8);
|
|
195
274
|
}
|
|
196
275
|
|
|
197
|
-
function
|
|
198
|
-
|
|
199
|
-
|
|
276
|
+
function truncateUtf8(value: string, maxBytes: number): string {
|
|
277
|
+
if (Buffer.byteLength(value, "utf-8") <= maxBytes) return value;
|
|
278
|
+
const truncated = Buffer.from(value, "utf-8").subarray(0, maxBytes).toString("utf-8");
|
|
279
|
+
return /[\uD800-\uDFFF]$/u.test(truncated) ? truncated.slice(0, -1) : truncated;
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** Convert an arbitrary label to a single safe filesystem/branch component. */
|
|
283
|
+
export function sanitizeWorktreePathComponent(value: string, maxBytes = WORKTREE_NAMING_COMPONENT_MAX_BYTES): string {
|
|
284
|
+
const raw = value.trim();
|
|
285
|
+
let normalized = raw
|
|
286
|
+
.replace(/[\\/\s]+/g, "-")
|
|
287
|
+
.replace(/[^A-Za-z0-9._-]+/g, "-")
|
|
288
|
+
.replace(/-+/g, "-")
|
|
289
|
+
.replace(/^[._-]+|[._-]+$/g, "");
|
|
290
|
+
if (!normalized) return "task";
|
|
291
|
+
const changed = normalized !== raw;
|
|
292
|
+
if (changed || Buffer.byteLength(normalized, "utf-8") > maxBytes) {
|
|
293
|
+
const suffix = `-${shortWorktreeHash(raw || "task")}`;
|
|
294
|
+
const prefix = truncateUtf8(normalized, Math.max(1, maxBytes - Buffer.byteLength(suffix, "utf-8"))).replace(/[._-]+$/g, "");
|
|
295
|
+
normalized = `${prefix || "task"}${suffix}`;
|
|
296
|
+
}
|
|
297
|
+
return truncateUtf8(normalized, maxBytes).replace(/^[._-]+|[._-]+$/g, "") || "task";
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function validGitRef(ref: string): boolean {
|
|
301
|
+
if (!ref || ref === "@" || Buffer.byteLength(ref, "utf-8") > 1024 || ref.startsWith("/") || ref.endsWith("/") || ref.includes("//") || ref.includes("..") || ref.includes("@{")) return false;
|
|
302
|
+
if (/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/iu.test(ref)) return false;
|
|
303
|
+
if (/[[\]\\~^:?*\u0000-\u0020\u007f]/u.test(ref) || ref.endsWith(".") || ref.endsWith(".lock")) return false;
|
|
304
|
+
return ref.split("/").every((component) => component.length > 0 && component !== "." && component !== ".." && !component.startsWith(".") && !component.endsWith(".") && !component.endsWith(".lock"));
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/** Normalize and validate a configured worktree base ref without resolving it. */
|
|
308
|
+
export function normalizeWorktreeBaseRef(value: unknown): string | undefined {
|
|
309
|
+
if (value === undefined) return undefined;
|
|
310
|
+
if (typeof value !== "string" || !validGitRef(value)) throw new Error("baseRef must be a valid Git ref");
|
|
311
|
+
return value;
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** Normalize and validate the configured Git branch namespace. */
|
|
315
|
+
export function normalizeWorktreeBranchPrefix(value: string | undefined): string {
|
|
316
|
+
const raw = value === undefined ? DEFAULT_WORKTREE_BRANCH_PREFIX : value.trim();
|
|
317
|
+
if (!raw) throw new Error("worktree branch prefix cannot be empty");
|
|
318
|
+
if (raw.includes("\\") || /[\u0000-\u001f\u007f\s]/u.test(raw) || raw.startsWith("/") || raw.includes("//") || raw.includes("..") || raw.includes("@{")) {
|
|
319
|
+
throw new Error("worktree branch prefix contains invalid Git ref characters");
|
|
320
|
+
}
|
|
321
|
+
const withoutTrailingSlash = raw.replace(/\/+$/u, "");
|
|
322
|
+
if (!withoutTrailingSlash || withoutTrailingSlash.startsWith("-") || withoutTrailingSlash.split("/").some((component) => component === "." || component === ".." || component.startsWith("."))) {
|
|
323
|
+
throw new Error("worktree branch prefix contains an invalid Git ref component");
|
|
324
|
+
}
|
|
325
|
+
const prefix = `${withoutTrailingSlash}/`;
|
|
326
|
+
if (!validGitRef(`${prefix}task`)) throw new Error("worktree branch prefix is not a valid Git ref namespace");
|
|
327
|
+
return prefix;
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
function runShortId(runId: string): string {
|
|
331
|
+
const base = runId.replace(/-s\d+$/u, "");
|
|
332
|
+
const normalized = sanitizeWorktreePathComponent(base || runId, 16);
|
|
333
|
+
return normalized.length > 12 ? normalized.slice(0, 12) : normalized;
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function nonNegativeNamingIndex(value: number | undefined, label: string, fallback: number): number {
|
|
337
|
+
const resolved = value ?? fallback;
|
|
338
|
+
if (!Number.isSafeInteger(resolved) || resolved < 0) throw new Error(`${label} must be a non-negative integer`);
|
|
339
|
+
return resolved;
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
/** Build the shared branch identity used by native and Worktrunk allocation. */
|
|
343
|
+
export function buildWorktreeNaming(input: WorktreeNamingInput): WorktreeNaming {
|
|
344
|
+
if (!input.runId.trim()) throw new Error("worktree run id cannot be empty");
|
|
345
|
+
const index = nonNegativeNamingIndex(input.index, "worktree index", 0);
|
|
346
|
+
const stepIndex = nonNegativeNamingIndex(input.stepIndex, "worktree step index", Number(input.runId.match(/-s(\d+)$/u)?.[1] ?? 0));
|
|
347
|
+
const taskIndex = nonNegativeNamingIndex(input.taskIndex, "worktree task index", index);
|
|
348
|
+
const label = input.laneKey?.trim()
|
|
349
|
+
|| input.workflowKey?.trim()
|
|
350
|
+
|| input.outputName?.trim()
|
|
351
|
+
|| input.taskKey?.trim()
|
|
352
|
+
|| input.label?.trim()
|
|
353
|
+
|| (input.agent?.trim() && input.task?.trim() ? `${input.agent.trim()}-${input.task.trim()}` : undefined)
|
|
354
|
+
|| input.agent?.trim()
|
|
355
|
+
|| "task";
|
|
356
|
+
const branchPrefix = normalizeWorktreeBranchPrefix(input.branchPrefix);
|
|
357
|
+
const labelComponent = sanitizeWorktreePathComponent(label);
|
|
358
|
+
const pathComponentBase = `${labelComponent}-${runShortId(input.runId)}-s${stepIndex}-t${taskIndex}`;
|
|
359
|
+
const sanitizedPathComponent = validGitRef(`${branchPrefix}${pathComponentBase}`)
|
|
360
|
+
? pathComponentBase
|
|
361
|
+
: sanitizeWorktreePathComponent(pathComponentBase, WORKTREE_NAMING_COMPONENT_MAX_BYTES);
|
|
362
|
+
let requestedBranch = `${branchPrefix}${sanitizedPathComponent}`;
|
|
363
|
+
if (!validGitRef(requestedBranch) || Buffer.byteLength(requestedBranch, "utf-8") > WORKTREE_NAMING_BRANCH_MAX_BYTES) {
|
|
364
|
+
const suffix = `-${shortWorktreeHash(pathComponentBase)}`;
|
|
365
|
+
const available = Math.max(1, WORKTREE_NAMING_BRANCH_MAX_BYTES - Buffer.byteLength(branchPrefix, "utf-8") - Buffer.byteLength(suffix, "utf-8"));
|
|
366
|
+
requestedBranch = `${branchPrefix}${truncateUtf8(pathComponentBase, available).replace(/[._-]+$/g, "")}${suffix}`;
|
|
367
|
+
}
|
|
368
|
+
if (!validGitRef(requestedBranch) || Buffer.byteLength(requestedBranch, "utf-8") > WORKTREE_NAMING_BRANCH_MAX_BYTES) throw new Error(`generated worktree branch is not a valid Git ref: ${requestedBranch}`);
|
|
369
|
+
const metadataLabel = truncateUtf8(label.replace(/[\u0000-\u001f\u007f]+/gu, " ").replace(/\s+/gu, " ").trim() || "task", WORKTREE_NAMING_LABEL_MAX_BYTES);
|
|
370
|
+
return {
|
|
371
|
+
requestedBranch,
|
|
372
|
+
branchPrefix,
|
|
373
|
+
label: metadataLabel,
|
|
374
|
+
sanitizedPathComponent: requestedBranch.slice(branchPrefix.length),
|
|
375
|
+
};
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function hasConfiguredWorktreeBaseDir(baseDir: string | undefined): boolean {
|
|
379
|
+
return baseDir !== undefined
|
|
380
|
+
? true
|
|
381
|
+
: (process.env.PI_SUBAGENTS_WORKTREE_DIR?.trim().length ?? 0) > 0;
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
interface WorktrunkCapability {
|
|
385
|
+
available: boolean;
|
|
386
|
+
reason?: string;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
interface SourceCheckoutSnapshot {
|
|
390
|
+
head: string;
|
|
391
|
+
branch?: string;
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
function runWorktrunk(args: string[], cwd?: string): WorktreeCommandResult {
|
|
395
|
+
try {
|
|
396
|
+
const result = spawnSync("wt", args, {
|
|
397
|
+
cwd,
|
|
398
|
+
encoding: "utf-8",
|
|
399
|
+
windowsHide: true,
|
|
400
|
+
shell: false,
|
|
401
|
+
maxBuffer: WORKTREE_COMMAND_OUTPUT_MAX_BYTES,
|
|
402
|
+
});
|
|
403
|
+
const stdout = result.stdout ?? "";
|
|
404
|
+
const stderr = result.stderr ?? "";
|
|
405
|
+
if (Buffer.byteLength(stdout, "utf-8") > WORKTREE_COMMAND_OUTPUT_MAX_BYTES) throw new Error("Worktrunk stdout exceeds the output limit");
|
|
406
|
+
return { stdout, stderr, status: result.status, ...(result.error ? { error: result.error } : {}) };
|
|
407
|
+
} catch (error) {
|
|
408
|
+
return { stdout: "", stderr: "", status: null, error: error instanceof Error ? error : new Error(String(error)) };
|
|
409
|
+
}
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
function probeWorktrunk(): WorktrunkCapability {
|
|
413
|
+
const result = runWorktrunk(["--version"]);
|
|
414
|
+
if (result.status !== 0) return { available: false, reason: result.error?.message || result.stderr.trim() || "Worktrunk is unavailable" };
|
|
415
|
+
const version = result.stdout.trim().match(/\b(?:wt\s+)?v?(\d+\.\d+(?:\.\d+)?)\b/i)?.[1];
|
|
416
|
+
if (!version) return { available: false, reason: "Worktrunk returned an invalid version" };
|
|
417
|
+
const help = runWorktrunk(["switch", "--help"]);
|
|
418
|
+
if (help.status !== 0) return { available: false, reason: help.error?.message || help.stderr.trim() || "Worktrunk switch capability is unavailable" };
|
|
419
|
+
const helpText = `${help.stdout}\n${help.stderr}`;
|
|
420
|
+
const requiredCapabilities = ["--create", "--base", "--no-cd", "--no-hooks", "--format"];
|
|
421
|
+
const missing = requiredCapabilities.filter((flag) => !helpText.includes(flag));
|
|
422
|
+
if (missing.length > 0) return { available: false, reason: `Worktrunk switch is missing required capabilities: ${missing.join(", ")}` };
|
|
423
|
+
return { available: true };
|
|
424
|
+
}
|
|
425
|
+
|
|
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
|
+
/** Resolve a requested provider without silently switching after allocation starts. */
|
|
439
|
+
export function resolveWorktreeProvider(requested: WorktreeProvider | undefined, baseDir?: string): ManagedWorktreeProvider {
|
|
440
|
+
const selection = requested ?? DEFAULT_WORKTREE_PROVIDER;
|
|
441
|
+
if (selection !== "auto" && selection !== "native" && selection !== "worktrunk") throw new Error(`worktree provider must be "auto", "native", or "worktrunk"`);
|
|
442
|
+
if (selection === "native") return "native";
|
|
443
|
+
if (hasConfiguredWorktreeBaseDir(baseDir)) {
|
|
444
|
+
if (selection === "worktrunk") throw new Error("worktreeProvider='worktrunk' cannot be combined with worktreeBaseDir or PI_SUBAGENTS_WORKTREE_DIR");
|
|
445
|
+
return "native";
|
|
446
|
+
}
|
|
447
|
+
const capability = probeWorktrunk();
|
|
448
|
+
if (capability.available) return "worktrunk";
|
|
449
|
+
if (selection === "worktrunk") throw new Error(`Worktrunk provider is unavailable: ${capability.reason ?? "unknown capability failure"}`);
|
|
450
|
+
return "native";
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/** Whether a launch must bind its worktree-dependent paths after allocation. */
|
|
454
|
+
export function shouldDeferWorktreeCwd(requested: WorktreeProvider | undefined, baseDir?: string): boolean {
|
|
455
|
+
return (requested ?? DEFAULT_WORKTREE_PROVIDER) !== "native" && !hasConfiguredWorktreeBaseDir(baseDir);
|
|
456
|
+
}
|
|
200
457
|
|
|
201
|
-
|
|
202
|
-
|
|
458
|
+
/**
|
|
459
|
+
* Resolves the dedicated worktree root: the configured base directory or
|
|
460
|
+
* PI_SUBAGENTS_WORKTREE_DIR when set, otherwise a `worktrees` folder sibling
|
|
461
|
+
* to the repository. Managed leaves always nest one level deeper under the
|
|
462
|
+
* project folder (`basename(repoRoot)`).
|
|
463
|
+
*/
|
|
464
|
+
function resolveWorktreeDedicatedRoot(configuredBaseDir: string | undefined, repoRoot: string): string {
|
|
465
|
+
const rawBaseDir = configuredBaseDir ?? process.env.PI_SUBAGENTS_WORKTREE_DIR;
|
|
466
|
+
let expanded: string;
|
|
467
|
+
if (rawBaseDir === undefined || (configuredBaseDir === undefined && !rawBaseDir.trim())) {
|
|
468
|
+
expanded = path.join(path.dirname(repoRoot), "worktrees");
|
|
469
|
+
} else {
|
|
470
|
+
const trimmed = rawBaseDir.trim();
|
|
471
|
+
if (!trimmed) throw new Error("worktree base directory cannot be empty");
|
|
203
472
|
|
|
204
|
-
|
|
205
|
-
|
|
473
|
+
const candidate = trimmed.startsWith("~/") ? path.join(os.homedir(), trimmed.slice(2)) : trimmed;
|
|
474
|
+
expanded = path.isAbsolute(candidate) ? candidate : path.resolve(repoRoot, candidate);
|
|
475
|
+
}
|
|
206
476
|
const extensionsDir = normalizeComparableCwd(path.join(getAgentDir(), "extensions"));
|
|
207
|
-
|
|
208
|
-
if (!relativeToExtensions || (!relativeToExtensions.startsWith(`..${path.sep}`) && relativeToExtensions !== ".." && !path.isAbsolute(relativeToExtensions))) {
|
|
477
|
+
if (isPathInside(extensionsDir, normalizeComparableCwd(expanded))) {
|
|
209
478
|
throw new Error(`worktree base directory cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
210
479
|
}
|
|
480
|
+
return expanded;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function buildNativeProjectPath(dedicatedRoot: string, repoRoot: string): string {
|
|
484
|
+
return path.join(dedicatedRoot, path.basename(repoRoot));
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
/**
|
|
488
|
+
* Creates the project folder (parents included) so `git worktree add` can create
|
|
489
|
+
* the leaf inside it. Must only run after `assertSafeWorktreeLocation` accepted
|
|
490
|
+
* the planned leaf — an unsafe base must never be materialized on disk.
|
|
491
|
+
*/
|
|
492
|
+
function ensureProjectWorktreeDir(dedicatedRoot: string, repoRoot: string): void {
|
|
211
493
|
try {
|
|
212
|
-
fs.mkdirSync(
|
|
494
|
+
fs.mkdirSync(buildNativeProjectPath(dedicatedRoot, repoRoot), { recursive: true });
|
|
213
495
|
} catch (error) {
|
|
214
496
|
const message = error instanceof Error ? error.message : String(error);
|
|
215
|
-
throw new Error(`failed to create worktree base directory ${
|
|
497
|
+
throw new Error(`failed to create worktree base directory ${dedicatedRoot}: ${message}`);
|
|
216
498
|
}
|
|
217
|
-
return resolved;
|
|
218
499
|
}
|
|
219
500
|
|
|
220
|
-
function
|
|
221
|
-
return path.join(
|
|
501
|
+
function buildNativeWorktreePath(dedicatedRoot: string, repoRoot: string, runId: string, index: number): string {
|
|
502
|
+
return path.join(buildNativeProjectPath(dedicatedRoot, repoRoot), `pi-worktree-${sanitizeWorktreePathComponent(runId, 120)}-${index}`);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
function isPathInside(parent: string, child: string): boolean {
|
|
506
|
+
const relative = path.relative(parent, child);
|
|
507
|
+
if (!relative || relative === ".") return true;
|
|
508
|
+
return relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
function isStrictChildPath(parent: string, child: string): boolean {
|
|
512
|
+
const relative = path.relative(parent, child);
|
|
513
|
+
return Boolean(relative) && relative !== "." && relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative);
|
|
514
|
+
}
|
|
515
|
+
|
|
516
|
+
/** Fail closed before `git worktree add`: reject unsafe planned/realpath locations. */
|
|
517
|
+
function assertSafeWorktreeLocation(worktreePath: string, repoRoot: string, dedicatedRoot: string): void {
|
|
518
|
+
const resolvedLeaf = normalizeComparableCwd(worktreePath);
|
|
519
|
+
const resolvedRepoRoot = normalizeComparableCwd(repoRoot);
|
|
520
|
+
const projectDir = normalizeComparableCwd(buildNativeProjectPath(dedicatedRoot, repoRoot));
|
|
521
|
+
const repoParent = normalizeComparableCwd(path.dirname(resolvedRepoRoot));
|
|
522
|
+
const leafParent = normalizeComparableCwd(path.dirname(resolvedLeaf));
|
|
523
|
+
const extensionsDir = normalizeComparableCwd(path.join(getAgentDir(), "extensions"));
|
|
524
|
+
|
|
525
|
+
if (isPathInside(extensionsDir, projectDir) || isPathInside(extensionsDir, resolvedLeaf)) {
|
|
526
|
+
throw new Error(`worktree path cannot be inside Pi extensions directory: ${extensionsDir}. Choose a directory outside it.`);
|
|
527
|
+
}
|
|
528
|
+
if (isPathInside(resolvedRepoRoot, resolvedLeaf)) {
|
|
529
|
+
throw new Error(`worktree path would land inside the repository checkout: ${resolvedLeaf}`);
|
|
530
|
+
}
|
|
531
|
+
if (leafParent === repoParent) {
|
|
532
|
+
throw new Error(`worktree path would be a direct child of the repository parent: ${resolvedLeaf}`);
|
|
533
|
+
}
|
|
534
|
+
if (!isStrictChildPath(projectDir, resolvedLeaf)) {
|
|
535
|
+
throw new Error(`worktree path must be a strict child of the project worktree directory ${projectDir}: ${resolvedLeaf}`);
|
|
536
|
+
}
|
|
222
537
|
}
|
|
223
538
|
|
|
224
539
|
function resolveRepoCwdRelative(cwd: string): string {
|
|
@@ -236,7 +551,9 @@ function resolveRepoCwdRelative(cwd: string): string {
|
|
|
236
551
|
export function resolveExpectedWorktreeAgentCwd(cwd: string, runId: string, index: number, baseDir?: string): string {
|
|
237
552
|
const cwdRelative = resolveRepoCwdRelative(cwd);
|
|
238
553
|
const repoRoot = runGitChecked(cwd, ["rev-parse", "--show-toplevel"]).trim();
|
|
239
|
-
const
|
|
554
|
+
const dedicatedRoot = resolveWorktreeDedicatedRoot(baseDir, repoRoot);
|
|
555
|
+
const worktreePath = buildNativeWorktreePath(dedicatedRoot, repoRoot, runId, index);
|
|
556
|
+
assertSafeWorktreeLocation(worktreePath, repoRoot, dedicatedRoot);
|
|
240
557
|
return cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath;
|
|
241
558
|
}
|
|
242
559
|
|
|
@@ -379,58 +696,183 @@ function runWorktreeSetupHook(
|
|
|
379
696
|
return [...uniquePaths];
|
|
380
697
|
}
|
|
381
698
|
|
|
382
|
-
function
|
|
699
|
+
function finalizeCreatedWorktree(
|
|
383
700
|
toplevel: string,
|
|
384
701
|
cwdRelative: string,
|
|
385
702
|
runId: string,
|
|
386
|
-
index: number,
|
|
387
703
|
baseCommit: string,
|
|
388
704
|
setupHook: ResolvedWorktreeSetupHook | undefined,
|
|
389
705
|
agent: string | undefined,
|
|
390
|
-
|
|
706
|
+
worktree: WorktreeInfo,
|
|
391
707
|
): WorktreeInfo {
|
|
392
|
-
const
|
|
393
|
-
const worktreePath = buildWorktreePath(baseDir, runId, index);
|
|
394
|
-
const add = runGit(toplevel, ["worktree", "add", worktreePath, "-b", branch, "HEAD"]);
|
|
395
|
-
if (add.status !== 0) {
|
|
396
|
-
const message = add.stderr.trim() || add.stdout.trim() || `failed to create worktree ${worktreePath}`;
|
|
397
|
-
throw new Error(message);
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
const agentCwd = cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath;
|
|
708
|
+
const agentCwd = cwdRelative ? path.join(worktree.path, cwdRelative) : worktree.path;
|
|
401
709
|
try {
|
|
402
|
-
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel,
|
|
710
|
+
const nodeModulesLinked = linkNodeModulesIfPresent(toplevel, worktree.path);
|
|
403
711
|
const syntheticPaths = nodeModulesLinked ? ["node_modules"] : [];
|
|
404
|
-
|
|
405
712
|
if (setupHook) {
|
|
406
713
|
const hookSyntheticPaths = runWorktreeSetupHook(setupHook, {
|
|
407
714
|
version: 1,
|
|
408
715
|
repoRoot: toplevel,
|
|
409
|
-
worktreePath,
|
|
716
|
+
worktreePath: worktree.path,
|
|
410
717
|
agentCwd,
|
|
411
|
-
branch,
|
|
412
|
-
index,
|
|
718
|
+
branch: worktree.branch,
|
|
719
|
+
index: worktree.index,
|
|
413
720
|
runId,
|
|
414
721
|
baseCommit,
|
|
415
722
|
agent,
|
|
416
723
|
});
|
|
417
724
|
syntheticPaths.push(...hookSyntheticPaths);
|
|
418
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;
|
|
735
|
+
}
|
|
736
|
+
}
|
|
419
737
|
|
|
738
|
+
function createNativeWorktree(
|
|
739
|
+
toplevel: string,
|
|
740
|
+
cwdRelative: string,
|
|
741
|
+
runId: string,
|
|
742
|
+
index: number,
|
|
743
|
+
baseCommit: string,
|
|
744
|
+
setupHook: ResolvedWorktreeSetupHook | undefined,
|
|
745
|
+
agent: string | undefined,
|
|
746
|
+
dedicatedRoot: string,
|
|
747
|
+
labels: Array<string | undefined> | undefined,
|
|
748
|
+
tasks: Array<string | undefined> | undefined,
|
|
749
|
+
branchPrefix: string | undefined,
|
|
750
|
+
): WorktreeInfo {
|
|
751
|
+
const naming = buildWorktreeNaming({ runId, index, agent, label: labels?.[index], task: tasks?.[index], branchPrefix });
|
|
752
|
+
const worktreePath = buildNativeWorktreePath(dedicatedRoot, toplevel, runId, index);
|
|
753
|
+
assertSafeWorktreeLocation(worktreePath, toplevel, dedicatedRoot);
|
|
754
|
+
ensureProjectWorktreeDir(dedicatedRoot, toplevel);
|
|
755
|
+
const add = runGit(toplevel, ["worktree", "add", worktreePath, "-b", naming.requestedBranch, baseCommit]);
|
|
756
|
+
if (add.status !== 0) {
|
|
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, {
|
|
761
|
+
path: worktreePath,
|
|
762
|
+
agentCwd: worktreePath,
|
|
763
|
+
branch: naming.requestedBranch,
|
|
764
|
+
index,
|
|
765
|
+
nodeModulesLinked: false,
|
|
766
|
+
syntheticPaths: [],
|
|
767
|
+
provider: "native",
|
|
768
|
+
naming,
|
|
769
|
+
});
|
|
770
|
+
}
|
|
771
|
+
|
|
772
|
+
interface WorktrunkSwitchOutput {
|
|
773
|
+
action?: unknown;
|
|
774
|
+
branch?: unknown;
|
|
775
|
+
path?: unknown;
|
|
776
|
+
created_branch?: unknown;
|
|
777
|
+
base_branch?: unknown;
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function parseWorktrunkSwitchOutput(rawStdout: string): WorktrunkSwitchOutput {
|
|
781
|
+
if (Buffer.byteLength(rawStdout, "utf-8") > WORKTREE_COMMAND_OUTPUT_MAX_BYTES) throw new Error("Worktrunk provisioning output exceeds the output limit");
|
|
782
|
+
const trimmed = rawStdout.trim();
|
|
783
|
+
if (!trimmed) throw new Error("Worktrunk provisioning returned empty stdout; expected JSON object");
|
|
784
|
+
let parsed: unknown;
|
|
785
|
+
try {
|
|
786
|
+
parsed = JSON.parse(trimmed);
|
|
787
|
+
} catch (error) {
|
|
788
|
+
throw new Error(`Worktrunk provisioning returned invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
|
|
789
|
+
}
|
|
790
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) throw new Error("Worktrunk provisioning stdout must be a JSON object");
|
|
791
|
+
return parsed as WorktrunkSwitchOutput;
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function createWorktrunkWorktree(
|
|
795
|
+
toplevel: string,
|
|
796
|
+
cwdRelative: string,
|
|
797
|
+
runId: string,
|
|
798
|
+
index: number,
|
|
799
|
+
baseCommit: string,
|
|
800
|
+
sourceCheckout: SourceCheckoutSnapshot,
|
|
801
|
+
agents: string[] | undefined,
|
|
802
|
+
labels: Array<string | undefined> | undefined,
|
|
803
|
+
tasks: Array<string | undefined> | undefined,
|
|
804
|
+
branchPrefix: string | undefined,
|
|
805
|
+
): WorktreeInfo {
|
|
806
|
+
const naming = buildWorktreeNaming({ runId, index, agent: agents?.[index], label: labels?.[index], task: tasks?.[index], branchPrefix });
|
|
807
|
+
const args = ["-C", toplevel, "switch", "--create", naming.requestedBranch, "--base", baseCommit, "--no-cd", "--no-hooks", "--format", "json"];
|
|
808
|
+
const result = runWorktrunk(args, toplevel);
|
|
809
|
+
if (result.status !== 0) {
|
|
810
|
+
const message = result.error?.message || result.stderr.trim() || result.stdout.trim() || "Worktrunk provisioning failed";
|
|
811
|
+
throw new Error(`Worktrunk provisioning failed: ${message}`);
|
|
812
|
+
}
|
|
813
|
+
let createdAllocation = false;
|
|
814
|
+
let returnedPath: string | undefined;
|
|
815
|
+
try {
|
|
816
|
+
const output = parseWorktrunkSwitchOutput(result.stdout);
|
|
817
|
+
createdAllocation = output.action === "created" && output.created_branch === true;
|
|
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) {
|
|
820
|
+
throw new Error("Worktrunk provisioning returned inconsistent creation metadata");
|
|
821
|
+
}
|
|
822
|
+
if (typeof output.path !== "string" || !path.isAbsolute(output.path)) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
823
|
+
const worktreePathCandidate = returnedPath;
|
|
824
|
+
if (!worktreePathCandidate) throw new Error("Worktrunk provisioning returned a non-absolute worktree path");
|
|
825
|
+
let stat: fs.Stats;
|
|
826
|
+
try {
|
|
827
|
+
stat = fs.lstatSync(worktreePathCandidate);
|
|
828
|
+
} catch (error) {
|
|
829
|
+
throw new Error(`Worktrunk provisioning returned a missing worktree path: ${worktreePathCandidate}`, { cause: error instanceof Error ? error : undefined });
|
|
830
|
+
}
|
|
831
|
+
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error("Worktrunk provisioning returned a path that is not a real directory");
|
|
832
|
+
const worktreePath = normalizeComparableCwd(worktreePathCandidate);
|
|
833
|
+
if (worktreePath === normalizeComparableCwd(toplevel)) throw new Error("Worktrunk provisioning returned the source checkout path");
|
|
834
|
+
const sourceCommonDirRaw = runGitChecked(toplevel, ["rev-parse", "--git-common-dir"]).trim();
|
|
835
|
+
const returnedCommonDirRaw = runGitChecked(worktreePath, ["rev-parse", "--git-common-dir"]).trim();
|
|
836
|
+
const sourceCommonDir = normalizeComparableCwd(path.isAbsolute(sourceCommonDirRaw) ? sourceCommonDirRaw : path.resolve(toplevel, sourceCommonDirRaw));
|
|
837
|
+
const returnedCommonDir = normalizeComparableCwd(path.isAbsolute(returnedCommonDirRaw) ? returnedCommonDirRaw : path.resolve(worktreePath, returnedCommonDirRaw));
|
|
838
|
+
if (returnedCommonDir !== sourceCommonDir) throw new Error("Worktrunk provisioning returned a worktree for a different repository");
|
|
839
|
+
const returnedBranch = runGitChecked(worktreePath, ["symbolic-ref", "--quiet", "--short", "HEAD"]).trim();
|
|
840
|
+
if (returnedBranch !== naming.requestedBranch) throw new Error("Worktrunk provisioning returned a worktree on a different branch");
|
|
841
|
+
const returnedHead = runGitChecked(worktreePath, ["rev-parse", "HEAD"]).trim();
|
|
842
|
+
if (returnedHead !== baseCommit) throw new Error("Worktrunk provisioning returned a worktree at a different base commit");
|
|
420
843
|
return {
|
|
421
844
|
path: worktreePath,
|
|
422
|
-
agentCwd,
|
|
423
|
-
branch,
|
|
845
|
+
agentCwd: cwdRelative ? path.join(worktreePath, cwdRelative) : worktreePath,
|
|
846
|
+
branch: naming.requestedBranch,
|
|
424
847
|
index,
|
|
425
|
-
nodeModulesLinked,
|
|
426
|
-
syntheticPaths,
|
|
848
|
+
nodeModulesLinked: false,
|
|
849
|
+
syntheticPaths: [],
|
|
850
|
+
provider: "worktrunk",
|
|
851
|
+
naming,
|
|
427
852
|
};
|
|
428
853
|
} catch (error) {
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
854
|
+
if (createdAllocation) {
|
|
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
|
+
}
|
|
434
876
|
}
|
|
435
877
|
throw error;
|
|
436
878
|
}
|
|
@@ -577,6 +1019,8 @@ function cleanupSingleWorktree(
|
|
|
577
1019
|
index: worktree.index,
|
|
578
1020
|
path: worktree.path,
|
|
579
1021
|
branch: worktree.branch,
|
|
1022
|
+
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1023
|
+
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
580
1024
|
worktreeRemoved: false,
|
|
581
1025
|
branchRemoved: false,
|
|
582
1026
|
preserved: true,
|
|
@@ -599,6 +1043,8 @@ function cleanupSingleWorktree(
|
|
|
599
1043
|
index: worktree.index,
|
|
600
1044
|
path: worktree.path,
|
|
601
1045
|
branch: worktree.branch,
|
|
1046
|
+
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1047
|
+
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
602
1048
|
worktreeRemoved: false,
|
|
603
1049
|
branchRemoved: false,
|
|
604
1050
|
preserved: true,
|
|
@@ -620,6 +1066,8 @@ function cleanupSingleWorktree(
|
|
|
620
1066
|
index: worktree.index,
|
|
621
1067
|
path: worktree.path,
|
|
622
1068
|
branch: worktree.branch,
|
|
1069
|
+
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1070
|
+
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
623
1071
|
worktreeRemoved: false,
|
|
624
1072
|
branchRemoved: false,
|
|
625
1073
|
preserved: true,
|
|
@@ -639,6 +1087,8 @@ function cleanupSingleWorktree(
|
|
|
639
1087
|
index: worktree.index,
|
|
640
1088
|
path: worktree.path,
|
|
641
1089
|
branch: worktree.branch,
|
|
1090
|
+
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1091
|
+
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
642
1092
|
worktreeRemoved: false,
|
|
643
1093
|
branchRemoved: false,
|
|
644
1094
|
preserved: true,
|
|
@@ -666,6 +1116,8 @@ function cleanupSingleWorktree(
|
|
|
666
1116
|
index: worktree.index,
|
|
667
1117
|
path: worktree.path,
|
|
668
1118
|
branch: worktree.branch,
|
|
1119
|
+
...(worktree.provider ? { provider: worktree.provider } : {}),
|
|
1120
|
+
...(worktree.naming ? { naming: worktree.naming } : {}),
|
|
669
1121
|
worktreeRemoved,
|
|
670
1122
|
branchRemoved,
|
|
671
1123
|
...(errors.length ? { errors } : {}),
|
|
@@ -677,23 +1129,80 @@ function hasWorktreeChanges(diff: WorktreeDiff): boolean {
|
|
|
677
1129
|
}
|
|
678
1130
|
|
|
679
1131
|
export function createWorktrees(cwd: string, runId: string, count: number, options?: CreateWorktreesOptions): WorktreeSetup {
|
|
680
|
-
|
|
1132
|
+
if (!Number.isSafeInteger(count) || count < 0) throw new Error("worktree count must be a non-negative integer");
|
|
1133
|
+
const repo = resolveRepoState(cwd, options?.baseRef);
|
|
681
1134
|
const setupHook = resolveWorktreeSetupHook(repo.toplevel, options?.setupHook);
|
|
682
|
-
const
|
|
1135
|
+
const provider = resolveWorktreeProvider(options?.provider, options?.baseDir);
|
|
1136
|
+
const branchPrefix = normalizeWorktreeBranchPrefix(options?.branchPrefix);
|
|
1137
|
+
const dedicatedRoot = provider === "native" ? resolveWorktreeDedicatedRoot(options?.baseDir, repo.toplevel) : undefined;
|
|
683
1138
|
const worktrees: WorktreeInfo[] = [];
|
|
684
1139
|
|
|
685
1140
|
try {
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
repo.toplevel,
|
|
689
|
-
repo.
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
1141
|
+
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
|
+
for (let index = 0; index < count; index++) {
|
|
1163
|
+
worktrees.push(createNativeWorktree(
|
|
1164
|
+
repo.toplevel,
|
|
1165
|
+
repo.cwdRelative,
|
|
1166
|
+
runId,
|
|
1167
|
+
index,
|
|
1168
|
+
repo.baseCommit,
|
|
1169
|
+
setupHook,
|
|
1170
|
+
options?.agents?.[index],
|
|
1171
|
+
dedicatedRoot!,
|
|
1172
|
+
options?.labels,
|
|
1173
|
+
options?.tasks,
|
|
1174
|
+
branchPrefix,
|
|
1175
|
+
));
|
|
1176
|
+
}
|
|
1177
|
+
} else {
|
|
1178
|
+
for (let index = 0; index < count; index++) {
|
|
1179
|
+
worktrees.push(createWorktrunkWorktree(
|
|
1180
|
+
repo.toplevel,
|
|
1181
|
+
repo.cwdRelative,
|
|
1182
|
+
runId,
|
|
1183
|
+
index,
|
|
1184
|
+
repo.baseCommit,
|
|
1185
|
+
repo.sourceCheckout,
|
|
1186
|
+
options?.agents,
|
|
1187
|
+
options?.labels,
|
|
1188
|
+
options?.tasks,
|
|
1189
|
+
branchPrefix,
|
|
1190
|
+
));
|
|
1191
|
+
}
|
|
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
|
+
for (let index = 0; index < worktrees.length; index++) {
|
|
1196
|
+
worktrees[index] = finalizeCreatedWorktree(
|
|
1197
|
+
repo.toplevel,
|
|
1198
|
+
repo.cwdRelative,
|
|
1199
|
+
runId,
|
|
1200
|
+
repo.baseCommit,
|
|
1201
|
+
setupHook,
|
|
1202
|
+
options?.agents?.[index],
|
|
1203
|
+
worktrees[index]!,
|
|
1204
|
+
);
|
|
1205
|
+
}
|
|
697
1206
|
}
|
|
698
1207
|
} catch (error) {
|
|
699
1208
|
cleanupWorktrees({
|