Skip to content

Commit 46bbeba

Browse files
mchwangclaude
andcommitted
Address Copilot round 7 on F2d: marker line only, draft flag repair, recovery draft reconcile
- A PR's marker is read only from its description's first line; a marker-shaped string in plan text or problems no longer identifies, or blocks, anything. - When publish sees the task's PR, it corrects the recorded draft flag from GitHub under the state-version guard, so a draft change whose record was lost is repaired. - Recovering a lost draft opening turns a PR that was made ready meanwhile back into a draft before confirming it; a failure keeps the opening owned. - AGENTS.md: markers only from their reserved position; correct owned fields from the observed external record. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent fa037c9 commit 46bbeba

6 files changed

Lines changed: 85 additions & 16 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,8 @@ Every reproduced race requires a failing-before and passing-after regression. As
9999
- Order an operation's external writes so that any step the remote can definitely refuse comes before the writes that cannot be taken back. A refusal after a push or a description change leaves a half-updated record.
100100
- Correlate retry observations to the current attempt with an immutable external identity or event boundary, and fail closed when multiple post-boundary action sequences appear. Matching only the resource or commit identity can replay another attempt's terminal event.
101101
- When recovery looks for the result of an earlier attempt, recognise the identities of all earlier attempts, abandoned ones included. A result that appears after its attempt was abandoned must be adopted, not treated as foreign, or recovery can never settle.
102+
- Read an identity marker only from its reserved position (for example the first line of a description). Text around it may be agent-controlled, so a marker-shaped string elsewhere must never identify or disqualify a record.
103+
- When the external record is observed, correct the local copy of any field the operation owns (such as a draft flag) from it. A change that landed but whose confirmation was lost is otherwise never repaired, because the next run sees nothing left to change.
102104
- Make an idempotency key required at the API boundary for every replayable action, and look up its saved outcome before any other guard, including in-flight, validation and coordinator shutdown guards. The one exception is the server's HTTP 503 during shutdown, which applies nothing; the client must keep the key and resend it. Save every definite outcome under the key (refusals before admission too), keep the saved response current with the durable outcome it reports, and replay failures as failures with complete result fields. Only a passing, nothing-applied outcome (shutdown, abort, deadline, storage error) stays resendable.
103105
- When a refusal must also change durable state (for example, handing an expired task to a person), commit that change outside the refused transaction, together with the saved refusal. Never write it inside the transaction the refusal rolls back.
104106

‎docs/implementation/pull-request-opening.md‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
| Own PR | A PR that codeboost opened for this task, identified by repository and number. |
2121
| Own commit | A commit in the task's ledger with origin `owned`. |
2222
| Opening | The Store record written just before the GitHub call that opens a PR. Its state is `opening`, `opened` or `abandoned`. |
23-
| Marker | The HTML comment `<!-- codeboost:opening=<opening ID> -->` at the top of the PR description. |
23+
| Marker | The HTML comment `<!-- codeboost:opening=<opening ID> -->` that is the PR description's first line. Only that line identifies the PR; a marker-shaped string anywhere else (plan text, problems) is ignored. |
2424
| Publish | `PullRequestPublisher.publish` in `runner/publish.ts`: the check, push, and open (or reuse) steps together. |
2525

2626
## The check
@@ -50,9 +50,9 @@ A cancelled check throws. It does not return `unknown`.
5050

5151
Only one publish runs per task at a time; a second one is refused. A publish whose signal is already aborted changes nothing. Publish runs these steps in order:
5252

