worktrees 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. checksums.yaml +7 -0
  2. data/.claude/commands/plan.md +42 -0
  3. data/.claude/commands/specify.md +12 -0
  4. data/.claude/commands/tasks.md +60 -0
  5. data/.cursor/commands/plan.md +42 -0
  6. data/.cursor/commands/specify.md +12 -0
  7. data/.cursor/commands/tasks.md +60 -0
  8. data/.cursor/rules +81 -0
  9. data/.specify/memory/constitution-v1.0.1-formal.md +90 -0
  10. data/.specify/memory/constitution.md +153 -0
  11. data/.specify/memory/constitution_update_checklist.md +88 -0
  12. data/.specify/scripts/bash/check-task-prerequisites.sh +15 -0
  13. data/.specify/scripts/bash/common.sh +37 -0
  14. data/.specify/scripts/bash/create-new-feature.sh +58 -0
  15. data/.specify/scripts/bash/get-feature-paths.sh +7 -0
  16. data/.specify/scripts/bash/setup-plan.sh +17 -0
  17. data/.specify/scripts/bash/update-agent-context.sh +57 -0
  18. data/.specify/templates/agent-file-template.md +23 -0
  19. data/.specify/templates/plan-template.md +254 -0
  20. data/.specify/templates/spec-template.md +116 -0
  21. data/.specify/templates/tasks-template.md +152 -0
  22. data/CLAUDE.md +145 -0
  23. data/Gemfile +15 -0
  24. data/Gemfile.lock +150 -0
  25. data/README.md +163 -0
  26. data/Rakefile +52 -0
  27. data/exe/worktrees +52 -0
  28. data/lib/worktrees/cli.rb +36 -0
  29. data/lib/worktrees/commands/create.rb +74 -0
  30. data/lib/worktrees/commands/list.rb +87 -0
  31. data/lib/worktrees/commands/remove.rb +62 -0
  32. data/lib/worktrees/commands/status.rb +95 -0
  33. data/lib/worktrees/commands/switch.rb +57 -0
  34. data/lib/worktrees/git_operations.rb +106 -0
  35. data/lib/worktrees/models/feature_worktree.rb +92 -0
  36. data/lib/worktrees/models/repository.rb +75 -0
  37. data/lib/worktrees/models/worktree_config.rb +74 -0
  38. data/lib/worktrees/version.rb +5 -0
  39. data/lib/worktrees/worktree_manager.rb +238 -0
  40. data/lib/worktrees.rb +27 -0
  41. data/specs/001-build-a-tool/GEMINI.md +20 -0
  42. data/specs/001-build-a-tool/contracts/cli-contracts.md +43 -0
  43. data/specs/001-build-a-tool/contracts/openapi.yaml +135 -0
  44. data/specs/001-build-a-tool/data-model.md +51 -0
  45. data/specs/001-build-a-tool/plan.md +241 -0
  46. data/specs/001-build-a-tool/quickstart.md +67 -0
  47. data/specs/001-build-a-tool/research.md +76 -0
  48. data/specs/001-build-a-tool/spec.md +153 -0
  49. data/specs/001-build-a-tool/tasks.md +209 -0
  50. metadata +138 -0
