Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -327,6 +327,23 @@ rules below are; it is still the right place to start.
existed in either repository to test against. Verified on 2026-09-12
against `crm.promosys` and `velocity.foremost-print.com`.

36. **A merge can answer 202, and the task is named only in `Location`.**
`POST pullrequests/{id}/merge` queues the merge when Bitbucket is slow and
answers 202 with an empty body. `PostAsync` drops headers, so 1.5.0 printed
`""`, exited 0 and lost the task ID (16 Nov 2026; two queued merges were then
dropped without a word, and a third landed 40 minutes later while `pr view`
still said OPEN). Without `?async=true` the same POST can also block past the
30s client timeout, which happened on the same day, so the handler always
sends it and polls instead. `MergePullRequestHandler` uses
`PostForResponseAsync` and polls `merge/task-status/{id}` through
`MergeTask`, which retries a poll that times out or answers 5xx or 429:
live, one poll hung 30s after two minutes of PENDING and aborted the wait.
A merge still pending at the timeout exits 75 (EX_TEMPFAIL)
with the task in its JSON; a handler sets a non-zero exit while still
printing by returning a `CommandOutcome`. Never test this on a live
repository: `AsyncMergeTests` fakes the 202 path, and a live check belongs
on a throwaway repository.

## Live testing

If you test against real Bitbucket:
Expand Down
36 changes: 36 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,42 @@ so commit history is the source of truth for the fine grain.

