cascade-cli 0.1.152

Stacked diffs CLI for Bitbucket Server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
# Bitbucket Integration Guide

This guide covers Cascade CLI's integration with Bitbucket for pull request management and automated landing.

## Auto-Land Feature

The auto-land functionality allows you to automatically merge pull requests when they meet Bitbucket's server-side requirements, with intelligent polling and safety checks.

### Quick Start

```bash
# Simple auto-land all ready PRs
ca stacks autoland

# Auto-land with custom settings
ca stacks autoland --wait-for-builds --strategy merge

# Traditional syntax (equivalent to autoland)
ca stacks land --auto
```

### Command Variants

#### `ca stacks autoland` (Recommended)
**Shorthand for auto-landing** - automatically lands all ready PRs using Bitbucket's authoritative merge endpoint:

- βœ… **Server-side validation**: Uses Bitbucket's merge endpoint to check all requirements
- βœ… **Respects all rules**: Honors server-configured approval, build, and conflict requirements
- βœ… **Author filtering**: Optional allowlist for trusted authors only
- βœ… **Build waiting**: Waits for builds to complete before attempting merge

#### Traditional Flags

| Flag | Behavior | Use Case |
|------|----------|----------|
| `--auto` | Uses Bitbucket's authoritative merge endpoint | **All repositories** - respects server rules |
| `--wait-for-builds` | Only waits for builds, skips server merge validation | **Testing/development** - when you want to bypass some checks |

**For all Beta repositories**: Use `autoland` (default `--auto`) as it respects your Bitbucket server's actual merge requirements.

### Polling Behavior

When auto-landing with `--wait-for-builds`, the system polls every **30 seconds** to check build status:

```rust
// Poll every 30 seconds until builds complete or timeout
sleep(Duration::from_secs(30)).await;
```

**Default timeout**: 30 minutes (1800 seconds)

### Smart Merge Logic

Instead of duplicating Bitbucket's complex merge rules, Cascade asks Bitbucket directly:

1. **Query Bitbucket**: "Can this PR be merged right now?"
2. **Respect the answer**: Only attempt merge if Bitbucket says "yes"
3. **Display helpful status**: Show what's blocking merge (builds, approvals, conflicts)

This approach works with **any Bitbucket configuration**:
- Custom approval requirements (1, 2, 3+ approvals)
- Build requirements (any CI/CD system)
- Merge restrictions (branch permissions)
- Conflict detection

### Auto-Merge Conditions

```rust
// Simplified conditions - let Bitbucket do the validation
AutoMergeConditions {
    merge_strategy: MergeStrategy::Squash,  // How to merge
    wait_for_builds: true,                  // Wait for builds?
    build_timeout: Duration::from_secs(1800), // 30 min timeout
    allowed_authors: None,                  // Optional: restrict by author
}
```

#### Scenario 1: Development Team with Server Restrictions
Your Bitbucket server requires 2 approvals + 2 passing builds:

```bash
# Perfect - respects all server requirements automatically
ca stacks autoland
```

#### Scenario 2: Personal Repository
Minimal server restrictions, you only care about builds:

```bash
# Skip server validation, just wait for builds
ca stacks autoland --wait-for-builds
```

#### Scenario 3: Trusted Authors Only
Only auto-land PRs from specific team members:

```bash
# Configure in .cascade/config.json
{
  "auto_merge": {
    "allowed_authors": ["alice", "bob", "charlie"]
  }
}
```

### Usage Examples

#### Basic Stack Management
```bash
# πŸ“Š Check if your stack needs updates (read-only)
ca stacks check

# πŸ”„ Sync with remote changes (recommended daily workflow)
ca stacks sync

# πŸ”„ Force sync even if there are issues
ca stacks sync --force

# πŸ”„ Interactive sync for manual conflict resolution
ca stacks sync --interactive

# πŸ”„ Sync without cleaning up merged branches
ca stacks sync --skip-cleanup
```

#### Complete Development Workflow
```bash
# Morning routine: sync with latest changes
ca stacks sync

# Make changes and push to stack
ca stacks push --message "Add feature X"

# Submit for review
ca stacks submit

# Later: sync again to get latest changes
ca stacks sync

# Land completed PRs
ca stacks land
```

#### Simplified Landing Commands βœ…
```bash
# 🎯 Default: Land all ready PRs with safety checks (RECOMMENDED)
ca stacks land

# 🎯 Land specific entry by number (1-based) 
ca stacks land 2

# πŸ” Preview what would be landed
ca stacks land --dry-run

# ⚠️ Force land ignoring safety checks (dangerous)
ca stacks land --force

# πŸ”’ Use server-side validation (extra safety)
ca stacks land --auto

# πŸ• Wait for builds before landing
ca stacks land --wait-for-builds

# πŸš€ Shorthand for land --auto
ca stacks autoland
```