@@ -0,0 +1,241 @@
1
+ # Implementation Plan: Manage Git feature worktrees
2
+
3
+
4
+ **Branch**: `[001-build-a-tool]` | **Date**: 2025-09-15 | **Spec**: /Users/drewgoddyn/projects/claude-worktrees/specs/001-build-a-tool/spec.md
5
+ **Input**: Feature specification from `/specs/001-build-a-tool/spec.md`
6
+
7
+ ## Execution Flow (/plan command scope)
8
+ ```
9
+ 1. Load feature spec from Input path
10
+ → If not found: ERROR "No feature spec at {path}"
11
+ 2. Fill Technical Context (scan for NEEDS CLARIFICATION)
12
+ → Detect Project Type from context (web=frontend+backend, mobile=app+api)
13
+ → Set Structure Decision based on project type
14
+ 3. Evaluate Constitution Check section below
15
+ → If violations exist: Document in Complexity Tracking
16
+ → If no justification possible: ERROR "Simplify approach first"
17
+ → Update Progress Tracking: Initial Constitution Check
18
+ 4. Execute Phase 0 → research.md
19
+ → If NEEDS CLARIFICATION remain: ERROR "Resolve unknowns"
20
+ 5. Execute Phase 1 → contracts, data-model.md, quickstart.md, agent-specific template file (e.g., `CLAUDE.md` for Claude Code, `.github/copilot-instructions.md` for GitHub Copilot, or `GEMINI.md` for Gemini CLI).
21
+ 6. Re-evaluate Constitution Check section
22
+ → If new violations: Refactor design, return to Phase 1
23
+ → Update Progress Tracking: Post-Design Constitution Check
24
+ 7. Plan Phase 2 → Describe task generation approach (DO NOT create tasks.md)
25
+ 8. STOP - Ready for /tasks command
26
+ ```
27
+
28
+ **IMPORTANT**: The /plan command STOPS at step 7. Phases 2-4 are executed by other commands:
29
+ - Phase 2: /tasks command creates tasks.md
30
+ - Phase 3-4: Implementation execution (manual or via tools)
31
+
32
+ ## Summary
33
+ Manage lifecycle and navigation of Git feature worktrees via a CLI: create from a chosen base, list and switch between them, and safely clean them up with conservative safety checks and explicit opt-in for branch deletion when fully merged. Technical approach: POSIX shell (bash) tooling built around Git CLI, global hidden worktrees root at `$HOME/.worktrees`, strict naming and validation, and structured output with `--format json` for tooling.
34
+
35
+ ## Technical Context
36
+ **Language/Version**: Bash (POSIX), Git ≥ 2.33
37
+ **Primary Dependencies**: Git CLI
38
+ **Storage**: Filesystem (worktrees under `$HOME/.worktrees` by default)
39
+ **Testing**: bats (planned), shellcheck for linting
40
+ **Target Platform**: macOS/Linux shells
41
+ **Project Type**: single
42
+ **Performance Goals**: Responsive CLI; list paging defaults pageSize=20, max=100
43
+ **Constraints**: Conservative safety for removal; structured outputs; zero external runtimes
44
+ **Scale/Scope**: Up to ~100 worktrees per repo (paged listing)
45
+
46
+ ## Constitution Check
47
+ *GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*
48
+
49
+ **Simplicity**:
50
+ - Projects: 2 (cli, tests)
51
+ - Using framework directly? (no wrapper classes)
52
+ - Single data model? (no DTOs unless serialization differs)
53
+ - Avoiding patterns? (no Repository/UoW without proven need)
54
+
55
+ **Architecture**:
56
+ - EVERY feature as library? (no direct app code)
57
+ - Libraries listed: `worktrees-cli` (feature lifecycle commands)
58
+ - CLI per library: commands provide `--help|--version|--format`
59
+ - Library docs: llms.txt/GEMINI.md planned
60
+
61
+ **Testing (NON-NEGOTIABLE)**:
62
+ - RED-GREEN-Refactor cycle enforced? (test MUST fail first)
63
+ - Git commits show tests before implementation?
64
+ - Order: Contract→Integration→E2E→Unit strictly followed?
65
+ - Real dependencies used? (actual DBs, not mocks)
66
+ - Integration tests for: new libraries, contract changes, shared schemas?
67
+ - FORBIDDEN: Implementation before test, skipping RED phase
68
+
69
+ **Observability**:
70
+ - Structured logging included?
71
+ - Frontend logs → backend? (unified stream)
72
+ - Error context sufficient?
73
+
74
+ **Versioning**:
75
+ - Version number assigned? (MAJOR.MINOR.BUILD)
76
+ - BUILD increments on every change?
77
+ - Breaking changes handled? (parallel tests, migration plan)
78
+
79
+ ## Project Structure
80
+
81
+ ### Documentation (this feature)
82
+ ```
83
+ specs/[###-feature]/
84
+ ├── plan.md # This file (/plan command output)
85
+ ├── research.md # Phase 0 output (/plan command)
86
+ ├── data-model.md # Phase 1 output (/plan command)
87
+ ├── quickstart.md # Phase 1 output (/plan command)
88
+ ├── contracts/ # Phase 1 output (/plan command)
89
+ └── tasks.md # Phase 2 output (/tasks command - NOT created by /plan)
90
+ ```
91
+
92
+ ### Source Code (repository root)
93
+ ```
94
+ # Option 1: Single project (DEFAULT)
95
+ src/
96
+ ├── models/
97
+ ├── services/
98
+ ├── cli/
99
+ └── lib/
100
+
101
+ tests/
102
+ ├── contract/
103
+ ├── integration/
104
+ └── unit/
105
+
106
+ # Option 2: Web application (when "frontend" + "backend" detected)
107
+ backend/
108
+ ├── src/
109
+ │ ├── models/
110
+ │ ├── services/
111
+ │ └── api/
112
+ └── tests/
113
+
114
+ frontend/
115
+ ├── src/
116
+ │ ├── components/
117
+ │ ├── pages/
118
+ │ └── services/
119
+ └── tests/
120
+
121
+ # Option 3: Mobile + API (when "iOS/Android" detected)
122
+ api/
123
+ └── [same as backend above]
124
+
125
+ ios/ or android/
126
+ └── [platform-specific structure]
127
+ ```
128
+
129
+ **Structure Decision**: Option 1 (Single project: src/, tests/)
130
+
131
+ ## Phase 0: Outline & Research
132
+ 1. **Extract unknowns from Technical Context** above:
133
+ - For each NEEDS CLARIFICATION → research task
134
+ - For each dependency → best practices task
135
+ - For each integration → patterns task
136
+
137
+ 2. **Generate and dispatch research agents**:
138
+ ```
139
+ For each unknown in Technical Context:
140
+ Task: "Research {unknown} for {feature context}"
141
+ For each technology choice:
142
+ Task: "Find best practices for {tech} in {domain}"
143
+ ```
144
+
145
+ 3. **Consolidate findings** in `research.md` using format:
146
+ - Decision: [what was chosen]
147
+ - Rationale: [why chosen]
148
+ - Alternatives considered: [what else evaluated]
149
+
150
+ **Output**: research.md with all NEEDS CLARIFICATION resolved
151
+
152
+ ## Phase 1: Design & Contracts
153
+ *Prerequisites: research.md complete*
154
+
155
+ 1. **Extract entities from feature spec** → `data-model.md`:
156
+ - Entity name, fields, relationships
157
+ - Validation rules from requirements
158
+ - State transitions if applicable
159
+
160
+ 2. **Generate API contracts** from functional requirements:
161
+ - For each user action → endpoint
162
+ - Use standard REST/GraphQL patterns
163
+ - Output OpenAPI/GraphQL schema to `/contracts/`
164
+
165
+ 3. **Generate contract tests** from contracts:
166
+ - One test file per endpoint
167
+ - Assert request/response schemas
168
+ - Tests must fail (no implementation yet)
169
+
170
+ 4. **Extract test scenarios** from user stories:
171
+ - Each story → integration test scenario
172
+ - Quickstart test = story validation steps
173
+
174
+ 5. **Update agent file incrementally** (O(1) operation):
175
+ - Run `/scripts/bash/update-agent-context.sh cursor` for your AI assistant
176
+ - Run `/scripts/bash/update-agent-contxt.sh clude` for your AI assistant
177
+ - If exists: Add only NEW tech from current plan
178
+ - Preserve manual additions between markers
179
+ - Update recent changes (keep last 3)
180
+ - Keep under 150 lines for token efficiency
181
+ - Output to repository root
182
+
183
+ **Output**: data-model.md, /contracts/*, quickstart.md, agent-specific file
184
+
185
+ ## Phase 2: Task Planning Approach
186
+ *This section describes what the /tasks command will do - DO NOT execute during /plan*
187
+
188
+ **Task Generation Strategy**:
189
+ - Load `/templates/tasks-template.md` as base
190
+ - Generate tasks from Phase 1 design docs (contracts, data model, quickstart)
191
+ - Each contract → contract test task [P]
192
+ - Each entity → model creation task [P]
193
+ - Each user story → integration test task
194
+ - Implementation tasks to make tests pass
195
+
196
+ **Ordering Strategy**:
197
+ - TDD order: Tests before implementation
198
+ - Dependency order: Models before services before UI
199
+ - Mark [P] for parallel execution (independent files)
200
+
201
+ **Estimated Output**: 25-30 numbered, ordered tasks in tasks.md
202
+
203
+ **IMPORTANT**: This phase is executed by the /tasks command, NOT by /plan
204
+
205
+ ## Phase 3+: Future Implementation
206
+ *These phases are beyond the scope of the /plan command*
207
+
208
+ **Phase 3**: Task execution (/tasks command creates tasks.md)
209
+ **Phase 4**: Implementation (execute tasks.md following constitutional principles)
210
+ **Phase 5**: Validation (run tests, execute quickstart.md, performance validation)
211
+
212
+ ## Complexity Tracking
213
+ *Fill ONLY if Constitution Check has violations that must be justified*
214
+
215
+ | Violation | Why Needed | Simpler Alternative Rejected Because |
216
+ |-----------|------------|-------------------------------------|
217
+ | [e.g., 4th project] | [current need] | [why 3 projects insufficient] |
218
+ | [e.g., Repository pattern] | [specific problem] | [why direct DB access insufficient] |
219
+
220
+
221
+ ## Progress Tracking
222
+ *This checklist is updated during execution flow*
223
+
224
+ **Phase Status**:
225
+ - [x] Phase 0: Research complete (/plan command)
226
+ - [x] Phase 1: Design complete (/plan command)
227
+ - [x] Phase 2: Task planning complete (/plan command - describe approach only)
228
+ - [x] Phase 3: Tasks generated (/tasks command)
229
+ - [x] Phase 4: Implementation complete (Ruby CLI T001-T035)
230
+ - [x] Phase 5: Validation passed (all tests passing, spec-kit gates cleared)
231
+
232
+ **Gate Status**:
233
+ - [x] Initial Constitution Check: PASS
234
+ - [x] Post-Design Constitution Check: PASS
235
+ - [x] All NEEDS CLARIFICATION resolved
236
+ - [x] Complexity deviations documented (Ruby chosen over Bash for better testing, maintainability)
237
+
238
+ **Final Status**: ✅ COMPLETE - Ruby implementation delivered with comprehensive test suite
239
+
240
+ ---
241
+ *Based on Constitution v2.1.1 - See `/memory/constitution.md`*
@@ -0,0 +1,67 @@
1
+ # Quickstart: Manage Git feature worktrees
2
+
3
+ Prerequisites:
4
+ - Git ≥ 2.33
5
+ - macOS or Linux shell (zsh/bash)
6
+
7
+ Concepts:
8
+ - Feature worktrees are isolated working copies tied to branches, created under a global root (default `$HOME/.worktrees`).
9
+ - Names must match `NNN-kebab-feature` (lowercase, ≤ 40 chars feature part).
10
+
11
+ Common flows:
12
+
13
+ ## Create a worktree
14
+ ```bash
15
+ worktrees create 001-build-a-tool --base main --format json
16
+ ```
17
+
18
+ ## List worktrees (paged)
19
+ ```bash
20
+ # Text format (default)
21
+ worktrees list --page 1 --page-size 20
22
+
23
+ # JSON format with all status fields
24
+ worktrees list --format json --page 1 --page-size 20
25
+
26
+ # Fast JSON format without expensive status checks (for large repos)
27
+ worktrees list --format json --no-status --page-size 50
28
+ ```
29
+
30
+ ## Switch to a worktree (allowed even if current is dirty; warning shown)
31
+ ```bash
32
+ worktrees switch 001-build-a-tool
33
+ ```
34
+
35
+ ## Remove a worktree safely (keep branch)
36
+ ```bash
37
+ worktrees remove 001-build-a-tool
38
+ ```
39
+
40
+ ## Remove and delete branch when fully merged
41
+ ```bash
42
+ worktrees remove 001-build-a-tool --delete-branch --merged-into main
43
+ ```
44
+
45
+ ## Check current status
46
+ ```bash
47
+ worktrees status
48
+ ```
49
+
50
+ ## Advanced Options
51
+ - Use `--root <path>` to override the global worktrees root
52
+ - Use `--reuse-branch` to reuse an existing local branch not checked out elsewhere
53
+ - Use `--sibling` to create a sibling branch when the branch is already checked out in another worktree
54
+ - Use `--no-status` with list command for better performance on large repositories
55
+ - Use `--format json` for structured output suitable for scripts and tools
56
+
57
+ ## Performance Tips
58
+ For repositories with many worktrees (>100):
59
+ ```bash
60
+ # Use filters to narrow results
61
+ worktrees list --filter-name "001-*" --filter-base main
62
+
63
+ # Skip expensive git status checks for faster listing
64
+ worktrees list --no-status --page-size 100
65
+ ```
66
+
67
+
@@ -0,0 +1,76 @@
1
+ # Research: Manage Git feature worktrees
2
+
3
+ This document consolidates decisions made to resolve ambiguities and define the technical approach for the Git worktrees management tool. Each decision includes rationale and alternatives considered.
4
+
5
+ ## Unknowns Resolved
6
+
7
+ ### U1. Language/Runtime for CLI
8
+ - Decision: Bash (POSIX-compatible) using Git CLI; require Git ≥ 2.33.
9
+ - Rationale: Native fit for Git operations; zero external runtime; easiest distribution; portable across macOS/Linux.
10
+ - Alternatives considered: Python 3.11 (richer stdlib, dependency mgmt), Node.js 20 (ecosystem). Rejected for added runtime dependency and packaging overhead for v1.
11
+
12
+ ### U2. Default worktrees root
13
+ - Decision: `$HOME/.worktrees` as the global hidden root; override via `--root` flag or config env `WORKTREES_ROOT`.
14
+ - Rationale: Hidden, global, avoids clutter inside repo; clear single place to manage storage.
15
+ - Alternatives considered: Project-local `.worktrees` under repo root (risks clutter, nested repos), `$HOME/worktrees` (not hidden).
16
+
17
+ ### U3. Base detection when not provided
18
+ - Decision: Default to repository default branch (remote HEAD) if available; else `main` if present; else `master`.
19
+ - Mechanism: Use `git symbolic-ref --quiet refs/remotes/origin/HEAD` to detect remote HEAD; fall back via `git show-ref --verify` checks.
20
+ - Rationale: Matches FR-008; ensures predictable default.
21
+
22
+ ### U4. Naming convention enforcement
23
+ - Decision: Enforce regex `^[0-9]{3}-[a-z0-9-]{1,40}$`; case-insensitive uniqueness across worktrees; reserved names `main`, `master` disallowed.
24
+ - Rationale: Meets FR-005; prevents collisions; keeps names readable and sortable.
25
+ - Alternatives considered: Allow uppercase/underscores; rejected for cross-platform safety and simplicity.
26
+
27
+ ### U5. Pre-existing local branch with requested feature name (different base)
28
+ - Decision: Error by default. Provide `--reuse-branch` to reuse if not checked out in any worktree; require explicit `--base` acknowledgment mismatch.
29
+ - Rationale: Safety first; avoids silent divergence.
30
+
31
+ ### U6. Branch already checked out in another worktree
32
+ - Decision: Disallow duplicate checkout. Offer selecting existing worktree or `--sibling <suffix>` to create a sibling branch (e.g., `-2`).
33
+ - Rationale: Aligns FR-013 and Git worktree rules.
34
+
35
+ ### U7. Dirty-state policies
36
+ - Decision: Switching allowed with a prominent warning summarizing dirty state. Removal blocked if tracked changes exist or an operation is in progress; removal blocked if unpushed commits or no upstream. `--force` only deletes untracked/ignored files.
37
+ - Rationale: Matches FR-011.
38
+
39
+ ### U8. Cleanup semantics for tags
40
+ - Decision: Never delete tags automatically. Tag deletion (if desired) must be manual.
41
+ - Rationale: Tags are often shared/released artifacts; high risk to remove automatically.
42
+
43
+ ### U9. Scale expectations and listing
44
+ - Decision: Expect up to ~100 worktrees per repo. Implement filtering by name and base; paging with `--page` and `--page-size` (default 20, max 100).
45
+ - Rationale: Keeps CLI responsive; avoids overwhelming output (Edge case note in spec).
46
+
47
+ ### U10. Safety checks for removal
48
+ - Decision: Consider fully merged only if `git merge-base --is-ancestor <branch> <base>` returns success; require explicit `--delete-branch` and `--merged-into <base>` to delete branch.
49
+ - Rationale: Prevents data loss and enforces explicit user intent.
50
+
51
+ ### U11. Worktree path issues
52
+ - Decision: Prevent creation if target path exists/non-empty; robust quoting for spaces/special chars; treat names differing only by case as duplicates on case-insensitive filesystems.
53
+ - Rationale: Cross-platform correctness and safety.
54
+
55
+ ### U12. Non-repo execution
56
+ - Decision: Detect repo root via `git rev-parse --show-toplevel`; refuse commands outside a repo; print clear guidance.
57
+ - Rationale: Avoid misuse and unclear state.
58
+
59
+ ## Best Practices Collected
60
+ - Provide `--format json|text` across commands; default `text` for humans, `json` for tooling.
61
+ - Print actionable errors with remediation steps (e.g., suggest `git fetch --all --prune` when base missing remotely).
62
+ - Log to stderr for warnings/errors; stdout reserved for primary output payloads.
63
+ - Exit codes: 0 success, 2 validation error, 3 precondition failure, 4 conflict, 5 unsafe state, 6 not found.
64
+
65
+ ## Decisions Summary
66
+ - Language: Bash + Git CLI; Tests planned with `bats` during implementation.
67
+ - Root: `$HOME/.worktrees` with `--root` and `WORKTREES_ROOT` override.
68
+ - Naming: `^[0-9]{3}-[a-z0-9-]{1,40}$`, case-insensitive unique; reserved names disallowed.
69
+ - Defaults: Base auto-detected from remote HEAD; explicit override supported.
70
+ - Safety: Conservative removal policy; explicit flags for dangerous ops.
71
+ - Scale: Paging and filtering supported in list.
72
+ - Tags: Never auto-deleted.
73
+
74
+ All NEEDS CLARIFICATION items are resolved above.
75
+
76
+
@@ -0,0 +1,153 @@
1
+ # Feature Specification: Manage Git feature worktrees
2
+
3
+ **Feature Branch**: `[001-build-a-tool]`
4
+ **Created**: 2025-09-15
5
+ **Status**: Draft
6
+ **Input**: User description: "Build a tool to manage Git worktrees for feature-based development: enable quick creation of feature-specific worktrees from a chosen base, list and switch between worktrees, enforce clear naming to avoid collisions, and support safe cleanup of completed worktrees. Focus narrowly on worktree lifecycle and navigation."
7
+
8
+ ## Execution Flow (main)
9
+ ```
10
+ 1. Parse user description from Input
11
+ → If empty: ERROR "No feature description provided"
12
+ 2. Extract key concepts from description
13
+ → Identify: actors, actions, data, constraints
14
+ 3. For each unclear aspect:
15
+ → Mark with [NEEDS CLARIFICATION: specific question]
16
+ 4. Fill User Scenarios & Testing section
17
+ → If no clear user flow: ERROR "Cannot determine user scenarios"
18
+ 5. Generate Functional Requirements
19
+ → Each requirement must be testable
20
+ → Mark ambiguous requirements
21
+ 6. Identify Key Entities (if data involved)
22
+ 7. Run Review Checklist
23
+ → If any [NEEDS CLARIFICATION]: WARN "Spec has uncertainties"
24
+ → If implementation details found: ERROR "Remove tech details"
25
+ 8. Return: SUCCESS (spec ready for planning)
26
+ ```
27
+
28
+ ---
29
+
30
+ ## ⚡ Quick Guidelines
31
+ - ✅ Focus on WHAT users need and WHY
32
+ - ❌ Avoid HOW to implement (no tech stack, APIs, code structure)
33
+ - 👥 Written for business stakeholders, not developers
34
+
35
+ ### Section Requirements
36
+ - **Mandatory sections**: Must be completed for every feature
37
+ - **Optional sections**: Include only when relevant to the feature
38
+ - When a section doesn't apply, remove it entirely (don't leave as "N/A")
39
+
40
+ ### For AI Generation
41
+ When creating this spec from a user prompt:
42
+ 1. **Mark all ambiguities**: Use [NEEDS CLARIFICATION: specific question] for any assumption you'd need to make
43
+ 2. **Don't guess**: If the prompt doesn't specify something (e.g., "login system" without auth method), mark it
44
+ 3. **Think like a tester**: Every vague requirement should fail the "testable and unambiguous" checklist item
45
+ 4. **Common underspecified areas**:
46
+ - User types and permissions
47
+ - Data retention/deletion policies
48
+ - Performance targets and scale
49
+ - Error handling behaviors
50
+ - Integration requirements
51
+ - Security/compliance needs
52
+
53
+ ---
54
+
55
+ ## User Scenarios & Testing *(mandatory)*
56
+
57
+ ### Primary User Story
58
+ As a developer working across multiple features, I want to create isolated Git worktrees per feature, list and switch between them, and safely clean them up when finished so that I can work in parallel without polluting my main repository workspace.
59
+
60
+ ### Acceptance Scenarios
61
+ 1. **Given** no existing worktree for a requested feature, **When** a developer requests creation from a specified base, **Then** a uniquely named feature worktree is created and made active.
62
+ 2. **Given** multiple worktrees exist, **When** a developer requests a list of worktrees, **Then** the system returns each worktree's name, source/base reference, and whether it is currently active.
63
+ 3. **Given** a feature worktree exists, **When** a developer switches to it, **Then** the active working copy becomes that worktree without modifying other worktrees.
64
+ 4. **Given** a finished worktree, **When** a developer requests safe cleanup, **Then** the worktree is removed without unintended data loss, the branch is kept by default, and branch deletion is allowed only with explicit opt-in and only if fully merged into a specified base.
65
+ 5. **Given** a worktree has uncommitted changes, **When** a developer switches away to another worktree, **Then** switching proceeds and a clear warning summarizes the dirty state.
66
+ 6. **Given** a worktree has uncommitted changes or untracked/ignored files, **When** a developer requests removal, **Then** removal is blocked by default; explicit force is allowed only for untracked/ignored files; removal is never allowed if there are unpushed commits or an operation (e.g., rebase/merge/cherry-pick) in progress.
67
+
68
+ ### Edge Cases
69
+ - Base reference does not exist or is unreachable.
70
+ - Duplicate or invalid feature name: prevent collisions and guide the user to choose a different name.
71
+ - Existing branch without a corresponding worktree: on create, reuse the existing branch for the new worktree; no new branch is required.
72
+ - Attempt to remove the currently active worktree: disallow and guide the user.
73
+ - Worktree directory manually moved or deleted outside the tool: detect and reconcile or offer cleanup.
74
+ - Large repositories with many worktrees: provide filtering or paging for listing. [NEEDS CLARIFICATION: expected scale and limits]
75
+ - Base reference exists only on remote and is not fetched locally: auto-fetch the base; on fetch failure, abort with clear guidance.
76
+ - Branch already checked out in another worktree: disallow duplicate checkout; offer selecting the existing worktree or creating a sibling branch via explicit opt-in.
77
+ - Pre-existing local branch name conflicts with requested feature name (different base): decide whether to reuse or error. [NEEDS CLARIFICATION]
78
+ - Target worktree path already exists or is non-empty: prevent creation and guide to a new path/name.
79
+ - Worktree path contains spaces or special characters: ensure operations handle quoting safely.
80
+ - Case-insensitive filesystem collisions (e.g., macOS): treat names differing only by case as duplicates.
81
+ - Dirty worktree handling: switching away is allowed with a warning; removal is blocked if tracked changes are present and blocked by default for untracked/ignored files unless explicitly forced; removal is never allowed if there are unpushed commits/no upstream or an operation in progress.
82
+ - Command executed outside a Git repository or inside a nested repository: detect repository root and prevent misuse with clear messaging.
83
+ - Stale worktree metadata after manual filesystem changes: offer pruning or repair.
84
+ - Environment lacks required Git features/version for worktrees: detect and inform with remediation steps.
85
+
86
+ ## Requirements *(mandatory)*
87
+
88
+ ### Functional Requirements
89
+ - **FR-001**: The system MUST allow developers to create isolated feature worktrees from a specified base reference.
90
+ - **FR-002**: The system MUST list existing worktrees for the current repository with name, base reference, and active status.
91
+ - **FR-003**: The system MUST switch the active working copy to a selected worktree on request.
92
+ - **FR-004**: The system MUST safely remove a finished worktree without unintended data loss; keep the branch by default, and allow branch deletion only with explicit opt-in and only if fully merged into a specified base.
93
+ - **FR-005**: The system MUST enforce this naming convention and uniqueness:
94
+ - Format: NNN-kebab-feature
95
+ - Charset: lowercase [a-z0-9-]
96
+ - Length: feature segment ≤ 40 characters
97
+ - Uniqueness: case-insensitive unique across existing worktrees
98
+ - Reserved names disallowed: 'main', 'master'
99
+ - **FR-006**: The system MUST validate preconditions (e.g., base reference existence, clean state) and provide actionable feedback, including auto-fetching a remote-only base before creation and aborting with clear guidance on failure.
100
+ - **FR-007**: The system MUST present clear status of the current worktree (name, base reference, path).
101
+ - **FR-008**: The system MUST select a default base when none is provided: use the repository's default branch (remote HEAD) when available; else use 'main' if it exists; else use 'master'. The chosen base MUST be displayed and always overrideable via flag/config.
102
+ - **FR-009**: The system MUST handle invalid or conflicting operations with informative messages (e.g., cannot remove active worktree).
103
+ - **FR-010**: The system MUST default to a global hidden worktrees root under the user's workspace (kept separate from primary repositories) and MUST allow override via flag and config. The chosen location MUST be displayed.
104
+ - **FR-011**: The system MUST enforce conservative dirty-state policies: allow switching between worktrees even if the current worktree is dirty (with a visible warning); block removal if tracked changes are present or an operation is in progress; block removal if the branch has unpushed commits or no upstream; allow explicit force solely to delete untracked/ignored files.
105
+ - **FR-012**: The system SHOULD provide responsive UX for common operations (create, list, switch); specific performance targets are deferred until post-MVP metrics are collected.
106
+ - **FR-013**: When a requested branch is already checked out in another worktree, the system MUST disallow duplicate checkout and offer either selecting the existing worktree or creating a sibling branch via explicit opt-in.
107
+ - **FR-014**: When creating a worktree and a local branch with the requested name exists and is not checked out in any worktree, the system MUST reuse that branch rather than creating a new branch.
108
+ - **FR-015**: For v1, the system MUST expose a command-line interface. Non-CLI interfaces are out of scope.
109
+ - **FR-016**: For v1, the system MUST operate only on the current Git repository; cross-repository scanning or actions are out of scope.
110
+
111
+ *Ambiguities to resolve:*
112
+ - Cleanup semantics are [NEEDS CLARIFICATION: whether to delete associated tags]
113
+
114
+ ### Key Entities *(include if feature involves data)*
115
+ - **Feature Worktree**: An isolated working copy tied to a specific feature branch; created from a base reference.
116
+ - **Base Reference**: The source branch or commit from which a feature worktree is created.
117
+ - **Feature Name**: The human-readable label used to name and identify a worktree.
118
+ - **Repository**: The Git project within which feature worktrees are managed.
119
+
120
+ ---
121
+
122
+ ## Review & Acceptance Checklist
123
+ *GATE: Automated checks run during main() execution*
124
+
125
+ ### Content Quality
126
+ - [ ] No implementation details (languages, frameworks, APIs)
127
+ - [ ] Focused on user value and business needs
128
+ - [ ] Written for non-technical stakeholders
129
+ - [ ] All mandatory sections completed
130
+
131
+ ### Requirement Completeness
132
+ - [ ] No [NEEDS CLARIFICATION] markers remain
133
+ - [ ] Requirements are testable and unambiguous
134
+ - [ ] Success criteria are measurable
135
+ - [ ] Scope is clearly bounded
136
+ - [ ] Dependencies and assumptions identified
137
+
138
+ ---
139
+
140
+ ## Execution Status
141
+ *Updated by main() during processing*
142
+
143
+ - [ ] User description parsed
144
+ - [ ] Key concepts extracted
145
+ - [ ] Ambiguities marked
146
+ - [ ] User scenarios defined
147
+ - [ ] Requirements generated
148
+ - [ ] Entities identified
149
+ - [ ] Review checklist passed
150
+
151
+ ---
152
+
153
+