pi-worktrees/.pi/extensions/pi-worktree.ts
David Kong fc19b36cd8 fix: address all code review findings for issue-3
Critical fixes:
- Normalize path comparison with path.resolve() (Task 001)
- Add validation guards for malformed lines in parser (Task 002)

Major fixes:
- Extract tool definitions to factory functions (Task 003)
- Use WorktreeListResult interface with enriched metadata (Tasks 004, 010)
- Add unit tests for parseWorktreeList — 12 tests covering edge cases (Task 005)
- Return warning message when zero worktrees found (Task 006)

Minor fixes:
- Apply consistent JSDoc to all functions including factories (Task 007)
- Replace em-dash with ASCII separator for encoding safety (Task 008)
- Add section comments between tool factories and command registration (Task 009)

Suggestions implemented:
- Export parseWorktreeList in separate testable module (Task 011)
2026-07-24 23:01:40 +10: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,
};
},
});
}