53-
1. **Recover.** If an opening is still `opening`, look for the open PR from the task branch, with the markers of all the task's openings for that branch. If it has this opening's marker, record it as opened. If it has another opening's marker, this opening created nothing (one open PR per branch): mark it `abandoned` and continue. If none exists, the request may still be in flight or not yet visible. So publish stops with `OpeningUnsettled` until the opening is 10 minutes old (`settleMs`). After that, it marks the opening `abandoned` and continues.
53+
1. **Recover.** If an opening is still `opening`, look for the open PR from the task branch, with the markers of all the task's openings for that branch. If it has this opening's marker, record it as opened; if this was a draft opening and the PR has since been made ready, turn it back into a draft first (a failure keeps the opening owned). If it has another opening's marker, this opening created nothing (one open PR per branch): mark it `abandoned` and continue. If none exists, the request may still be in flight or not yet visible. So publish stops with `OpeningUnsettled` until the opening is 10 minutes old (`settleMs`). After that, it marks the opening `abandoned` and continues.
5454
2. **Status and no changes.** Refuse unless the task is running (or in needs human, for a draft). If the task head is its base, open nothing. A running task moves to needs human.
55-
3. **Find the branch PR.** Ask GitHub for the branch's open PR every time, with the markers of the task's opened and abandoned openings for that branch (none if the task has no PR yet). An open PR that carries none of them was not opened by codeboost: publish refuses before anything is pushed. A PR with an opened record's marker but another number is refused too. This comes before the check: an abandoned opening's PR links the issue and has no recorded number, so only its marker shows it is the task's own, and its number is added to the own PRs for the check.
55+
3. **Find the branch PR.** Ask GitHub for the branch's open PR every time, with the markers of the task's opened and abandoned openings for that branch (none if the task has no PR yet). An open PR that carries none of them was not opened by codeboost: publish refuses before anything is pushed. A PR with an opened record's marker but another number is refused too. When the PR's draft state on GitHub differs from the record, the record is corrected here (for example after a draft change whose record was lost), under the task's state-version guard. This comes before the check: an abandoned opening's PR links the issue and has no recorded number, so only its marker shows it is the task's own, and its number is added to the own PRs for the check.
5656
4. **Check.** Run the check. Record the result, and any status change, in one transaction. That transaction refuses if the task changed during the check.
5757
5. **Push.** When the task already has an open PR, the refresh is recorded first (the push moves that PR's head), then the push runs; otherwise the push runs straight after the check's transaction with no await in between. Push the task head to `codeboost/issue-<issue>-<task slug>-<hash>`. The slug is readable but can collide. The hash is 16 hex characters of SHA-256 over the exact task identity, so two tasks never share a branch.
5858
6. **Re-read.** Right before the GitHub call, the Store confirms that the latest check is clear and that nothing changed since that check: same task state version, same review version (approvals, choices and notes), same snapshot, same head.

‎github/pull-requests.ts‎

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ async function draftCall<T>(call: () => Promise<T>): Promise<T> {
4242
throw error;
4343
}
4444
}
45+
/**
46+
* A PR's marker is its description's first line and nothing else. Plan text and problems later in the description are
47+
* agent-controlled, so a marker-shaped string there never identifies a PR.
48+
*/
49+
export const markerOf = (body: string): string => body.split('\n', 1)[0]!.trim();
4550
/** GitHub updates a PR's head a moment after a push; the read-back waits up to this many polls for the pushed head. */
4651
export const HEAD_POLLS = 5, HEAD_POLL_MS = 500;
4752

@@ -87,12 +92,12 @@ export class GhPullRequestGateway implements PullRequestGateway {
8792

8893
async open(input: OpenPullRequestInput, signal?: AbortSignal): Promise<OpenedPullRequest> {
8994
this.#validate(input);
90-
if (!input.body.includes(input.marker)) throw new Error('The pull request description must carry its marker.');
95+
if (markerOf(input.body) !== input.marker) throw new Error('The pull request description must start with its marker.');
9196
const post = () => this.#json(['api', '-X', 'POST', '-H', 'Accept: application/vnd.github+json', `repos/${this.repository}/pulls`], signal,
9297
{ title: input.title, body: input.body, head: input.headBranch, base: input.base, draft: input.draft });
9398
const response = input.draft ? await draftCall(post) : await post();
9499
const { body, ...pr } = this.#pull(response, input);
95-
if (!body.includes(input.marker)) throw new Error('GitHub returned a pull request without its marker.');
100+
if (markerOf(body) !== input.marker) throw new Error('GitHub returned a pull request without its marker.');
96101
return pr;
97102
}
98103

@@ -105,18 +110,18 @@ export class GhPullRequestGateway implements PullRequestGateway {
105110
if (!Array.isArray(response) || response.length > 1) throw new Error('GitHub returned an invalid pull request list.');
106111
if (!response.length) return null;
107112
const { body, ...pr } = this.#pull(response[0], input);
108-
const found = input.markers.filter(marker => body.includes(marker));
113+
const found = input.markers.filter(marker => markerOf(body) === marker);
109114
if (found.length !== 1) throw new Error(`An open pull request from ${input.headBranch} exists that codeboost did not open.`);
110115
return { ...pr, marker: found[0]! };
111116
}
112117