Versioning follows [Semantic Versioning](https://semver.org/): `MAJOR.MINOR.PATCH`.

## [1.6.0]

### Fixed

- `pr merge` printed `""` and exited 0 when Bitbucket queued the merge (HTTP
202), so the pull request stayed open and the task ID appeared nowhere. Seen
during the Bitbucket slowdown of 16 Nov 2026, when two queued merges were
dropped without a word. The client now keeps the 202's `Location` header,
where Bitbucket names the task.

### Added

- `pr merge` sends `async=true`. Without it Bitbucket holds the request open
while it merges, and during the slowdown that ran past the 30-second client
timeout and exited 1 with the outcome unknown. Even with `async=true`,
Bitbucket took over 30 seconds to accept a merge during the slowdown, so the
merge request alone now waits up to 120 seconds; every other call keeps 30.
If it still times out, the error says the merge may have been queued.
- `pr merge` waits for a queued merge by polling its task status, then prints
the merged pull request just as a direct merge does. If the merge is still
pending after `--timeout` seconds (default 120) it prints
`"status": "queued"` with `task_id`, `task_status_url` and the follow-up
command, and exits **75**. A failed task exits 1. `--no-wait` prints the
queued record at once and exits 0.
- While waiting, a task-status poll that times out or answers 5xx or 429 is
retried rather than ending the wait, which is what happened live: after two
minutes of PENDING one poll hung for 30 seconds. The queued record carries
the last such error as `last_poll_error`.
- `pr merge-status` takes `--wait` and `--timeout`, and `--task-id` now
accepts the `task_status_url` as well as the bare ID.

### Changed

- `pipeline deployments changes` says "Queued change" rather than "Updated",
because Bitbucket answers 202 and applies the change later.

## [1.5.0]

### Changed
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
Bitbucket has no first-party CLI. `bbx` fills that gap the way `gh` does for GitHub:

- **JSON on stdout, diagnostics on stderr.** Pipe straight into `jq` without filtering noise.
- **Exit codes that mean something.** `0` on success, `1` on any failure, so `set -e` and `if !` work.
- **Exit codes that mean something.** `0` on success, `1` on any failure, so `set -e` and `if !` work. `75` means a queued merge has not finished yet.
- **One credential.** An Atlassian API token, stored `0600`, with scopes you choose.
- **Wide coverage.** Repos, pull requests, branches, tags, commits, source files, downloads, pipelines, snippets, workspaces, projects and users.
- **Errors you can act on.** A missing scope tells you which scope and where to re-issue the token.
Expand Down Expand Up @@ -237,7 +237,7 @@ bbx pr statuses 42 -w myws -r myrepo

bbx pr diffstat 42 -w myws -r myrepo # per-file line counts
bbx pr conflicts 42 -w myws -r myrepo
bbx pr merge-status 42 --task-id <id> -w myws -r myrepo
bbx pr merge-status 42 --task-id <id> --wait -w myws -r myrepo # follow a queued merge
bbx pr activity -w myws -r myrepo # no ID: the whole repository

bbx pr comment 42 --body "LGTM" -w myws -r myrepo
Expand Down
13 changes: 12 additions & 1 deletion docs/api-coverage.md
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,17 @@ Nothing was added except two optional query parameters on `POST .../pipelines/`
on-demand runs, `merge_defaults` and `target_branch_to_create`, both covered by
`bbx pipeline trigger --yaml` (1.4.0). No other operation, body or response changed.

## Endpoints that answer 202

Three operations in the spec can answer 202 Accepted. Checked on 2026-11-16 after
`bbx pr merge` lost a queued merge's task ID:

| Method | Path | What 202 means | What `bbx` does |
| --- | --- | --- | --- |
| `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge` | Merge queued; the task-status URL is in the `Location` header | Before 1.6.0 it printed `""` and exited 0. Now it sends `async=true` so the 202 comes at once instead of after a wait that can outlast the client timeout, reads the task ID from `Location` (or `links.self.href`), polls task-status for up to `--timeout` seconds (default 120), and exits 75 with `"status": "queued"` and the task ID if the merge has not finished. `--no-wait` returns the task at once with exit 0 |
| `POST` | `/repositories/{workspace}/{repo_slug}/environments/{environment_uuid}/changes` | Change queued; empty body | `bbx pipeline deployments changes` now says "Queued change" rather than "Updated". There is no task to poll |
| `GET` | `/repositories/{workspace}/{repo_slug}/commit/{commit}/pullrequests` | Pull request links still being indexed; the page may be partial | Left as is. `bbx commit pullrequests` prints what came back |

## Why things are skipped

Four reasons account for every skip.
Expand Down Expand Up @@ -136,7 +147,7 @@ Three things the spec gets wrong or leaves out:
| `POST` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/comments/{comment_id}/resolve` | cover | `bbx pr comment-resolve` |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/conflicts` | cover | `bbx pr conflicts` |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/diffstat` | cover | `bbx pr diffstat` |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge/task-status/{task_id}` | cover | `bbx pr merge-status` |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/merge/task-status/{task_id}` | cover | `bbx pr merge-status`, and `bbx pr merge` polls it after a 202 (1.6.0) |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pull_request_id}/tasks/{task_id}` | cover | `bbx pr tasks view` |
| `DELETE` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pullrequest_id}/properties/{app_key}/{property_name}` | skip | Connect app property; app key unobtainable from a CLI |
| `GET` | `/repositories/{workspace}/{repo_slug}/pullrequests/{pullrequest_id}/properties/{app_key}/{property_name}` | skip | Connect app property; app key unobtainable from a CLI |
Expand Down
46 changes: 43 additions & 3 deletions docs/llm-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,10 @@ relevant table.
- **exit codes:** `0` on success, `1` on any handled error
(`BbxUserException` for user-facing errors like "not authenticated",
`HttpRequestException` for network/API failures wrapped with
`"Error: "`).
`"Error: "`). `75` means "not finished yet, check again": only
`pr merge` and `pr merge-status --wait` use it, when Bitbucket has queued
a merge that is still pending at `--timeout`. The JSON on stdout still
carries the task ID.
- **No interactive prompts by default for an agent.** Set
`BBX_NO_INTERACTIVE=1` or redirect stdin to disable the first-run
credential prompt and the `--yes`-less confirmation prompts.
Expand Down Expand Up @@ -182,7 +185,7 @@ offered; use `remove`.
| `view <id>` | `GET repositories/{ws}/{repo}/pullrequests/{id}` |
| `create` | `POST repositories/{ws}/{repo}/pullrequests` — `--title`, `--source`, `--dest`, `--body`, `--close-source-branch`, `--reviewers <account-id>` |
| `update <id>` | `PUT repositories/{ws}/{repo}/pullrequests/{id}` — `--title`, `--body`, `--dest`, `--reviewers <account-id>...`, `--close-source-branch`, `--no-close-source-branch`. Open pull requests only. |
| `merge <id>` | `POST .../merge` — `--strategy`, `--message`, `--close-source-branch`, `--yes`. Six strategies: `merge_commit`, `squash`, `fast_forward`, `squash_fast_forward`, `rebase_fast_forward`, `rebase_merge`. Left off, `bbx` reads the destination branch's `default_merge_strategy` (two extra GETs); named explicitly, it is sent straight through with no lookups. May answer 202 with a task ID instead of merging on the spot; read it with `merge-status` |
| `merge <id>` | `POST .../merge` — `--strategy`, `--message`, `--close-source-branch`, `--yes`. Six strategies: `merge_commit`, `squash`, `fast_forward`, `squash_fast_forward`, `rebase_fast_forward`, `rebase_merge`. Left off, `bbx` reads the destination branch's `default_merge_strategy` (two extra GETs); named explicitly, it is sent straight through with no lookups. Waits for a queued merge: see below. `--no-wait`, `--timeout <seconds>` (default 120) |
| `approve <id>` / `unapprove <id>` | `POST/DELETE .../approve` |
| `decline <id>` | `POST .../decline`. Takes no body, so there is no `--close-source-branch` here: the source branch stays until `bbx branch delete` removes it |
| `comments <id>` / `comment <id>` | `GET/POST .../comments` — `--body` for `comment`. Each row carries `deleted`; a tombstone reads `deleted: true` with empty `content` |
Expand All @@ -195,14 +198,51 @@ offered; use `remove`.
| `commits <id>` | `GET .../commits` |
| `diffstat <id>` | `GET .../pullrequests/{id}/diffstat` — per-file line counts, cheaper than the whole diff |
| `conflicts <id>` | `GET .../pullrequests/{id}/conflicts` — answers 403 to an API token |
| `merge-status <id>` | `GET .../pullrequests/{id}/merge/task-status/{task-id}` — `--task-id` |
| `merge-status <id>` | `GET .../pullrequests/{id}/merge/task-status/{task-id}` — `--task-id` takes the `task_id` or the `task_status_url` that `merge` printed. `--wait` polls like `merge` does, with `--timeout`. Without `--wait` it prints Bitbucket's status (`PENDING` or `SUCCESS` with `merge_result`) and exits 0 |
| `activity [<id>]` | `GET .../pullrequests/activity` with no ID, `.../pullrequests/{id}/activity` with one — `--limit` |
| `comment-view <id>` | `GET .../comments/{comment-id}` — `--comment-id` |
| `comment-update <id>` | `PUT .../comments/{comment-id}` — `--comment-id`, `--body` |
| `comment-delete <id>` | `DELETE .../comments/{comment-id}` — `--comment-id`, `--yes`. Leaves a tombstone: `comments` still counts the row and shows `"content": ""` |
| `comment-resolve <id>` / `comment-unresolve <id>` | `POST/DELETE .../comments/{comment-id}/resolve` — `--comment-id` |
| `tasks view <id>` | `GET .../tasks/{task-id}` — `--task-id` |

#### Queued merges (202)

`pr merge` sends `?async=true`, so Bitbucket queues the merge, answers 202 at
once and names a task. Without it Bitbucket holds the request open while it
merges, and on 16 Nov 2026 that ran past the 30-second client timeout and left
the outcome unknown. Even with `async=true` Bitbucket took over 30 seconds to
accept a merge that day, so the merge request alone waits up to 120 seconds.
`pr merge` then polls the task every 3 seconds:

| What happens | stdout | Exit |
| --- | --- | --- |
| Merged inline (200), or the queued task finishes | the merged pull request, as before | `0` |
| Still `PENDING` at `--timeout` | `{"status": "queued", "task_id": …, "task_status_url": …, "task_status": "PENDING", "waited_seconds": …, "last_poll_error": …, "next": "bbx pr merge-status …"}` | `75` |
| The task fails | the error, on stderr | `1` |
| The merge request itself times out | a "may still have been queued" error, on stderr | `1` |
| `--no-wait` | the same `"status": "queued"` record, at once | `0` |

A poll that times out or answers 5xx or 429 does not end the wait: it says
nothing about the merge, so polling carries on until `--timeout`, and the last
such error appears as `last_poll_error`. A 4xx ends it, because 400 is how
Bitbucket reports a failed task.

A queued merge can still land after the timeout, or be dropped: during the
Bitbucket slowdown of 16 Nov 2026 two of three queued merges vanished and the
third landed 40 minutes later. So on exit 75, do not merge again. Follow the
task, which is the command the `next` field holds:

```bash
bbx pr merge 42 -r myrepo --yes; rc=$?
if [ $rc -eq 75 ]; then
bbx pr merge-status 42 -r myrepo --task-id <task_id> --wait --timeout 900
fi
```

`pr view` can report `OPEN` for a while after a queued merge has landed. Trust
the task status over it.

`pr update` sends only the flags you pass. Anything you leave out keeps its
current value, so you can retitle a pull request without touching its
description. An empty `--body ""` clears the description.
Expand Down
65 changes: 60 additions & 5 deletions src/Bbx/Api/BitbucketClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,32 @@ public async Task CopyToAsync(string endpoint, Stream destination, CancellationT
public Task<T?> PutMultipartAsync<T>(string endpoint, MultipartFormDataContent content, CancellationToken ct = default)
=> SendForJsonAsync<T>(HttpMethod.Put, endpoint, content, ct);

/// <summary>
/// POST and keep the status and <c>Location</c> header, which
/// <see cref="PostAsync{T}"/> throws away. The merge endpoint answers 202
/// when it queues the merge, and the only place it names the task is the
/// Location header; dropping it is how <c>bbx pr merge</c> printed a bare
/// <c>""</c> and lost the task ID.
/// </summary>
public async Task<ApiResponse> PostForResponseAsync(string endpoint, object? body = null,
CancellationToken ct = default, TimeSpan? timeout = null)
{
using var response = await SendAsync(HttpMethod.Post, endpoint, JsonContent(body), ct, timeout: timeout);
await EnsureSuccessAsync(response);
var json = await response.Content.ReadAsStringAsync(ct);
var location = response.Headers.Location;
if (location is { IsAbsoluteUri: false } && response.RequestMessage?.RequestUri is { } requestUri)
location = new Uri(requestUri, location);

JsonElement parsed = default;
if (!string.IsNullOrWhiteSpace(json))
{
try { parsed = JsonSerializer.Deserialize<JsonElement>(json, JsonOptions); }
catch (JsonException) { }
}
return new ApiResponse((int)response.StatusCode, location, parsed);
}

private static StringContent? JsonContent(object? body) => body is null
? null
: new StringContent(JsonSerializer.Serialize(body, JsonOptions), Encoding.UTF8, "application/json");
Expand Down Expand Up @@ -129,11 +155,12 @@ private async Task<HttpResponseMessage> SendAsync(
HttpContent? content,
CancellationToken ct,
string? accept = null,
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead)
HttpCompletionOption completionOption = HttpCompletionOption.ResponseContentRead,
TimeSpan? timeout = null)
{
var current = new Uri(_client.BaseAddress!, NormalizeEndpoint(endpoint));
var response = await SendOnceAsync(
method, current.AbsoluteUri, content, ct, accept, completionOption, IsApiOrigin(current));
method, current.AbsoluteUri, content, ct, accept, completionOption, IsApiOrigin(current), timeout);

// Redirects are followed here rather than by HttpClient because
// HttpClient drops the Authorization header when it follows one, which
Expand Down Expand Up @@ -170,7 +197,8 @@ private async Task<HttpResponseMessage> SendOnceAsync(
CancellationToken ct,
string? accept,
HttpCompletionOption completionOption,
bool applyAuth = true)
bool applyAuth = true,
TimeSpan? timeout = null)
{
var request = new HttpRequestMessage(method, url)
{
Expand All @@ -184,9 +212,30 @@ private async Task<HttpResponseMessage> SendOnceAsync(
{
await _auth.ApplyAsync(request, ct);
}
return await _client.SendAsync(request, completionOption, ct);
var limit = timeout ?? DefaultTimeout;
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct);
deadline.CancelAfter(limit);
try
{
return await _client.SendAsync(request, completionOption, deadline.Token);
}
catch (OperationCanceledException e) when (!ct.IsCancellationRequested)
{
// Keep the shape HttpClient.Timeout used to give: Program tells a
// timeout (exit 1) from Ctrl+C (exit 130) by the inner
// TimeoutException, and a bare cancellation would read as Ctrl+C.
throw new TaskCanceledException(
$"{method} {new Uri(url).AbsolutePath} got no answer within {limit.TotalSeconds:0} seconds.",
new TimeoutException(e.Message, e));
}
}

/// <summary>
/// Applied per request rather than through <c>HttpClient.Timeout</c>, so a
/// call that is slow by nature can ask for longer.
/// </summary>
public static readonly TimeSpan DefaultTimeout = TimeSpan.FromSeconds(30);

private bool IsApiOrigin(Uri target) => Uri.Compare(
target,
_client.BaseAddress!,
Expand Down Expand Up @@ -256,7 +305,7 @@ private static async Task EnsureSuccessAsync(HttpResponseMessage response)
{
}

throw new HttpRequestException(errorMessage);
throw new HttpRequestException(errorMessage, null, response.StatusCode);
}

private static JsonSerializerOptions JsonOptions => new()
Expand All @@ -279,6 +328,12 @@ public void Dispose()
}
}

/// <summary>
/// A response whose status and Location header matter as well as its body.
/// <see cref="Body"/> is the default element (ValueKind Undefined) when there was no JSON body.
/// </summary>
public sealed record ApiResponse(int Status, Uri? Location, JsonElement Body);

public class PaginatedResponse<T>
{
public int Size { get; set; }
Expand Down
2 changes: 1 addition & 1 deletion src/Bbx/Bbx.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

<!-- First public release. CI bumps this; a plain push to master bumps the
patch, larger bumps go through workflow_dispatch. -->
<Version>1.5.0</Version>
<Version>1.6.0</Version>

<!-- NuGet metadata -->
<Authors>solrevdev</Authors>
Expand Down
11 changes: 11 additions & 0 deletions src/Bbx/BbxExitException.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace Bbx;

/// <summary>
/// Ends the run with a specific exit code after the command has already printed
/// its JSON. Used when the output is useful but the job is not done, such as a
/// merge still queued when the wait ran out.
/// </summary>
public sealed class BbxExitException(int exitCode, string message) : Exception(message)
{
public int ExitCode { get; } = exitCode;
}
Loading
Loading