Skip to content

Commit d5f844a

Browse files
mchwangclaude
andcommitted
Merge F6b fbfe4ce into the #48 browser fixes
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2 parents d948c5a + fbfe4ce commit d5f844a

8 files changed

Lines changed: 345 additions & 29 deletions

File tree

‎docs/implementation/merge-handoff.md‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ Without a runner, **Merge PR** works as before.
3535
| Wait for checks | The job inspects the pull request (fresh) at once, then again after 10 s, with the wait doubling up to 60 s. | every required check succeeds, or the required set was read and is empty, and nothing else blocks | a required check fails, or 30 minutes pass (job: `blocked`, if the preparation still applies: the block re-checks readiness in its transaction, and a review edit or other task change meanwhile ends the job `failed` instead); the pull request moved, another blocker appears, or GitHub or the local review cannot be read (job: `failed`; one failed read fails closed rather than retrying; each inspection also loads the review, which awaits a history worker since #170, within the same 30-minute limit) |
3636
| Merge | The job calls the guarded merge with the current review token. Its inspections rerun the already-fixed check. | GitHub merged or queued the head, as the job's own merge attempt records it (job: `merged` or `queued`; `submitted` when GitHub accepted the merge but saving its outcome failed, so the attempt is still submitting and reconciles from GitHub) | GitHub refused (job: `blocked`; `failed` when GitHub refused because the head changed, which needs a fresh review, or when the review, snapshot or plan revision changed while GitHub was asked: the block is for the review the merge attempt was admitted for), validation refused (job: `failed`), or the outcome is unknown (job: `submitted`; the merge attempt reconciles as before) |
3737

38-
While waiting, an unknown mergeability (GitHub is still computing it) and a pending or missing required check keep the job waiting. No inspection starts after the 30 minutes, and one still running when they end is stopped, so only checks seen passing within the limit count. The guarded merge that follows inspects again and may ask GitHub to merge shortly after the limit; it refuses anything no longer clear. Unreadable branch rules never pass. Another blocker outranks a failing check: checks that fail on a head a collaborator pushed say nothing about this review, so the job ends `failed` and the task's status is unchanged.
38+
A required check run passes when it completed with success, neutral or skipped, as GitHub counts required checks; a commit status passes only with success. When a check has several runs or statuses with its name (a re-run), the one that started last counts, and a run not yet started counts as the latest. While waiting, an unknown mergeability (GitHub is still computing it) and a pending or missing required check keep the job waiting. No inspection starts after the 30 minutes, and one still running when they end is stopped, so only checks seen passing within the limit count. Only that stop counts as the wait timing out: an inspection that GitHub failed before the limit, but that settles after it (its stopped reads finishing), ends the job `failed` with GitHub's error. The guarded merge that follows inspects again and may ask GitHub to merge shortly after the limit; it refuses anything no longer clear. Unreadable branch rules never pass. Another blocker outranks a failing check: checks that fail on a head a collaborator pushed say nothing about this review, so the job ends `failed` and the task's status is unchanged.
3939

4040
## Outcomes
4141

@@ -68,19 +68,19 @@ A rebase moves the pull request's base. The guarded merge would then scan only t
6868

6969
## Storage
7070

71-
Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening followed) and `merge_jobs`: one row per job or refused click, with three columns: `id` (the click's action ID, primary key), `plan_key` (the task, indexed by `merge_jobs_plan`) and `data`. `data` is a JSON record holding the rest: the click's review token, the guarded merge's action ID once the job reaches that step, `state`, `step`, `reason`, required-check names and states, the merge result URL, start and update times, and `refused` for a refused click. Lookups by state (the running job, the latest job that was not refused) read these JSON fields. A refused click's row is replayed to that click and never shown as the task's job. Writing it never changes the task's state version, so the readiness preparation recorded stays valid while the job waits. A resend of the same click returns its row; another click while a job runs is refused. While a job runs, `prepare-merge` is refused (the job prepares the merge itself). `publish` is refused too, by publishing's own status rule: it publishes only a running task whose plan items have all run, or a task that needs a person, and a job runs only for a task in review or approved but merge blocked. The runner's `start` and `resume` actions are refused too ("A merge is running for this task; wait for it to end or cancel the task."), saved and replayed like other refusals, and neither is offered: a run would move the task's head, and the publish at its end would push it. So no run starts, and no publish can push the pull request's head or begin a refresh of it while the job prepares, waits or merges. Plan import stays allowed during a job, as at any time in review. It changes only the plan, never the branch or the pull request; the readiness the job prepared is then for an older review, so the job's next inspection ends it `failed` ("Pre-merge preparation has not completed for the current review."), or the guarded merge refuses, and nothing is merged.
71+
Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening followed) and `merge_jobs`: one row per job or refused click, with three columns: `id` (the click's action ID, primary key), `plan_key` (the task, indexed by `merge_jobs_plan`) and `data`. `data` is a JSON record holding the rest: the click's review token, the guarded merge's action ID once the job reaches that step, `state`, `step`, `reason`, required-check names and states, the merge result URL, `sequence` (the record's place among the task's jobs and refused clicks, from 1, so the browser orders jobs without comparing clock times), start and update times, and `refused` for a refused click. Lookups by state (the running job, the latest job that was not refused) read these JSON fields. A refused click's row is replayed to that click and never shown as the task's job. Writing it never changes the task's state version, so the readiness preparation recorded stays valid while the job waits. A resend of the same click returns its row; another click while a job runs is refused. While a job runs, `prepare-merge` is refused (the job prepares the merge itself). `publish` is refused too, by publishing's own status rule: it publishes only a running task whose plan items have all run, or a task that needs a person, and a job runs only for a task in review or approved but merge blocked. The runner's `start` and `resume` actions are refused too ("A merge is running for this task; wait for it to end or cancel the task."), saved and replayed like other refusals, and neither is offered: a run would move the task's head, and the publish at its end would push it. So no run starts, and no publish can push the pull request's head or begin a refresh of it while the job prepares, waits or merges. Plan import stays allowed during a job, as at any time in review. It changes only the plan, never the branch or the pull request; the readiness the job prepared is then for an older review, so the job's next inspection ends it `failed` ("Pre-merge preparation has not completed for the current review."), or the guarded merge refuses, and nothing is merged.
7272

7373
## API and browser
7474

7575
- `POST /api/action` with `merge` returns at once when the server runs merge jobs (a runner and a pull request published by it, which requires preparation): the reloaded review with the job's latest record as `job`, or, if that reload failed, `{ job, mergeRefreshRequired: true }`. The job may already have moved on or ended by then; the page follows a running job and, for an ended one, asks for a refresh.
7676
- `GET /api/merge` returns `{ queue, job }`: `job` is the task's latest job. A saved refusal is not a job; it is replayed only to its own click.
7777
- Merge PR is offered only while the task is in a mergeable status (read after the inspection) and the only blockers left are ones the job resolves or reports: preparation, a moved base (with a merge conflict it causes), `cmd:` checks, required checks (the job waits for pending ones and ends `blocked` on failing ones, so a person can retry after re-running CI), and mergeability GitHub is still computing.
78-
- While a job runs, the Merge button keeps keyboard focus: it is marked `aria-disabled`, not disabled, and a repeat activation starts nothing.
79-
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record of the same job (by its `updatedAt`) keeps that newer record, so a slow **Refresh** does not restart following a job the poll saw end. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
78+
- While a job runs, the Merge button keeps keyboard focus: it is marked `aria-disabled`, not disabled, and a repeat activation starts nothing. While the click's own request is in flight, the button reads **Requesting merge…** and stays marked, also when the page renders meanwhile (for example when a person selects an item).
79+
- The browser polls `GET /api/merge` with the existing 2 s to 30 s backoff while a job runs, shows its step in the merge banner, and lists waiting checks in the blocker dialog. A full review response read before the poll's latest record keeps that newer record: a later record of the same job (by its `updatedAt`), or a later job (by its `sequence`, which another tab's click may have started). A kept running job keeps Merge PR not ready and its poll running, so a slow **Refresh**, review action, **Refresh plan**, plan import or **Apply** reload does not restart following a job the poll saw end, or stop following a newer job and offer Retry while it runs. A click's key is kept until its own job ends or a job newer than the one shown at the click is the latest, so a retry that failed with no answer is resent with the same key. When the job ends, the page updates only the merge control and banner (the outcome, and "Refresh to see the result"), so a person's selection and input survive; after **Refresh**, the page offers **Retry merge** when the job is `blocked`. The design's full step list and a Cancel button come later.
8080

