pi-gauntlet 4.0.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 (46) hide show
  1. package/CHANGELOG.md +300 -0
  2. package/LICENSE +24 -0
  3. package/README.md +278 -0
  4. package/agents/code-reviewer.md +48 -0
  5. package/agents/conformance-reviewer.md +139 -0
  6. package/agents/implementer.md +40 -0
  7. package/agents/spec-council-member.md +47 -0
  8. package/agents/spec-council-synthesizer.md +39 -0
  9. package/agents/spec-reviewer.md +47 -0
  10. package/agents/spec-summarizer.md +42 -0
  11. package/bin/install-agents.mjs +141 -0
  12. package/extensions/phase-tracker.ts +622 -0
  13. package/extensions/plan-tracker.ts +308 -0
  14. package/extensions/verify-before-ship.ts +132 -0
  15. package/package.json +43 -0
  16. package/skills/brainstorming/SKILL.md +290 -0
  17. package/skills/dispatching-parallel-agents/SKILL.md +192 -0
  18. package/skills/finishing-a-development-branch/SKILL.md +311 -0
  19. package/skills/receiving-code-review/SKILL.md +200 -0
  20. package/skills/requesting-code-review/SKILL.md +115 -0
  21. package/skills/requesting-code-review/code-reviewer.md +166 -0
  22. package/skills/roasting-the-spec/SKILL.md +139 -0
  23. package/skills/subagent-driven-development/SKILL.md +223 -0
  24. package/skills/subagent-driven-development/code-quality-reviewer-prompt.md +25 -0
  25. package/skills/subagent-driven-development/implementer-prompt.md +113 -0
  26. package/skills/subagent-driven-development/spec-reviewer-prompt.md +68 -0
  27. package/skills/systematic-debugging/SKILL.md +151 -0
  28. package/skills/systematic-debugging/condition-based-waiting-example.ts +158 -0
  29. package/skills/systematic-debugging/condition-based-waiting.md +115 -0
  30. package/skills/systematic-debugging/defense-in-depth.md +122 -0
  31. package/skills/systematic-debugging/find-polluter.sh +63 -0
  32. package/skills/systematic-debugging/reference/rationalizations.md +61 -0
  33. package/skills/systematic-debugging/root-cause-tracing.md +169 -0
  34. package/skills/test-driven-development/SKILL.md +230 -0
  35. package/skills/test-driven-development/reference/examples.md +99 -0
  36. package/skills/test-driven-development/reference/rationalizations.md +65 -0
  37. package/skills/test-driven-development/reference/when-stuck.md +31 -0
  38. package/skills/test-driven-development/testing-anti-patterns.md +299 -0
  39. package/skills/using-git-worktrees/SKILL.md +193 -0
  40. package/skills/verification-before-completion/SKILL.md +169 -0
  41. package/skills/verification-before-completion/reference/conformance-check.md +220 -0
  42. package/skills/writing-plans/SKILL.md +244 -0
  43. package/skills/writing-skills/SKILL.md +429 -0
  44. package/skills/writing-skills/reference/anthropic-best-practices.md +1130 -0
  45. package/skills/writing-skills/reference/persuasion.md +187 -0
  46. package/skills/writing-skills/reference/testing-skills-with-subagents.md +384 -0