#### AutoLand Shorthand
```bash
# Equivalent to: ca stacks land --auto
ca stacks autoland
```

#### Advanced Options
```bash
# Use merge strategy instead of squash
ca stacks autoland --strategy merge

# Custom build timeout (20 minutes)
ca stacks autoland --build-timeout 1200

# Wait for builds but skip other validation
ca stacks autoland --wait-for-builds
```

#### Status and Monitoring
```bash
# Check stack status with merge readiness
ca stack --mergeable

# List all PRs with their status
ca stacks prs

# Get detailed status for debugging
ca stacks status
```

### Error Handling

Auto-land provides clear feedback when PRs can't be merged:

```
❌ PR #123: Cannot auto-merge
   - Build failed: CI/CD pipeline
   - Missing 1 approval from: [@reviewer1]
   - Conflicts in: src/main.rs

⏳ PR #124: Waiting for builds
   - CI/CD pipeline: In Progress (5 minutes remaining)
   - Ready to merge once builds pass

βœ… PR #125: Merged successfully
   - Strategy: squash
   - Commit: abc123 "Implement feature X"
```

### Troubleshooting

#### Auto-land not working?

1. **Check PR status**: `ca stack --mergeable`
2. **Verify Bitbucket rules**: Does the PR meet server requirements?
3. **Review build status**: Are builds passing?
4. **Check conflicts**: Are there merge conflicts?

#### Common issues:

- **"Not mergeable"**: Check approvals, builds, and conflicts in Bitbucket UI
- **Build timeout**: Increase timeout with `--build-timeout 3600`
- **Author restricted**: Ensure PR author is in `allowed_authors` list

## API Integration Details

### Authentication
Configure Bitbucket authentication:

```bash
ca config set bitbucket.url "https://bitbucket.company.com"
ca config set bitbucket.username "your-username"

# Store token securely (recommended)
ca config set bitbucket.token "your-app-password"
```

### Supported Endpoints

Cascade integrates with these Bitbucket Server APIs:

- **Merge endpoint**: `GET/POST /rest/api/1.0/projects/{project}/repos/{repo}/pull-requests/{id}/merge`
- **Build status**: `GET /rest/build-status/1.0/commits/{commit}`
- **PR details**: `GET /rest/api/1.0/projects/{project}/repos/{repo}/pull-requests/{id}`
- **Participants**: `GET /rest/api/1.0/projects/{project}/repos/{repo}/pull-requests/{id}/participants`

### Rate Limiting

Cascade respects Bitbucket API limits:
- **Polling frequency**: 30 seconds (configurable)
- **Concurrent requests**: Limited to avoid overwhelming server
- **Exponential backoff**: On rate limit errors

## Security Considerations

### Token Permissions
App passwords need these permissions:
- **Repositories**: Read, Write
- **Pull requests**: Read, Write
- **Account**: Read (for user info)

### Author Allowlist
For security, restrict auto-merge to trusted authors:

```json
{
  "auto_merge": {
    "allowed_authors": ["team-lead", "senior-dev", "ci-bot"]
  }
}
```

This prevents unauthorized auto-merging from:
- External contributors
- Compromised accounts
- Untrusted automation

### Audit Trail
All auto-merge activities are logged:
- **Who**: PR author and merger
- **When**: Timestamp of merge
- **What**: Commit hash and strategy
- **Why**: Merge trigger (manual/auto)

### Best Practices

1. **Use app passwords**: More secure than user passwords
2. **Restrict authors**: Don't allow auto-merge from everyone
3. **Monitor activity**: Review auto-merge logs regularly
4. **Set reasonable timeouts**: Don't wait forever for builds
5. **Test in dev**: Validate auto-land in development repos first

## Stack Landing Mechanics

### Current Implementation βœ…
When landing stacked PRs, each PR is merged individually in dependency order **with automatic retargeting**:

```
PR #101: feature-base β†’ main        (merges first)
PR #102: feature-part2 β†’ feature-base   (merges second)  
PR #103: feature-final β†’ feature-part2   (merges third)
```

### Automatic Retargeting System πŸ”„
**NEW**: After each PR merge, the system automatically retargets remaining PRs to the latest base:

1. **Merge base PR**: Land PR #101 (`feature-base` β†’ `main`) βœ…
2. **Auto-retarget dependents**: Change PR #102 target from `feature-base` to `main` πŸ”„ **AUTOMATIC**
3. **Update Bitbucket PRs**: Use force-push to preserve PR history and comments πŸ”„ **AUTOMATIC**
4. **Continue sequence**: Process remaining PRs with updated targets πŸ”„ **AUTOMATIC**

