Commit graph

10 commits

Author SHA1 Message Date
David Kong
39dd626f10 feat: implement git_worktree_switch tool (Issue #6)
- Add pi-worktree-switch.ts with pure functions:
  - validateSwitchInput: validates target is non-empty
  - resolveWorktreeTarget: resolves path or branch name to worktree path
  - isAlreadyInWorktree: checks if cwd matches target
- Wire up createSwitchWorktreeTool with full validation pipeline:
  1. Validate input parameters
  2. List worktrees and resolve target to path
  3. Refuse if already in target worktree
  4. Fail fast on uncommitted changes in source
  5. Change cwd via ctx.chdir()
  6. Return success with branch info
- Remove dead resolveWorktreeTarget from main module
- 21 unit tests, 103 total passing, 0 regressions
2026-07-25 12:30:38 +10:00
8761c3af5f feat: implement git_worktree_remove tool (Issue #5) (#18)
## Summary
Implement `git_worktree_remove` tool with proper validation and error handling.

## Changes
- Add `pi-worktree-remove.ts` — pure validation functions for remove operation
  - `validateRemoveWorktreeInput()` — validates path is non-empty
  - `isMainRepository()` — refuses removal of main repo root (suggests `git worktree prune`)
  - `hasUncommittedChanges()` — checks git status --porcelain output
  - `buildWorktreeRemoveCommand()` — builds `git worktree remove` args with optional `--force`
- Add `pi-worktree-remove.test.ts` — 17 unit tests covering all validation paths
- Wire up `createRemoveWorktreeTool()` in main extension with full validation pipeline

## Testing
- [x] All 72 tests pass (55 existing + 17 new)
- [x] No regressions in existing test suite
- [ ] Manual verification — remove a worktree, try removing main repo, try removing worktree with changes

## Checklist
- [x] Self-reviewed the diff
- [x] Code follows project conventions (pure functions, fail-fast validation)
- [x] Descriptive naming (no single-character variables)

Co-authored-by: David Kong <davkon@gmail.com>
Reviewed-on: #18
2026-07-25 02:21:03 +00:00
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
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
dd2202f54c Milestone 1.2: Register all four worktree tools (#15)
## Summary
Register all four git worktree tools with correct TypeBox schemas and placeholder implementations.

## Changes
- Added `.pi/extensions/pi-worktree.ts` with four tool registrations:
  - `git_worktree_list` — no params, lists linked worktrees
  - `git_worktree_create` — path, branch?, create_branch? params
  - `git_worktree_switch` — target param for switching cwd
  - `git_worktree_remove` — path param for removing worktrees
- Each tool returns "Not implemented yet." placeholder response

## Testing
- [x] All four tools registered with correct TypeBox schemas
- [x] Calling each tool returns a response (placeholder)
- [ ] Extension loads without errors when pi starts (manual verification needed)

## Checklist
- [ ] Self-reviewed the diff
- [ ] Code follows project conventions
- [ ] Descriptive naming (no single-character variables)

Co-authored-by: David Kong <davkon@gmail.com>
Reviewed-on: #15
2026-07-24 12:31:29 +00:00
6c696f282d Fix code review issues: structured error returns, remove unused count, add JSDoc (#14)
# Code Review: issue-1 vs main

**Date:** 2025-07-24
**Language:** TypeScript (pi extension)
**Files changed:** 4
**Lines added:** +246 / Lines removed: -0

## Files Under Review

| File | Status | Purpose |
|------|--------|---------|
| `.pi/extensions/pi-worktree.ts` | New | Extension scaffold — types, schemas, tool/command stubs |
| `findings.md` | New | Research findings and session discoveries |
| `progress.md` | New | Progress log with TDD phase tracking |
| `task_plan.md` | New | Task plan for issue #1 implementation |

---

## Critical (0)

_None._

## Major (2)

### [MAJOR] Execute functions throw errors instead of returning structured error objects

**File:** `.pi/extensions/pi-worktree.ts`
**Lines:** 97, 105, 113, 121, 138

**Detail:** All `execute()` functions and the command handler use `throw new Error("not implemented")`. Per AGENTS.md error handling pattern, tools should return structured objects:

```typescript
return {
  content: [{ type: "text", text: `Error: ${message}. Suggestion: <fix>` }],
  isError: true
};
```

Even stub implementations should follow this pattern so the extension loads without unhandled exceptions. Throwing from an execute function will crash the tool invocation rather than surfacing a clean error to the user.

**Fix:** Replace `throw new Error("not implemented")` with structured return objects that include a suggestion, e.g.:

```typescript
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
  return {
    content: [{ type: "text", text: "Error: git_worktree_create not yet implemented. Suggestion: Use `git worktree add` manually until this tool is complete." }],
    isError: true
  };
}
```

### [MAJOR] `WorktreeListResult.count` field has no consumer and duplicates available info

**File:** `.pi/extensions/pi-worktree.ts`
**Line:** 32

**Detail:** The interface defines `count: number` but nothing in the scaffold uses it. Since callers can derive count from `worktrees.length`, this field adds maintenance burden (must stay in sync) without clear value. If included for API convenience, document why it's separate from `.length`.

**Fix:** Either remove `count` from the interface or add a comment justifying its presence (e.g., "cached to avoid repeated .length calls" or "included for tool response schema consistency").

---

## Minor (3)

### [MINOR] `WorktreeError` interface is defined but unused

**File:** `.pi/extensions/pi-worktree.ts`
**Lines:** 38–43

**Detail:** The `WorktreeError` interface (`message`, `suggestion?`) is well-designed and aligns with AGENTS.md conventions, but isn't referenced anywhere in the current code. It will be needed when implementing error returns.

**Fix:** No action needed for scaffold phase — this is forward-looking type design. Confirm it's used when implementing actual tool logic.

### [MINOR] `ExtensionContext` imported but only used indirectly via type definitions

**File:** `.pi/extensions/pi-worktree.ts`
**Line:** 16

**Detail:** `ExtensionContext` is imported as a type and referenced in the `pathExists()` helper signature. This is correct forward-looking design — it will be needed when implementing file system checks. No issue, just noting for completeness.

### [MINOR] Tool definitions lack JSDoc comments unlike helper functions

**File:** `.pi/extensions/pi-worktree.ts`
**Lines:** 95–123

**Detail:** Helper functions (`parseWorktreeList`, `pathExists`, `resolveWorktreeTarget`) have thorough JSDoc with parameter descriptions and return types. The tool definitions (`gitWorktreeCreateTool`, etc.) have no comments. For a single-file extension, inline documentation helps future maintainers understand each tool's contract at a glance.

**Fix:** Add brief JSDoc above each `defineTool()` call summarizing its purpose and key behaviors:

```typescript
/**
 * Create a linked worktree for a branch.
 * Runs `git worktree add <path> [branch]` with optional `-b` flag.
 */
const gitWorktreeCreateTool = defineTool({ ... });
```

---

## Suggestions (2)

### [SUGGESTION] Consider adding a `pi.exec()` usage example in comments for future implementers

**File:** `.pi/extensions/pi-worktree.ts`

**Detail:** AGENTS.md specifies "Git: native via `pi.exec("git", [...])`" but the scaffold has no indication of how git commands will be invoked. A comment near the helper functions showing the expected pattern would reduce friction for the next implementation phase:

```typescript
// Example: const result = await ctx.exec("git", ["worktree", "add", path, branch]);
```

### [SUGGESTION] `task_plan.md` lists only Task 001 but milestone context references Tasks 1.1–1.3

**File:** `task_plan.md`
**Lines:** 6, 12–14

**Detail:** The task table has one entry (Task 001) marked done, but the milestone context below references three subtasks (1.1: Create Extension File, 1.2: Register Tool Scaffolding, 1.3: Implement `git_worktree_list`). This creates ambiguity about whether Task 001 encompasses all three or if 1.2 and 1.3 are still pending.

**Fix:** Either expand the task table to list subtasks 1.1–1.3 separately with individual status, or clarify that Task 001 covers all three milestones.

---

## Summary

| Severity | Count |
|----------|-------|
| Critical | 0 |
| Major | 2 |
| Minor | 3 |
| Suggestions | 2 |
| **Total** | **7** |

 No critical issues. Major issues should be addressed before the extension is loadable in pi — specifically, execute functions must return structured error objects instead of throwing to avoid unhandled exceptions at runtime.

---

## Review Fix Plan

| Task | Issue | Severity | File | Description |
|------|-------|----------|------|-------------|
| 001 | Execute stubs throw instead of returning errors | major | `.pi/extensions/pi-worktree.ts` | Replace `throw new Error()` with structured `{ content, isError: true }` returns in all execute functions and command handler |
| 002 | Unused `count` field in `WorktreeListResult` | major | `.pi/extensions/pi-worktree.ts` | Remove or document the `count` field |
| 003 | Tool definitions lack JSDoc | minor | `.pi/extensions/pi-worktree.ts` | Add JSDoc comments above each `defineTool()` call |
| 004 | Task plan subtask ambiguity | suggestion | `task_plan.md` | Clarify relationship between Task 001 and milestone subtasks 1.1–1.3 |

### Task 001: Execute stubs throw instead of returning errors

**Severity:** major
**File:** `.pi/extensions/pi-worktree.ts`
**Lines:** 97, 105, 113, 121, 138

**Issue:** All five execute/handler functions use `throw new Error("not implemented")`. When pi invokes a tool, an uncaught exception will crash the tool invocation rather than returning a clean error message to the user. AGENTS.md specifies the pattern: return `{ content: [{ type: "text", text }], isError: true }`.

**Fix:** For each of the 4 tools and 1 command handler, replace the throw with:

```typescript
async execute(_toolCallId, _params, _signal, _onUpdate, _ctx) {
  return {
    content: [{ type: "text", text: `Error: <tool_name> is not yet implemented. Suggestion: Use git worktree commands directly until this tool is complete.` }],
    isError: true
  };
}
```

**Verification:** Extension loads in pi without errors; calling any tool returns an error message instead of crashing.

### Task 002: Unused `count` field in `WorktreeListResult`

**Severity:** major
**File:** `.pi/extensions/pi-worktree.ts`
**Line:** 32

**Issue:** `count: number` is defined but never populated or consumed. Callers can use `worktrees.length`. Dead fields create maintenance burden and confusion about whether they're intentional API design or leftover scaffolding.

**Fix:** Remove the `count` field from `WorktreeListResult`:

```typescript
interface WorktreeListResult {
  worktrees: WorktreeEntry[];
}
```

Or add a comment if intentionally kept for API schema reasons.

**Verification:** No references to `.count` in code; interface matches actual usage.

### Task 003: Tool definitions lack JSDoc

**Severity:** minor
**File:** `.pi/extensions/pi-worktree.ts`
**Lines:** 95–123

**Issue:** Helper functions have thorough JSDoc but tool definitions don't. In a single-file extension, inline docs help readers scan the file and understand each tool's purpose without reading implementation details.

**Fix:** Add JSDoc above each `defineTool()`:

```typescript
/** Create a linked worktree for a branch in the current repo. */
const gitWorktreeCreateTool = defineTool({ ... });

/** List all linked worktrees in the current repo. */
const gitWorktreeListTool = defineTool({ ... });

/** Switch pi's working directory to a linked worktree. */
const gitWorktreeSwitchTool = defineTool({ ... });

/** Remove a linked worktree. */
const gitWorktreeRemoveTool = defineTool({ ... });
```

**Verification:** Each tool definition has a JSDoc comment matching its description field.

### Task 004: Task plan subtask ambiguity

**Severity:** suggestion
**File:** `task_plan.md`
**Lines:** 6, 12–14

**Issue:** The task table shows one completed Task 001, but the milestone context references three distinct subtasks (1.1, 1.2, 1.3). It's unclear whether all are done or only partially complete.

**Fix:** Expand the task table:

| Task | Description | Done |
|------|-------------|------|
| 001.1 | Create extension file with correct imports | ☑ |
| 001.2 | Register tool scaffolding (4 tools + command) | ☑ |
| 001.3 | Implement `git_worktree_list` | ☐ |

**Verification:** Task plan clearly shows what's done vs pending within the issue scope.

Co-authored-by: David Kong <davkon@gmail.com>
Reviewed-on: #14
2026-07-24 08:43:34 +00:00
David Kong
37e6ab25c3 add DOMAIN.md file to initial commits 2026-07-24 12:45:32 +10:00
David Kong
13a2ec6581 initial commit 2026-07-24 12:36:57 +10:00
David Kong
3f7ccd0f34 Move docs into main/ subdirectory 2026-07-24 12:27:47 +10:00
David Kong
cd51baa2c1 Initial commit: extension docs and design plan 2026-07-24 12:16:00 +10:00