@@ -0,0 +1,99 @@
1
+ # TDD Examples Reference
2
+
3
+ ## Good vs Bad Tests
4
+
5
+ ### RED — Write Failing Test
6
+
7
+ <Good>
8
+ ```typescript
9
+ test('retries failed operations 3 times', async () => {
10
+ let attempts = 0;
11
+ const operation = () => {
12
+ attempts++;
13
+ if (attempts < 3) throw new Error('fail');
14
+ return 'success';
15
+ };
16
+ const result = await retryOperation(operation);
17
+ expect(result).toBe('success');
18
+ expect(attempts).toBe(3);
19
+ });
20
+ ```
21
+ Clear name, tests real behavior, one thing
22
+ </Good>
23
+
24
+ <Bad>
25
+ ```typescript
26
+ test('retry works', async () => {
27
+ const mock = jest.fn()
28
+ .mockRejectedValueOnce(new Error())
29
+ .mockRejectedValueOnce(new Error())
30
+ .mockResolvedValueOnce('success');
31
+ await retryOperation(mock);
32
+ expect(mock).toHaveBeenCalledTimes(3);
33
+ });
34
+ ```
35
+ Vague name, tests mock not code
36
+ </Bad>
37
+
38
+ ### GREEN — Minimal Code
39
+
40
+ <Good>
41
+ ```typescript
42
+ async function retryOperation<T>(fn: () => Promise<T>): Promise<T> {
43
+ for (let i = 0; i < 3; i++) {
44
+ try { return await fn(); }
45
+ catch (e) { if (i === 2) throw e; }
46
+ }
47
+ throw new Error('unreachable');
48
+ }
49
+ ```
50
+ Just enough to pass
51
+ </Good>
52
+
53
+ <Bad>
54
+ ```typescript
55
+ async function retryOperation<T>(
56
+ fn: () => Promise<T>,
57
+ options?: { maxRetries?: number; backoff?: 'linear' | 'exponential'; onRetry?: (attempt: number) => void }
58
+ ): Promise<T> { /* YAGNI */ }
59
+ ```
60
+ Over-engineered
61
+ </Bad>
62
+
63
+ ## Good Tests Table
64
+
65
+ | Quality | Good | Bad |
66
+ |---------|------|-----|
67
+ | **Minimal** | One thing. "and" in name? Split it. | `test('validates email and domain and whitespace')` |
68
+ | **Clear** | Name describes behavior | `test('test1')` |
69
+ | **Shows intent** | Demonstrates desired API | Obscures what code should do |
70
+
71
+ ## Bug Fix Example
72
+
73
+ **Bug:** Empty email accepted
74
+
75
+ **RED**
76
+ ```typescript
77
+ test('rejects empty email', async () => {
78
+ const result = await submitForm({ email: '' });
79
+ expect(result.error).toBe('Email required');
80
+ });
81
+ ```
82
+
83
+ **Verify RED**
84
+ ```bash
85
+ $ npm test
86
+ FAIL: expected 'Email required', got undefined
87
+ ```
88
+
89
+ **GREEN**
90
+ ```typescript
91
+ function submitForm(data: FormData) {
92
+ if (!data.email?.trim()) return { error: 'Email required' };
93
+ // ...
94
+ }
95
+ ```
96
+
97
+ **Verify GREEN** → PASS
98
+
99
+ **REFACTOR** — Extract validation for multiple fields if needed.
@@ -0,0 +1,65 @@
1
+ # TDD Rationalizations Reference
2
+
3
+ ## Why Order Matters
4
+
5
+ **"I'll write tests after to verify it works"**
6
+ Tests written after code pass immediately. Passing immediately proves nothing:
7
+ - Might test wrong thing
8
+ - Might test implementation, not behavior
9
+ - Might miss edge cases you forgot
10
+ - You never saw it catch the bug
11
+
12
+ Test-first forces you to see the test fail, proving it actually tests something.
13
+
14
+ **"I already manually tested all the edge cases"**
15
+ Manual testing is ad-hoc. You think you tested everything but:
16
+ - No record of what you tested
17
+ - Can't re-run when code changes
18
+ - Easy to forget cases under pressure
19
+ - "It worked when I tried it" ≠ comprehensive
20
+
21
+ **"Deleting X hours of work is wasteful"**
22
+ Sunk cost fallacy. The time is already gone. Your choice:
23
+ - Delete and rewrite with TDD (X more hours, high confidence)
24
+ - Keep it and add tests after (30 min, low confidence, likely bugs)
25
+
26
+ **"TDD is dogmatic, being pragmatic means adapting"**
27
+ TDD IS pragmatic. "Pragmatic" shortcuts = debugging in production = slower.
28
+
29
+ **"Tests after achieve the same goals - it's spirit not ritual"**
30
+ Tests-after answer "What does this do?" Tests-first answer "What should this do?"
31
+ Tests-after are biased by your implementation. 30 minutes of tests after ≠ TDD.
32
+
33
+ ## Common Rationalizations Table
34
+
35
+ | Excuse | Reality |
36
+ |--------|---------|
37
+ | "Too simple to test" | Simple code breaks. Test takes 30 seconds. |
38
+ | "I'll test after" | Tests passing immediately prove nothing. |
39
+ | "Tests after achieve same goals" | Tests-after = "what does this do?" Tests-first = "what should this do?" |
40
+ | "Already manually tested" | Ad-hoc ≠ systematic. No record, can't re-run. |
41
+ | "Deleting X hours is wasteful" | Sunk cost fallacy. Keeping unverified code is technical debt. |
42
+ | "Keep as reference, write tests first" | You'll adapt it. That's testing after. Delete means delete. |
43
+ | "Need to explore first" | Fine. Throw away exploration, start with TDD. |
44
+ | "Test hard = design unclear" | Listen to test. Hard to test = hard to use. |
45
+ | "TDD will slow me down" | TDD faster than debugging. Pragmatic = test-first. |
46
+ | "Manual test faster" | Manual doesn't prove edge cases. You'll re-test every change. |
47
+ | "Existing code has no tests" | You're improving it. Add tests for existing code. |
48
+
49
+ ## Red Flags — STOP and Start Over
50
+
51
+ - Code before test
52
+ - Test after implementation
53
+ - Test passes immediately
54
+ - Can't explain why test failed
55
+ - Tests added "later"
56
+ - Rationalizing "just this once"
57
+ - "I already manually tested it"
58
+ - "Tests after achieve the same purpose"
59
+ - "It's about spirit not ritual"
60
+ - "Keep as reference" or "adapt existing code"
61
+ - "Already spent X hours, deleting is wasteful"
62
+ - "TDD is dogmatic, I'm being pragmatic"
63
+ - "This is different because..."
64
+
65
+ **All of these mean: Delete code. Start over with TDD.**
@@ -0,0 +1,31 @@
1
+ # TDD When Stuck Reference
2
+
3
+ ## When Stuck
4
+
5
+ | Problem | Solution |
6
+ |---------|----------|
7
+ | Don't know how to test | Write wished-for API. Write assertion first. Ask your human partner. |
8
+ | Test too complicated | Design too complicated. Simplify interface. |
9
+ | Must mock everything | Code too coupled. Use dependency injection. |
10
+ | Test setup huge | Extract helpers. Still complex? Simplify design. |
11
+
12
+ ## Verification Checklist
13
+
14
+ Before marking work complete:
15
+
16
+ - [ ] Every new function/method has a test
17
+ - [ ] Watched each test fail before implementing
18
+ - [ ] Each test failed for expected reason (feature missing, not typo)
19
+ - [ ] Wrote minimal code to pass each test
20
+ - [ ] All tests pass
21
+ - [ ] Output pristine (no errors, warnings)
22
+ - [ ] Tests use real code (mocks only if unavoidable)
23
+ - [ ] Edge cases and errors covered
24
+
25
+ Can't check all boxes? You skipped TDD. Start over.
26
+
27
+ ## Debugging Integration
28
+
29
+ Bug found? Write failing test reproducing it. Follow TDD cycle. Test proves fix and prevents regression.
30
+
31
+ Never fix bugs without a test.
@@ -0,0 +1,299 @@
1
+ # Testing Anti-Patterns
2
+
3
+ **Load this reference when:** writing or changing tests, adding mocks, or tempted to add test-only methods to production code.
4
+
5
+ ## Overview
6
+
7
+ Tests must verify real behavior, not mock behavior. Mocks are a means to isolate, not the thing being tested.
8
+
9
+ **Core principle:** Test what the code does, not what the mocks do.
10
+
11
+ **Following strict TDD prevents these anti-patterns.**
12
+
13
+ ## The Iron Laws
14
+
15
+ ```
16
+ 1. NEVER test mock behavior
17
+ 2. NEVER add test-only methods to production classes
18
+ 3. NEVER mock without understanding dependencies
19
+ ```
20
+
21
+ ## Anti-Pattern 1: Testing Mock Behavior
22
+
23
+ **The violation:**
24
+ ```typescript
25
+ // ❌ BAD: Testing that the mock exists
26
+ test('renders sidebar', () => {
27
+ render(<Page />);
28
+ expect(screen.getByTestId('sidebar-mock')).toBeInTheDocument();
29
+ });
30
+ ```
31
+
32
+ **Why this is wrong:**
33
+ - You're verifying the mock works, not that the component works
34
+ - Test passes when mock is present, fails when it's not
35
+ - Tells you nothing about real behavior
36
+
37
+ **your human partner's correction:** "Are we testing the behavior of a mock?"
38
+
39
+ **The fix:**
40
+ ```typescript
41
+ // ✅ GOOD: Test real component or don't mock it
42
+ test('renders sidebar', () => {
43
+ render(<Page />); // Don't mock sidebar
44
+ expect(screen.getByRole('navigation')).toBeInTheDocument();
45
+ });
46
+
47
+ // OR if sidebar must be mocked for isolation:
48
+ // Don't assert on the mock - test Page's behavior with sidebar present
49
+ ```
50
+
51
+ ### Gate Function
52
+
53
+ ```
54
+ BEFORE asserting on any mock element:
55
+ Ask: "Am I testing real component behavior or just mock existence?"
56
+
57
+ IF testing mock existence:
58
+ STOP - Delete the assertion or unmock the component
59
+
60
+ Test real behavior instead
61
+ ```
62
+
63
+ ## Anti-Pattern 2: Test-Only Methods in Production
64
+
65
+ **The violation:**
66
+ ```typescript
67
+ // ❌ BAD: destroy() only used in tests
68
+ class Session {
69
+ async destroy() { // Looks like production API!
70
+ await this._workspaceManager?.destroyWorkspace(this.id);
71
+ // ... cleanup
72
+ }
73
+ }
74
+
75
+ // In tests
76
+ afterEach(() => session.destroy());
77
+ ```
78
+
79
+ **Why this is wrong:**
80
+ - Production class polluted with test-only code
81
+ - Dangerous if accidentally called in production
82
+ - Violates YAGNI and separation of concerns
83
+ - Confuses object lifecycle with entity lifecycle
84
+
85
+ **The fix:**
86
+ ```typescript
87
+ // ✅ GOOD: Test utilities handle test cleanup
88
+ // Session has no destroy() - it's stateless in production
89
+
90
+ // In test-utils/
91
+ export async function cleanupSession(session: Session) {
92
+ const workspace = session.getWorkspaceInfo();
93
+ if (workspace) {
94
+ await workspaceManager.destroyWorkspace(workspace.id);
95
+ }
96
+ }
97
+
98
+ // In tests
99
+ afterEach(() => cleanupSession(session));
100
+ ```
101
+
102
+ ### Gate Function
103
+
104
+ ```
105
+ BEFORE adding any method to production class:
106
+ Ask: "Is this only used by tests?"
107
+
108
+ IF yes:
109
+ STOP - Don't add it
110
+ Put it in test utilities instead
111
+
112
+ Ask: "Does this class own this resource's lifecycle?"
113
+
114
+ IF no:
115
+ STOP - Wrong class for this method
116
+ ```
117
+
118
+ ## Anti-Pattern 3: Mocking Without Understanding
119
+
120
+ **The violation:**
121
+ ```typescript
122
+ // ❌ BAD: Mock breaks test logic
123
+ test('detects duplicate server', () => {
124
+ // Mock prevents config write that test depends on!
125
+ vi.mock('ToolCatalog', () => ({
126
+ discoverAndCacheTools: vi.fn().mockResolvedValue(undefined)
127
+ }));
128
+
129
+ await addServer(config);
130
+ await addServer(config); // Should throw - but won't!
131
+ });
132
+ ```
133
+
134
+ **Why this is wrong:**
135
+ - Mocked method had side effect test depended on (writing config)
136
+ - Over-mocking to "be safe" breaks actual behavior
137
+ - Test passes for wrong reason or fails mysteriously
138
+
139
+ **The fix:**
140
+ ```typescript
141
+ // ✅ GOOD: Mock at correct level
142
+ test('detects duplicate server', () => {
143
+ // Mock the slow part, preserve behavior test needs
144
+ vi.mock('MCPServerManager'); // Just mock slow server startup
145
+
146
+ await addServer(config); // Config written
147
+ await addServer(config); // Duplicate detected ✓
148
+ });
149
+ ```
150
+
151
+ ### Gate Function
152
+
153
+ ```
154
+ BEFORE mocking any method:
155
+ STOP - Don't mock yet
156
+
157
+ 1. Ask: "What side effects does the real method have?"
158
+ 2. Ask: "Does this test depend on any of those side effects?"
159
+ 3. Ask: "Do I fully understand what this test needs?"
160
+
161
+ IF depends on side effects:
162
+ Mock at lower level (the actual slow/external operation)
163
+ OR use test doubles that preserve necessary behavior
164
+ NOT the high-level method the test depends on
165
+
166
+ IF unsure what test depends on:
167
+ Run test with real implementation FIRST
168
+ Observe what actually needs to happen
169
+ THEN add minimal mocking at the right level
170
+
171
+ Red flags:
172
+ - "I'll mock this to be safe"
173
+ - "This might be slow, better mock it"
174
+ - Mocking without understanding the dependency chain
175
+ ```
176
+
177
+ ## Anti-Pattern 4: Incomplete Mocks
178
+
179
+ **The violation:**
180
+ ```typescript
181
+ // ❌ BAD: Partial mock - only fields you think you need
182
+ const mockResponse = {
183
+ status: 'success',
184
+ data: { userId: '123', name: 'Alice' }
185
+ // Missing: metadata that downstream code uses
186
+ };
187
+
188
+ // Later: breaks when code accesses response.metadata.requestId
189
+ ```
190
+
191
+ **Why this is wrong:**
192
+ - **Partial mocks hide structural assumptions** - You only mocked fields you know about
193
+ - **Downstream code may depend on fields you didn't include** - Silent failures
194
+ - **Tests pass but integration fails** - Mock incomplete, real API complete
195
+ - **False confidence** - Test proves nothing about real behavior
196
+
197
+ **The Iron Rule:** Mock the COMPLETE data structure as it exists in reality, not just fields your immediate test uses.
198
+
199
+ **The fix:**
200
+ ```typescript
201
+ // ✅ GOOD: Mirror real API completeness
202
+ const mockResponse = {
203
+ status: 'success',
204
+ data: { userId: '123', name: 'Alice' },
205
+ metadata: { requestId: 'req-789', timestamp: 1234567890 }
206
+ // All fields real API returns
207
+ };
208
+ ```
209
+
210
+ ### Gate Function
211
+
212
+ ```
213
+ BEFORE creating mock responses:
214
+ Check: "What fields does the real API response contain?"
215
+
216
+ Actions:
217
+ 1. Examine actual API response from docs/examples
218
+ 2. Include ALL fields system might consume downstream
219
+ 3. Verify mock matches real response schema completely
220
+
221
+ Critical:
222
+ If you're creating a mock, you must understand the ENTIRE structure
223
+ Partial mocks fail silently when code depends on omitted fields
224
+
225
+ If uncertain: Include all documented fields
226
+ ```
227
+
228
+ ## Anti-Pattern 5: Integration Tests as Afterthought
229
+
230
+ **The violation:**
231
+ ```
232
+ ✅ Implementation complete
233
+ ❌ No tests written
234
+ "Ready for testing"
235
+ ```
236
+
237
+ **Why this is wrong:**
238
+ - Testing is part of implementation, not optional follow-up
239
+ - TDD would have caught this
240
+ - Can't claim complete without tests
241
+
242
+ **The fix:**
243
+ ```
244
+ TDD cycle:
245
+ 1. Write failing test
246
+ 2. Implement to pass
247
+ 3. Refactor
248
+ 4. THEN claim complete
249
+ ```
250
+
251
+ ## When Mocks Become Too Complex
252
+
253
+ **Warning signs:**
254
+ - Mock setup longer than test logic
255
+ - Mocking everything to make test pass
256
+ - Mocks missing methods real components have
257
+ - Test breaks when mock changes
258
+
259
+ **your human partner's question:** "Do we need to be using a mock here?"
260
+
261
+ **Consider:** Integration tests with real components often simpler than complex mocks
262
+
263
+ ## TDD Prevents These Anti-Patterns
264
+
265
+ **Why TDD helps:**
266
+ 1. **Write test first** → Forces you to think about what you're actually testing
267
+ 2. **Watch it fail** → Confirms test tests real behavior, not mocks
268
+ 3. **Minimal implementation** → No test-only methods creep in
269
+ 4. **Real dependencies** → You see what the test actually needs before mocking
270
+
271
+ **If you're testing mock behavior, you violated TDD** - you added mocks without watching test fail against real code first.
272
+
273
+ ## Quick Reference
274
+
275
+ | Anti-Pattern | Fix |
276
+ |--------------|-----|
277
+ | Assert on mock elements | Test real component or unmock it |
278
+ | Test-only methods in production | Move to test utilities |
279
+ | Mock without understanding | Understand dependencies first, mock minimally |
280
+ | Incomplete mocks | Mirror real API completely |
281
+ | Tests as afterthought | TDD - tests first |
282
+ | Over-complex mocks | Consider integration tests |
283
+
284
+ ## Red Flags
285
+
286
+ - Assertion checks for `*-mock` test IDs
287
+ - Methods only called in test files
288
+ - Mock setup is >50% of test
289
+ - Test fails when you remove mock
290
+ - Can't explain why mock is needed
291
+ - Mocking "just to be safe"
292
+
293
+ ## The Bottom Line
294
+
295
+ **Mocks are tools to isolate, not things to test.**
296
+
297
+ If TDD reveals you're testing mock behavior, you've gone wrong.
298
+
299
+ Fix: Test real behavior or question why you're mocking at all.
@@ -0,0 +1,193 @@
1
+ ---
2
+ name: using-git-worktrees
3
+ description: Use when starting feature work that needs isolation from current workspace or before executing implementation plans - creates isolated git worktrees with smart directory selection and safety verification
4
+ ---
5
+
6
+ > **Related skills:** Set up **before** `/skill:brainstorming` — the spec is the worktree's first commit, not a separate one on `main`. Execute with `/skill:subagent-driven-development`. Clean up with `/skill:finishing-a-development-branch`.
7
+
8
+ # Using Git Worktrees
9
+
10
+ ## Overview
11
+
12
+ Git worktrees create isolated workspaces sharing the same repository, allowing work on multiple branches simultaneously without switching.
13
+
14
+ **Core principle:** Detect existing isolation first → prefer the project's native tool → default to `<repo>/.worktrees/<branch>`, creating it if missing.
15
+
16
+ **Announce at start:** "I'm using the using-git-worktrees skill to set up an isolated workspace."
17
+
18
+ ## Step 0 — Detect Existing Isolation (REQUIRED)
19
+
20
+ Before doing anything else, check whether you are **already** inside an isolated worktree. Creating a worktree inside another worktree, or inside a submodule, produces silent corruption.
21
+
22
+ ```bash
23
+ GIT_DIR=$(cd "$(git rev-parse --git-dir)" 2>/dev/null && pwd -P)
24
+ GIT_COMMON=$(cd "$(git rev-parse --git-common-dir)" 2>/dev/null && pwd -P)
25
+ BRANCH=$(git branch --show-current)
26
+ ```
27
+
28
+ **Submodule guard:** `GIT_DIR != GIT_COMMON` is also true inside git submodules. Before concluding "already in a worktree," verify you are not in a submodule:
29
+
30
+ ```bash
31
+ # If this returns a path, you're in a submodule, not a worktree — treat as normal repo
32
+ git rev-parse --show-superproject-working-tree 2>/dev/null
33
+ ```
34
+
35
+ **If `GIT_DIR != GIT_COMMON` (and not a submodule):** You are already in a linked worktree. Skip to Step 3 (Verify Clean Baseline). Do NOT create another worktree.
36
+
37
+ Report with branch state:
38
+ - On a branch: "Already in isolated workspace at `<path>` on branch `<name>`."
39
+ - Detached HEAD: "Already in isolated workspace at `<path>` (detached HEAD, externally managed)."
40
+
41
+ **If `GIT_DIR == GIT_COMMON` (or in a submodule):** You are in a normal repo checkout. Proceed to Step 1.
42
+
43
+ ## Step 1 — Announce, Don't Ask (skill-driven work defaults to a worktree)
44
+
45
+ For gauntlet-driven work — brainstorming, plans, implementation — the worktree is the default, not a question. Announce and proceed:
46
+
47
+ > "Setting up an isolated worktree at `<path>` on branch `<branch>` for this work."
48
+
49
+ Pause for explicit consent **only** when one of these holds:
50
+ - A trivial one-off the user named (typo, format run, dependency bump)
51
+ - The user already set up a workspace, or asked to work in place
52
+ - The sandbox can't support multiple checkouts (see Sandbox fallback)
53
+
54
+ Otherwise create it. The gate is "is this real work?", not "did the user approve this worktree?"
55
+
56
+ ## Step 1a — Prefer Native Worktree Tools
57
+
58
+ Do you already have a way to create a worktree? It might be a tool with a name like `EnterWorktree`, `WorktreeCreate`, a `/worktree` command, or a `--worktree` flag. If you do, use it and skip to Step 3.
59
+
60
+ Native tools handle directory placement, branch creation, and cleanup automatically. Using `git worktree add` when you have a native tool creates phantom state your harness can't see or manage.
61
+
62
+ **If your project ships a wrapper script instead of a native tool** (commonly `script/worktree`, `bin/worktree`, or similar — check `AGENTS.md`, the repo root, and `script/` / `bin/`), use the wrapper. A typical wrapper handles:
63
+ - Sibling-worktree placement under a project-conventional path
64
+ - Tool-trust setup (e.g. `mise trust`, `direnv allow`)
65
+ - Subproject dependency install (`bundle install`, `uv sync`, `npm install`)
66
+ - Isolated dev/test DB provisioning where the runtime needs it
67
+ - Branch naming conventions (e.g. `<user>/<name>`)
68
+
69
+ **Do not call `git worktree add` directly when a native tool or wrapper exists.** Only proceed to Step 2 if neither is available.
70
+
71
+ ## Step 2 — Fallback: Manual Worktree Creation
72
+
73
+ Only when no native tool exists:
74
+
75
+ ### 2a. Pick a location
76
+
77
+ The canonical home is `<repo>/.worktrees/<branch>`. Resolve in this order:
78
+
79
+ 1. **Project override** — a wrapper/script or a `.pi/gauntlet-overrides.md` worktree path (`grep -i worktree README.md AGENTS.md .pi/settings.json .pi/gauntlet-overrides.md`). Obey it.
80
+ 2. **Default** — `<repo>/.worktrees/<branch>`. Create the directory if missing (Step 2b).
81
+ 3. **No enclosing repo** — only when there's no repo to anchor `.worktrees/`, fall back to `~/.worktrees/<project>/<branch>`.
82
+
83
+ Don't ask local-vs-global and don't invent other paths — `.worktrees/` is the default.
84
+
85
+ ### 2b. Create — gitignore the home first
86
+
87
+ `.worktrees/` must be gitignored before a worktree lands inside it. Fold the check into creation:
88
+
89
+ ```bash
90
+ ROOT=$(git rev-parse --show-toplevel)
91
+ cd "$ROOT"
92
+ if ! git check-ignore -q .worktrees; then
93
+ echo ".worktrees/" >> .gitignore
94
+ git add .gitignore && git commit -m "Ignore .worktrees/"
95
+ fi
96
+ git worktree add ".worktrees/$BRANCH_NAME" -b "$BRANCH_NAME"
97
+ cd ".worktrees/$BRANCH_NAME"
98
+ ```
99
+
100
+ For the outside-a-repo `~/.worktrees/<project>/` fallback, no .gitignore check applies.
101
+
102
+ ### 2c. Run project setup
103
+
104
+ ```bash
105
+ if [ -f pnpm-lock.yaml ]; then pnpm install
106
+ elif [ -f yarn.lock ]; then yarn install
107
+ elif [ -f package.json ]; then npm install
108
+ fi
109
+ [ -f Cargo.toml ] && cargo build
110
+ [ -f pyproject.toml ] && uv sync
111
+ [ -f Gemfile ] && bundle install
112
+ [ -f go.mod ] && go mod download
113
+ ```
114
+
115
+ ### 2d. Sandbox fallback
116
+
117
+ If worktree creation fails on permissions (read-only filesystem, container sandbox without write to parent dirs): stop, announce the failure, and continue in the current directory on a feature branch.
118
+
119
+ ## Step 3 — Verify Clean Baseline
120
+
121
+ ```bash
122
+ # pick the project's test command — see AGENTS.md for the canonical entrypoint
123
+ make ci # cross-language convention
124
+ pnpm test # JS / TS (or npm test / yarn test)
125
+ uv run pytest # Python
126
+ bundle exec rspec # Ruby
127
+ cargo test # Rust
128
+ go test ./... # Go
129
+ ```
130
+
131
+ - Tests pass → report ready.
132
+ - Tests fail → report failures, ask whether to proceed or investigate. Don't assume pre-existing breakage is fine.
133
+
134
+ ## Step 4 — Report Location
135
+
136
+ ```
137
+ Worktree ready at <full-path>
138
+ Branch: <branch-name>
139
+ Baseline: <test-result>
140
+ Ready to implement <feature>
141
+ ```
142
+
143
+ ## Detached HEAD
144
+
145
+ If `git symbolic-ref -q HEAD` returns nothing, you're on a detached HEAD. Do not create a worktree from this state — first ask the user whether to branch from the current commit or from `main`.
146
+
147
+ ## Keeping a Worktree Current
148
+
149
+ For longer-running work the base branch advances:
150
+
151
+ ```bash
152
+ git fetch origin
153
+ git rebase origin/main # or merge if branch is shared
154
+ ```
155
+
156
+ Re-run tests after rebasing.
157
+
158
+ ## Quick Reference
159
+
160
+ | Situation | Action |
161
+ |---|---|
162
+ | `GIT_DIR != GIT_COMMON` | Already in worktree — do NOT create another |
163
+ | `git rev-parse --show-superproject-working-tree` returns a path | Submodule — treat as normal repo |
164
+ | Project-native wrapper exists | Use the wrapper (commonly `script/worktree create`) |
165
+ | No native tool | Create `<repo>/.worktrees/<branch>` (gitignore `.worktrees/` first) |
166
+ | No enclosing repo | Fall back to `~/.worktrees/<project>/<branch>` |
167
+ | Detached HEAD | Ask before branching |
168
+ | Sandbox/permission failure | Work in place on a feature branch |
169
+ | Tests fail at baseline | Report + ask |
170
+
171
+ ## Red Flags — STOP
172
+
173
+ - About to run `git worktree add` from inside a worktree (`GIT_DIR != GIT_COMMON`)
174
+ - About to call `git worktree add` directly when the project ships a wrapper (use the wrapper)
175
+ - Created a `.worktrees/` worktree without gitignoring `.worktrees/` first
176
+ - Placed a worktree outside `.worktrees/` (or the project's configured path) for no reason
177
+ - Tests fail at baseline and you proceed anyway
178
+
179
+ ## Integration
180
+
181
+ **Called by:**
182
+ - `/skill:brainstorming` — **before** writing the spec; the spec is the worktree's first commit
183
+ - `/skill:subagent-driven-development` — required before any implementation tasks
184
+ - Any skill needing isolated workspace
185
+
186
+ **Pairs with:**
187
+ - `/skill:finishing-a-development-branch` — REQUIRED for cleanup. Default finish squashes the worktree's full history into a single commit on `main`. If the worktree was created by a project-native wrapper, cleanup defers to the wrapper's destroy command.
188
+
189
+ **Note:** Trivial one-off edits the user explicitly asks for (e.g. "fix this typo") do not require a worktree. Everything else — specs, plans, implementation — belongs in a worktree from the first artifact onward.
190
+
191
+ ## Project overrides
192
+
193
+ If `.pi/gauntlet-overrides.md` exists, read it. Any sections relevant to this skill — by name match, by topic (routing, verification, worktrees, etc.), or by workflow convention — override or extend the instructions above. Project-local `AGENTS.md` is already in context — check it for project-specific routing tables, service paths, and verification commands.