### How It Works

The landing system now integrates with the sophisticated rebase engine:

- **After each merge**: Triggers rebase system to retarget remaining PRs
- **Branch mapping**: Creates old→new branch mapping for PR updates  
- **PR preservation**: Uses `force_push_branch` to update PRs without losing history
- **Conflict resolution**: Leverages existing conflict resolution for complex cases
- **Automatic comments**: Adds explanatory comments to updated PRs

### Landing Commands

All these commands now include automatic retargeting:

```bash
# 🎯 Default: Land all ready PRs with safety checks (RECOMMENDED)
ca stacks land

# 🎯 Land specific entry by number (1-based) 
ca stacks land 2

# πŸ” Preview what would be landed
ca stacks land --dry-run

# ⚠️ Force land ignoring safety checks (dangerous)
ca stacks land --force

# πŸ”’ Use server-side validation (extra safety)
ca stacks land --auto

# πŸ• Wait for builds before landing
ca stacks land --wait-for-builds

# πŸš€ Shorthand for land --auto
ca stacks autoland
```

### Benefits

βœ… **No manual intervention**: Never need `ca stacks rebase --onto main` manually  
βœ… **Preserves PR history**: All reviews, comments, and discussions remain intact  
βœ… **Handles conflicts**: Uses intelligent conflict resolution system  
βœ… **Progress transparency**: Shows retargeting progress and results  
βœ… **Fallback guidance**: Provides manual steps if auto-retargeting fails

### Conflict Resolution Workflow 🚨

If conflicts occur during auto-retargeting, the land operation will pause and provide clear guidance:

```bash
ca stacks land                     # Start landing all ready PRs

# βœ… PR #1 lands successfully
# πŸ”„ Auto-retargeting begins  
# ❌ Conflict detected during retargeting!

# CLI Output:
#   ❌ Auto-retargeting conflicts detected!
#   πŸ“ To resolve conflicts and continue landing:
#      1. Resolve conflicts in the affected files
#      2. Stage resolved files: git add <files>
#      3. Continue the process: ca stacks continue-land
#      4. Or abort the operation: ca stacks abort-land
#   πŸ’‘ Check current status: ca stacks land-status
```

#### Manual Resolution Steps

```bash
# 1. Check what conflicts need resolution
ca stacks land-status

# 2. Edit conflicted files manually
vim src/conflicted-file.rs       # Resolve <<<<<<< ======= >>>>>>> markers

# 3. Stage resolved files  
git add src/conflicted-file.rs

# 4. Continue the land operation
ca stacks continue-land            # Resumes landing remaining PRs

# 5. Alternative: Abort if conflicts too complex
ca stacks abort-land              # Restores pre-land state
```

### Base Branch Update Mechanism πŸ“₯

**NEW**: The land command now automatically updates the base branch after each PR merge:

1. **Merge PR #1** β†’ `main` gets new commits βœ…
2. **Update local base**: `git pull origin main` πŸ”„ **AUTOMATIC**  
3. **Retarget remaining PRs** to updated `main` πŸ”„ **AUTOMATIC**
4. **Continue with next PR** using latest base βœ…

### βœ… **FIXED**: Industry-Standard Sync Commands

We now match the industry standard (Graphite) for sync functionality:

**NEW Behavior** (matches `gt sync`):
```bash
ca stacks sync    # βœ… Pulls main + restacks + cleans up merged branches  
ca stacks check   # βœ… Read-only status validation (old sync behavior)
```

This provides the intuitive workflow developers expect from modern stacked diff tools.

### Sync vs Check Commands ✨

#### **NEW**: Proper Sync (Industry Standard)
```bash
ca stacks sync    # πŸ”„ Pull + rebase + cleanup (like Graphite's gt sync)
```

**What it does**:
1. **πŸ“₯ Pull latest changes** from base branch (e.g., main)
2. **πŸ” Check if rebase needed** based on new commits
3. **πŸ”€ Auto-rebase stack** onto updated base if needed
4. **πŸ”„ Update PRs** with preserved history using force-push
5. **🧹 Cleanup merged branches** (optional with `--skip-cleanup`)

**Options**:
- `--force`: Continue even if pull/checkout fails
- `--skip-cleanup`: Skip merged branch cleanup
- `--interactive`: Use interactive mode for conflict resolution

#### **Status Check Only**
```bash
ca stacks check   # πŸ“Š Read-only status check (old sync behavior)
```

**What it does**:
- βœ… Validates stack integrity
- βœ… Checks if base branch exists
- βœ… Detects if stack needs sync
- βœ… Updates stack status (`Clean`/`NeedsSync`/etc.)
- ❌ **Does NOT** pull or rebase