pi-worktrees/.pi/extensions/pi-worktree.ts
David Kong 3d1b2f5443 Milestone 1.3: Implement git_worktree_list tool (#3) (#16)
## Summary
Implement the `git_worktree_list` tool that parses `git worktree list` output into structured data with path, branch, commit hash, and current directory marker.

## Changes
- Implemented `parseWorktreeList()` helper to parse raw `git worktree list` output
  - Handles standard branches (e.g., `[main]`)
  - Handles detached HEAD (marked as `(detached)`)
  - Marks the current working directory with `isCurrent: true`
- Wired parser into `git_worktree_list` tool execute function
- Returns both formatted display text and structured `details.worktrees` array
- Added error handling for non-git-repo directories
- Restructured tool definitions inside extension factory to capture `pi` via closure

## Testing
- [x] Parsing logic verified against real `git worktree list` output (3 worktrees)
- [ ] Manual verification in pi TUI pending extension load test

## Checklist
- [x] Self-reviewed the diff
- [x] Code follows project conventions (AGENTS.md, DESIGN.md, DOMAIN.md)
- [x] Descriptive naming (no single-character variables)
- [x] Error handling with clear messages and suggestions

Co-authored-by: David Kong <davkon@gmail.com>
Reviewed-on: #16
2026-07-24 13:11:08 +00:00

217 lines
7.6 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 { defineTool } from "@earendil-works/pi-coding-agent";
import { Type } from "@earendil-works/pi-ai";
import { parseWorktreeList, type WorktreeEntry } from "./pi-worktree-parser";
// ─── 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;
}
/** Error returned when a worktree operation fails. */
interface WorktreeError {
/** Human-readable error message from git or validation. */
message: string;
/** Suggested fix for the user. */
suggestion?: 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 false.",
}),
),
});
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 (stubs) ──────────────────────────────────────
/**
* Check if the target path exists.
* @param checkPath - Path to check
* @param ctx - Extension context for file system access
* @returns True if the path exists
*/
async function pathExists(checkPath: string, ctx: ExtensionContext): Promise<boolean> {
throw new Error("not implemented");
}
/**
* Resolve a worktree target (path or branch name) to its full path.
* @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 {
throw new Error("not implemented");
}
// ─── 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 (unused in stub)
* @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) {
return {
content: [{ type: "text", text: "Error: git_worktree_create is not yet implemented. Suggestion: Use `git worktree add` manually until this tool is complete." }],
isError: true,
};
},
});
}
/**
* 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,
};
},
});
}