mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-20 07:15:25 +00:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
524116e111 | ||
|
|
1230337165 |
@@ -471,6 +471,18 @@ Workspace records decide ownership, including explicit non-ownership after recov
|
||||
ownership checks prefer the marker-verified worktree root over the legacy
|
||||
path shape: a plugin can place a worktree several directories below the default worktrees root.
|
||||
|
||||
A plugin can also take over worktree creation, removal, and restoration with
|
||||
`server.registerWorktreeManager({ create, remove?, restore? })`. It runs after
|
||||
`worktree.create.before` and before `worktree.create.after`, with a 120-second timeout matching Git
|
||||
worktree commands. Paseo snapshots existing worktree paths before calling `create` so a manager
|
||||
cannot adopt a pre-existing directory as Paseo-owned, verifies Git worktree postconditions, records
|
||||
`worktreeManagerPluginId` in `paseo/worktree.json` and on the workspace record,
|
||||
and skips first-agent branch auto-rename. Removal saves `refs/paseo/kept-commits/<sha>` before
|
||||
calling the owning plugin's `remove`, and both `remove` and `restore` carry `untrusted` for fork
|
||||
change requests and fall back to built-in Git when the plugin declines or is disabled. See the
|
||||
[worktree managers reference](../public-docs/plugins/reference.md#worktree-managers) and
|
||||
`plugin-examples/worktrunk`.
|
||||
|
||||
Emit from the operation owner, not a client subscription. Provider history replay must not trigger
|
||||
live hooks. Notifications must not be awaited inside agent mutations: a handler can send a prompt
|
||||
or answer a permission through its own daemon session. Awaiting it there deadlocks that command.
|
||||
|
||||
@@ -589,3 +589,68 @@ describe("sidebar data SDK boundary", () => {
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe("worktree manager SDK boundary", () => {
|
||||
it("types create, remove, and restore handlers with discriminated results and cleanup", () => {
|
||||
expect(
|
||||
typeErrors(`
|
||||
import type {
|
||||
PluginServerContext,
|
||||
WorktreeManagerRegistration,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateResult,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRemoveResult,
|
||||
PluginWorktreeRestoreRequest,
|
||||
PluginWorktreeRestoreResult,
|
||||
} from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const manager: WorktreeManagerRegistration = {
|
||||
async create(request: PluginWorktreeCreateInput, { paseo, signal }) {
|
||||
if (request.kind === "branch-off") {
|
||||
const start: string = request.startPoint ?? request.baseRef;
|
||||
// @ts-expect-error startPoint is read-only
|
||||
request.startPoint = "other";
|
||||
if (!start) return;
|
||||
}
|
||||
if (signal.aborted) return;
|
||||
void paseo;
|
||||
const result: PluginWorktreeCreateResult = { type: "created", path: request.path };
|
||||
return result;
|
||||
},
|
||||
async remove(request: PluginWorktreeRemoveRequest, { signal }) {
|
||||
const reason: "archive" | "rollback" = request.reason;
|
||||
const force: boolean = request.force;
|
||||
const untrusted: boolean = request.untrusted;
|
||||
// @ts-expect-error remove request fields are read-only
|
||||
request.path = "/other";
|
||||
if (!reason || !force || untrusted || signal.aborted) return;
|
||||
const result: PluginWorktreeRemoveResult = { type: "removed" };
|
||||
return result;
|
||||
},
|
||||
async restore(request: PluginWorktreeRestoreRequest) {
|
||||
const untrusted: boolean = request.untrusted;
|
||||
void untrusted;
|
||||
if (request.target.type === "commit") return;
|
||||
if (request.target.type === "from-base") {
|
||||
const base: string = request.target.baseRef;
|
||||
void base;
|
||||
}
|
||||
const result: PluginWorktreeRestoreResult = { type: "restored", path: request.path };
|
||||
return result;
|
||||
},
|
||||
};
|
||||
const dispose: () => void = server.registerWorktreeManager(manager);
|
||||
server.registerWorktreeManager({
|
||||
// @ts-expect-error create result requires discriminant
|
||||
async create() {
|
||||
return { path: "/tmp/wt" };
|
||||
},
|
||||
});
|
||||
return dispose;
|
||||
}
|
||||
`),
|
||||
).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -5,6 +5,7 @@ import type { PluginCleanup } from "../contracts.js";
|
||||
import type { ProviderRegistration } from "./provider.js";
|
||||
import type { UsageSourceRegistration } from "./usage.js";
|
||||
import type { PluginLifecycleRegistration } from "./lifecycle.js";
|
||||
import type { WorktreeManagerRegistration } from "./worktree.js";
|
||||
|
||||
export interface PluginHandlerContext {
|
||||
paseo: PaseoApi;
|
||||
@@ -64,6 +65,7 @@ export interface PluginServerContext extends PluginLifecycleRegistration {
|
||||
): void;
|
||||
registerProvider(provider: ProviderRegistration): void;
|
||||
registerUsageSource(source: UsageSourceRegistration): void;
|
||||
registerWorktreeManager(manager: WorktreeManagerRegistration): () => void;
|
||||
}
|
||||
|
||||
export type PluginServerContribution = (server: PluginServerContext) => PluginCleanup;
|
||||
|
||||
@@ -35,3 +35,14 @@ export { spawnProcess, execCommand, terminateProcess } from "./process.js";
|
||||
|
||||
export { defineAgentTool } from "./agent-tools.js";
|
||||
export type { AgentToolDefinition, AgentToolResult, AgentToolContext } from "./agent-tools.js";
|
||||
export type {
|
||||
PluginWorktreeContext,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeCreateResult,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRemoveResult,
|
||||
PluginWorktreeRestoreTarget,
|
||||
PluginWorktreeRestoreRequest,
|
||||
PluginWorktreeRestoreResult,
|
||||
WorktreeManagerRegistration,
|
||||
} from "./worktree.js";
|
||||
|
||||
@@ -37,7 +37,12 @@ export type PluginWorktreeCreateRequest = {
|
||||
slug: string;
|
||||
path: string;
|
||||
} & (
|
||||
| { kind: "branch-off"; baseRef: string }
|
||||
| {
|
||||
kind: "branch-off";
|
||||
baseRef: string;
|
||||
/** Where the new branch starts when that is not `baseRef`, such as a fork's head. */
|
||||
readonly startPoint?: string;
|
||||
}
|
||||
| { kind: "checkout-branch" }
|
||||
| {
|
||||
kind: "checkout-change-request";
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import type { PluginHookContext, PluginWorktreeCreateRequest } from "./lifecycle.js";
|
||||
|
||||
/** Context passed to worktree manager callbacks. */
|
||||
export type PluginWorktreeContext = PluginHookContext;
|
||||
|
||||
/** Resolved creation request handed to a worktree manager after `worktree.create.before`. */
|
||||
export type PluginWorktreeCreateInput = PluginWorktreeCreateRequest;
|
||||
|
||||
/** Return `{ type: "created", path }` to claim creation, or `undefined` to decline. */
|
||||
export interface PluginWorktreeCreateResult {
|
||||
type: "created";
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface PluginWorktreeRemoveRequest {
|
||||
readonly repoRoot: string | null;
|
||||
readonly path: string;
|
||||
readonly branch: string | null;
|
||||
readonly reason: "archive" | "rollback";
|
||||
readonly force: boolean;
|
||||
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
|
||||
readonly untrusted: boolean;
|
||||
}
|
||||
|
||||
/** Return `{ type: "removed" }` after removing the worktree, or `undefined` to fall back to Git. */
|
||||
export interface PluginWorktreeRemoveResult {
|
||||
type: "removed";
|
||||
}
|
||||
|
||||
export type PluginWorktreeRestoreTarget =
|
||||
| { readonly type: "branch"; readonly branch: string }
|
||||
| { readonly type: "commit"; readonly commit: string }
|
||||
| { readonly type: "from-base"; readonly branch: string; readonly baseRef: string };
|
||||
|
||||
export interface PluginWorktreeRestoreRequest {
|
||||
readonly repoRoot: string;
|
||||
/** Recorded path the worktree must be restored to. */
|
||||
readonly path: string;
|
||||
readonly target: PluginWorktreeRestoreTarget;
|
||||
readonly baseRef: string | null;
|
||||
/** True when the worktree came from an untrusted source such as a fork change request; skip repository-defined hooks. */
|
||||
readonly untrusted: boolean;
|
||||
}
|
||||
|
||||
/** Return `{ type: "restored", path }` after recreating the worktree, or `undefined` to fall back to Git. */
|
||||
export interface PluginWorktreeRestoreResult {
|
||||
type: "restored";
|
||||
path: string;
|
||||
}
|
||||
|
||||
export interface WorktreeManagerRegistration {
|
||||
create(
|
||||
request: PluginWorktreeCreateInput,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeCreateResult | void>;
|
||||
remove?(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeRemoveResult | void>;
|
||||
restore?(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
context: PluginWorktreeContext,
|
||||
): Promise<PluginWorktreeRestoreResult | void>;
|
||||
}
|
||||
@@ -17,10 +17,12 @@ import type {
|
||||
} from "../messages.js";
|
||||
import type { AgentManager, AgentSubscriber, SubscribeOptions } from "./agent-manager.js";
|
||||
import type { AgentStorage } from "./agent-storage.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
|
||||
|
||||
interface CreateAgentLifecycleDispatchDependencies {
|
||||
paseoHome: string;
|
||||
worktreesRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
agentManager: AgentManager;
|
||||
agentStorage: AgentStorage;
|
||||
github: ForgeService;
|
||||
@@ -184,6 +186,7 @@ export class CreateAgentLifecycleDispatch {
|
||||
{
|
||||
paseoHome: this.dependencies.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.dependencies.worktreesRoot,
|
||||
worktreeManagers: this.dependencies.worktreeManagers,
|
||||
github: this.dependencies.github,
|
||||
workspaceGitService: this.dependencies.workspaceGitService,
|
||||
agentManager: this.dependencies.agentManager,
|
||||
|
||||
@@ -139,6 +139,7 @@ export interface PaseoToolHostDependencies {
|
||||
"getSnapshot" | "listWorktrees" | "resolveRepoRoot" | "invalidateWorktrees"
|
||||
>;
|
||||
findWorkspaceIdForCwd?: ArchiveDependencies["findWorkspaceIdForCwd"];
|
||||
worktreeManagers?: ArchiveDependencies["worktreeManagers"];
|
||||
listActiveWorkspaces?: ArchiveDependencies["listActiveWorkspaces"];
|
||||
archiveWorkspaceRecord?: ArchiveDependencies["archiveWorkspaceRecord"];
|
||||
emitWorkspaceUpdatesForWorkspaceIds?: ArchiveDependencies["emitWorkspaceUpdatesForWorkspaceIds"];
|
||||
@@ -3409,6 +3410,7 @@ function archiveWorktreeDependencies(
|
||||
return {
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.worktreesRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
agentManager: context.agentManager,
|
||||
|
||||
@@ -16,10 +16,12 @@ import type { ForgeService } from "../../services/forge-service.js";
|
||||
import type { TerminalManager } from "../../terminal/terminal-manager.js";
|
||||
import { isPaseoOwnedWorktreeCwd } from "../../utils/worktree.js";
|
||||
import type { WorkspaceArchiveContext } from "../workspace-registry.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../plugins/runtime.js";
|
||||
|
||||
export interface AutoArchiveArchiveOptions {
|
||||
paseoHome: string;
|
||||
paseoWorktreesBaseRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
daemonConfigStore: DaemonConfigStore;
|
||||
workspaceGitService: WorkspaceGitServiceImpl;
|
||||
github: ForgeService;
|
||||
@@ -99,6 +101,7 @@ export async function archiveIfSafe(input: {
|
||||
{
|
||||
paseoHome: options.paseoHome,
|
||||
paseoWorktreesBaseRoot: options.paseoWorktreesBaseRoot,
|
||||
worktreeManagers: options.worktreeManagers,
|
||||
github: options.github,
|
||||
workspaceGitService: options.workspaceGitService,
|
||||
agentManager: options.agentManager,
|
||||
|
||||
@@ -1160,6 +1160,8 @@ export async function createPaseoDaemon(
|
||||
worktreeRoot: workspace.worktreeRoot,
|
||||
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
|
||||
untrustedSource: workspace.untrustedSource,
|
||||
}));
|
||||
};
|
||||
const markWorkspaceArchivingExternal = (workspaceIds: Iterable<string>, archivingAt: string) => {
|
||||
@@ -1218,6 +1220,7 @@ export async function createPaseoDaemon(
|
||||
setupAutoArchiveOnMerge({
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
daemonConfigStore,
|
||||
workspaceGitService,
|
||||
github,
|
||||
@@ -1246,6 +1249,7 @@ export async function createPaseoDaemon(
|
||||
createPaseoWorktree: async (workflowInput, workflowOptions) => {
|
||||
return createRegisteredPaseoWorktree(workflowInput, {
|
||||
lifecycle: pluginRuntime,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
...(workflowOptions?.resolveDefaultBranch
|
||||
? {
|
||||
@@ -1306,6 +1310,7 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1330,6 +1335,7 @@ export async function createPaseoDaemon(
|
||||
const hubAgentLifecycle = new CreateAgentLifecycleDispatch({
|
||||
paseoHome: config.paseoHome,
|
||||
worktreesRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
agentManager,
|
||||
agentStorage,
|
||||
github,
|
||||
@@ -1428,6 +1434,7 @@ export async function createPaseoDaemon(
|
||||
{
|
||||
paseoHome: config.paseoHome,
|
||||
paseoWorktreesBaseRoot: config.worktreesRoot,
|
||||
worktreeManagers: pluginRuntime,
|
||||
github,
|
||||
workspaceGitService,
|
||||
agentManager,
|
||||
@@ -1577,6 +1584,7 @@ export async function createPaseoDaemon(
|
||||
daemonConfigStore,
|
||||
github,
|
||||
workspaceGitService,
|
||||
worktreeManagers: pluginRuntime,
|
||||
findWorkspaceIdForCwd: findWorkspaceIdForCwdExternal,
|
||||
listActiveWorkspaces: listActiveWorkspacesExternal,
|
||||
archiveWorkspaceRecord: (workspaceId, archivedAt) =>
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import type { JsonValue } from "@getpaseo/protocol/agent-types";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
import { stat } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
|
||||
@@ -63,6 +64,7 @@ export interface AttemptFirstAgentBranchAutoNameResult {
|
||||
|
||||
export interface CreatePaseoWorktreeDeps extends CreateWorktreeCoreDeps {
|
||||
lifecycle?: Pick<PluginLifecycle, "wait" | "before">;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "createWorktree" | "removeWorktree">;
|
||||
workspaceGitService: WorkspaceGitService;
|
||||
workspaceProvisioning: Pick<WorkspaceProvisioningService, "createWorkspaceForWorktree">;
|
||||
}
|
||||
@@ -114,6 +116,7 @@ async function createPaseoWorktreeWithPriority(
|
||||
worktreeRoot: createdWorktree.worktree.worktreePath,
|
||||
branch: createdWorktree.worktree.branchName || null,
|
||||
baseBranch: createdWorktree.worktree.comparisonBaseRef,
|
||||
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
|
||||
title: input.title?.trim() || resolveFirstAgentPromptTitle(input.firstAgentContext),
|
||||
metadata: input.metadata,
|
||||
expectsInitialAgent: Boolean(input.firstAgentContext),
|
||||
@@ -152,6 +155,12 @@ async function createPaseoWorktreeWithPriority(
|
||||
teardownCwds: [],
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesBaseRoot: input.worktreesRoot,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
worktreeManagerPluginId: createdWorktree.worktree.worktreeManagerPluginId ?? null,
|
||||
removeReason: "rollback",
|
||||
untrusted:
|
||||
createdWorktree.intent.kind === "checkout-change-request" &&
|
||||
Boolean(createdWorktree.intent.headRepository),
|
||||
},
|
||||
error,
|
||||
);
|
||||
@@ -286,6 +295,10 @@ async function maybeMarkFirstAgentBranchAutoNameEligible(options: {
|
||||
if (!createdWorktree.created || createdWorktree.intent.kind !== "branch-off") {
|
||||
return;
|
||||
}
|
||||
// A worktree manager plugin owns branch and directory naming, so skip silent renames.
|
||||
if (createdWorktree.worktree.worktreeManagerPluginId) {
|
||||
return;
|
||||
}
|
||||
// A branch the caller named is their choice; only a placeholder slug is replaced.
|
||||
if (input.branchName !== undefined) {
|
||||
return;
|
||||
|
||||
@@ -24,7 +24,7 @@ import { type ManagedPluginCandidate, ManagedPluginSources } from "./managed-sou
|
||||
import { readPluginManifest } from "./manifest.js";
|
||||
import { expandTilde } from "../../utils/path.js";
|
||||
import { runPluginBuild } from "./preparation.js";
|
||||
import { PluginRuntime } from "./runtime.js";
|
||||
import { PluginRuntime, type PluginWorktreeManagerRuntime } from "./runtime.js";
|
||||
import type { PluginRuntimeSubscription } from "./runtime-subscription.js";
|
||||
import { BuiltinPluginLoader, type BuiltinPlugin } from "./builtin/index.js";
|
||||
import type {
|
||||
@@ -50,6 +50,9 @@ interface PluginRuntimePort {
|
||||
drainEvents?: PluginRuntime["drainEvents"];
|
||||
before?: PluginLifecycle["before"];
|
||||
wait?: PluginLifecycle["wait"];
|
||||
createWorktree?: PluginWorktreeManagerRuntime["createWorktree"];
|
||||
removeWorktree?: PluginWorktreeManagerRuntime["removeWorktree"];
|
||||
restoreWorktree?: PluginWorktreeManagerRuntime["restoreWorktree"];
|
||||
catalog: PluginRuntime["catalog"];
|
||||
invoke(pluginId: string, method: string, input: unknown): Promise<unknown>;
|
||||
startSubscription: PluginRuntime["startSubscription"];
|
||||
@@ -192,6 +195,27 @@ export class PluginService {
|
||||
return request;
|
||||
};
|
||||
|
||||
readonly createWorktree: PluginWorktreeManagerRuntime["createWorktree"] = async (
|
||||
request,
|
||||
options,
|
||||
) => {
|
||||
return (await this.runtime.createWorktree?.(request, options)) ?? null;
|
||||
};
|
||||
|
||||
readonly removeWorktree: PluginWorktreeManagerRuntime["removeWorktree"] = async (
|
||||
request,
|
||||
options,
|
||||
) => {
|
||||
return (await this.runtime.removeWorktree?.(request, options)) ?? null;
|
||||
};
|
||||
|
||||
readonly restoreWorktree: PluginWorktreeManagerRuntime["restoreWorktree"] = async (
|
||||
request,
|
||||
options,
|
||||
) => {
|
||||
return (await this.runtime.restoreWorktree?.(request, options)) ?? null;
|
||||
};
|
||||
|
||||
subscribeSettings(listener: (pluginId: string, settingsId: string) => void): () => void {
|
||||
this.settingsListeners.add(listener);
|
||||
return () => this.settingsListeners.delete(listener);
|
||||
|
||||
@@ -57,7 +57,12 @@ const changeRequestFields = {
|
||||
};
|
||||
const worktreeRequestSchema = z.discriminatedUnion("kind", [
|
||||
z
|
||||
.object({ ...worktreeRequestFields, kind: z.literal("branch-off"), baseRef: z.string().min(1) })
|
||||
.object({
|
||||
...worktreeRequestFields,
|
||||
kind: z.literal("branch-off"),
|
||||
baseRef: z.string().min(1),
|
||||
startPoint: z.string().min(1).optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
@@ -239,6 +244,28 @@ function changesSessionOpenTarget(previous: SessionOpenRequest, next: SessionOpe
|
||||
);
|
||||
}
|
||||
|
||||
type WorktreeBeforeRequest = z.infer<(typeof beforeSchemas)["worktree.create.before"]>;
|
||||
|
||||
function validateWorktreeBeforeResult(
|
||||
previous: WorktreeBeforeRequest,
|
||||
next: WorktreeBeforeRequest,
|
||||
): WorktreeBeforeRequest {
|
||||
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
|
||||
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
|
||||
}
|
||||
if (previous.kind === "branch-off" && next.kind === "branch-off") {
|
||||
if (next.startPoint !== undefined && next.startPoint !== previous.startPoint) {
|
||||
throw new Error("worktree.create.before hooks cannot change startPoint");
|
||||
}
|
||||
if (next.startPoint === undefined && previous.startPoint !== undefined) {
|
||||
return { ...next, startPoint: previous.startPoint };
|
||||
}
|
||||
} else if (next.kind === "branch-off" && next.startPoint !== undefined) {
|
||||
throw new Error("worktree.create.before hooks cannot change startPoint");
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
export async function validateBeforeResult<Name extends keyof PluginWireBeforeRequests>(
|
||||
name: Name,
|
||||
input: PluginWireBeforeRequests[Name],
|
||||
@@ -280,9 +307,7 @@ export async function validateBeforeResult<Name extends keyof PluginWireBeforeRe
|
||||
if (name === "worktree.create.before") {
|
||||
const previous = beforeSchemas["worktree.create.before"].parse(input);
|
||||
const next = beforeSchemas["worktree.create.before"].parse(result);
|
||||
if (previous.repoRoot !== next.repoRoot || previous.sourceCheckout !== next.sourceCheckout) {
|
||||
throw new Error("worktree.create.before hooks cannot change repoRoot or sourceCheckout");
|
||||
}
|
||||
return validateWorktreeBeforeResult(previous, next) as PluginWireBeforeRequests[Name];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@@ -45,6 +45,11 @@ export interface PluginUsageSourceMetadata {
|
||||
icon?: string;
|
||||
}
|
||||
|
||||
export interface PluginWorktreeManagerCapabilities {
|
||||
hasRemove: boolean;
|
||||
hasRestore: boolean;
|
||||
}
|
||||
|
||||
export type PluginProcessRequest =
|
||||
| { type: "tool.call"; requestId: string; agent: PluginHookAgent; name: string; input: unknown }
|
||||
| { type: "tool.cancel"; requestId: string }
|
||||
@@ -84,6 +89,10 @@ export type PluginProcessRequest =
|
||||
}
|
||||
| { type: "hook"; requestId: string; name: string; input: unknown }
|
||||
| { type: "hook.cancel"; requestId: string }
|
||||
| { type: "worktree.create"; requestId: string; request: unknown }
|
||||
| { type: "worktree.remove"; requestId: string; request: unknown }
|
||||
| { type: "worktree.restore"; requestId: string; request: unknown }
|
||||
| { type: "worktree.cancel"; requestId: string }
|
||||
| { type: "usage.fetch"; requestId: string; sourceId: string; input: unknown }
|
||||
| { type: "usage.discover"; requestId: string; sourceId: string; scope: UsageScope }
|
||||
| { type: "invoke"; requestId: string; method: string; input: unknown }
|
||||
@@ -115,6 +124,10 @@ export type PluginProcessRequest =
|
||||
export type PluginProcessMessage =
|
||||
| { type: "settings.changed"; settingsId: string }
|
||||
| { type: "hooks.changed"; hooks: string[] }
|
||||
| {
|
||||
type: "worktree_manager.changed";
|
||||
worktreeManager: PluginWorktreeManagerCapabilities | null;
|
||||
}
|
||||
| {
|
||||
type: "ready";
|
||||
methods: string[];
|
||||
@@ -122,6 +135,7 @@ export type PluginProcessMessage =
|
||||
providers: PluginProviderMetadata[];
|
||||
usageSources?: PluginUsageSourceMetadata[];
|
||||
hooks?: string[];
|
||||
worktreeManager?: PluginWorktreeManagerCapabilities | null;
|
||||
}
|
||||
| { type: "result"; requestId: string; output: unknown }
|
||||
| { type: "error"; requestId: string; error: string }
|
||||
@@ -149,6 +163,12 @@ export type PluginProcessMessage =
|
||||
| { type: "paseo_close" };
|
||||
|
||||
const hooksSchema = z.array(z.string());
|
||||
const worktreeManagerCapabilitiesSchema = z
|
||||
.object({
|
||||
hasRemove: z.boolean(),
|
||||
hasRestore: z.boolean(),
|
||||
})
|
||||
.strict();
|
||||
|
||||
const providerMetadataSchema = z
|
||||
.object({
|
||||
@@ -294,6 +314,14 @@ export const PluginProcessRequestSchema: z.ZodType<PluginProcessRequest> = z.dis
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal("hook.cancel"), requestId: z.string() }).strict(),
|
||||
z
|
||||
.object({
|
||||
type: z.enum(["worktree.create", "worktree.remove", "worktree.restore"]),
|
||||
requestId: z.string().min(1),
|
||||
request: z.unknown(),
|
||||
})
|
||||
.strict(),
|
||||
z.object({ type: z.literal("worktree.cancel"), requestId: z.string().min(1) }).strict(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("usage.fetch"),
|
||||
@@ -356,6 +384,12 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
|
||||
[
|
||||
z.object({ type: z.literal("settings.changed"), settingsId: z.string() }).strict(),
|
||||
z.object({ type: z.literal("hooks.changed"), hooks: hooksSchema }).strict(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("worktree_manager.changed"),
|
||||
worktreeManager: worktreeManagerCapabilitiesSchema.nullable(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
.object({
|
||||
type: z.literal("ready"),
|
||||
@@ -364,6 +398,7 @@ export const PluginProcessMessageSchema: z.ZodType<PluginProcessMessage> = z.dis
|
||||
providers: z.array(providerMetadataSchema),
|
||||
usageSources: z.array(usageSourceMetadataSchema).optional(),
|
||||
hooks: hooksSchema.optional(),
|
||||
worktreeManager: worktreeManagerCapabilitiesSchema.nullable().optional(),
|
||||
})
|
||||
.strict(),
|
||||
z
|
||||
|
||||
@@ -16,6 +16,10 @@ import type {
|
||||
PluginHandlerContext,
|
||||
PluginServerContext,
|
||||
PluginServerContribution,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRestoreRequest,
|
||||
WorktreeManagerRegistration,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { assertPluginWireValue } from "@getpaseo/protocol/binary-frames/index";
|
||||
import {
|
||||
@@ -115,6 +119,8 @@ export function createPluginWorker(options: {
|
||||
const subscriptions = new PluginSubscriptionHandlers({ send, sendAndWait });
|
||||
const providers = new Map<string, ProviderRegistration>();
|
||||
const usageSources = new Map<string, UsageSourceRegistration>();
|
||||
let worktreeManager: WorktreeManagerRegistration | null = null;
|
||||
const worktreeRequests = new Map<string, AbortController>();
|
||||
const providerConnections = new Map<
|
||||
string,
|
||||
{ connection: ProviderConnection; unsubscribe: () => void; closing?: Promise<void> }
|
||||
@@ -228,6 +234,36 @@ export function createPluginWorker(options: {
|
||||
usageSources.set(id, { ...source, id });
|
||||
}
|
||||
|
||||
function worktreeManagerCapabilities() {
|
||||
if (!worktreeManager) return null;
|
||||
return {
|
||||
hasRemove: worktreeManager.remove !== undefined,
|
||||
hasRestore: worktreeManager.restore !== undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function registerWorktreeManager(manager: WorktreeManagerRegistration): () => void {
|
||||
if (!manager || typeof manager.create !== "function") {
|
||||
throw new Error("Plugin worktree manager must implement create()");
|
||||
}
|
||||
if (manager.remove !== undefined && typeof manager.remove !== "function") {
|
||||
throw new Error("Invalid remove callback for plugin worktree manager");
|
||||
}
|
||||
if (manager.restore !== undefined && typeof manager.restore !== "function") {
|
||||
throw new Error("Invalid restore callback for plugin worktree manager");
|
||||
}
|
||||
if (worktreeManager !== null) {
|
||||
throw new Error("Plugin already registered a worktree manager");
|
||||
}
|
||||
worktreeManager = manager;
|
||||
send({ type: "worktree_manager.changed", worktreeManager: worktreeManagerCapabilities() });
|
||||
return () => {
|
||||
if (worktreeManager !== manager) return;
|
||||
worktreeManager = null;
|
||||
send({ type: "worktree_manager.changed", worktreeManager: null });
|
||||
};
|
||||
}
|
||||
|
||||
function providerMetadata(provider: ProviderRegistration) {
|
||||
return {
|
||||
id: provider.id,
|
||||
@@ -433,6 +469,7 @@ export function createPluginWorker(options: {
|
||||
handle,
|
||||
registerProvider,
|
||||
registerUsageSource,
|
||||
registerWorktreeManager,
|
||||
registerSettings,
|
||||
addHook: hooks.addHook,
|
||||
on: hooks.on,
|
||||
@@ -459,6 +496,7 @@ export function createPluginWorker(options: {
|
||||
methods: [...handlers.keys()].sort(),
|
||||
subscriptions: subscriptions.catalog(),
|
||||
hooks: hooks.catalog(),
|
||||
worktreeManager: worktreeManagerCapabilities(),
|
||||
providers: [...providers.values()]
|
||||
.sort((left, right) => left.id.localeCompare(right.id))
|
||||
.map(providerMetadata),
|
||||
@@ -478,6 +516,8 @@ export function createPluginWorker(options: {
|
||||
for (const pending of pendingProviderConnections.values()) pending.tombstoned = true;
|
||||
for (const request of installationRequests.values())
|
||||
request.abort(new Error("Plugin is stopping"));
|
||||
for (const request of worktreeRequests.values()) request.abort(new Error("Plugin is stopping"));
|
||||
worktreeManager = null;
|
||||
const currentCleanup = cleanup;
|
||||
cleanup = null;
|
||||
try {
|
||||
@@ -519,6 +559,9 @@ export function createPluginWorker(options: {
|
||||
message.type === "provider.catalog_key" ||
|
||||
message.type === "usage.fetch" ||
|
||||
message.type === "usage.discover" ||
|
||||
message.type === "worktree.create" ||
|
||||
message.type === "worktree.remove" ||
|
||||
message.type === "worktree.restore" ||
|
||||
message.type === "subscribe"
|
||||
) {
|
||||
send({ type: "error", requestId: message.requestId, error: "Plugin is stopping" });
|
||||
@@ -704,6 +747,10 @@ export function createPluginWorker(options: {
|
||||
handleHookMessage(message);
|
||||
return;
|
||||
}
|
||||
if (isWorktreeMessage(message)) {
|
||||
handleWorktreeMessage(message);
|
||||
return;
|
||||
}
|
||||
if (message.type === "invoke") invoke(message);
|
||||
else handleSubscriptionMessage(message);
|
||||
}
|
||||
@@ -769,6 +816,88 @@ export function createPluginWorker(options: {
|
||||
): message is Extract<PluginProcessRequest, { type: "hook" | "hook.cancel" }> {
|
||||
return message.type === "hook" || message.type === "hook.cancel";
|
||||
}
|
||||
|
||||
function isWorktreeMessage(
|
||||
message: PluginProcessRequest,
|
||||
): message is Extract<
|
||||
PluginProcessRequest,
|
||||
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
|
||||
> {
|
||||
return (
|
||||
message.type === "worktree.create" ||
|
||||
message.type === "worktree.remove" ||
|
||||
message.type === "worktree.restore" ||
|
||||
message.type === "worktree.cancel"
|
||||
);
|
||||
}
|
||||
|
||||
function handleWorktreeMessage(
|
||||
message: Extract<
|
||||
PluginProcessRequest,
|
||||
{ type: "worktree.create" | "worktree.remove" | "worktree.restore" | "worktree.cancel" }
|
||||
>,
|
||||
): void {
|
||||
if (message.type === "worktree.cancel") {
|
||||
worktreeRequests.get(message.requestId)?.abort(new Error("Worktree request canceled"));
|
||||
return;
|
||||
}
|
||||
if (!paseo) {
|
||||
send({
|
||||
type: "error",
|
||||
requestId: message.requestId,
|
||||
error: "Plugin Paseo API is unavailable",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const manager = worktreeManager;
|
||||
if (!manager) {
|
||||
send({
|
||||
type: "error",
|
||||
requestId: message.requestId,
|
||||
error: "Plugin has no registered worktree manager",
|
||||
});
|
||||
return;
|
||||
}
|
||||
const controller = new AbortController();
|
||||
worktreeRequests.set(message.requestId, controller);
|
||||
const context = { paseo, signal: controller.signal };
|
||||
void (async () => {
|
||||
if (message.type === "worktree.create") {
|
||||
return (
|
||||
(await manager.create(
|
||||
structuredClone(message.request) as PluginWorktreeCreateInput,
|
||||
context,
|
||||
)) ?? null
|
||||
);
|
||||
}
|
||||
if (message.type === "worktree.remove") {
|
||||
if (!manager.remove) {
|
||||
throw new Error("Plugin worktree manager does not implement remove");
|
||||
}
|
||||
return (
|
||||
(await manager.remove(
|
||||
structuredClone(message.request) as PluginWorktreeRemoveRequest,
|
||||
context,
|
||||
)) ?? null
|
||||
);
|
||||
}
|
||||
if (!manager.restore) {
|
||||
throw new Error("Plugin worktree manager does not implement restore");
|
||||
}
|
||||
return (
|
||||
(await manager.restore(
|
||||
structuredClone(message.request) as PluginWorktreeRestoreRequest,
|
||||
context,
|
||||
)) ?? null
|
||||
);
|
||||
})()
|
||||
.then(
|
||||
(output) => send({ type: "result", requestId: message.requestId, output }),
|
||||
(error) =>
|
||||
send({ type: "error", requestId: message.requestId, error: describeError(error) }),
|
||||
)
|
||||
.finally(() => worktreeRequests.delete(message.requestId));
|
||||
}
|
||||
return { shutdown };
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,15 @@ import {
|
||||
type ProviderStatus,
|
||||
type ProviderStatusRequest,
|
||||
} from "@getpaseo/plugin/server/provider";
|
||||
import type { PluginHookEvents, PluginHookAgent, AgentToolResult } from "@getpaseo/plugin/server";
|
||||
import type {
|
||||
PluginHookEvents,
|
||||
PluginHookAgent,
|
||||
AgentToolResult,
|
||||
PluginWorktreeCreateInput,
|
||||
PluginWorktreeRemoveRequest,
|
||||
PluginWorktreeRestoreRequest,
|
||||
} from "@getpaseo/plugin/server";
|
||||
import { z } from "zod";
|
||||
import { validateBeforeRequest, validateBeforeResult } from "./lifecycle/index.js";
|
||||
import { fork } from "node:child_process";
|
||||
import path from "node:path";
|
||||
@@ -42,6 +50,7 @@ import type {
|
||||
PluginProcessRequest,
|
||||
PluginProviderMetadata,
|
||||
PluginUsageSourceMetadata,
|
||||
PluginWorktreeManagerCapabilities,
|
||||
} from "./plugin-process-protocol.js";
|
||||
import { PluginProcessMessageSchema } from "./plugin-process-protocol.js";
|
||||
import {
|
||||
@@ -53,7 +62,36 @@ import { InternalPluginChild } from "./internal-child.js";
|
||||
import { evaluateBundle } from "./bundle-evaluator.js";
|
||||
|
||||
const REQUEST_TIMEOUT_MS = 30_000;
|
||||
const WORKTREE_MANAGER_TIMEOUT_MS = 120_000;
|
||||
const TOOL_CALL_TIMEOUT_MS = 10 * 60_000;
|
||||
|
||||
const worktreeCreateResultSchema = z
|
||||
.object({ type: z.literal("created"), path: z.string().min(1) })
|
||||
.strict()
|
||||
.nullable();
|
||||
const worktreeRemoveResultSchema = z
|
||||
.object({ type: z.literal("removed") })
|
||||
.strict()
|
||||
.nullable();
|
||||
const worktreeRestoreResultSchema = z
|
||||
.object({ type: z.literal("restored"), path: z.string().min(1) })
|
||||
.strict()
|
||||
.nullable();
|
||||
|
||||
export interface PluginWorktreeManagerRuntime {
|
||||
createWorktree(
|
||||
request: PluginWorktreeCreateInput,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null>;
|
||||
removeWorktree(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string } | null>;
|
||||
restoreWorktree(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null>;
|
||||
}
|
||||
const MAX_LOG_ENTRIES = 500;
|
||||
const MAX_LOG_BYTES = 256 * 1024;
|
||||
const MAX_LOG_LINE_BYTES = 16 * 1024;
|
||||
@@ -100,6 +138,7 @@ interface LoadedPlugin {
|
||||
subscriptionMethods: ReadonlySet<string>;
|
||||
subscriptions: Map<string, BufferedPluginSubscription>;
|
||||
hooks: string[];
|
||||
worktreeManager: PluginWorktreeManagerCapabilities | null;
|
||||
providers: readonly PluginProviderMetadata[];
|
||||
usageSources: readonly PluginUsageSourceMetadata[];
|
||||
child: PluginChild | null;
|
||||
@@ -293,8 +332,17 @@ function isInstallationRequest(message: PluginProcessRequest): boolean {
|
||||
);
|
||||
}
|
||||
|
||||
function isWorktreeManagerRequest(message: PluginProcessRequest): boolean {
|
||||
return (
|
||||
message.type === "worktree.create" ||
|
||||
message.type === "worktree.remove" ||
|
||||
message.type === "worktree.restore"
|
||||
);
|
||||
}
|
||||
|
||||
function requestTimeoutMs(message: PluginProcessRequest): number | null {
|
||||
if (message.type === "tool.call") return TOOL_CALL_TIMEOUT_MS;
|
||||
if (isWorktreeManagerRequest(message)) return WORKTREE_MANAGER_TIMEOUT_MS;
|
||||
// An updater runs as long as it needs; daemon shutdown aborts it.
|
||||
if (message.type === "provider.installation.update") return null;
|
||||
return REQUEST_TIMEOUT_MS;
|
||||
@@ -752,6 +800,83 @@ export class PluginRuntime {
|
||||
return request;
|
||||
}
|
||||
|
||||
async createWorktree(
|
||||
request: PluginWorktreeCreateInput,
|
||||
options?: { signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null> {
|
||||
const plugins = [...this.plugins.values()]
|
||||
.filter((plugin) => plugin.worktreeManager !== null)
|
||||
.sort((left, right) => left.id.localeCompare(right.id));
|
||||
for (const loaded of plugins) {
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.create", requestId: randomUUID(), request },
|
||||
{ signal: options?.signal },
|
||||
);
|
||||
const parsed = worktreeCreateResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id, path: parsed.path };
|
||||
}
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.create failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
async removeWorktree(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string } | null> {
|
||||
if (!options?.preferredPluginId) return null;
|
||||
const loaded = this.plugins.get(options.preferredPluginId);
|
||||
if (!loaded?.worktreeManager?.hasRemove) return null;
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.remove", requestId: randomUUID(), request },
|
||||
{ signal: options.signal },
|
||||
);
|
||||
const parsed = worktreeRemoveResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id };
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.remove failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async restoreWorktree(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
options?: { preferredPluginId?: string; signal?: AbortSignal },
|
||||
): Promise<{ pluginId: string; path: string } | null> {
|
||||
if (!options?.preferredPluginId) return null;
|
||||
const loaded = this.plugins.get(options.preferredPluginId);
|
||||
if (!loaded?.worktreeManager?.hasRestore) return null;
|
||||
try {
|
||||
const raw = await this.request(
|
||||
loaded,
|
||||
{ type: "worktree.restore", requestId: randomUUID(), request },
|
||||
{ signal: options.signal },
|
||||
);
|
||||
const parsed = worktreeRestoreResultSchema.parse(raw ?? null);
|
||||
if (parsed !== null) {
|
||||
return { pluginId: loaded.id, path: parsed.path };
|
||||
}
|
||||
return null;
|
||||
} catch (error) {
|
||||
throw new Error(`Plugin ${loaded.id} worktree.restore failed: ${describeError(error)}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async getProviderCatalogCacheKey(
|
||||
pluginId: string,
|
||||
providerId: string,
|
||||
@@ -853,10 +978,12 @@ export class PluginRuntime {
|
||||
loaded.pending.delete(requestId);
|
||||
if (message.type === "tool.call")
|
||||
void send(child, { type: "tool.cancel", requestId }).catch(() => {});
|
||||
if (isWorktreeManagerRequest(message))
|
||||
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
|
||||
if (isInstallationRequest(message))
|
||||
void send(child, { type: "provider.installation.cancel", requestId }).catch(() => {});
|
||||
signal?.removeEventListener("abort", cancel);
|
||||
reject(signal?.reason ?? new Error("Tool call canceled"));
|
||||
reject(signal?.reason ?? new Error("Plugin request canceled"));
|
||||
};
|
||||
const timeoutMs = requestTimeoutMs(message);
|
||||
const timeout =
|
||||
@@ -870,6 +997,9 @@ export class PluginRuntime {
|
||||
if (message.type === "hook") {
|
||||
void send(child, { type: "hook.cancel", requestId }).catch(() => {});
|
||||
}
|
||||
if (isWorktreeManagerRequest(message)) {
|
||||
void send(child, { type: "worktree.cancel", requestId }).catch(() => {});
|
||||
}
|
||||
// The handler may still start after the daemon gave up on it.
|
||||
if (message.type === "subscribe") {
|
||||
const { subscriptionId } = message;
|
||||
@@ -935,6 +1065,7 @@ export class PluginRuntime {
|
||||
subscriptionMethods: new Set(),
|
||||
subscriptions: new Map(),
|
||||
hooks: [],
|
||||
worktreeManager: null,
|
||||
providers: [],
|
||||
usageSources: [],
|
||||
child: null,
|
||||
@@ -1067,6 +1198,7 @@ export class PluginRuntime {
|
||||
subscriptionMethods: new Set(ready.subscriptions ?? []),
|
||||
subscriptions: new Map(),
|
||||
hooks: ready.hooks ?? [],
|
||||
worktreeManager: ready.worktreeManager ?? null,
|
||||
providers: ready.providers ?? [],
|
||||
usageSources: ready.usageSources ?? [],
|
||||
child,
|
||||
@@ -1156,6 +1288,10 @@ export class PluginRuntime {
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (message.type === "worktree_manager.changed") {
|
||||
loaded.worktreeManager = message.worktreeManager;
|
||||
return;
|
||||
}
|
||||
if (message.type === "settings.changed") {
|
||||
this.dependencies.onSettingsChanged?.(loaded.id, message.settingsId);
|
||||
return;
|
||||
|
||||
@@ -0,0 +1,692 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmod, mkdir, mkdtemp, readFile, realpath, rm, stat, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { expect, test } from "vitest";
|
||||
import { DaemonClient } from "../test-utils/daemon-client.js";
|
||||
import { createTestPaseoDaemon } from "../test-utils/paseo-daemon.js";
|
||||
import { readPaseoWorktreeMetadata } from "../../utils/worktree-metadata.js";
|
||||
|
||||
const REPO_ROOT = path.resolve(fileURLToPath(new URL("../../../../..", import.meta.url)));
|
||||
const WORKTRUNK_EXAMPLE = path.join(REPO_ROOT, "plugin-examples", "worktrunk");
|
||||
|
||||
function git(cwd: string, args: string[]): string {
|
||||
return execFileSync(
|
||||
"git",
|
||||
[
|
||||
"-c",
|
||||
"user.name=Test",
|
||||
"-c",
|
||||
"user.email=test@example.com",
|
||||
"-c",
|
||||
"commit.gpgsign=false",
|
||||
...args,
|
||||
],
|
||||
{ cwd, encoding: "utf8", stdio: "pipe" },
|
||||
).trim();
|
||||
}
|
||||
|
||||
async function createRepo(dir: string): Promise<string> {
|
||||
await mkdir(dir, { recursive: true });
|
||||
git(dir, ["init", "-b", "main"]);
|
||||
await writeFile(path.join(dir, "README.md"), "hello\n");
|
||||
git(dir, ["add", "README.md"]);
|
||||
git(dir, ["commit", "-m", "initial"]);
|
||||
return realpath(dir);
|
||||
}
|
||||
|
||||
async function createFakeWorktrunkCli(dir: string, logFile: string): Promise<string> {
|
||||
const scriptPath = path.join(dir, "fake-wt.mjs");
|
||||
await writeFile(
|
||||
scriptPath,
|
||||
`#!/usr/bin/env node
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync, mkdirSync, writeFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
const rawArgs = process.argv.slice(2);
|
||||
let cwd = process.cwd();
|
||||
const args = [];
|
||||
for (let index = 0; index < rawArgs.length; index++) {
|
||||
if (rawArgs[index] === "-C" && rawArgs[index + 1]) {
|
||||
cwd = rawArgs[++index];
|
||||
} else {
|
||||
args.push(rawArgs[index]);
|
||||
}
|
||||
}
|
||||
|
||||
const command = args[0];
|
||||
if (command === "switch") {
|
||||
const create = args.includes("--create");
|
||||
const baseIdx = args.indexOf("--base");
|
||||
const base = baseIdx !== -1 ? args[baseIdx + 1] : undefined;
|
||||
const pathIdx = args.indexOf("--path");
|
||||
const explicitPath = pathIdx !== -1 ? args[pathIdx + 1] : undefined;
|
||||
const skip = new Set(["switch", "--create", "--no-cd", "--yes", "--no-hooks", "--format=json"]);
|
||||
if (baseIdx !== -1) {
|
||||
skip.add("--base");
|
||||
skip.add(base);
|
||||
}
|
||||
if (pathIdx !== -1) {
|
||||
skip.add("--path");
|
||||
skip.add(explicitPath);
|
||||
}
|
||||
const branch = args.find((arg) => !skip.has(arg));
|
||||
if (!branch) {
|
||||
console.error("missing branch");
|
||||
process.exit(1);
|
||||
}
|
||||
if (!create && !explicitPath && branch === "main") {
|
||||
appendFileSync(
|
||||
${JSON.stringify(logFile)},
|
||||
JSON.stringify({ command: "switch", cwd, branch, action: "existing", args }) + "\\n",
|
||||
);
|
||||
process.stdout.write(JSON.stringify({ path: cwd, branch, action: "existing" }) + "\\n");
|
||||
process.exit(0);
|
||||
}
|
||||
const repoName = path.basename(cwd);
|
||||
const target =
|
||||
explicitPath ?? path.join(path.dirname(cwd), \`\${repoName}.\${branch.replaceAll("/", "-")}\`);
|
||||
mkdirSync(path.dirname(target), { recursive: true });
|
||||
const gitArgs = create
|
||||
? ["worktree", "add", "-b", branch, target, ...(base ? [base] : [])]
|
||||
: ["worktree", "add", target, branch];
|
||||
execFileSync("git", gitArgs, { cwd, stdio: "pipe" });
|
||||
writeFileSync(path.join(target, ".wt-hook-ran"), create ? "pre-start" : "reopen");
|
||||
appendFileSync(
|
||||
${JSON.stringify(logFile)},
|
||||
JSON.stringify({ command: "switch", cwd, branch, base, create, explicitPath, target, args }) + "\\n",
|
||||
);
|
||||
process.stdout.write(JSON.stringify({ path: target, branch, action: "created" }) + "\\n");
|
||||
if (branch.endsWith("fail-pre-start")) {
|
||||
console.error("pre-start hook failed");
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (command === "remove") {
|
||||
const target = args.at(-1);
|
||||
const keptRefs = execFileSync("git", ["for-each-ref", "--format=%(refname)", "refs/paseo/kept-commits"], {
|
||||
cwd,
|
||||
encoding: "utf8",
|
||||
stdio: "pipe",
|
||||
})
|
||||
.trim()
|
||||
.split("\\n")
|
||||
.filter(Boolean);
|
||||
appendFileSync(
|
||||
${JSON.stringify(logFile)},
|
||||
JSON.stringify({ command: "remove", cwd, target, args, keptRefsCount: keptRefs.length }) + "\\n",
|
||||
);
|
||||
execFileSync("git", ["worktree", "remove", target, "--force"], { cwd, stdio: "pipe" });
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
if (command === "config" && args[1] === "state" && args[2] === "marker") {
|
||||
appendFileSync(
|
||||
${JSON.stringify(logFile)},
|
||||
JSON.stringify({ command: "marker", cwd, args: args.slice(3) }) + "\\n",
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
console.error("unexpected wt command: " + rawArgs.join(" "));
|
||||
process.exit(1);
|
||||
`,
|
||||
);
|
||||
if (process.platform === "win32") {
|
||||
const cmdPath = path.join(dir, "fake-wt.cmd");
|
||||
await writeFile(cmdPath, `@node "${scriptPath}" %*\r\n`);
|
||||
return cmdPath;
|
||||
}
|
||||
await chmod(scriptPath, 0o755);
|
||||
return scriptPath;
|
||||
}
|
||||
|
||||
test("plugin-examples/worktrunk manages create, before-hook chaining, archive with kept-commits, and restore across daemon restarts", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktrunk-example-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
git(repository, ["branch", "release"]);
|
||||
const wtLog = path.join(root, "wt-log.jsonl");
|
||||
const fakeWt = await createFakeWorktrunkCli(root, wtLog);
|
||||
const previousBin = process.env.WORKTRUNK_BIN;
|
||||
process.env.WORKTRUNK_BIN = fakeWt;
|
||||
|
||||
const transformPluginDir = path.join(root, "a-branch-transform");
|
||||
await mkdir(transformPluginDir);
|
||||
await writeFile(
|
||||
path.join(transformPluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "a-branch-transform", requirements: { paseo: ">=0.14.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(transformPluginDir, "index.server.ts"),
|
||||
`export default function contribute(server) {
|
||||
return server.addHook("worktree.create.before", async ({ request }) => {
|
||||
if (request.kind !== "branch-off") return;
|
||||
return { ...request, branch: "team/" + request.branch, baseRef: "release" };
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
let daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "state"),
|
||||
cleanup: false,
|
||||
});
|
||||
let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(transformPluginDir)).status).toBe("running");
|
||||
expect((await client.installDirectoryPlugin(WORKTRUNK_EXAMPLE)).status).toBe("running");
|
||||
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, worktreeSlug: "feat-one" },
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspaceId = created.workspace!.id;
|
||||
const worktreePath = created.workspace!.workspaceDirectory;
|
||||
const expectedPath = path.join(path.dirname(repository), "repo.team-feat-one");
|
||||
expect(await realpath(worktreePath)).toBe(await realpath(expectedPath));
|
||||
expect(git(worktreePath, ["branch", "--show-current"])).toBe("team/feat-one");
|
||||
expect(await readFile(path.join(worktreePath, ".wt-hook-ran"), "utf8")).toBe("pre-start");
|
||||
|
||||
const metadata = await readPaseoWorktreeMetadata(worktreePath);
|
||||
expect(metadata).toMatchObject({
|
||||
baseRefName: "release",
|
||||
baseRef: "refs/heads/release",
|
||||
worktreeManagerPluginId: "worktrunk",
|
||||
changeRequestLookupTarget: {
|
||||
headRef: "team/feat-one",
|
||||
localBranchName: "team/feat-one",
|
||||
},
|
||||
});
|
||||
// Worktree manager plugins own branch/directory naming, so auto-rename must stay skipped.
|
||||
expect(
|
||||
metadata && "firstAgentBranchAutoName" in metadata
|
||||
? metadata.firstAgentBranchAutoName
|
||||
: undefined,
|
||||
).toBeUndefined();
|
||||
|
||||
// Checking out a branch already checked out in the main repo causes wt to return
|
||||
// action="existing", so the example declines and Paseo falls back to Git.
|
||||
const checkedOutMain = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, action: "checkout", refName: "main" },
|
||||
});
|
||||
expect(checkedOutMain.error).toBeNull();
|
||||
expect(
|
||||
(await readPaseoWorktreeMetadata(checkedOutMain.workspace!.workspaceDirectory))
|
||||
?.worktreeManagerPluginId,
|
||||
).toBeUndefined();
|
||||
await client.archiveWorkspace(checkedOutMain.workspace!.id);
|
||||
|
||||
// If wt exits non-zero after creating the worktree (e.g. pre-start hook failure),
|
||||
// the example cleans up the partial worktree from stdout before rethrowing.
|
||||
const failedPreStart = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, worktreeSlug: "fail-pre-start" },
|
||||
});
|
||||
expect(failedPreStart.workspace).toBeNull();
|
||||
expect(failedPreStart.error).toContain("pre-start hook failed");
|
||||
await expect(
|
||||
stat(path.join(path.dirname(repository), "repo.team-fail-pre-start")),
|
||||
).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
// Archive delegates removal to `wt remove` (run from repoRoot) AFTER Paseo writes refs/paseo/kept-commits/*.
|
||||
const archived = await client.archiveWorkspace(workspaceId);
|
||||
expect(archived.error).toBeNull();
|
||||
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
// Restart daemon and restore: delegates to `wt switch --path <recordedPath> <branch>`.
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "state"),
|
||||
cleanup: false,
|
||||
pluginsEnabled: true,
|
||||
plugins: {
|
||||
"a-branch-transform": { source: "directory", path: transformPluginDir, enabled: true },
|
||||
worktrunk: { source: "directory", path: WORKTRUNK_EXAMPLE, enabled: true },
|
||||
},
|
||||
});
|
||||
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await client.connect();
|
||||
|
||||
await client.restoreWorkspace(workspaceId);
|
||||
expect(git(worktreePath, ["branch", "--show-current"])).toBe("team/feat-one");
|
||||
expect(await readFile(path.join(worktreePath, ".wt-hook-ran"), "utf8")).toBe("reopen");
|
||||
expect(await readPaseoWorktreeMetadata(worktreePath)).toMatchObject({
|
||||
worktreeManagerPluginId: "worktrunk",
|
||||
baseRefName: "release",
|
||||
});
|
||||
|
||||
const events = (await readFile(wtLog, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
expect(events).toEqual([
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "team/feat-one",
|
||||
base: "release",
|
||||
create: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "main",
|
||||
action: "existing",
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "team/fail-pre-start",
|
||||
create: true,
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "remove",
|
||||
cwd: repository,
|
||||
args: expect.arrayContaining([
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--no-hooks",
|
||||
"--force",
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "remove",
|
||||
cwd: repository,
|
||||
keptRefsCount: 1,
|
||||
args: expect.arrayContaining([
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--yes",
|
||||
"--force",
|
||||
]),
|
||||
}),
|
||||
expect.objectContaining({
|
||||
command: "switch",
|
||||
branch: "team/feat-one",
|
||||
create: false,
|
||||
explicitPath: await realpath(worktreePath),
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
if (previousBin === undefined) delete process.env.WORKTRUNK_BIN;
|
||||
else process.env.WORKTRUNK_BIN = previousBin;
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("worktree manager supports decline fallback, rollback delegation, and disabled-plugin fallback on archive and restore", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-fallback-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
const eventsFile = path.join(root, "events.jsonl");
|
||||
|
||||
const pluginDir = path.join(root, "custom-manager");
|
||||
await mkdir(pluginDir);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "custom-manager", requirements: { paseo: ">=0.16.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "index.server.ts"),
|
||||
`import { execFileSync } from "node:child_process";
|
||||
import { appendFileSync } from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
export default function contribute(server) {
|
||||
const removeManager = server.registerWorktreeManager({
|
||||
async create(request) {
|
||||
if (request.branch === "decline-me") return;
|
||||
const target = path.join(path.dirname(request.repoRoot), "managed-" + request.branch);
|
||||
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
|
||||
cwd: request.repoRoot,
|
||||
stdio: "pipe",
|
||||
});
|
||||
appendFileSync(${JSON.stringify(eventsFile)}, JSON.stringify({ op: "create", branch: request.branch, target }) + "\\n");
|
||||
return { type: "created", path: target };
|
||||
},
|
||||
async remove(request) {
|
||||
appendFileSync(${JSON.stringify(eventsFile)}, JSON.stringify({ op: "remove", reason: request.reason, path: request.path }) + "\\n");
|
||||
execFileSync("git", ["worktree", "remove", request.path, "--force"], {
|
||||
cwd: request.repoRoot,
|
||||
stdio: "pipe",
|
||||
});
|
||||
return { type: "removed" };
|
||||
},
|
||||
});
|
||||
const removeAfter = server.addHook("worktree.create.after", async ({ worktree }) => {
|
||||
if (worktree.branch === "abort-after") {
|
||||
throw new Error("rejected after creation");
|
||||
}
|
||||
});
|
||||
return () => {
|
||||
removeAfter();
|
||||
removeManager();
|
||||
};
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: path.join(root, "state"),
|
||||
cleanup: false,
|
||||
});
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(pluginDir)).status).toBe("running");
|
||||
|
||||
// 1. Declining falls back cleanly to Paseo's built-in git worktree creation.
|
||||
const declined = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "decline-me" },
|
||||
});
|
||||
expect(declined.error).toBeNull();
|
||||
const declinedMeta = await readPaseoWorktreeMetadata(declined.workspace!.workspaceDirectory);
|
||||
expect(declinedMeta?.worktreeManagerPluginId).toBeUndefined();
|
||||
|
||||
// 2. Failure in worktree.create.after rolls back through the manager's remove(reason: "rollback").
|
||||
const aborted = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "abort-after" },
|
||||
});
|
||||
expect(aborted.workspace).toBeNull();
|
||||
expect(aborted.error).toContain("rejected after creation");
|
||||
await expect(
|
||||
stat(path.join(path.dirname(repository), "managed-abort-after")),
|
||||
).rejects.toMatchObject({
|
||||
code: "ENOENT",
|
||||
});
|
||||
|
||||
// 3. Create a managed worktree, then disable the plugin: archive & restore fall back to Git.
|
||||
const managed = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "survive-disable" },
|
||||
});
|
||||
expect(managed.error).toBeNull();
|
||||
const managedPath = managed.workspace!.workspaceDirectory;
|
||||
await client.disablePlugin("custom-manager");
|
||||
|
||||
const archived = await client.archiveWorkspace(managed.workspace!.id);
|
||||
expect(archived.error).toBeNull();
|
||||
await expect(stat(managedPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
await client.restoreWorkspace(managed.workspace!.id);
|
||||
expect(git(managedPath, ["branch", "--show-current"])).toBe("survive-disable");
|
||||
// Re-enabling the plugin must not route removal of a Git-restored worktree back to the plugin.
|
||||
await client.enablePlugin("custom-manager");
|
||||
await client.archiveWorkspace(managed.workspace!.id);
|
||||
await expect(stat(managedPath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
const events = (await readFile(eventsFile, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line));
|
||||
expect(events).toEqual([
|
||||
expect.objectContaining({ op: "create", branch: "abort-after" }),
|
||||
expect.objectContaining({ op: "remove", reason: "rollback" }),
|
||||
expect.objectContaining({ op: "create", branch: "survive-disable" }),
|
||||
]);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("worktree manager rejects pre-existing worktrees, detached HEAD, wrong repos, and non-worktree paths without modifying them", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-guards-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
const otherRepo = await createRepo(path.join(root, "other-repo"));
|
||||
|
||||
// Pre-existing manual worktree the user created outside Paseo.
|
||||
const existingManual = path.join(root, "manual-existing");
|
||||
git(repository, ["worktree", "add", "-b", "manual-branch", existingManual, "main"]);
|
||||
|
||||
const plainDir = path.join(root, "not-a-worktree");
|
||||
await mkdir(plainDir);
|
||||
|
||||
const pluginDir = path.join(root, "bad-manager");
|
||||
await mkdir(pluginDir);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "bad-manager", requirements: { paseo: ">=0.16.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(pluginDir, "index.server.ts"),
|
||||
`import { execFileSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
|
||||
export default function contribute(server) {
|
||||
return server.registerWorktreeManager({
|
||||
async create(request) {
|
||||
if (request.branch === "existing") {
|
||||
return { type: "created", path: ${JSON.stringify(existingManual)} };
|
||||
}
|
||||
if (request.branch === "plain-dir") {
|
||||
return { type: "created", path: ${JSON.stringify(plainDir)} };
|
||||
}
|
||||
if (request.branch === "other-repo") {
|
||||
const target = path.join(${JSON.stringify(root)}, "other-wt");
|
||||
execFileSync("git", ["worktree", "add", "-b", "other-wt", target, "main"], {
|
||||
cwd: ${JSON.stringify(otherRepo)},
|
||||
stdio: "pipe",
|
||||
});
|
||||
return { type: "created", path: target };
|
||||
}
|
||||
if (request.branch === "detached") {
|
||||
const target = path.join(${JSON.stringify(root)}, "detached-wt");
|
||||
execFileSync("git", ["worktree", "add", "--detach", target, "main"], {
|
||||
cwd: request.repoRoot,
|
||||
stdio: "pipe",
|
||||
});
|
||||
return { type: "created", path: target };
|
||||
}
|
||||
return { type: "created", path: "relative/path" };
|
||||
},
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(pluginDir)).status).toBe("running");
|
||||
|
||||
const cases: Array<[string, string]> = [
|
||||
["existing", "already-existing worktree"],
|
||||
["plain-dir", "did not create a Git worktree"],
|
||||
["other-repo", "outside the repository"],
|
||||
["detached", "detached HEAD"],
|
||||
["relative", "relative path"],
|
||||
];
|
||||
for (const [branchName, expectedError] of cases) {
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName },
|
||||
});
|
||||
expect(created.workspace).toBeNull();
|
||||
expect(created.error).toContain(expectedError);
|
||||
}
|
||||
|
||||
// The pre-existing manual worktree must stay untouched and un-owned by Paseo.
|
||||
expect(await readPaseoWorktreeMetadata(existingManual)).toBeNull();
|
||||
expect((await stat(existingManual)).isDirectory()).toBe(true);
|
||||
// The newly created detached worktree failed adoption and must be rolled back cleanly.
|
||||
await expect(stat(path.join(root, "detached-wt"))).rejects.toMatchObject({ code: "ENOENT" });
|
||||
expect(git(repository, ["worktree", "list", "--porcelain"])).not.toContain("detached-wt");
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("worktree manager rejects duplicate registration and fails removal when the directory remains on disk", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktree-manager-edge-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
|
||||
const dupPluginDir = path.join(root, "dup-manager");
|
||||
await mkdir(dupPluginDir);
|
||||
await writeFile(
|
||||
path.join(dupPluginDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "dup-manager", requirements: { paseo: ">=0.16.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(dupPluginDir, "index.server.ts"),
|
||||
`export default function contribute(server) {
|
||||
server.registerWorktreeManager({ async create() {} });
|
||||
server.registerWorktreeManager({ async create() {} });
|
||||
return () => {};
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const leakyRemoveDir = path.join(root, "leaky-remove");
|
||||
await mkdir(leakyRemoveDir);
|
||||
await writeFile(
|
||||
path.join(leakyRemoveDir, "paseo-plugin.json"),
|
||||
JSON.stringify({ id: "leaky-remove", requirements: { paseo: ">=0.16.0" } }),
|
||||
);
|
||||
await writeFile(
|
||||
path.join(leakyRemoveDir, "index.server.ts"),
|
||||
`import { execFileSync } from "node:child_process";
|
||||
import path from "node:path";
|
||||
|
||||
export default function contribute(server) {
|
||||
return server.registerWorktreeManager({
|
||||
async create(request) {
|
||||
const target = path.join(path.dirname(request.repoRoot), "leaky-" + request.branch);
|
||||
execFileSync("git", ["worktree", "add", "-b", request.branch, target, request.baseRef], {
|
||||
cwd: request.repoRoot,
|
||||
stdio: "pipe",
|
||||
});
|
||||
return { type: "created", path: target };
|
||||
},
|
||||
async remove() {
|
||||
// Claims removed without deleting the directory.
|
||||
return { type: "removed" };
|
||||
},
|
||||
});
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
const daemon = await createTestPaseoDaemon();
|
||||
const client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
|
||||
await expect(client.installDirectoryPlugin(dupPluginDir)).rejects.toThrow(
|
||||
"Plugin already registered a worktree manager",
|
||||
);
|
||||
|
||||
expect((await client.installDirectoryPlugin(leakyRemoveDir)).status).toBe("running");
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "still-here" },
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const worktreePath = created.workspace!.workspaceDirectory;
|
||||
|
||||
const archived = await client.archiveWorkspace(created.workspace!.id);
|
||||
expect(archived.error).toBeNull();
|
||||
// Removal failure keeps the directory instead of silently deleting behind the manager.
|
||||
expect((await stat(worktreePath)).isDirectory()).toBe(true);
|
||||
} finally {
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
|
||||
test("untrusted workspaces pass untrusted=true to worktree manager remove and restore, and worktrunk skips hooks", async () => {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "paseo-worktrunk-untrusted-"));
|
||||
const repository = await createRepo(path.join(root, "repo"));
|
||||
const wtLog = path.join(root, "wt-log.jsonl");
|
||||
const fakeWt = await createFakeWorktrunkCli(root, wtLog);
|
||||
const previousBin = process.env.WORKTRUNK_BIN;
|
||||
process.env.WORKTRUNK_BIN = fakeWt;
|
||||
|
||||
const stateDir = path.join(root, "state");
|
||||
let daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: stateDir,
|
||||
cleanup: false,
|
||||
});
|
||||
let client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
try {
|
||||
await client.connect();
|
||||
await client.patchDaemonConfig({ pluginsEnabled: true });
|
||||
expect((await client.installDirectoryPlugin(WORKTRUNK_EXAMPLE)).status).toBe("running");
|
||||
|
||||
const created = await client.createWorkspace({
|
||||
source: { kind: "worktree", cwd: repository, branchName: "fork-pr-branch" },
|
||||
});
|
||||
expect(created.error).toBeNull();
|
||||
const workspaceId = created.workspace!.id;
|
||||
const worktreePath = created.workspace!.workspaceDirectory;
|
||||
|
||||
// Mark the persisted workspace record as originating from an untrusted fork PR and reload daemon.
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
const workspacesPath = path.join(daemon.paseoHome, "projects", "workspaces.json");
|
||||
const records = JSON.parse(await readFile(workspacesPath, "utf8")) as Array<
|
||||
Record<string, unknown>
|
||||
>;
|
||||
for (const record of records) {
|
||||
if (record.workspaceId === workspaceId) {
|
||||
record.untrustedSource = {
|
||||
kind: "change_request",
|
||||
forge: "github",
|
||||
number: 42,
|
||||
headRepository: "fork-owner/repo",
|
||||
};
|
||||
}
|
||||
}
|
||||
await writeFile(workspacesPath, JSON.stringify(records, null, 2));
|
||||
|
||||
daemon = await createTestPaseoDaemon({
|
||||
paseoHomeRoot: stateDir,
|
||||
cleanup: false,
|
||||
pluginsEnabled: true,
|
||||
plugins: {
|
||||
worktrunk: { source: "directory", path: WORKTRUNK_EXAMPLE, enabled: true },
|
||||
},
|
||||
});
|
||||
client = new DaemonClient({ url: `ws://127.0.0.1:${daemon.port}/ws` });
|
||||
await client.connect();
|
||||
|
||||
const archived = await client.archiveWorkspace(workspaceId);
|
||||
expect(archived.error).toBeNull();
|
||||
await expect(stat(worktreePath)).rejects.toMatchObject({ code: "ENOENT" });
|
||||
|
||||
await client.restoreWorkspace(workspaceId);
|
||||
expect(git(worktreePath, ["branch", "--show-current"])).toBe("fork-pr-branch");
|
||||
|
||||
const events = (await readFile(wtLog, "utf8"))
|
||||
.trim()
|
||||
.split("\n")
|
||||
.map((line) => JSON.parse(line) as { command: string; cwd: string; args: string[] });
|
||||
const removeEvent = events.find((event) => event.command === "remove");
|
||||
expect(removeEvent).toBeDefined();
|
||||
expect(removeEvent!.cwd).toBe(repository);
|
||||
expect(removeEvent!.args).toContain("--no-hooks");
|
||||
expect(removeEvent!.args).not.toContain("--yes");
|
||||
|
||||
const restoreEvent = events.at(-1);
|
||||
expect(restoreEvent?.command).toBe("switch");
|
||||
expect(restoreEvent?.args).toContain("--no-hooks");
|
||||
expect(restoreEvent?.args).not.toContain("--yes");
|
||||
} finally {
|
||||
if (previousBin === undefined) delete process.env.WORKTRUNK_BIN;
|
||||
else process.env.WORKTRUNK_BIN = previousBin;
|
||||
await client.close();
|
||||
await daemon.close();
|
||||
await rm(root, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
}
|
||||
}, 60_000);
|
||||
@@ -529,6 +529,9 @@ test("routes plugin requests and releases its owned catalog subscription on clea
|
||||
return request;
|
||||
},
|
||||
emit: () => {},
|
||||
createWorktree: async () => null,
|
||||
removeWorktree: async () => null,
|
||||
restoreWorktree: async () => null,
|
||||
listPlugins: async () => [plugin],
|
||||
getLogs: () => [
|
||||
{
|
||||
@@ -670,6 +673,9 @@ test("leaves out the client bundles a catalog request already holds", async () =
|
||||
const pluginRuntime: NonNullable<SessionOptions["pluginRuntime"]> = {
|
||||
before: async (_name, request) => request,
|
||||
emit: () => {},
|
||||
createWorktree: async () => null,
|
||||
removeWorktree: async () => null,
|
||||
restoreWorktree: async () => null,
|
||||
listPlugins: async () => [],
|
||||
getLogs: () => [],
|
||||
installDirectory: async () => {
|
||||
|
||||
@@ -529,6 +529,9 @@ export interface SessionOptions {
|
||||
wait: import("./plugins/lifecycle/index.js").PluginLifecycle["wait"];
|
||||
before: import("./plugins/lifecycle/index.js").PluginLifecycle["before"];
|
||||
emit: import("./plugins/lifecycle/index.js").PluginLifecycle["emit"];
|
||||
createWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["createWorktree"];
|
||||
removeWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["removeWorktree"];
|
||||
restoreWorktree: import("./plugins/runtime.js").PluginWorktreeManagerRuntime["restoreWorktree"];
|
||||
listPlugins(): Promise<import("@getpaseo/protocol/messages").PluginListItem[]>;
|
||||
getLogs(pluginId: string): import("@getpaseo/protocol/messages").PluginLogEntry[];
|
||||
installDirectory(input: {
|
||||
@@ -1034,6 +1037,7 @@ export class Session {
|
||||
this.workspaceRecovery = createWorkspaceRecoveryService({
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
getWorkspace: (workspaceId) => this.workspaceRegistry.get(workspaceId),
|
||||
getProject: (projectId) => this.projectRegistry.get(projectId),
|
||||
isDirectory: (path) => this.filesystem.isDirectory(path),
|
||||
@@ -1254,6 +1258,7 @@ export class Session {
|
||||
this.createAgentLifecycleDispatch = new CreateAgentLifecycleDispatch({
|
||||
paseoHome: this.paseoHome,
|
||||
worktreesRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
agentManager: this.agentManager,
|
||||
agentStorage: this.agentStorage,
|
||||
github: this.github,
|
||||
@@ -5780,6 +5785,7 @@ export class Session {
|
||||
{
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
agentManager: this.agentManager,
|
||||
@@ -6550,6 +6556,7 @@ export class Session {
|
||||
): Promise<CreatePaseoWorktreeResult> {
|
||||
const result = await createPaseoWorktree(input, {
|
||||
lifecycle: this.pluginRuntime,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
github: this.github,
|
||||
...(options?.resolveDefaultBranch
|
||||
? { resolveDefaultBranch: options.resolveDefaultBranch }
|
||||
@@ -6580,6 +6587,8 @@ export class Session {
|
||||
worktreeRoot: workspace.worktreeRoot,
|
||||
isPaseoOwnedWorktree: workspace.isPaseoOwnedWorktree,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
worktreeManagerPluginId: workspace.worktreeManagerPluginId,
|
||||
untrustedSource: workspace.untrustedSource,
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -8128,6 +8137,7 @@ export class Session {
|
||||
{
|
||||
paseoHome: this.paseoHome,
|
||||
paseoWorktreesBaseRoot: this.worktreesRoot,
|
||||
worktreeManagers: this.pluginRuntime,
|
||||
github: this.github,
|
||||
workspaceGitService: this.workspaceGitService,
|
||||
agentManager: this.agentManager,
|
||||
|
||||
+3
@@ -52,6 +52,7 @@ export interface CreateWorktreeWorkspaceInput {
|
||||
worktreeRoot: string;
|
||||
branch: string | null;
|
||||
baseBranch: string | null;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
title: string | null;
|
||||
metadata?: Record<string, JsonValue>;
|
||||
expectsInitialAgent?: boolean;
|
||||
@@ -279,6 +280,7 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
projectId: project.projectId,
|
||||
...initialWorkspacePlacement({ source: "checkout", cwd: normalizedCwd, checkout }),
|
||||
baseBranch: baseMetadata?.baseRef ?? baseMetadata?.baseRefName ?? null,
|
||||
worktreeManagerPluginId: baseMetadata?.worktreeManagerPluginId ?? null,
|
||||
title: title?.trim() || null,
|
||||
metadata: context?.metadata,
|
||||
createdAt: timestamp,
|
||||
@@ -320,6 +322,7 @@ export function createWorkspaceProvisioningService(deps: {
|
||||
baseBranch: input.baseBranch,
|
||||
mainRepoRoot: repoRoot,
|
||||
}),
|
||||
worktreeManagerPluginId: input.worktreeManagerPluginId ?? null,
|
||||
title: input.title,
|
||||
metadata: input.metadata,
|
||||
createdAt: timestamp,
|
||||
|
||||
+116
-11
@@ -5,12 +5,18 @@ import { resolveRepositoryDefaultBranch } from "../../../utils/checkout-git.js";
|
||||
import { createRealpathAwarePathMatcher } from "../../../utils/path.js";
|
||||
import { runGitCommand } from "../../../utils/run-git-command.js";
|
||||
import {
|
||||
adoptPluginWorktree,
|
||||
cleanupFailedPluginWorktree,
|
||||
createWorktree,
|
||||
isPaseoOwnedWorktreeCwd,
|
||||
listGitWorktreePaths,
|
||||
mapWorkspaceCwdToWorktree,
|
||||
rollbackCreatedPaseoWorktree,
|
||||
type WorktreeSource,
|
||||
} from "../../../utils/worktree.js";
|
||||
import { validateWorktreePath } from "../../../utils/worktree-path.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../../plugins/runtime.js";
|
||||
import type { PluginWorktreeRestoreTarget } from "@getpaseo/plugin/server";
|
||||
import { WorktreeRequestError, toWorktreeRequestError } from "../../worktree-errors.js";
|
||||
import {
|
||||
resolveWorkspaceDisplayName,
|
||||
@@ -64,6 +70,7 @@ type UnavailableRecoveryState = Extract<WorkspaceRecoveryState, { kind: "unavail
|
||||
export function createWorkspaceRecoveryService(deps: {
|
||||
paseoHome: string;
|
||||
worktreesRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "restoreWorktree" | "removeWorktree">;
|
||||
getWorkspace: (workspaceId: string) => Promise<PersistedWorkspaceRecord | null>;
|
||||
getProject: (projectId: string) => Promise<PersistedProjectRecord | null>;
|
||||
isDirectory: (path: string) => Promise<boolean>;
|
||||
@@ -140,17 +147,27 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
throw new Error(resolved.message);
|
||||
}
|
||||
|
||||
let workspaceToUnarchive = resolved.workspace;
|
||||
if (resolved.kind === "restore") {
|
||||
await recreateArchivedWorktree(resolved.workspace, resolved.sourceRepoRoot);
|
||||
const restoredByPluginId = await recreateArchivedWorktree(
|
||||
resolved.workspace,
|
||||
resolved.sourceRepoRoot,
|
||||
);
|
||||
if ((resolved.workspace.worktreeManagerPluginId ?? null) !== restoredByPluginId) {
|
||||
const { worktreeManagerPluginId: _previous, ...withoutManager } = resolved.workspace;
|
||||
workspaceToUnarchive = restoredByPluginId
|
||||
? { ...withoutManager, worktreeManagerPluginId: restoredByPluginId }
|
||||
: withoutManager;
|
||||
}
|
||||
}
|
||||
await deps.unarchiveWorkspace(resolved.workspace);
|
||||
await deps.unarchiveWorkspace(workspaceToUnarchive);
|
||||
return { workspaceId, action: resolved.kind };
|
||||
}
|
||||
|
||||
async function recreateArchivedWorktree(
|
||||
workspace: PersistedWorkspaceRecord,
|
||||
sourceRepoRoot: string,
|
||||
): Promise<void> {
|
||||
): Promise<string | null> {
|
||||
let source: WorktreeSource;
|
||||
const checkout = parseWorkspaceHead(workspace);
|
||||
if (checkout.kind === "branch") {
|
||||
@@ -195,17 +212,17 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
}
|
||||
|
||||
let recreatedWorktreePath: string;
|
||||
let restoredByPluginId: string | null = null;
|
||||
try {
|
||||
const result = await createWorktree({
|
||||
cwd: sourceRepoRoot,
|
||||
worktreeSlug: basename(previousWorktreePath),
|
||||
const restored = await recreateWorktreeCheckout({
|
||||
workspace,
|
||||
sourceRepoRoot,
|
||||
source,
|
||||
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesRoot: deps.worktreesRoot,
|
||||
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
|
||||
previousWorktreePath,
|
||||
hasRecordedWorktreePath,
|
||||
});
|
||||
recreatedWorktreePath = result.worktreePath;
|
||||
recreatedWorktreePath = restored.worktreePath;
|
||||
restoredByPluginId = restored.pluginId;
|
||||
} catch (error) {
|
||||
throw toWorktreeRequestError(error);
|
||||
}
|
||||
@@ -236,15 +253,103 @@ export function createWorkspaceRecoveryService(deps: {
|
||||
teardownCwds: [],
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesBaseRoot: deps.worktreesRoot,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
worktreeManagerPluginId: restoredByPluginId,
|
||||
removeReason: "rollback",
|
||||
untrusted: Boolean(workspace.untrustedSource),
|
||||
},
|
||||
error,
|
||||
);
|
||||
}
|
||||
return restoredByPluginId;
|
||||
}
|
||||
|
||||
async function recreateWorktreeCheckout(options: {
|
||||
workspace: PersistedWorkspaceRecord;
|
||||
sourceRepoRoot: string;
|
||||
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>;
|
||||
previousWorktreePath: string;
|
||||
hasRecordedWorktreePath: boolean;
|
||||
}): Promise<{ worktreePath: string; pluginId: string | null }> {
|
||||
const { workspace, sourceRepoRoot, source, previousWorktreePath, hasRecordedWorktreePath } =
|
||||
options;
|
||||
const managerPluginId = workspace.worktreeManagerPluginId;
|
||||
const untrusted = Boolean(workspace.untrustedSource);
|
||||
if (managerPluginId && hasRecordedWorktreePath && deps.worktreeManagers) {
|
||||
const existingWorktreePaths = await listGitWorktreePaths(sourceRepoRoot);
|
||||
const managed = await deps.worktreeManagers.restoreWorktree(
|
||||
{
|
||||
repoRoot: sourceRepoRoot,
|
||||
path: previousWorktreePath,
|
||||
target: restoreTargetFromWorktreeSource(source),
|
||||
baseRef: workspace.baseBranch,
|
||||
untrusted,
|
||||
},
|
||||
{ preferredPluginId: managerPluginId },
|
||||
);
|
||||
if (managed) {
|
||||
try {
|
||||
const validatedPath = await validateWorktreePath({
|
||||
candidate: managed.path,
|
||||
repoPath: sourceRepoRoot,
|
||||
allowExistingPath: true,
|
||||
});
|
||||
if (!createRealpathAwarePathMatcher(previousWorktreePath)(validatedPath)) {
|
||||
throw new WorktreeRequestError({
|
||||
code: "unknown",
|
||||
message: `Plugin ${managed.pluginId} restored worktree to ${validatedPath}, expected ${previousWorktreePath}`,
|
||||
});
|
||||
}
|
||||
const adopted = await adoptPluginWorktree({
|
||||
cwd: sourceRepoRoot,
|
||||
source,
|
||||
worktreePath: validatedPath,
|
||||
worktreeManagerPluginId: managed.pluginId,
|
||||
existingWorktreePaths,
|
||||
});
|
||||
return { worktreePath: adopted.worktreePath, pluginId: managed.pluginId };
|
||||
} catch (error) {
|
||||
await cleanupFailedPluginWorktree({
|
||||
cwd: sourceRepoRoot,
|
||||
candidatePath: managed.path,
|
||||
existingWorktreePaths,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
worktreeManagerPluginId: managed.pluginId,
|
||||
untrusted,
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesBaseRoot: deps.worktreesRoot,
|
||||
}).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = await createWorktree({
|
||||
cwd: sourceRepoRoot,
|
||||
worktreeSlug: basename(previousWorktreePath),
|
||||
source,
|
||||
paseoHome: deps.paseoHome,
|
||||
worktreesRoot: deps.worktreesRoot,
|
||||
...(hasRecordedWorktreePath ? { worktreePath: previousWorktreePath } : {}),
|
||||
});
|
||||
return { worktreePath: result.worktreePath, pluginId: null };
|
||||
}
|
||||
|
||||
return { inspect, restore };
|
||||
}
|
||||
|
||||
function restoreTargetFromWorktreeSource(
|
||||
source: Extract<WorktreeSource, { kind: "restore" | "restore-commit" | "restore-from-base" }>,
|
||||
): PluginWorktreeRestoreTarget {
|
||||
if (source.kind === "restore") {
|
||||
return { type: "branch", branch: source.branchName };
|
||||
}
|
||||
if (source.kind === "restore-commit") {
|
||||
return { type: "commit", commit: source.commit };
|
||||
}
|
||||
return { type: "from-base", branch: source.branchName, baseRef: source.baseRef };
|
||||
}
|
||||
|
||||
async function resolveRecoveryBase(repoRoot: string, recordedBase: string | null): Promise<string> {
|
||||
if (recordedBase) {
|
||||
try {
|
||||
|
||||
@@ -22,16 +22,21 @@ import type {
|
||||
import { createRealpathAwarePathMatcher } from "../utils/path.js";
|
||||
import { runWithGitCommandPriority } from "../utils/run-git-command.js";
|
||||
import { WorkspaceAutomationBlockedError } from "./workspace-automation-gate.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
|
||||
export type ActiveWorkspaceRef = Pick<
|
||||
PersistedWorkspaceRecord,
|
||||
"workspaceId" | "cwd" | "kind" | "worktreeRoot" | "isPaseoOwnedWorktree" | "mainRepoRoot"
|
||||
>;
|
||||
> & {
|
||||
worktreeManagerPluginId?: string | null;
|
||||
untrustedSource?: PersistedWorkspaceRecord["untrustedSource"];
|
||||
};
|
||||
|
||||
export interface ArchiveDependencies {
|
||||
paseoHome?: string;
|
||||
// Base directory that may hold worktrees across repositories.
|
||||
paseoWorktreesBaseRoot?: string;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
github: ForgeService;
|
||||
workspaceGitService: Pick<WorkspaceGitService, "getSnapshot" | "invalidateWorktrees">;
|
||||
agentManager: Pick<AgentManager, "listAgents" | "getAgent" | "archiveAgent" | "archiveSnapshot">;
|
||||
@@ -119,6 +124,8 @@ interface BackingDirectory {
|
||||
registryProven: boolean;
|
||||
mainRepoRoot: string | null;
|
||||
paseoWorktreesRoot: string | null;
|
||||
worktreeManagerPluginId: string | null;
|
||||
untrusted: boolean;
|
||||
}
|
||||
|
||||
interface ArchiveTarget {
|
||||
@@ -313,6 +320,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
workspace: ActiveWorkspaceRef,
|
||||
dependencies: Pick<ArchiveDependencies, "paseoHome" | "paseoWorktreesBaseRoot">,
|
||||
): Promise<BackingDirectory> {
|
||||
const worktreeManagerPluginId = workspace.worktreeManagerPluginId ?? null;
|
||||
const untrusted = Boolean(workspace.untrustedSource);
|
||||
if (workspace.isPaseoOwnedWorktree === false) {
|
||||
return {
|
||||
path: resolve(workspace.worktreeRoot ?? workspace.cwd),
|
||||
@@ -321,6 +330,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
if (workspace.isPaseoOwnedWorktree && workspace.worktreeRoot && workspace.mainRepoRoot) {
|
||||
@@ -331,6 +342,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: true,
|
||||
mainRepoRoot: workspace.mainRepoRoot,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
if (workspace.kind !== "worktree") {
|
||||
@@ -341,6 +354,8 @@ async function resolveWorkspaceBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? null,
|
||||
paseoWorktreesRoot: null,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -350,7 +365,12 @@ async function resolveWorkspaceBackingDirectory(
|
||||
workspace.worktreeRoot ?? workspace.cwd,
|
||||
dependencies,
|
||||
);
|
||||
return { ...backing, mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot };
|
||||
return {
|
||||
...backing,
|
||||
mainRepoRoot: workspace.mainRepoRoot ?? backing.mainRepoRoot,
|
||||
worktreeManagerPluginId: worktreeManagerPluginId ?? backing.worktreeManagerPluginId,
|
||||
untrusted: untrusted || backing.untrusted,
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveBackingDirectory(
|
||||
@@ -369,6 +389,8 @@ async function resolveBackingDirectory(
|
||||
registryProven: false,
|
||||
mainRepoRoot: ownership.repoRoot ?? null,
|
||||
paseoWorktreesRoot: ownership.worktreeRoot ?? null,
|
||||
worktreeManagerPluginId: null,
|
||||
untrusted: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -453,11 +475,15 @@ async function maybeRemoveDirectory(
|
||||
teardownTarget.workspaceId === null || archivedWorkspaceIdSet.has(teardownTarget.workspaceId),
|
||||
);
|
||||
|
||||
let untrustedBacking = backing.untrusted;
|
||||
try {
|
||||
const allowedTeardownTargets = await filterAllowedTeardownTargets(
|
||||
dependencies,
|
||||
teardownTargets,
|
||||
);
|
||||
if (allowedTeardownTargets.length < teardownTargets.length) {
|
||||
untrustedBacking = true;
|
||||
}
|
||||
for (const teardownTarget of uniqueTeardownTargets(allowedTeardownTargets)) {
|
||||
request.checkpoint();
|
||||
await runWorktreeTeardownCommands({
|
||||
@@ -501,6 +527,10 @@ async function maybeRemoveDirectory(
|
||||
paseoHome: dependencies.paseoHome,
|
||||
worktreesBaseRoot: dependencies.paseoWorktreesBaseRoot,
|
||||
registryProven: backing.registryProven,
|
||||
worktreeManagers: dependencies.worktreeManagers,
|
||||
worktreeManagerPluginId: backing.worktreeManagerPluginId,
|
||||
removeReason: "archive",
|
||||
untrusted: untrustedBacking,
|
||||
});
|
||||
dependencies.workspaceGitService.invalidateWorktrees();
|
||||
dependencies.github.invalidate({ cwd: backing.path });
|
||||
|
||||
@@ -88,6 +88,7 @@ const PersistedWorkspaceRecordSchema = z.object({
|
||||
.transform((value) => value ?? null),
|
||||
isPaseoOwnedWorktree: z.boolean().default(false),
|
||||
mainRepoRoot: z.string().nullable().default(null),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
createdAt: z.string(),
|
||||
updatedAt: z.string(),
|
||||
archivedAt: z.string().nullable(),
|
||||
@@ -698,6 +699,7 @@ export function createPersistedWorkspaceRecord(input: {
|
||||
baseBranch?: string | null;
|
||||
isPaseoOwnedWorktree?: boolean;
|
||||
mainRepoRoot?: string | null;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
archivedAt?: string | null;
|
||||
@@ -708,7 +710,7 @@ export function createPersistedWorkspaceRecord(input: {
|
||||
untrustedSource?: UntrustedWorkspaceSource;
|
||||
background?: boolean;
|
||||
}): PersistedWorkspaceRecord {
|
||||
const { background, ...rest } = input;
|
||||
const { background, worktreeManagerPluginId, ...rest } = input;
|
||||
return PersistedWorkspaceRecordSchema.parse({
|
||||
...rest,
|
||||
background: background ?? false,
|
||||
@@ -718,6 +720,7 @@ export function createPersistedWorkspaceRecord(input: {
|
||||
baseBranch: input.baseBranch ?? null,
|
||||
isPaseoOwnedWorktree: input.isPaseoOwnedWorktree ?? false,
|
||||
mainRepoRoot: input.mainRepoRoot ?? null,
|
||||
...(worktreeManagerPluginId ? { worktreeManagerPluginId } : {}),
|
||||
archivedAt: input.archivedAt ?? null,
|
||||
autoArchivedChangeRequestUrl: input.autoArchivedChangeRequestUrl ?? null,
|
||||
pinnedAt: input.pinnedAt ?? null,
|
||||
|
||||
@@ -1,16 +1,21 @@
|
||||
import type { PluginWorktreeCreateRequest } from "@getpaseo/plugin/server";
|
||||
import type { PluginLifecycle } from "./plugins/lifecycle/index.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "./plugins/runtime.js";
|
||||
import { createNameId } from "mnemonic-id";
|
||||
|
||||
import type { ForgeService } from "../services/forge-service.js";
|
||||
import {
|
||||
adoptPluginWorktree,
|
||||
cleanupFailedPluginWorktree,
|
||||
createWorktree,
|
||||
fetchFirstAvailableRef,
|
||||
listGitWorktreePaths,
|
||||
resolveDefaultWorktreePath,
|
||||
slugify,
|
||||
validateBranchSlug,
|
||||
type CreatedWorktree,
|
||||
} from "../utils/worktree.js";
|
||||
import { validateWorktreePath } from "../utils/worktree-path.js";
|
||||
import {
|
||||
resolveWorktreeCreationIntent,
|
||||
type ResolveWorktreeCreationIntentInput,
|
||||
@@ -36,6 +41,7 @@ export interface CreateWorktreeCoreInput {
|
||||
|
||||
export interface CreateWorktreeCoreDeps {
|
||||
lifecycle?: Pick<PluginLifecycle, "before">;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "createWorktree" | "removeWorktree">;
|
||||
github: ForgeService;
|
||||
workspaceGitService?: Pick<
|
||||
WorkspaceGitService,
|
||||
@@ -149,6 +155,22 @@ async function createWorktreeCoreWithPriority(
|
||||
normalizedSlug = validateWorktreeSlug(transformed.slug);
|
||||
intent = creationIntentFromRequest(transformed, intent);
|
||||
|
||||
const managedWorktree = await tryCreateWithWorktreeManager({
|
||||
repoRoot,
|
||||
transformed,
|
||||
intent,
|
||||
input,
|
||||
deps,
|
||||
});
|
||||
if (managedWorktree) {
|
||||
return {
|
||||
worktree: managedWorktree,
|
||||
intent,
|
||||
repoRoot,
|
||||
created: true,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
worktree: await createWorktree({
|
||||
cwd: repoRoot,
|
||||
@@ -164,6 +186,47 @@ async function createWorktreeCoreWithPriority(
|
||||
};
|
||||
}
|
||||
|
||||
async function tryCreateWithWorktreeManager(options: {
|
||||
repoRoot: string;
|
||||
transformed: PluginWorktreeCreateRequest;
|
||||
intent: WorktreeCreationIntent;
|
||||
input: Pick<CreateWorktreeCoreInput, "paseoHome" | "worktreesRoot">;
|
||||
deps: Pick<CreateWorktreeCoreDeps, "worktreeManagers">;
|
||||
}): Promise<CreatedWorktree | null> {
|
||||
const { repoRoot, transformed, intent, input, deps } = options;
|
||||
if (!deps.worktreeManagers) return null;
|
||||
const existingWorktreePaths = await listGitWorktreePaths(repoRoot);
|
||||
const managed = await deps.worktreeManagers.createWorktree(transformed);
|
||||
if (!managed) return null;
|
||||
const untrusted = intent.kind === "checkout-change-request" && Boolean(intent.headRepository);
|
||||
try {
|
||||
const validatedPath = await validateWorktreePath({
|
||||
candidate: managed.path,
|
||||
repoPath: repoRoot,
|
||||
allowExistingPath: true,
|
||||
});
|
||||
return await adoptPluginWorktree({
|
||||
cwd: repoRoot,
|
||||
source: intent,
|
||||
worktreePath: validatedPath,
|
||||
worktreeManagerPluginId: managed.pluginId,
|
||||
existingWorktreePaths,
|
||||
});
|
||||
} catch (error) {
|
||||
await cleanupFailedPluginWorktree({
|
||||
cwd: repoRoot,
|
||||
candidatePath: managed.path,
|
||||
existingWorktreePaths,
|
||||
worktreeManagers: deps.worktreeManagers,
|
||||
worktreeManagerPluginId: managed.pluginId,
|
||||
untrusted,
|
||||
paseoHome: input.paseoHome,
|
||||
worktreesBaseRoot: input.worktreesRoot,
|
||||
}).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
function describeCreationRequest(
|
||||
intent: WorktreeCreationIntent,
|
||||
placement: Pick<PluginWorktreeCreateRequest, "repoRoot" | "sourceCheckout" | "slug" | "path">,
|
||||
@@ -174,6 +237,7 @@ function describeCreationRequest(
|
||||
kind: intent.kind,
|
||||
branch: intent.branchName,
|
||||
baseRef: intent.baseBranch,
|
||||
...(intent.startPoint ? { startPoint: intent.startPoint } : {}),
|
||||
};
|
||||
if (intent.kind === "checkout-branch")
|
||||
return { ...placement, kind: intent.kind, branch: intent.branchName };
|
||||
|
||||
@@ -22,6 +22,7 @@ const PaseoWorktreeMetadataV1Schema = z.object({
|
||||
baseRefName: z.string().min(1),
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
});
|
||||
|
||||
const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
@@ -29,6 +30,7 @@ const PaseoWorktreeMetadataV2Schema = z.object({
|
||||
baseRefName: z.string().min(1),
|
||||
baseRef: z.string().min(1).optional(),
|
||||
changeRequestLookupTarget: ChangeRequestLookupTargetSchema.optional(),
|
||||
worktreeManagerPluginId: z.string().min(1).optional(),
|
||||
firstAgentBranchAutoName: z
|
||||
.discriminatedUnion("status", [
|
||||
z.object({
|
||||
@@ -227,6 +229,7 @@ export async function writePaseoWorktreeMetadata(
|
||||
baseRefName: string;
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
worktreeManagerPluginId?: string;
|
||||
},
|
||||
): Promise<void> {
|
||||
return mutateMetadata(worktreeRoot, async (root) => {
|
||||
@@ -244,6 +247,9 @@ export async function writePaseoWorktreeMetadata(
|
||||
...(options.changeRequestLookupTarget
|
||||
? { changeRequestLookupTarget: options.changeRequestLookupTarget }
|
||||
: {}),
|
||||
...(options.worktreeManagerPluginId
|
||||
? { worktreeManagerPluginId: options.worktreeManagerPluginId }
|
||||
: {}),
|
||||
};
|
||||
await writePaseoWorktreeMetadataFile(root, metadata);
|
||||
});
|
||||
|
||||
@@ -47,8 +47,10 @@ async function pathExists(path: string): Promise<boolean> {
|
||||
export async function validateWorktreePath(options: {
|
||||
candidate: string;
|
||||
repoPath: string;
|
||||
/** The worktree manager already created the destination, so it is expected to exist. */
|
||||
allowExistingPath?: boolean;
|
||||
}): Promise<string> {
|
||||
const { candidate, repoPath } = options;
|
||||
const { candidate, repoPath, allowExistingPath = false } = options;
|
||||
if (!isAbsolute(candidate)) {
|
||||
throw new Error(
|
||||
`Worktree hook returned a relative path '${candidate}'; it must be an absolute path`,
|
||||
@@ -79,7 +81,7 @@ export async function validateWorktreePath(options: {
|
||||
if (relativeToCandidate !== null && relativeToCandidate !== "") {
|
||||
throw new Error(`Worktree hook returned an ancestor of the repository: ${normalized}`);
|
||||
}
|
||||
if ((await pathExists(normalized)) || (await pathExists(candidate))) {
|
||||
if (!allowExistingPath && ((await pathExists(normalized)) || (await pathExists(candidate)))) {
|
||||
throw new Error(
|
||||
`Worktree hook returned a path that already exists: ${normalized}. Paseo creates the returned path.`,
|
||||
);
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
isPathInsideRoot,
|
||||
} from "./path.js";
|
||||
import { terminateWithTreeKill } from "./tree-kill.js";
|
||||
import type { PluginWorktreeManagerRuntime } from "../server/plugins/runtime.js";
|
||||
|
||||
export { slugify, validateBranchSlug } from "@getpaseo/protocol/branch-slug";
|
||||
|
||||
@@ -62,6 +63,7 @@ export interface WorktreeConfig {
|
||||
|
||||
export interface CreatedWorktree extends WorktreeConfig {
|
||||
comparisonBaseRef: string | null;
|
||||
worktreeManagerPluginId?: string;
|
||||
}
|
||||
|
||||
export interface WorktreeRuntimeEnv {
|
||||
@@ -1211,6 +1213,19 @@ export async function listPaseoWorktrees({
|
||||
return worktrees;
|
||||
}
|
||||
|
||||
/** Normalized paths of all currently registered worktrees for the repo containing `cwd`. */
|
||||
export async function listGitWorktreePaths(cwd: string): Promise<Set<string>> {
|
||||
const { stdout } = await runGitCommand(["worktree", "list", "--porcelain"], {
|
||||
cwd,
|
||||
envOverlay: READ_ONLY_GIT_ENV,
|
||||
});
|
||||
const paths = new Set<string>();
|
||||
for (const entry of parseWorktreeList(stdout)) {
|
||||
paths.add(await normalizePathForOwnership(entry.path));
|
||||
}
|
||||
return paths;
|
||||
}
|
||||
|
||||
export interface DeletePaseoWorktreeOptions {
|
||||
cwd: string | null;
|
||||
worktreePath?: string;
|
||||
@@ -1225,6 +1240,11 @@ export interface DeletePaseoWorktreeOptions {
|
||||
// gone, where the marker proof can no longer be verified. Only pass
|
||||
// this when the record was matched against the path by the caller.
|
||||
registryProven?: boolean;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
removeReason?: "archive" | "rollback";
|
||||
untrusted?: boolean;
|
||||
signal?: AbortSignal;
|
||||
}
|
||||
|
||||
// Project scoping for delete: a proof for some other repo's worktree must
|
||||
@@ -1280,6 +1300,11 @@ export async function deletePaseoWorktree({
|
||||
paseoHome,
|
||||
worktreesBaseRoot,
|
||||
registryProven,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason = "archive",
|
||||
untrusted = false,
|
||||
signal,
|
||||
}: DeletePaseoWorktreeOptions): Promise<void> {
|
||||
if (!worktreePath && !worktreeSlug) {
|
||||
throw new Error("worktreePath or worktreeSlug is required");
|
||||
@@ -1320,17 +1345,19 @@ export async function deletePaseoWorktree({
|
||||
}
|
||||
|
||||
if (await pathExists(resolvedWorktree)) {
|
||||
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: resolvedWorktree,
|
||||
teardownCwd,
|
||||
});
|
||||
}
|
||||
const commit = await readWorktreeHead(resolvedWorktree);
|
||||
if (commit) {
|
||||
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
|
||||
cwd: resolvedWorktree,
|
||||
});
|
||||
const removedByPlugin = await prepareAndTryPluginWorktreeRemove({
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
untrusted,
|
||||
signal,
|
||||
});
|
||||
if (removedByPlugin) {
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1349,16 +1376,83 @@ export async function deletePaseoWorktree({
|
||||
}
|
||||
|
||||
await removeDirectoryWithRetries(resolvedWorktree);
|
||||
await pruneWorktreesBestEffort(cwd);
|
||||
}
|
||||
|
||||
if (cwd) {
|
||||
try {
|
||||
await runGitCommand(["worktree", "prune"], { cwd, timeout: 30_000 });
|
||||
} catch {
|
||||
// not critical; git will prune lazily
|
||||
}
|
||||
async function pruneWorktreesBestEffort(cwd: string | null): Promise<void> {
|
||||
if (!cwd) return;
|
||||
try {
|
||||
await runGitCommand(["worktree", "prune"], { cwd, timeout: 30_000 });
|
||||
} catch {
|
||||
// not critical; git will prune lazily
|
||||
}
|
||||
}
|
||||
|
||||
async function prepareAndTryPluginWorktreeRemove(options: {
|
||||
cwd: string | null;
|
||||
resolvedWorktree: string;
|
||||
teardownCwds?: string[];
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
worktreeManagerPluginId?: string | null;
|
||||
removeReason: "archive" | "rollback";
|
||||
untrusted: boolean;
|
||||
signal?: AbortSignal;
|
||||
}): Promise<boolean> {
|
||||
const {
|
||||
cwd,
|
||||
resolvedWorktree,
|
||||
teardownCwds,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason,
|
||||
untrusted,
|
||||
signal,
|
||||
} = options;
|
||||
for (const teardownCwd of teardownCwds ?? [resolvedWorktree]) {
|
||||
await runWorktreeTeardownCommands({
|
||||
worktreePath: resolvedWorktree,
|
||||
teardownCwd,
|
||||
});
|
||||
}
|
||||
const effectiveManagerPluginId =
|
||||
worktreeManagerPluginId !== undefined
|
||||
? worktreeManagerPluginId
|
||||
: ((await readPaseoWorktreeMetadata(resolvedWorktree).catch(() => null))
|
||||
?.worktreeManagerPluginId ?? null);
|
||||
const branch = effectiveManagerPluginId
|
||||
? await getCurrentBranch(resolvedWorktree).catch(() => null)
|
||||
: null;
|
||||
const commit = await readWorktreeHead(resolvedWorktree);
|
||||
if (commit) {
|
||||
await runGitCommand(["update-ref", `refs/paseo/kept-commits/${commit}`, commit], {
|
||||
cwd: resolvedWorktree,
|
||||
});
|
||||
}
|
||||
if (!effectiveManagerPluginId || !worktreeManagers) {
|
||||
return false;
|
||||
}
|
||||
const removedByPlugin = await worktreeManagers.removeWorktree(
|
||||
{
|
||||
repoRoot: cwd,
|
||||
path: resolvedWorktree,
|
||||
branch,
|
||||
reason: removeReason,
|
||||
force: true,
|
||||
untrusted,
|
||||
},
|
||||
{ preferredPluginId: effectiveManagerPluginId, signal },
|
||||
);
|
||||
if (removedByPlugin === null) {
|
||||
return false;
|
||||
}
|
||||
if (await pathExists(resolvedWorktree)) {
|
||||
throw new Error(
|
||||
`Plugin ${removedByPlugin.pluginId} worktree.remove reported removed, but the directory still exists: ${resolvedWorktree}`,
|
||||
);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export async function rollbackCreatedPaseoWorktree(
|
||||
options: DeletePaseoWorktreeOptions,
|
||||
cause: unknown,
|
||||
@@ -1568,6 +1662,242 @@ export async function createWorktree({
|
||||
}
|
||||
}
|
||||
|
||||
export interface AdoptPluginWorktreeOptions {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
worktreePath: string;
|
||||
worktreeManagerPluginId: string;
|
||||
/** Worktree paths that existed before creation; an overlap fails instead of hijacking user worktrees. */
|
||||
existingWorktreePaths?: ReadonlySet<string>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Roll back a newly created worktree that failed adoption or path verification.
|
||||
* Only touches a directory that was absent from `existingWorktreePaths` and
|
||||
* shares the source repository's Git common dir.
|
||||
*/
|
||||
export async function cleanupFailedPluginWorktree(options: {
|
||||
cwd: string;
|
||||
candidatePath: string;
|
||||
existingWorktreePaths?: ReadonlySet<string>;
|
||||
worktreeManagers?: Pick<PluginWorktreeManagerRuntime, "removeWorktree">;
|
||||
worktreeManagerPluginId: string;
|
||||
untrusted?: boolean;
|
||||
paseoHome?: string;
|
||||
worktreesBaseRoot?: string;
|
||||
}): Promise<void> {
|
||||
const {
|
||||
cwd,
|
||||
candidatePath,
|
||||
existingWorktreePaths,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
untrusted,
|
||||
paseoHome,
|
||||
worktreesBaseRoot,
|
||||
} = options;
|
||||
let rootPath: string;
|
||||
try {
|
||||
const { stdout } = await runGitCommand(["rev-parse", "--show-toplevel"], {
|
||||
cwd: candidatePath,
|
||||
});
|
||||
rootPath = await normalizePathForOwnership(stdout.trim());
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (existingWorktreePaths?.has(rootPath)) {
|
||||
return;
|
||||
}
|
||||
const [worktreeCommonDir, repoCommonDir] = await Promise.all([
|
||||
getGitCommonDir(rootPath).catch(() => null),
|
||||
getGitCommonDir(cwd).catch(() => null),
|
||||
]);
|
||||
if (
|
||||
!worktreeCommonDir ||
|
||||
!repoCommonDir ||
|
||||
(await normalizePathForOwnership(worktreeCommonDir)) !==
|
||||
(await normalizePathForOwnership(repoCommonDir))
|
||||
) {
|
||||
return;
|
||||
}
|
||||
await deletePaseoWorktree({
|
||||
cwd,
|
||||
worktreePath: rootPath,
|
||||
teardownCwds: [],
|
||||
paseoHome,
|
||||
worktreesBaseRoot,
|
||||
registryProven: true,
|
||||
worktreeManagers,
|
||||
worktreeManagerPluginId,
|
||||
removeReason: "rollback",
|
||||
untrusted,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify and adopt a worktree created or restored by a worktree manager plugin.
|
||||
* Paseo validates Git worktree postconditions and writes `paseo/worktree.json`
|
||||
* so diffs, PR/MR lookup hints, listing, ownership, and removal continue to work.
|
||||
*/
|
||||
export function adoptPluginWorktree(
|
||||
options: AdoptPluginWorktreeOptions & {
|
||||
source: Exclude<WorktreeSource, { kind: "restore-commit" }>;
|
||||
},
|
||||
): Promise<CreatedWorktree>;
|
||||
export function adoptPluginWorktree(
|
||||
options: AdoptPluginWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }>;
|
||||
export async function adoptPluginWorktree(
|
||||
options: AdoptPluginWorktreeOptions,
|
||||
): Promise<Omit<CreatedWorktree, "branchName"> & { branchName: string | null }> {
|
||||
const { cwd, source, worktreePath, worktreeManagerPluginId, existingWorktreePaths } = options;
|
||||
const normalizedPath = await normalizePathForOwnership(worktreePath);
|
||||
if (existingWorktreePaths?.has(normalizedPath)) {
|
||||
throw new Error(
|
||||
`Plugin ${worktreeManagerPluginId} returned an already-existing worktree: ${normalizedPath}`,
|
||||
);
|
||||
}
|
||||
const { stdout: rootStdout } = await runGitCommand(["rev-parse", "--show-toplevel"], {
|
||||
cwd: normalizedPath,
|
||||
}).catch(() => {
|
||||
throw new Error(
|
||||
`Plugin ${worktreeManagerPluginId} did not create a Git worktree at: ${normalizedPath}`,
|
||||
);
|
||||
});
|
||||
if ((await normalizePathForOwnership(rootStdout.trim())) !== normalizedPath) {
|
||||
throw new Error(
|
||||
`Plugin ${worktreeManagerPluginId} created a worktree whose root is not the returned path: ${normalizedPath}`,
|
||||
);
|
||||
}
|
||||
const [worktreeCommonDir, repoCommonDir] = await Promise.all([
|
||||
getGitCommonDir(normalizedPath),
|
||||
getGitCommonDir(cwd),
|
||||
]);
|
||||
if (
|
||||
(await normalizePathForOwnership(worktreeCommonDir)) !==
|
||||
(await normalizePathForOwnership(repoCommonDir))
|
||||
) {
|
||||
throw new Error(
|
||||
`Plugin ${worktreeManagerPluginId} created a worktree outside the repository: ${normalizedPath}`,
|
||||
);
|
||||
}
|
||||
const { stdout: branchStdout } = await runGitCommand(["rev-parse", "--abbrev-ref", "HEAD"], {
|
||||
cwd: normalizedPath,
|
||||
});
|
||||
const rawBranch = branchStdout.trim();
|
||||
const detached = !rawBranch || rawBranch === "HEAD";
|
||||
if (detached && source.kind !== "restore-commit") {
|
||||
throw new Error(
|
||||
`Plugin ${worktreeManagerPluginId} created a worktree with a detached HEAD: ${normalizedPath}`,
|
||||
);
|
||||
}
|
||||
const branchName = detached ? null : rawBranch;
|
||||
|
||||
const metadata = await resolveAdoptedWorktreeMetadata({ cwd, source, branchName });
|
||||
await writePaseoWorktreeMetadata(normalizedPath, {
|
||||
baseRefName: metadata.baseRefName,
|
||||
...(metadata.baseRef ? { baseRef: metadata.baseRef } : {}),
|
||||
...(metadata.changeRequestLookupTarget
|
||||
? { changeRequestLookupTarget: metadata.changeRequestLookupTarget }
|
||||
: {}),
|
||||
worktreeManagerPluginId,
|
||||
});
|
||||
await seedPaseoConfigFile({ sourceCwd: cwd, targetCwd: normalizedPath });
|
||||
|
||||
return {
|
||||
branchName,
|
||||
worktreePath: normalizedPath,
|
||||
comparisonBaseRef: metadata.baseRef ?? metadata.baseRefName,
|
||||
worktreeManagerPluginId,
|
||||
};
|
||||
}
|
||||
|
||||
async function tryResolveExactBaseRef(cwd: string, ref: string): Promise<string | undefined> {
|
||||
try {
|
||||
return await resolveBaseBranchForWorktree(cwd, ref);
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function branchChangeRequestHint(
|
||||
branchName: string | null,
|
||||
): { changeRequestLookupTarget: PaseoWorktreeChangeRequestHint } | Record<string, never> {
|
||||
if (!branchName) return {};
|
||||
return {
|
||||
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
|
||||
headRef: branchName,
|
||||
localBranchName: branchName,
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveAdoptedChangeRequestMetadata(
|
||||
cwd: string,
|
||||
source: Extract<WorktreeSource, { kind: "checkout-change-request" | "checkout-github-pr" }>,
|
||||
branchName: string | null,
|
||||
): Promise<{
|
||||
baseRefName: string;
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget: PaseoWorktreeChangeRequestHint;
|
||||
}> {
|
||||
const changeRequestNumber =
|
||||
source.kind === "checkout-github-pr" ? source.githubPrNumber : source.changeRequestNumber;
|
||||
const baseRefName = normalizeRequiredBaseBranch(source.baseRefName);
|
||||
const baseRef = await tryResolveExactBaseRef(cwd, source.baseRefName);
|
||||
return {
|
||||
baseRefName,
|
||||
...(baseRef ? { baseRef } : {}),
|
||||
changeRequestLookupTarget: createPaseoWorktreeChangeRequestHint({
|
||||
headRef: source.headRef,
|
||||
...(source.headRepositoryOwner ? { headRepositoryOwner: source.headRepositoryOwner } : {}),
|
||||
changeRequestNumber,
|
||||
...(branchName ? { localBranchName: branchName } : {}),
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
async function resolveAdoptedWorktreeMetadata(options: {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
branchName: string | null;
|
||||
}): Promise<{
|
||||
baseRefName: string;
|
||||
baseRef?: string;
|
||||
changeRequestLookupTarget?: PaseoWorktreeChangeRequestHint;
|
||||
}> {
|
||||
const { cwd, source, branchName } = options;
|
||||
if (source.kind === "checkout-change-request" || source.kind === "checkout-github-pr") {
|
||||
return resolveAdoptedChangeRequestMetadata(cwd, source, branchName);
|
||||
}
|
||||
if (source.kind === "checkout-branch") {
|
||||
const resolvedBranch = branchName ?? source.branchName;
|
||||
const baseRefName = await resolveCheckoutBranchBaseRef(cwd, resolvedBranch);
|
||||
return { baseRefName, ...branchChangeRequestHint(resolvedBranch) };
|
||||
}
|
||||
if (source.kind === "branch-off") {
|
||||
const baseRefName = normalizeRequiredBaseBranch(source.baseBranch);
|
||||
const baseRef = await tryResolveExactBaseRef(cwd, source.baseBranch);
|
||||
return { baseRefName, ...(baseRef ? { baseRef } : {}), ...branchChangeRequestHint(branchName) };
|
||||
}
|
||||
if (source.kind === "restore") {
|
||||
const baseRefName = normalizeRequiredBaseBranch(
|
||||
source.baseRef ?? branchName ?? source.branchName,
|
||||
);
|
||||
const baseRef =
|
||||
source.baseRef && isQualifiedRef(source.baseRef)
|
||||
? await tryResolveExactBaseRef(cwd, source.baseRef)
|
||||
: undefined;
|
||||
return { baseRefName, ...(baseRef ? { baseRef } : {}), ...branchChangeRequestHint(branchName) };
|
||||
}
|
||||
const baseRefName = normalizeRequiredBaseBranch(source.baseRef);
|
||||
const baseRef =
|
||||
source.kind === "restore-from-base" || isQualifiedRef(source.baseRef)
|
||||
? await tryResolveExactBaseRef(cwd, source.baseRef)
|
||||
: undefined;
|
||||
return { baseRefName, ...(baseRef ? { baseRef } : {}) };
|
||||
}
|
||||
|
||||
interface ResolveWorktreeSourcePlanOptions {
|
||||
cwd: string;
|
||||
source: WorktreeSource;
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# Worktrunk plugin example
|
||||
|
||||
Delegates Paseo worktree creation, removal, and restoration to [Worktrunk](https://worktrunk.dev) (`wt`), and updates `wt list` activity markers (`🤖` / `💬`) as agents run.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Create:** routes branch-off, branch checkout, GitHub PR (`pr:N`), and GitLab MR (`mr:N`) creation through `wt switch --no-cd --yes --format=json` so Worktrunk controls placement, branch setup, and `pre-start` / `post-start` hooks. Unsupported forges decline and fall back to Paseo's Git checkout.
|
||||
- **Remove:** routes archive and creation rollback through `wt remove --foreground --no-delete-branch --yes` so Worktrunk runs `pre-remove` and `post-remove` hooks while keeping the branch for Paseo's restore flow.
|
||||
- **Restore:** routes archived worktree restoration through `wt switch --path <recorded-path>` for branch restores, and falls back to Paseo for detached-commit restores.
|
||||
- **Activity markers:** sets `🤖` when an agent turn starts, `💬` when a turn ends or awaits permission, and clears the marker on close or archive. Background helpers are skipped.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
Install Worktrunk (`wt`, or `git-wt.exe` on Windows) on `PATH`, or set `WORKTRUNK_BIN` in the daemon environment.
|
||||
|
||||
## Install
|
||||
|
||||
```bash
|
||||
paseo plugin install /absolute/path/to/plugin-examples/worktrunk
|
||||
```
|
||||
@@ -0,0 +1,44 @@
|
||||
import type { PluginServerContext } from "@getpaseo/plugin/server";
|
||||
import {
|
||||
WAITING_MARKER,
|
||||
WORKING_MARKER,
|
||||
createWithWorktrunk,
|
||||
removeWithWorktrunk,
|
||||
restoreWithWorktrunk,
|
||||
setActivityMarker,
|
||||
} from "./server/wt.js";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
const cleanups = [
|
||||
server.registerWorktreeManager({
|
||||
create: (request, { signal }) => createWithWorktrunk(request, signal),
|
||||
remove: (request, { signal }) => removeWithWorktrunk(request, signal),
|
||||
restore: (request, { signal }) => restoreWithWorktrunk(request, signal),
|
||||
}),
|
||||
|
||||
server.addHook("agent.turn.before", async ({ agent }, { signal }) => {
|
||||
if (agent.background) return;
|
||||
await setActivityMarker(agent.cwd, WORKING_MARKER, signal);
|
||||
}),
|
||||
server.addHook("agent.turn.after", async ({ agent }, { signal }) => {
|
||||
if (agent.background) return;
|
||||
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
|
||||
}),
|
||||
server.addHook("agent.permission.before", async ({ agent }, { signal }) => {
|
||||
if (agent.background) return;
|
||||
await setActivityMarker(agent.cwd, WAITING_MARKER, signal);
|
||||
}),
|
||||
server.addHook("agent.close.after", async ({ agent }, { signal }) => {
|
||||
if (agent.background) return;
|
||||
await setActivityMarker(agent.cwd, null, signal);
|
||||
}),
|
||||
server.addHook("agent.archive.after", async ({ agent }, { signal }) => {
|
||||
if (agent.background) return;
|
||||
await setActivityMarker(agent.cwd, null, signal);
|
||||
}),
|
||||
];
|
||||
|
||||
return () => {
|
||||
for (const cleanup of cleanups) cleanup();
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
{
|
||||
"id": "worktrunk",
|
||||
"name": "Worktrunk",
|
||||
"description": "Manage Git worktrees and agent activity markers through Worktrunk (wt).",
|
||||
"requirements": { "paseo": ">=0.16.0" }
|
||||
}
|
||||
@@ -0,0 +1,244 @@
|
||||
import { lstatSync } from "node:fs";
|
||||
import { delimiter, join } from "node:path";
|
||||
import {
|
||||
execCommand,
|
||||
type PluginWorktreeCreateInput,
|
||||
type PluginWorktreeRemoveRequest,
|
||||
type PluginWorktreeRestoreRequest,
|
||||
} from "@getpaseo/plugin/server";
|
||||
|
||||
const MAX_OUTPUT_BYTES = 16 * 1024 * 1024;
|
||||
|
||||
export const WORKING_MARKER = "🤖";
|
||||
export const WAITING_MARKER = "💬";
|
||||
|
||||
interface SwitchJsonOutput {
|
||||
path: string;
|
||||
action?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the Worktrunk CLI executable.
|
||||
* Honors `WORKTRUNK_BIN` first; on Windows prefers `git-wt.exe` and skips the
|
||||
* WindowsApps alias that points to Windows Terminal.
|
||||
*/
|
||||
export function resolveWorktrunkBin(): string | null {
|
||||
const configured = process.env.WORKTRUNK_BIN?.trim();
|
||||
if (configured) return configured;
|
||||
if (process.platform !== "win32") return "wt";
|
||||
|
||||
const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
|
||||
const findOnPath = (name: string) =>
|
||||
dirs
|
||||
.map((dir) => join(dir, name))
|
||||
.find((candidate) => {
|
||||
try {
|
||||
lstatSync(candidate);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
if (findOnPath("git-wt.exe")) return "git-wt.exe";
|
||||
const wt = findOnPath("wt.exe");
|
||||
return wt && !/[\\/]WindowsApps[\\/]/i.test(wt) ? "wt" : null;
|
||||
}
|
||||
|
||||
async function runWt(
|
||||
args: string[],
|
||||
options: { cwd?: string; signal?: AbortSignal } = {},
|
||||
): Promise<string> {
|
||||
const bin = resolveWorktrunkBin();
|
||||
if (!bin) {
|
||||
throw new Error(
|
||||
"Worktrunk CLI not found on PATH. Install wt (or git-wt.exe on Windows) or set WORKTRUNK_BIN.",
|
||||
);
|
||||
}
|
||||
try {
|
||||
const { stdout } = await execCommand(bin, args, {
|
||||
cwd: options.cwd,
|
||||
signal: options.signal,
|
||||
maxBuffer: MAX_OUTPUT_BYTES,
|
||||
});
|
||||
return stdout;
|
||||
} catch (error) {
|
||||
const stderr = (error as { stderr?: string }).stderr?.trim();
|
||||
throw new Error(stderr || (error instanceof Error ? error.message : String(error)), {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function tryParseSwitchOutput(stdout: string | undefined): SwitchJsonOutput | null {
|
||||
if (!stdout?.trim()) return null;
|
||||
try {
|
||||
const parsed = JSON.parse(stdout) as { path?: unknown; action?: unknown };
|
||||
if (typeof parsed.path !== "string" || parsed.path.length === 0) return null;
|
||||
return {
|
||||
path: parsed.path,
|
||||
...(typeof parsed.action === "string" ? { action: parsed.action } : {}),
|
||||
};
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function parseSwitchOutput(stdout: string): SwitchJsonOutput {
|
||||
const parsed = tryParseSwitchOutput(stdout);
|
||||
if (!parsed) {
|
||||
throw new Error("wt switch --format=json output did not include a worktree path");
|
||||
}
|
||||
return parsed;
|
||||
}
|
||||
|
||||
function isUntrustedCreate(request: PluginWorktreeCreateInput): boolean {
|
||||
return request.kind === "checkout-change-request" && Boolean(request.headRepository);
|
||||
}
|
||||
|
||||
function hookFlags(untrusted: boolean): string[] {
|
||||
// Never approve repository-defined hooks on untrusted checkouts such as fork PRs.
|
||||
return untrusted ? ["--no-hooks"] : ["--yes"];
|
||||
}
|
||||
|
||||
export function buildCreateArgs(request: PluginWorktreeCreateInput): string[] | null {
|
||||
const common = [
|
||||
"-C",
|
||||
request.repoRoot,
|
||||
"switch",
|
||||
"--no-cd",
|
||||
...hookFlags(isUntrustedCreate(request)),
|
||||
"--format=json",
|
||||
];
|
||||
switch (request.kind) {
|
||||
case "branch-off":
|
||||
return [
|
||||
...common,
|
||||
"--create",
|
||||
request.branch,
|
||||
"--base",
|
||||
request.startPoint ?? request.baseRef,
|
||||
];
|
||||
case "checkout-branch":
|
||||
return [...common, request.branch];
|
||||
case "checkout-change-request":
|
||||
if (request.forge === "github") return [...common, `pr:${request.changeRequestNumber}`];
|
||||
if (request.forge === "gitlab") return [...common, `mr:${request.changeRequestNumber}`];
|
||||
return null;
|
||||
case "checkout-github-pr":
|
||||
return [...common, `pr:${request.githubPrNumber}`];
|
||||
}
|
||||
}
|
||||
|
||||
async function cleanupPartiallyCreatedWorktree(repoRoot: string, error: unknown): Promise<void> {
|
||||
// Worktrunk prints `{ path, action: "created" }` on stdout even when a later hook exits non-zero.
|
||||
const stdout =
|
||||
error instanceof Error && error.cause && typeof error.cause === "object"
|
||||
? (error.cause as { stdout?: string }).stdout
|
||||
: undefined;
|
||||
const parsed = tryParseSwitchOutput(stdout);
|
||||
if (!parsed || (parsed.action !== undefined && parsed.action !== "created")) return;
|
||||
await runWt([
|
||||
"-C",
|
||||
repoRoot,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--no-hooks",
|
||||
"--force",
|
||||
parsed.path,
|
||||
]).catch(() => {});
|
||||
}
|
||||
|
||||
export async function createWithWorktrunk(
|
||||
request: PluginWorktreeCreateInput,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ type: "created"; path: string } | undefined> {
|
||||
const args = buildCreateArgs(request);
|
||||
if (!args) return undefined;
|
||||
let stdout: string;
|
||||
try {
|
||||
stdout = await runWt(args, { signal });
|
||||
} catch (error) {
|
||||
await cleanupPartiallyCreatedWorktree(request.repoRoot, error);
|
||||
throw error;
|
||||
}
|
||||
const output = parseSwitchOutput(stdout);
|
||||
// If Worktrunk switched to an already-existing checkout instead of creating one,
|
||||
// decline so Paseo falls back to Git (which creates a unique branch).
|
||||
if (output.action !== undefined && output.action !== "created") {
|
||||
return undefined;
|
||||
}
|
||||
return { type: "created", path: output.path };
|
||||
}
|
||||
|
||||
export async function removeWithWorktrunk(
|
||||
request: PluginWorktreeRemoveRequest,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ type: "removed" }> {
|
||||
// Run from the main repository root when available and skip repository hooks for
|
||||
// untrusted workspaces (or when repoRoot is unknown) so fork PRs cannot run hooks.
|
||||
const runDir = request.repoRoot ?? request.path;
|
||||
const skipHooks = request.untrusted || request.repoRoot === null;
|
||||
const args = [
|
||||
"-C",
|
||||
runDir,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
...hookFlags(skipHooks),
|
||||
...(request.force ? ["--force"] : []),
|
||||
request.path,
|
||||
];
|
||||
await runWt(args, { signal });
|
||||
return { type: "removed" };
|
||||
}
|
||||
|
||||
export async function restoreWithWorktrunk(
|
||||
request: PluginWorktreeRestoreRequest,
|
||||
signal: AbortSignal,
|
||||
): Promise<{ type: "restored"; path: string } | undefined> {
|
||||
if (request.target.type === "commit") {
|
||||
// Detached-commit restores fall back to Paseo's built-in Git restore.
|
||||
return undefined;
|
||||
}
|
||||
const common = [
|
||||
"-C",
|
||||
request.repoRoot,
|
||||
"switch",
|
||||
"--path",
|
||||
request.path,
|
||||
"--no-cd",
|
||||
...hookFlags(request.untrusted),
|
||||
"--format=json",
|
||||
];
|
||||
const args =
|
||||
request.target.type === "branch"
|
||||
? [...common, request.target.branch]
|
||||
: [...common, "--create", request.target.branch, "--base", request.target.baseRef];
|
||||
let stdout: string;
|
||||
try {
|
||||
stdout = await runWt(args, { signal });
|
||||
} catch (error) {
|
||||
await cleanupPartiallyCreatedWorktree(request.repoRoot, error);
|
||||
throw error;
|
||||
}
|
||||
const output = parseSwitchOutput(stdout);
|
||||
return { type: "restored", path: output.path };
|
||||
}
|
||||
|
||||
export async function setActivityMarker(
|
||||
cwd: string,
|
||||
marker: string | null,
|
||||
signal: AbortSignal,
|
||||
): Promise<void> {
|
||||
const args =
|
||||
marker === null
|
||||
? ["config", "state", "marker", "clear"]
|
||||
: ["config", "state", "marker", "set", marker];
|
||||
try {
|
||||
await runWt(args, { cwd, signal });
|
||||
} catch {
|
||||
// Activity markers are best-effort and must not disrupt agent sessions.
|
||||
}
|
||||
}
|
||||
@@ -208,7 +208,7 @@ Every field except `repoRoot` and `sourceCheckout` is transformable. Return all
|
||||
|
||||
Paseo resolves symlinked parents and validates the returned path. It must be absolute, must not exist, and must not be the filesystem root, your home directory, the repository root, inside a `.git` directory, or an ancestor of the repository. An existing destination fails creation; Paseo never adds a suffix to a plugin-chosen path. The plugin must leave directory creation to Paseo.
|
||||
|
||||
Ordering: `worktree.create.before` → `git worktree add` → `worktree.create.after` → workspace registration. Restoring a missing worktree recreates it at its recorded path without running either worktree creation hook.
|
||||
Ordering: `worktree.create.before` → worktree manager `create` (or `git worktree add`) → `worktree.create.after` → workspace registration. To delegate `git worktree add`, removal, and restoration to an external tool such as Worktrunk, register a [worktree manager](/docs/plugins/reference#worktree-managers) with `server.registerWorktreeManager()` instead of creating directories inside `worktree.create.before`. Restoring a missing worktree recreates it at its recorded path without running creation hooks, delegating to the owning manager's optional `restore` handler when present.
|
||||
|
||||
## worktree.create.after
|
||||
|
||||
@@ -700,6 +700,7 @@ replaces that scope's prior value.
|
||||
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | Follow-ups, permissions, environment, provider switching, worktree selection |
|
||||
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP injection and Codex sandbox/approval options |
|
||||
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | Label-targeted tools and file operations in the plugin process |
|
||||
| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | Worktree manager (`create`, `remove`, `restore`) and agent activity markers |
|
||||
|
||||
Read logger output with `paseo plugin logs lifecycle-logger` or the host's `daemon.log`.
|
||||
|
||||
|
||||
@@ -205,7 +205,7 @@ server.addHook("worktree.create.before", async ({ request }) => ({
|
||||
|
||||
Paseo 解析父目录中的符号链接并验证返回的路径。路径必须为绝对路径且不存在,不能是文件系统根目录、用户主目录、仓库根目录、`.git` 目录内的路径或仓库的祖先目录。目标已存在时创建失败,Paseo 不会为插件选择的路径添加后缀。插件应让 Paseo 创建目录。
|
||||
|
||||
顺序:`worktree.create.before` → `git worktree add` → `worktree.create.after` → 注册工作区。恢复缺失的 worktree 时使用记录的原路径,不运行这两个创建钩子。
|
||||
顺序:`worktree.create.before` → worktree 管理器 `create`(或 `git worktree add`)→ `worktree.create.after` → 注册工作区。若要将 `git worktree add`、移除和恢复委托给 Worktrunk 等外部工具,请使用 `server.registerWorktreeManager()` 注册 [worktree 管理器](/docs/plugins/reference#worktree-managers),而不是在 `worktree.create.before` 中创建目录。恢复缺失的 worktree 时使用记录的原路径,不运行创建钩子,并在对应管理器提供可选 `restore` 处理函数时委托给它。
|
||||
|
||||
## worktree.create.after {#worktreecreateafter}
|
||||
|
||||
@@ -677,12 +677,13 @@ Creation request
|
||||
|
||||
## 完整示例 {#complete-examples}
|
||||
|
||||
| 插件 | 包含 |
|
||||
| ------------------------------------------------------------------------------------------------------ | --------------------------------------------------------- |
|
||||
| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 |
|
||||
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree |
|
||||
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 |
|
||||
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 |
|
||||
| 插件 | 包含 |
|
||||
| ------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------- |
|
||||
| [lifecycle-logger](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-logger) | Agent、工作区和 worktree 钩子;隐去环境变量值的 JSON 日志 |
|
||||
| [lifecycle-actions](https://github.com/getpaseo/paseo/tree/main/plugin-examples/lifecycle-actions) | 后续消息、权限、环境变量、切换 Provider、选择 worktree |
|
||||
| [agent-configuration](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-configuration) | MCP 注入以及 Codex 沙盒/批准选项 |
|
||||
| [agent-tools](https://github.com/getpaseo/paseo/tree/main/plugin-examples/agent-tools) | 按标签选择 Agent,并在插件进程中执行文件操作的工具 |
|
||||
| [worktrunk](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk) | worktree 管理器(`create`、`remove`、`restore`)与 Agent 活动标记 |
|
||||
|
||||
用 `paseo plugin logs lifecycle-logger` 或主机的 `daemon.log` 读取 logger 的输出。
|
||||
|
||||
|
||||
@@ -692,6 +692,103 @@ for 0.10 clients and renders problems into its `error` string.
|
||||
|
||||
The source icon is a file path with the same rules as a provider icon.
|
||||
|
||||
## Worktree managers {#worktree-managers}
|
||||
|
||||
**Requires Paseo 0.16.** Register a worktree manager from `index.server.ts` with
|
||||
`server.registerWorktreeManager()` when an external tool such as Worktrunk should own creating,
|
||||
removing, and restoring Git worktrees instead of Paseo running `git worktree add` and
|
||||
`git worktree remove` directly.
|
||||
|
||||
```ts
|
||||
import { execCommand, type PluginServerContext } from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
return server.registerWorktreeManager({
|
||||
async create(request, { signal }) {
|
||||
if (request.kind !== "branch-off") return;
|
||||
const { stdout } = await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
request.repoRoot,
|
||||
"switch",
|
||||
"--create",
|
||||
request.branch,
|
||||
"--base",
|
||||
request.startPoint ?? request.baseRef,
|
||||
"--no-cd",
|
||||
"--yes",
|
||||
"--format=json",
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
const { path } = JSON.parse(stdout) as { path: string };
|
||||
return { type: "created", path };
|
||||
},
|
||||
async remove({ path, force }, { signal }) {
|
||||
await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
path,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--yes",
|
||||
...(force ? ["--force"] : []),
|
||||
path,
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
return { type: "removed" };
|
||||
},
|
||||
async restore({ repoRoot, path, target }, { signal }) {
|
||||
if (target.type !== "branch") return;
|
||||
const { stdout } = await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
repoRoot,
|
||||
"switch",
|
||||
target.branch,
|
||||
"--path",
|
||||
path,
|
||||
"--no-cd",
|
||||
"--yes",
|
||||
"--format=json",
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
const { path: restoredPath } = JSON.parse(stdout) as { path: string };
|
||||
return { type: "restored", path: restoredPath };
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- **Create** runs after all `worktree.create.before` hooks and before `worktree.create.after`, with a
|
||||
120-second timeout. Return `{ type: "created", path }` to claim creation, or `undefined` to decline
|
||||
so the next manager or Paseo's built-in Git checkout runs. Paseo verifies that `path` is a safe,
|
||||
newly created Git worktree of the same repository on a named branch, then records the checked-out
|
||||
`HEAD` branch (managers may normalize or uniquely name the branch, and should create a new branch
|
||||
for `branch-off`), writes comparison-base metadata, and seeds `paseo.json`. If adoption or a later
|
||||
creation step fails after a new worktree was created in the repository, Paseo rolls it back; if
|
||||
`create` throws before returning, the plugin is responsible for cleaning up any partial worktree it
|
||||
created. First-agent branch auto-rename is skipped for manager-created worktrees.
|
||||
- **Remove** is optional and runs on workspace archive and creation rollback, after Paseo runs
|
||||
`paseo.json` teardown and saves `refs/paseo/kept-commits/<sha>` for restore. Return
|
||||
`{ type: "removed" }` after removing the directory, or `undefined` to fall back to Git. When
|
||||
`untrusted` is `true` (for example, a fork change request), skip repository-defined hooks. Paseo
|
||||
routes removal to the plugin that created the worktree, falling back to Git when that plugin is
|
||||
disabled or uninstalled.
|
||||
- **Restore** is optional and runs when unarchiving a workspace whose worktree directory was deleted.
|
||||
It receives the recorded `path` that the recreated worktree must occupy, `target` (`branch`,
|
||||
`commit`, or `from-base`), and `untrusted`. Return `{ type: "restored", path }` or `undefined` to
|
||||
fall back to Git. When `restore` falls back to Git, Paseo clears the workspace's manager ownership
|
||||
so subsequent archives also use Git.
|
||||
|
||||
See the complete [worktrunk example](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk).
|
||||
|
||||
## Entry point and cleanup
|
||||
|
||||
Each present entry default-exports one contribution function and returns cleanup. Client entries
|
||||
|
||||
@@ -542,6 +542,83 @@ export default function contribute(server: PluginServerContext) {
|
||||
|
||||
来源图标是一个文件路径,规则与 Provider 图标相同。
|
||||
|
||||
## worktree 管理器 {#worktree-managers}
|
||||
|
||||
**需要 Paseo 0.16**。在服务端入口 `index.server.ts` 中调用 `server.registerWorktreeManager()`,可将 Git worktree 的创建、移除和恢复委托给 Worktrunk 等外部工具,而无需由 Paseo 直接运行 `git worktree add` 和 `git worktree remove`。
|
||||
|
||||
```ts
|
||||
import { execCommand, type PluginServerContext } from "@getpaseo/plugin/server";
|
||||
|
||||
export default function contribute(server: PluginServerContext) {
|
||||
return server.registerWorktreeManager({
|
||||
async create(request, { signal }) {
|
||||
if (request.kind !== "branch-off") return;
|
||||
const { stdout } = await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
request.repoRoot,
|
||||
"switch",
|
||||
"--create",
|
||||
request.branch,
|
||||
"--base",
|
||||
request.startPoint ?? request.baseRef,
|
||||
"--no-cd",
|
||||
"--yes",
|
||||
"--format=json",
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
const { path } = JSON.parse(stdout) as { path: string };
|
||||
return { type: "created", path };
|
||||
},
|
||||
async remove({ path, force }, { signal }) {
|
||||
await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
path,
|
||||
"remove",
|
||||
"--foreground",
|
||||
"--no-delete-branch",
|
||||
"--yes",
|
||||
...(force ? ["--force"] : []),
|
||||
path,
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
return { type: "removed" };
|
||||
},
|
||||
async restore({ repoRoot, path, target }, { signal }) {
|
||||
if (target.type !== "branch") return;
|
||||
const { stdout } = await execCommand(
|
||||
"wt",
|
||||
[
|
||||
"-C",
|
||||
repoRoot,
|
||||
"switch",
|
||||
target.branch,
|
||||
"--path",
|
||||
path,
|
||||
"--no-cd",
|
||||
"--yes",
|
||||
"--format=json",
|
||||
],
|
||||
{ signal },
|
||||
);
|
||||
const { path: restoredPath } = JSON.parse(stdout) as { path: string };
|
||||
return { type: "restored", path: restoredPath };
|
||||
},
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- **Create**:在所有 `worktree.create.before` 钩子之后、`worktree.create.after` 之前运行,超时为 120 秒。返回 `{ type: "created", path }` 表示接管创建,返回 `undefined` 表示放弃并交由下一个管理器或 Paseo 内置 Git 检出处理。Paseo 会验证 `path` 是同一仓库下新建且安全的命名分支 Git worktree,并记录实际检出的 `HEAD` 分支(管理器可自行规范或生成唯一分支名,但在 `branch-off` 时应创建新分支),随后写入基准元数据并生成 `paseo.json`。若在仓库内新建 worktree 后采纳或后续创建步骤失败,Paseo 会执行回滚;若 `create` 在返回前抛出错误,则由插件清理其部分创建的 worktree。由管理器创建的 worktree 会跳过首个 Agent 的分支自动重命名。
|
||||
- **Remove**:可选。在工作区归档和创建回滚时运行,位于 Paseo 执行 `paseo.json` 清理并保存 `refs/paseo/kept-commits/<sha>` 之后。删除目录后返回 `{ type: "removed" }`,或返回 `undefined` 回退到 Git。当 `untrusted` 为 `true`(例如来自 fork 变更请求)时,请跳过仓库内定义的钩子。Paseo 会将移除路由到创建该 worktree 的插件;若该插件已停用或移除,则回退到内置 Git。
|
||||
- **Restore**:可选。在取消归档且 worktree 目录已被删除时运行,接收必须恢复到的原路径 `path`、目标 `target`(`branch`、`commit` 或 `from-base`)以及 `untrusted`。返回 `{ type: "restored", path }`,或返回 `undefined` 回退到 Git。当 `restore` 回退到 Git 时,Paseo 会清除该工作区的管理器归属,后续归档也会使用 Git。
|
||||
|
||||
完整插件见 [worktrunk 示例](https://github.com/getpaseo/paseo/tree/main/plugin-examples/worktrunk)。
|
||||
|
||||
## 入口与清理 {#entry-point-and-cleanup}
|
||||
|
||||
每个存在的入口都默认导出一个贡献函数,并返回清理函数。客户端入口接收 `PluginClientContext`;服务端入口接收 `PluginServerContext`。客户端注册方法返回幂等的移除函数,但标题栏按钮和 Composer 标签除外,它们返回 `{ update, remove }` 句柄。入口的清理函数会在 Paseo 移除剩余的注册之前运行。
|
||||
|
||||
Reference in New Issue
Block a user