8181
## Tests
8282

83-
`test/merge-job.test.ts` runs the job against the real Store and guarded merge with a faked GitHub and preparation. It covers the three wait cases the design names (zero required checks, one check pending then passing, a timeout), a failing check, GitHub still computing mergeability, preparation ending for review or failing, another blocker while waiting, a failed GitHub read while waiting, GitHub's refusal, an unknown merge outcome, a merge queue (`queued`), cancel while waiting (told or not) and during the guarded merge's validation, shutdown while waiting and during the guarded merge, startup settlement, resends, a second click, a stale token, a busy runner, and which blockers keep Merge PR available (including Retry merge after `blocked`). `test/pre-merge.test.ts` runs the #22 acceptance cases through the job with real preparation: a base move that leaves approvals valid merges; a rebase that makes an approval stale stops for review; a breaking command after a rebase fails the job; a collaborator push stops for review; a cancel during a command check ends the job `cancelled`. Server tests cover the merge route, its trust admission (an untrusted click refused and replayed, a failed read saving nothing), `GET /api/merge`, the `prepare-merge` and `publish` refusals, the `start` refusal after a plan import and approval during the preparation, the `start` and `resume` refusals after the same during the check wait (the import then ends the job `failed`, with nothing run, pushed, published or merged), cancel closing the pull requests, and shutdown; a production test covers startup settlement; a browser test follows a job to merged.
83+
`test/merge-job.test.ts` runs the job against the real Store and guarded merge with a faked GitHub and preparation. It covers the three wait cases the design names (zero required checks, one check pending then passing, a timeout), a failing check, GitHub still computing mergeability, preparation ending for review or failing, another blocker while waiting, a failed GitHub read while waiting (also one that settles after the wait limit), GitHub's refusal, an unknown merge outcome, a merge queue (`queued`), cancel while waiting (told or not) and during the guarded merge's validation, shutdown while waiting and during the guarded merge, startup settlement, resends, a second click, a stale token, a busy runner, and which blockers keep Merge PR available (including Retry merge after `blocked`). `test/pre-merge.test.ts` runs the #22 acceptance cases through the job with real preparation: a base move that leaves approvals valid merges; a rebase that makes an approval stale stops for review; a breaking command after a rebase fails the job; a collaborator push stops for review; a cancel during a command check ends the job `cancelled`. Server tests cover the merge route, its trust admission (an untrusted click refused and replayed, a failed read saving nothing), `GET /api/merge`, the `prepare-merge` and `publish` refusals, the `start` refusal after a plan import and approval during the preparation, the `start` and `resume` refusals after the same during the check wait (the import then ends the job `failed`, with nothing run, pushed, published or merged), cancel closing the pull requests, and shutdown; a production test covers startup settlement; a browser test follows a job to merged.
8484