113118
async refresh(number: number, input: OpenPullRequestInput & { ready: boolean; headSha?: string }, signal?: AbortSignal): Promise<OpenedPullRequest> {
114119
this.#validate(input);
115120
if (!Number.isSafeInteger(number) || number < 1) throw new Error('Invalid pull request number.');
116-
if (!input.body.includes(input.marker)) throw new Error('The pull request description must carry its marker.');
121+
if (markerOf(input.body) !== input.marker) throw new Error('The pull request description must start with its marker.');
117122
const patched = this.#pull(await this.#json(['api', '-X', 'PATCH', '-H', 'Accept: application/vnd.github+json', `repos/${this.repository}/pulls/${number}`], signal,
118123
{ title: input.title, body: input.body }), input);
119-
if (patched.number !== number || !patched.body.includes(input.marker)) throw new Error('GitHub returned a different pull request.');
124+
if (patched.number !== number || markerOf(patched.body) !== input.marker) throw new Error('GitHub returned a different pull request.');
120125
// A ready PR whose task went back to needs human becomes a draft again; a draft whose task is ready leaves draft.
121126
if (input.ready && patched.draft) await this.run(['pr', 'ready', String(number), '--repo', this.repository], { signal });
122127
else if (input.draft && !patched.draft) await draftCall(() => this.run(['pr', 'ready', String(number), '--undo', '--repo', this.repository], { signal }));
@@ -144,7 +149,7 @@ export class GhPullRequestGateway implements PullRequestGateway {
144149
async #readBack(number: number, input: { base: string; headBranch: string; marker: string }, done: (pr: OpenedPullRequest) => boolean, signal?: AbortSignal): Promise<OpenedPullRequest> {
145150
for (let poll = 1; ; poll++) {
146151
const { body, ...pr } = this.#pull(await this.#json(['api', '-H', 'Accept: application/vnd.github+json', `repos/${this.repository}/pulls/${number}`], signal), input);
147-
if (pr.number !== number || !body.includes(input.marker)) throw new Error('GitHub returned a different pull request.');
152+
if (pr.number !== number || markerOf(body) !== input.marker) throw new Error('GitHub returned a different pull request.');
148153
if (done(pr) || poll >= HEAD_POLLS) return pr;
149154
await new Promise<void>((resolve, reject) => {
150155
signal?.throwIfAborted();

‎runner/publish.ts‎

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -96,6 +96,10 @@ export class PullRequestPublisher {
9696
const live = await this.#pulls.findOpened({ base: this.#config.baseBranch, headBranch: branch, markers: candidates.map(pr => marker(pr.openingId)) }, signal);
9797
signal?.throwIfAborted();
9898
const earlier = live ? candidates.find(pr => marker(pr.openingId) === live.marker)! : undefined;
99+
// What GitHub shows is the truth for the draft flag: a draft change whose record was lost is repaired here.
100+
let stateVersion = task.stateVersion;
101+
if (earlier && live && earlier.state === 'opened' && earlier.number === live.number && earlier.draft !== live.draft)
102+
stateVersion = this.#store.recordPullRequestDraft(identity, earlier.openingId, live.number, live.draft, stateVersion);
99103
const own = new Set(prs.filter(pr => pr.number !== null && pr.repository.toLowerCase() === this.#config.repository.toLowerCase()).map(pr => pr.number!));
100104
if (live) own.add(live.number);
101105
const result = await this.#checks.check({
@@ -111,15 +115,15 @@ export class PullRequestPublisher {
111115
// It is still a GitHub change for this task, so the task is re-read first: a reassignment or review during the check
112116
// means this publish is stale and must not touch the current generation's PR.
113117
const needsDraft = result.outcome !== 'clear' && earlier && live && !live.draft;
114-
if (needsDraft) this.#store.assertUnchangedSince(identity, { stateVersion: task.stateVersion, reviewVersion, snapshotId: snapshot.id, draft });
118+
if (needsDraft) this.#store.assertUnchangedSince(identity, { stateVersion, reviewVersion, snapshotId: snapshot.id, draft });
115119
let drafted = null, leftReady: number | undefined;
116120
if (needsDraft) {
117121
try { drafted = await this.#pulls.markDraft(live.number, { base: this.#config.baseBranch, headBranch: branch, marker: marker(earlier.openingId) }, signal); }
118122
catch (error) { if (!(error instanceof DraftsUnsupported)) throw error; leftReady = live.number; }
119123
}
120124
signal?.throwIfAborted();
121-
const check = this.#store.recordAlreadyFixed(identity, task.stateVersion, { snapshotId: snapshot.id, draft, result });
122-
if (drafted && earlier!.state === 'opened') this.#store.recordPullRequestDraft(identity, earlier!.openingId, drafted.number, drafted.draft);
125+
const check = this.#store.recordAlreadyFixed(identity, stateVersion, { snapshotId: snapshot.id, draft, result });
126+
if (drafted && earlier!.state === 'opened') this.#store.recordPullRequestDraft(identity, earlier!.openingId, drafted.number, drafted.draft, check.stateVersion);
123127
const ready = leftReady === undefined ? {} : { leftReady };
124128
if (result.outcome !== 'clear') return draft ? { kind: 'draft skipped', result, ...ready } : { kind: 'possibly already fixed', result, ...ready };
125129
if (earlier && live) {
@@ -202,7 +206,19 @@ export class PullRequestPublisher {
202206
this.#store.abandonPullRequestOpening(identity, lost.openingId);
203207
return null;
204208
}
205-
const status = this.#store.recordPullRequestOpened(identity, lost.openingId, pr);
206-
return { kind: 'opened', number: pr.number, url: pr.url, draft: pr.draft, status };
209+
// A lost draft opening must end as a draft: if the PR was made ready meanwhile, turn it back before confirming. Any
210+
// failure keeps the opening owned (the next publish retries); drafts being unsupported is definite, so the PR is
211+
// recorded as it is and reported.
212+
let found: { number: number; url: string; headSha: string; draft: boolean } = pr;
213+
if (lost.draft && !pr.draft) {
214+
try { found = await this.#pulls.markDraft(pr.number, { base: lost.base, headBranch: lost.headBranch, marker: marker(lost.openingId) }, signal); }
215+
catch (error) {
216+
if (!(error instanceof DraftsUnsupported)) throw error;
217+
this.#store.recordPullRequestOpened(identity, lost.openingId, pr);
218+
return { kind: 'draft unsupported', number: pr.number };
219+
}
220+
}
221+
const status = this.#store.recordPullRequestOpened(identity, lost.openingId, found);
222+
return { kind: 'opened', number: found.number, url: found.url, draft: found.draft, status };
207223
}
208224
}

‎runner/store.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1075,12 +1075,19 @@ export class Store {
10751075
});
10761076
}
10771077
/** Records that the task's open PR is now a draft (after a check matched). The task status does not change. */
1078-
recordPullRequestDraft(identity: PlanIdentity, openingId: string, number: number, draft: boolean): void {
1078+
/**
1079+
* Records the draft state GitHub shows for the task's open PR. It also repairs a record whose draft change landed on
1080+
* GitHub but was never recorded (a crash or cancel right after the call). Guarded by the state version the caller
1081+
* read, so a task change is still noticed; returns the new state version.
1082+
*/
1083+
recordPullRequestDraft(identity: PlanIdentity, openingId: string, number: number, draft: boolean, expectedStateVersion: number): number {
10791084
const key = identityKey(identity);
1080-
this.#transaction(() => {
1085+
return this.#transaction(() => {
1086+
if (this.#task(key).state_version !== expectedStateVersion) throw new GuardRefusal('Stale task state. Reload before writing.');
10811087
if (this.#run("UPDATE task_pull_requests SET draft=?, updated_at=? WHERE plan_key=? AND opening_id=? AND state='opened' AND number=?",
10821088
draft ? 1 : 0, new Date().toISOString(), key, openingId, number).changes !== 1) throw new GuardRefusal('Unknown pull request.');
10831089
this.#touch(key);
1090+
return this.#task(key).state_version as number;
10841091
});
10851092
}
10861093
/** Recovery found no PR for an opening whose outcome was lost; a new check and opening follow. */

0 commit comments

Comments
 (0)