pi-worktrees/.pi/extensions/pi-worktree.ts
David Kong a18e6fe64a Milestone 2.1: Implement git_worktree_create tool (#4) (#17)
## Summary
Implements the `git_worktree_create` tool with full validation and error handling per issue #4 acceptance criteria.

## Changes
- New `pi-worktree-create.ts` module with pure, testable functions (no pi SDK deps)
- `validateCreateWorktreeInput()` — validates path and branch name parameters
- `validatePathDoesNotExist()` — refuses if target path exists (injectable for testing)
- `isCurrentBranch()` — prevents creating worktree on current branch
- `buildWorktreeAddCommand()` — builds correct git command with `-b` flag support
- Integrated all helpers into `createCreateWorktreeTool()` in main extension
- 17 new tests covering all validation paths and edge cases (29 total, all passing)

## Testing
- [x] All 29 tests pass (`bun test .pi/extensions/*.test.ts`)
- [x] Full test suite run with no regressions
- [ ] Manual verification (requires pi runtime)

## Checklist
- [x] Self-reviewed the diff
- [x] Code follows project conventions
- [x] Descriptive naming (no single-character variables)
- [x] Documentation updated (JSDoc on all new functions)

Co-authored-by: David Kong <davkon@gmail.com>
Reviewed-on: #17
2026-07-24 20:50:45 +00:00

325 lines
11 KiB
TypeScript

/**
* pi-worktree Extension
*
* Manages git worktrees through tool commands and an interactive `/worktree` command.
*
* Tools:
* - git_worktree_create — Create a linked worktree for a branch
* - git_worktree_list — List all linked worktrees
* - git_worktree_switch — Switch working directory to a worktree
* - git_worktree_remove — Remove a linked worktree
*
* Command:
* - /worktree — Interactive picker to switch between worktrees
*/
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
import { stat } from "node:fs/promises";
import { defineTool } from "@earendil-works/pi-coding-agent";
import { Type } from "@earendil-works/pi-ai";
import { parseWorktreeList, type WorktreeEntry } from "./pi-worktree-parser";
import {
validateCreateWorktreeInput,
buildWorktreeAddCommand,
validatePathDoesNotExist,
isCurrentBranch,
type WorktreeError,
} from "./pi-worktree-create";
// ─── Type Definitions ──────────────────────────────────────────────
/** Result of listing all worktrees. */
interface WorktreeListResult {
/** All worktrees in the repository. */
worktrees: WorktreeEntry[];
/** Number of worktrees found. */
count: number;
/** Current working directory used for comparison. */
currentPath: string;
}
// ─── Tool Parameter Schemas ────────────────────────────────────────
const createWorktreeParams = Type.Object({
path: Type.String({ description: "Path for the new worktree (relative or absolute)" }),
branch: Type.Optional(Type.String({ description: "Branch name to check out. Defaults to 'main'." })),
create_branch: Type.Optional(
Type.Boolean({
description: "If true and branch doesn't exist, create it. Defaults to true.",
}),
),
});
const listWorktreeParams = Type.Object({});
const switchWorktreeParams = Type.Object({
target: Type.String({ description: "Path or branch name of the target worktree to switch to." }),
});
const removeWorktreeParams = Type.Object({
path: Type.String({ description: "Path of the worktree to remove." }),
});
// ─── Helper Functions ──────────────────────────────────────────────
/**
* Check if the target path exists using Bun's fs module.
* @param checkPath - Path to check (resolved against cwd)
* @param ctx - Extension context for working directory
* @returns True if the path exists
*/
async function pathExists(checkPath: string, ctx: ExtensionContext): Promise<boolean> {
const resolvedPath = checkPath.startsWith("/") ? checkPath : `${ctx.cwd}/${checkPath}`;
try {
await stat(resolvedPath);
return true;
} catch {
return false;
}
}
/**
* Get the current branch name from git.
* @param pi - Extension API for executing commands
* @param ctx - Extension context for working directory
* @returns Current branch name, or "unknown" if detection fails
*/
async function getCurrentBranch(pi: ExtensionAPI, ctx: ExtensionContext): Promise<string> {
const result = await pi.exec("git", ["rev-parse", "--abbrev-ref", "HEAD"], { cwd: ctx.cwd });
if (result.exitCode !== 0) {
return "unknown";
}
return result.stdout.trim();
}
/**
* Resolve a worktree target (path or branch name) to its full path.
*
* Used by git_worktree_switch and git_worktree_remove — dead code until those tools ship.
*
* @param target - Path or branch name to resolve
* @param worktrees - List of all worktrees
* @returns The resolved path, or undefined if not found
*/
function resolveWorktreeTarget(target: string, worktrees: WorktreeEntry[]): string | undefined {
const exactMatch = worktrees.find((w) => w.path === target);
if (exactMatch) return exactMatch.path;
const branchMatch = worktrees.find((w) => w.branch === target);
return branchMatch?.path;
}
/**
* Format a WorktreeError into the tool response text.
* @param error - The validation error
* @returns Formatted error string with suggestion if available
*/
function formatValidationError(error: { message: string; suggestion?: string }): string {
const base = `Error: ${error.message}`;
return error.suggestion ? `${base} Suggestion: ${error.suggestion}` : base;
}
/**
* Format a success response for worktree operations.
* @param action - The action performed (e.g., "Created")
* @param details - Key-value pairs to include in the message
* @returns Formatted success string
*/
function formatSuccessResponse(action: string, details: Record<string, string>): string {
const parts = Object.entries(details).map(([key, value]) => `${key} '${value}'`);
return `${action} worktree ${parts.join(" on ")}.`;
}
// ─── Tool Factories ────────────────────────────────────────────────
/**
* Create the git_worktree_create tool definition.
* @param pi - Extension API for registering and executing tools
* @returns The configured tool definition
*/
function createListWorktreeTool(pi: ExtensionAPI) {
return defineTool({
name: "git_worktree_list",
label: "Git Worktree List",
description: "List all linked worktrees in the current repo.",
parameters: listWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, ctx) {
const result = await pi.exec("git", ["worktree", "list"], { cwd: ctx.cwd });
if (result.exitCode !== 0) {
return {
content: [{ type: "text", text: `Error listing worktrees: ${result.stderr}. Suggestion: Ensure you are inside a git repository.` }],
isError: true,
};
}
const worktreeEntries = parseWorktreeList(result.stdout, ctx.cwd);
if (worktreeEntries.length === 0) {
return {
content: [{ type: "text", text: "No worktrees found." }],
details: <WorktreeListResult>{
worktrees: [],
count: 0,
currentPath: ctx.cwd,
warning: "No worktrees exist. Use git_worktree_create to add one.",
},
};
}
const displayLines = worktreeEntries.map(
(entry) => `${entry.branch} - ${entry.path}${entry.isCurrent ? " (current)" : ""}`,
);
return {
content: [{ type: "text", text: displayLines.join("\n") }],
details: <WorktreeListResult>{
worktrees: worktreeEntries,
count: worktreeEntries.length,
currentPath: ctx.cwd,
},
};
},
});
}
/**
* Create the git_worktree_create tool definition.
* @param pi - Extension API for registering and executing tools
* @returns The configured tool definition
*/
function createCreateWorktreeTool(pi: ExtensionAPI) {
return defineTool({
name: "git_worktree_create",
label: "Git Worktree Create",
description: "Create a linked worktree for a branch in the current repo.",
parameters: createWorktreeParams,
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
const worktreePath = params.path;
const branchName = params.branch || "main";
const createBranch = params.create_branch ?? true;
// 1. Validate input parameters
const inputError = validateCreateWorktreeInput(worktreePath, branchName);
if (inputError) {
return {
content: [{ type: "text", text: formatValidationError(inputError) }],
isError: true,
};
}
// 2. Check if path already exists — refuse if so
const pathExistsResult = await pathExists(worktreePath, ctx);
const pathError = validatePathDoesNotExist(worktreePath, () => pathExistsResult);
if (pathError) {
return {
content: [{ type: "text", text: formatValidationError(pathError) }],
isError: true,
};
}
// 3. Check if creating on current branch — refuse if so
const currentBranch = await getCurrentBranch(pi, ctx);
if (isCurrentBranch(branchName, currentBranch)) {
const currentBranchError: WorktreeError = {
message: "Can't create worktree on the current branch — switch first.",
suggestion: "Choose a different branch name or switch branches with 'git switch'.",
};
return {
content: [{ type: "text", text: formatValidationError(currentBranchError) }],
isError: true,
};
}
// 4. Build and run git worktree add command
const commandArgs = buildWorktreeAddCommand({
path: worktreePath,
branch: branchName,
createBranch,
});
const result = await pi.exec("git", commandArgs, { cwd: ctx.cwd });
if (result.exitCode !== 0) {
return {
content: [{
type: "text",
text: `Error creating worktree: ${result.stderr}. Suggestion: Check that the branch exists (or use create_branch=true) and that the parent directory is writable.`,
}],
isError: true,
};
}
return {
content: [{
type: "text",
text: formatSuccessResponse("Created", { at: worktreePath, branch: branchName }),
}],
};
},
});
}
/**
* Create the git_worktree_switch tool definition.
* @param _pi - Extension API (unused in stub)
* @returns The configured tool definition
*/
function createSwitchWorktreeTool(_pi: ExtensionAPI) {
return defineTool({
name: "git_worktree_switch",
label: "Git Worktree Switch",
description: "Switch pi's working directory to a linked worktree.",
parameters: switchWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
return {
content: [{ type: "text", text: "Error: git_worktree_switch is not yet implemented. Suggestion: Use the `/worktree` command or `git worktree` manually until this tool is complete." }],
isError: true,
};
},
});
}
/**
* Create the git_worktree_remove tool definition.
* @param _pi - Extension API (unused in stub)
* @returns The configured tool definition
*/
function createRemoveWorktreeTool(_pi: ExtensionAPI) {
return defineTool({
name: "git_worktree_remove",
label: "Git Worktree Remove",
description: "Remove a linked worktree.",
parameters: removeWorktreeParams,
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
return {
content: [{ type: "text", text: "Error: git_worktree_remove is not yet implemented. Suggestion: Use `git worktree remove` manually until this tool is complete." }],
isError: true,
};
},
});
}
// ─── Extension Entry Point ────────────────────────────────────────
export default function (pi: ExtensionAPI) {
// Register tools via factory functions
pi.registerTool(createCreateWorktreeTool(pi));
pi.registerTool(createListWorktreeTool(pi));
pi.registerTool(createSwitchWorktreeTool(pi));
pi.registerTool(createRemoveWorktreeTool(pi));
// ─── Command Registration ──────────────────────────────────────
pi.registerCommand("worktree", {
description: "Interactive picker to switch between linked worktrees.",
handler: async (_args, _ctx) => {
return {
content: [{ type: "text", text: "Error: /worktree command is not yet implemented. Suggestion: Use `git worktree list` and navigate manually until this command is complete." }],
isError: true,
};
},
});
}