8585
## Check this document with a reader
8686

‎github/merge.ts‎

Lines changed: 34 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -150,6 +150,33 @@ function timestamp(value: unknown, label: string): string {
150150
}
151151

152152
/** GitHub CLI adapter. All arguments are literal argv; no shell is involved. */
153+
/**
154+
* The state GitHub gives one observed required check. A check run that completed SUCCESS, NEUTRAL or SKIPPED passes, as
155+
* GitHub treats those conclusions for required checks; a commit status passes only with SUCCESS.
156+
*/
157+
function observedCheckState(check: Record<string, unknown>): 'success' | 'pending' | 'failure' {
158+
if (typeof check.name === 'string') {
159+
const status = String(check.status ?? '').toUpperCase();
160+
const conclusion = String(check.conclusion ?? '').toUpperCase();
161+
if (['QUEUED','IN_PROGRESS','WAITING','PENDING','REQUESTED'].includes(status)) return 'pending';
162+
if (status === 'COMPLETED') return ['SUCCESS','NEUTRAL','SKIPPED'].includes(conclusion) ? 'success' : 'failure';
163+
return 'failure';
164+
}
165+
const status = String(check.state ?? '').toUpperCase();
166+
return status === 'SUCCESS' ? 'success' : ['PENDING','EXPECTED'].includes(status) ? 'pending' : 'failure';
167+
}
168+
/**
169+
* When an observed check run or status started, to pick the latest of several with one name. gh reports a run that has
170+
* not started yet with no time or the zero time (year 1); such a run was queued after every started one, so it counts
171+
* as the latest.
172+
*/
173+
function observedCheckStart(check: Record<string, unknown>): number {
174+
const at = typeof check.startedAt === 'string' ? Date.parse(check.startedAt) : NaN;
175+
return Number.isFinite(at) && new Date(at).getUTCFullYear() > 1 ? at : Number.POSITIVE_INFINITY;
176+
}
177+
/** Among runs with the same start, the one that passes least counts, so a tie never reads as passing. */
178+
const checkStateRank = { failure: 0, pending: 1, success: 2 } as const;
179+
153180
export class GhMergeGateway implements MergeGateway, MergeQueueGateway {
154181
readonly config: GhMergeConfig;
155182
readonly run: RunGh;
@@ -366,24 +393,17 @@ export class GhMergeGateway implements MergeGateway, MergeQueueGateway {
366393
}
367394
}
368395
const requiredChecks = [...requirements.values()].map(required => {
369-
const match = observed.find(check => {
396+
const matches = observed.filter(check => {
370397
const context = typeof check.name === 'string' ? check.name : check.context;
371398
const app = check.app && typeof check.app === 'object' ? (check.app as { databaseId?: unknown }).databaseId : null;
372399
return context === required.context && (required.appId === null || app === required.appId);
373400
});
374-
if (!match) return { ...required, state: 'missing' as const };
375-
let state: RequiredCheck['state'];
376-
if (typeof match.name === 'string') {
377-
const status = String(match.status ?? '').toUpperCase();
378-
const conclusion = String(match.conclusion ?? '').toUpperCase();
379-
if (['QUEUED','IN_PROGRESS','WAITING','PENDING','REQUESTED'].includes(status)) state = 'pending';
380-
else if (status === 'COMPLETED') state = conclusion === 'SUCCESS' ? 'success' : 'failure';
381-
else state = 'failure';
382-
} else {
383-
const status = String(match.state ?? '').toUpperCase();
384-
state = status === 'SUCCESS' ? 'success' : ['PENDING','EXPECTED'].includes(status) ? 'pending' : 'failure';
385-
}
386-
return { ...required, state };
401+
if (!matches.length) return { ...required, state: 'missing' as const };
402+
// A re-run adds a newer run (or status) with the same name; GitHub counts the latest one, so an older failure
403+
// does not outrank a newer pending or passing run.
404+
const latest = matches.map(check => ({ state: observedCheckState(check), at: observedCheckStart(check) }))
405+
.reduce((best, next) => next.at > best.at || (next.at === best.at && checkStateRank[next.state] < checkStateRank[best.state]) ? next : best);
406+
return { ...required, state: latest.state };
387407
});
388408
return { rulesKnown, atomicBaseGuard, mergeQueue, requiredChecks };
389409
}

‎runner/merge-job.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -248,7 +248,9 @@ export class MergeJobCoordinator {
248248
try { status = await this.merges.status(undefined, true, AbortSignal.any([signal, limit])); }
249249
catch (error) {
250250
if (signal.aborted) return { kind: 'cancelled' };
251-
if (limit.aborted) return timedOut();
251+
// Only the limit's own abort is the wait's timeout: every layer below rejects with that reason, unchanged. A
252+
// failure that came first (a GitHub stage failing while its stopped peers settle past the limit) keeps its error.
253+
if (limit.aborted && error === limit.reason) return timedOut();
252254
return { kind: 'failed', reason: error instanceof Error ? error.message : String(error) };
253255
}
254256
const verdict = classify(status);

0 commit comments

Comments
 (0)