Skip to content

Commit d948c5a

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

4 files changed

Lines changed: 105 additions & 5 deletions

File tree

‎docs/implementation/merge-handoff.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ 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. So no publish can push the pull request's head or begin a refresh of it while the job prepares, waits or merges.
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.
7272

7373
## API and browser
7474

@@ -80,7 +80,7 @@ Schema v19 adds `task_pull_requests.check_id` (the pre-PR check each opening fol
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` refusal, 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, 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

‎runner/store.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2352,9 +2352,9 @@ export class Store {
23522352
return this.#db.prepare('SELECT * FROM task_pull_requests WHERE plan_key=? ORDER BY rowid').all(key).map(row => this.#pullRequestRecord(row));
23532353
}
23542354
/**
2355-
* The task's first already-fixed check that found nothing: the scan start for an opening recorded before schema v19,
2356-
* which did not record its own check. A compare range excludes its start commit, so only a scan from this check's tip
2357-
* onward is provably continuous with what was scanned before.
2355+
* The task's already-fixed check with this ID, or null if it has none with that ID. The guarded merge reads the check the
2356+
* task's first opening into the base branch recorded (`task_pull_requests.check_id`, schema v19) to decide where its
2357+
* already-fixed scan starts.
23582358
*/
23592359
getAlreadyFixed(identity: PlanIdentity, id: string): AlreadyFixedCheck | null {
23602360
const row = this.#get('SELECT * FROM already_fixed_checks WHERE plan_key=? AND id=?', identityKey(identity), id);

‎test/runner-publishing.test.ts‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1844,6 +1844,103 @@ describe('the one-click merge job (F6b of #22)', () => {
18441844
expect(served.store.getTask(served.identity).status).toBe('merged');
18451845
}, 60_000);
18461846

1847+
it('refuses start and resume while a merge job waits, even after a new plan revision is imported and approved; the import only ends the job failed', async () => {
1848+
const w = world(); mergeable(w);
1849+
let storeRef: Store | null = null;
1850+
const base = gateway(() => storeRef!, () => [{ context: 'ci', appId: null, state: 'pending' }]);
1851+
// The job's fresh inspections after its first are held until the test releases them (or the job's signal stops them),
1852+
// so the job is still waiting for checks at every step below, whatever the machine's speed.
1853+
let fresh = 0, release!: () => void;
1854+
const released = new Promise<void>(resolve => { release = resolve; });
1855+
const gh: MergeGateway = { merge: base.merge, inspect: async request => {
1856+
if (request?.fresh && ++fresh > 1) await new Promise<void>((resolve, reject) => {
1857+
void released.then(resolve);
1858+
request.signal?.addEventListener('abort', () => reject(request.signal!.reason), { once: true });
1859+
});
1860+
return base.inspect(request);
1861+
} };
1862+
const served = await serve(w, { before: async service => { completeAll(service); await acceptAndApprove(service); }, issueGateway, preMerge: preparation, mergeGateway: gh, runnerPublished: true,
1863+
mergeJobTiming: { checkWaitMs: 600_000, firstDelayMs: 20, maxDelayMs: 50 } });
1864+
storeRef = served.store; createIdentity = () => served.identity;
1865+
await publishSettled(served.app, served.identity);
1866+
expect((await merge(served.app, (await review(served.app)).token)).status).toBe(200);
1867+
// The first inspection has answered (its pending check is recorded) and the second is held.
1868+
await vi.waitFor(async () => {
1869+
expect((await mergeState(served.app)).job).toMatchObject({ state: 'running', step: 'checks', checks: [{ context: 'ci', state: 'pending' }] });
1870+
expect(fresh).toBe(2);
1871+
}, { timeout: 10_000 });
1872+
// As a person would: import a new revision of the plan (plan import has no task-status guard), then approve it all.
1873+
const plan = served.store.getPlan(served.identity);
1874+
const imported = await fetch(`${new URL(served.app.url).origin}/api/plan/import`, { method: 'POST', headers: { 'x-codeboost-token': served.app.token, 'content-type': 'application/json' },
1875+
body: JSON.stringify({ source: JSON.stringify(plan), format: 'json', expectedRevision: plan.revision, actionId: randomUUID() }) });
1876+
expect(imported.status).toBe(200);
1877+
expect(served.store.getPlan(served.identity).revision).toBe(plan.revision + 1);
1878+
await acceptAndApprove(served.app.service);
1879+
expect(served.store.unapprovedExecutionItems(served.identity, plan.revision + 1)).toEqual([]);
1880+
expect(served.store.getTask(served.identity).status).toBe('in review');
1881+
const calls = [...w.github.calls], branchHead = w.github.head(served.branch), attempts = served.store.recentAttempts(served.identity, 50).length;
1882+
// Neither is offered, and both are refused, while the job runs.
1883+
expect(await view(served.app)).toMatchObject({ startable: false, resumable: false });
1884+
for (const action of ['start', 'resume']) {
1885+
const id = randomUUID(), refused = await act(served.app, action, id);
1886+
expect(refused).toMatchObject({ status: 409, body: { error: 'A merge is running for this task; wait for it to end or cancel the task.' } });
1887+
// Saved like other refusals: the same action ID replays it.
1888+
expect(await act(served.app, action, id)).toMatchObject({ status: 409, body: { error: refused.body.error } });
1889+
}
1890+
expect((await mergeState(served.app)).job).toMatchObject({ state: 'running', step: 'checks' });
1891+
expect(fresh).toBe(2);
1892+
// What the import itself does to the job: the readiness it prepared is for the old review, so its next inspection
1893+
// ends it failed, and nothing is merged, run, pushed or published.
1894+
release();
1895+
await vi.waitFor(async () => expect((await mergeState(served.app)).job).toMatchObject({ state: 'failed',
1896+
reason: 'Pre-merge preparation has not completed for the current review. Prepare the merge again.' }), { timeout: 10_000 });
1897+
expect(served.store.getTask(served.identity).status).toBe('in review');
1898+
expect(served.store.recentAttempts(served.identity, 50)).toHaveLength(attempts);
1899+
expect(served.app.publishing!.busy(served.identity)).toBe(false);
1900+
expect(w.github.calls).toEqual(calls);
1901+
expect(w.github.head(served.branch)).toBe(branchHead);
1902+
expect(base.merged).toEqual([]);
1903+
}, 60_000);
1904+
1905+
it('refuses start while a merge job prepares, even after a new plan revision is imported and approved', async () => {
1906+
const w = world(); mergeable(w);
1907+
let storeRef: Store | null = null, release!: () => void, preparing = false;
1908+
const held = new Promise<void>(resolve => { release = resolve; });
1909+
const gh = gateway(() => storeRef!, () => []);
1910+
const served = await serve(w, { before: async service => { completeAll(service); await acceptAndApprove(service); }, issueGateway, mergeGateway: gh, runnerPublished: true,
1911+
// A preparation held until the test releases it; it then fails, as a real one does once the review changed under it.
1912+
preMerge: service => ({
1913+
get active() { return preparing; }, get last() { return null; }, assertStartable() {}, settlePendingPush: async () => null,
1914+
cancelTask: () => 'closed' as const, close: async () => undefined,
1915+
start: async (expected: { actionId: string }) => {
1916+
preparing = true;
1917+
await held;
1918+
preparing = false;
1919+
const identity = service.config.identity, snapshot = service.store.getSnapshot(identity);
1920+
return service.store.settlePreMergeAction(identity, expected.actionId,
1921+
{ state: 'failed', base: snapshot.base, head: snapshot.head, checked: [], reason: 'The review changed during preparation.' }, null);
1922+
},
1923+
} as unknown as PreMergeCoordinator) });
1924+
storeRef = served.store; createIdentity = () => served.identity;
1925+
await publishSettled(served.app, served.identity);
1926+
expect((await merge(served.app, (await review(served.app)).token)).status).toBe(200);
1927+
await vi.waitFor(async () => { expect(preparing).toBe(true); expect((await mergeState(served.app)).job).toMatchObject({ state: 'running', step: 'preparing' }); }, { timeout: 10_000 });
1928+
const plan = served.store.getPlan(served.identity);
1929+
const imported = await fetch(`${new URL(served.app.url).origin}/api/plan/import`, { method: 'POST', headers: { 'x-codeboost-token': served.app.token, 'content-type': 'application/json' },
1930+
body: JSON.stringify({ source: JSON.stringify(plan), format: 'json', expectedRevision: plan.revision, actionId: randomUUID() }) });
1931+
expect(imported.status).toBe(200);
1932+
await acceptAndApprove(served.app.service);
1933+
const calls = [...w.github.calls], attempts = served.store.recentAttempts(served.identity, 50).length;
1934+
expect(await view(served.app)).toMatchObject({ startable: false });
1935+
expect(await act(served.app, 'start')).toMatchObject({ status: 409, body: { error: 'A merge is running for this task; wait for it to end or cancel the task.' } });
1936+
expect(served.store.getTask(served.identity).status).toBe('in review');
1937+
expect(served.store.recentAttempts(served.identity, 50)).toHaveLength(attempts);
1938+
release();
1939+
await vi.waitFor(async () => expect((await mergeState(served.app)).job).toMatchObject({ state: 'failed' }), { timeout: 10_000 });
1940+
expect(w.github.calls).toEqual(calls);
1941+
expect(gh.merged).toEqual([]);
1942+
}, 60_000);
1943+
18471944
it('admits issue trust before a merge job starts: an untrusted click is refused and replayed, a failed read saves nothing', async () => {
18481945
const w = world(); mergeable(w);
18491946
let storeRef: Store | null = null, access: 'untrusted' | 'unreadable' | 'trusted' = 'trusted', reads = 0, prepared = 0;

‎web/server.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -220,6 +220,9 @@ export async function startServer(config: ReviewConfig, port = 4318, questionAge
220220
if (executor.busy(identity)) throw new GuardRefusal('An earlier run of this task is still finishing; try again when that run has ended.');
221221
// A publish reads the task head and pushes it; a new item must not move it meanwhile.
222222
if (publishing?.busy(identity)) throw new GuardRefusal('A pull request is being published for this task; try again when it has finished.');
223+
// A merge job prepares, waits for checks and merges the PR's head. A run would move that head, and its end publishes
224+
// (pushes the head, refreshes the PR) under the job. Before owed work too: settling it ends in the same publish.
225+
if (mergeJobs?.active) throw new GuardRefusal('A merge is running for this task; wait for it to end or cancel the task.');
223226
// Recovery owns this claim for Resume even when owed work will settle instead of admitting an item. Start must not
224227
// consume it and strand the task behind the resulting human gate.
225228
if (action === 'start' && task.requeuePending) throw new GuardRefusal('Recovery left this task to requeue; it cannot start until Resume resolves that claim.');

0 commit comments

Comments
 (0)