Skip to content

Commit 5c65b50

Browse files
authored
Merge pull request #20 from d3cker/codex/retry-pr-head-propagation
Retry PR publication while GitHub catches up with the pushed commit
2 parents 5991204 + a0afbc8 commit 5c65b50

9 files changed

Lines changed: 155 additions & 30 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,11 @@ include the full version, for example `## 0.7.0-beta.1`.
1818

1919
### Fixed
2020

21+
- Retry PR head propagation after a successful push when the remote branch still
22+
matches the verified commit. Preserve a durable push checkpoint across restarts,
23+
avoid repeating acknowledged pushes, and distinguish closed PRs from changed
24+
branches while preserving manual description edits.
25+
2126
- Keep repository inventory RPC responses valid JSON when an owner has no runtime
2227
snapshots. Isolate setup-test registries so validation never adds fixture
2328
repositories to the operator's inventory.

‎docs/advanced.md‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -239,8 +239,10 @@ The monitor reports task maintenance until closure completes.
239239

240240
Task state stores `completion` (final public text or an explicit unavailable
241241
reason, session, round, then verified commit and checks), `initialCompletion`,
242-
and `publishedBody` (the last acknowledged managed section). New rounds clear
243-
only the current completion. Older verifying/publishing tasks recover missing
242+
`publishedBody` (the last acknowledged managed section), and `pushedCommit` (the
243+
successfully pushed verified SHA). New rounds clear the current completion and
244+
push checkpoint while retaining the original report and published body.
245+
Older verifying/publishing tasks recover missing
244246
summaries from their saved sessions; this does not rerun the model. Missing or
245247
empty successful reports are marked unavailable, while transient reads retry.
246248
Already completed or closed tasks are not bulk rewritten on upgrade.
@@ -251,13 +253,22 @@ replaced; unknown unmarked text is retained with the new section appended, since
251253
it might contain manual edits. A later legacy round may not have enough saved
252254
information to identify its old acknowledgement exactly.
253255

254-
An edited/removed managed section, changed PR head, closed follow-up PR, or oversized
256+
After push, GitHub's PR head can temporarily lag behind its branch ref. Before
257+
description reconciliation and again before PATCH, the plugin reads the remote
258+
branch ref. If it matches the verified SHA but the PR head does not, publication
259+
enters `retry_wait` and retries with the normal backoff, up to `maxAttempts`.
260+
Retries reuse the saved report and verified commit, skipping a push already
261+
recorded in `pushedCommit`, including after a restart. Exhausted retries become
262+
`failed`; inspect the reported SHAs and use `/restartworkflow` after resolving the
263+
problem. An unacknowledged push still uses normal non-force push reconciliation.
264+
265+
An edited/removed managed section, changed remote branch, closed follow-up PR, or oversized
255266
body blocks at `publishing`. Preserve your notes outside the markers and restore
256267
the previous managed section from `publishedBody` in the task checkpoint (or PR
257268
edit history), then use the normal workflow retry. Do not delete the queue or
258269
restart implementation just to retry a description update. If a PATCH succeeded
259270
but its response was lost, matching desired content is accepted without another
260-
write. Body and head are reread before PATCH; edits after that final read cannot
271+
write. Body, PR head and branch ref are reread before PATCH; edits after those reads cannot
261272
be atomically excluded by this implementation.
262273

263274
Each rendered report is limited to 22,000 UTF-8 bytes with an explicit truncation

‎docs/architecture.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@ loads a generic scheduler, a GitHub dispatcher, and a terminal UI component.
3535
changes, bind the report to the verified commit, then push and create or reconcile
3636
the PR with that report and separate dispatcher checks. Generate its title only
3737
if creating a PR without an already-saved title.
38+
Checkpoint successful pushes. Retry a lagging PR head only while the remote
39+
branch matches the verified commit; block actual branch changes or closure.
3840
6. After publication, process queued authorized issue comments as new rounds on
3941
the same worktree and branch, with a new main session and the existing open PR.
4042
After cancellation, use a fresh local branch/worktree from the published head,

‎docs/bot-workflow.md‎

Lines changed: 36 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ flowchart TD
201201
V -->|Failed check or Git consistency guard| VB[verifying / blocked]
202202
VB -->|Operator retries saved stage| V
203203
P --> Done[pr_opened / done with PR and publishedAt]
204+
P -->|Branch matches, PR head not yet updated| Lag[publishing / retry_wait within attempt limit]
205+
Lag -->|Backoff elapsed, reuse saved push| P
204206
P -->|Publication failure| PB[Retain publishing phase and apply error policy]
205207
PB -->|Eligible retry| P
206208
Done -->|Pending authorized feedback| Round[Increment round, move feedback and reset per-round state]
@@ -449,19 +451,27 @@ flowchart TD
449451
Find --> Follow{Follow-up round?}
450452
Follow -->|Yes| Open{Existing PR open?}
451453
Open -->|No| Block
452-
Open -->|Yes| Push[Validate origin, workspace, saved HEAD and clean tree, push exact SHA]
454+
Open -->|Yes| Pushed{Saved pushedCommit matches verified SHA?}
455+
Pushed -->|Yes| Description
456+
Pushed -->|No| Push[Validate origin, workspace, saved HEAD and clean tree, push exact SHA]
453457
Follow -->|No| Exists{PR already exists?}
454458
Exists -->|Yes| Closed{PR closed?}
455459
Closed -->|Yes| Done[Record PR and publication time, pr_opened / done]
456460
Closed -->|No| Description
457461
Exists -->|No| Title[Generate title only if no saved prTitle]
458462
Title --> Issue{Issue still open?}
459463
Issue -->|No| Block
460-
Issue -->|Yes| PushNew[Validate origin and workspace, push exact verified SHA]
461-
PushNew --> Create[Create or reconcile signed PR against pinned base]
462-
Create --> Description[Read open PR at verified SHA, reconcile managed description]
463-
Push --> Description
464-
Description -->|Edited managed block, changed head or oversized body| Block
464+
Issue -->|Yes| NewPushed{Saved pushedCommit matches verified SHA?}
465+
NewPushed -->|Yes| Create
466+
NewPushed -->|No| PushNew[Validate origin and workspace, push exact verified SHA]
467+
PushNew --> SaveNew[Persist pushedCommit]
468+
SaveNew --> Create[Create or reconcile signed PR against pinned base]
469+
Create --> Description[Read open PR and remote branch, reconcile managed description]
470+
Push --> SavePush[Persist pushedCommit]
471+
SavePush --> Description
472+
Description -->|Branch matches, PR head differs| Pending[Retry saved publication with backoff and attempt limit]
473+
Pending --> Retry
474+
Description -->|Closed PR, changed branch, edited managed block or oversized body| Block
465475
Description -->|Unchanged or update succeeds| Acknowledge[Persist published body checkpoint]
466476
Acknowledge --> Done
467477
Failure[Other command, model or transport error] --> Policy[Keep current phase and apply retry policy in section 8]
@@ -473,9 +483,11 @@ flowchart TD
473483
```
474484

475485
Resuming `running` validates the saved session first; retrying `verifying` runs
476-
checks again. Retrying `publishing` uses the saved verified SHA and requires the
477-
worktree still to match it, rather than rerunning checks implicitly. An already
478-
pushed branch does not by itself make a task complete.
486+
checks again. Retrying `publishing` uses the saved verified SHA without rerunning
487+
checks implicitly. If a push is still required, the worktree must still match
488+
that SHA. After a checkpointed push, description reconciliation checks GitHub's
489+
branch and PR instead; it does not publish later local edits. An already pushed
490+
branch does not by itself make a task complete.
479491

480492
The configured checks are command argument arrays. A failing configured check
481493
produces `blocked`. With no configured checks, only Git consistency checks run;
@@ -498,9 +510,21 @@ follow-ups. Dispatcher checks appear separately from agent-reported tests, follo
498510
by `Closes #N`, session, round and verified commit. Push uses
499511
`COMMIT:refs/heads/TASK_BRANCH` without force. The first publication reconciles an
500512
existing branch PR without another push; follow-ups require an open PR and push
501-
the new verified commit before updating its description. The title is retained.
513+
the new verified commit before updating its description. A successful push saves
514+
`pushedCommit`; retries skip that push when it matches the verified SHA, including
515+
after an owner restart. New rounds clear this checkpoint. If push succeeded but
516+
its response or checkpoint was lost, normal non-force push reconciliation still
517+
applies. The title is retained.
502518
An already closed first-round PR is recorded without editing its description.
503519

520+
Before reconciling the description and again before PATCH, compare the remote
521+
branch ref with the verified SHA. If the branch matches but the PR head is stale,
522+
`PullHeadPending` uses the normal backoff and `maxAttempts` policy at `publishing`.
523+
It does not rerun implementation, verification, or a checkpointed push. A closed
524+
PR or different branch SHA blocks with a distinct error; a stale PR view is not
525+
permission to overwrite a changed branch. The guard also checks the branch when
526+
the PR view already reports the expected SHA.
527+
504528
A stable HTML marker pair encloses the bot-managed description. Notes outside
505529
it are preserved; an edited or removed managed section blocks publication rather
506530
than overwriting it. The last acknowledged body is checkpointed, so a lost update
@@ -666,9 +690,9 @@ flowchart TD
666690
Result -->|WaitingForAnswer| Wait[waiting, or ready if answer already arrived]
667691
Result -->|SessionStopped| Stop[running / blocked, sessionStopped true]
668692
Result -->|Other Blocked, description conflict or GitHub 401, 404, 422| Block[blocked at saved phase]
669-
Result -->|Other failure below attempt limit| Retry[retry_wait at saved phase]
693+
Result -->|PR head propagation or other failure below attempt limit| Retry[retry_wait at saved phase]
670694
Retry -->|nextAt elapsed| Work
671-
Result -->|Other failure at limit| Fail[failed at saved phase]
695+
Result -->|PR head propagation or other failure at limit| Fail[failed at saved phase]
672696
Stop --> Probe[On available worker pass, probe due saved session without unresolved question]
673697
Legacy[Recognized legacy timeout or outcome block] --> Probe
674698
Probe --> Complete{Matching location and task marker, succeeded outcome and valid final assistant?}

‎docs/runtime.md‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -431,6 +431,14 @@ durable as before.
431431

432432
## PR descriptions
433433

434+
After pushing a verified commit, GitHub may briefly show the previous commit in
435+
the PR. If the remote branch already matches the verified commit, the bot waits
436+
and automatically retries publication within its configured attempt limit. It
437+
keeps the saved report and does not repeat implementation or a checkpointed push.
438+
A changed remote branch or closed PR produces a separate blocking error. If the
439+
propagation retries are exhausted, inspect the error and use `/restartworkflow`;
440+
see [description recovery](advanced.md#pr-description-recovery).
441+
434442
The PR contains the agent's final completion summary from the successful session,
435443
with Markdown preserved, followed by dispatcher verification, the issue reference,
436444
session, round and verified commit. The initial issue acknowledgement is not a

‎src/dispatcher.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -44,7 +44,7 @@ export const Task = z.object({
4444
source: z.enum(["issue", "comment"]).optional(),
4545
feedback: z.array(Comment).optional(), pendingFeedback: z.array(Comment).optional(), commentCursor: z.number().optional(),
4646
previousSessionID: z.string().optional(),
47-
checks: z.array(z.string()).optional(), commit: z.string().optional(),
47+
checks: z.array(z.string()).optional(), commit: z.string().optional(), pushedCommit: z.string().optional(),
4848
publishedAt: z.number().optional(), merged: z.boolean().optional(), mergeError: z.string().optional(), mergeNextAt: z.number().optional(),
4949
completion: CompletionSummary.optional(), initialCompletion: CompletionSummary.optional(),
5050
publishedBody: z.string().optional(),
@@ -268,7 +268,7 @@ export class Dispatcher {
268268
} : {}), round: (finished.round ?? 1) + 1, feedback: finished.pendingFeedback, pendingFeedback: [], previousSessionID: finished.sessionID,
269269
phase: "queued", status: "ready", attempts: 0, nextAt: this.now(), analysis: undefined, commentID: undefined,
270270
analysisDecision: undefined, analysisDialogue: undefined, question: undefined,
271-
sessionID: undefined, sessionReady: false, promptAttempted: false, sessionStopped: undefined, recovery: undefined, completion: undefined, checks: undefined, commit: undefined, error: undefined });
271+
sessionID: undefined, sessionReady: false, promptAttempted: false, sessionStopped: undefined, recovery: undefined, completion: undefined, checks: undefined, commit: undefined, pushedCommit: undefined, error: undefined });
272272
await this.store.save(this.queue);
273273
});
274274
const resumable = this.queue.tasks.filter(t => ["ready", "retry_wait"].includes(t.status));
@@ -355,11 +355,16 @@ export class Dispatcher {
355355
const body = renderDescription(task.key, task.issue.number, task.initialCompletion!, task.completion!);
356356
let pr = await this.github.findPull(task.repo, task.branch);
357357
if (followup && (!pr || pr.state !== "open")) throw new Blocked("The original PR is no longer open; changes remain in the worktree");
358-
if (followup && pr) await this.executor.push(task, repo);
358+
const push = async (repository: Repository) => {
359+
if (task.pushedCommit === task.commit) return;
360+
await this.executor.push(task, repository);
361+
await this.update(task, { pushedCommit: task.commit });
362+
};
363+
if (followup && pr) await push(repo);
359364
if (!pr) {
360365
if (!task.prTitle) await this.update(task, { prTitle: await this.executor.title(task) });
361366
if ((await this.github.issue(task.repo, task.issue.number)).state !== "open") throw new Blocked("Issue closed before PR publication");
362-
await this.executor.push(task, repo);
367+
await push(repo);
363368
pr = await this.github.ensurePull(task.repo, task.branch, repo.baseBranch, task.prTitle!, body);
364369
}
365370
if (pr.state === "open") {

‎src/github.ts‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ export type Pull = z.infer<typeof Pull>;
1616
export class GithubError extends Error {
1717
constructor(readonly status: number, readonly retryAt?: number) { super(`GitHub HTTP ${status}`); }
1818
}
19+
export class PullHeadPending extends Error {}
1920
export class Github {
2021
private login?: string;
2122
constructor(private token: string, private signal: AbortSignal, private fetcher: typeof fetch = fetch, private signature?: string) {}
@@ -71,18 +72,26 @@ export class Github {
7172
return Pull.parse(await this.request(`/repos/${repo}/pulls`, "POST", { head: branch, base, title, body: signed }));
7273
}
7374
async updatePullBody(repo: string, number: number, commit: string, key: string, body: string, previous?: string, legacy?: string) {
74-
const schema = z.object({ state: z.string(), head: z.object({ sha: z.string() }), body: z.string().nullable() });
75+
const schema = z.object({ state: z.string(), head: z.object({ sha: z.string(), ref: z.string() }), body: z.string().nullable() });
7576
const read = async () => schema.parse(await this.request(`/repos/${repo}/pulls/${number}`));
77+
const requireHead = async (pr: z.infer<typeof schema>) => {
78+
if (pr.state !== "open") throw new DescriptionConflict(`PR #${number} is closed. Inspect it before retrying publication.`);
79+
const ref = z.object({ object: z.object({ sha: z.string() }) }).parse(
80+
await this.request(`/repos/${repo}/git/ref/heads/${encodeURIComponent(pr.head.ref)}`));
81+
if (ref.object.sha !== commit) throw new DescriptionConflict(`PR #${number} branch changed: expected ${commit}, found ${ref.object.sha}. Inspect it before retrying publication.`);
82+
if (pr.head.sha !== commit) throw new PullHeadPending(`Waiting for GitHub PR #${number} to reflect pushed commit ${commit}; its branch matches, but the PR reports ${pr.head.sha}. Publication will retry automatically within the configured attempt limit.`);
83+
};
7684
const current = await read();
77-
if (current.state !== "open" || current.head.sha !== commit) throw new DescriptionConflict("PR is closed or its head differs from the verified commit. Inspect it before retrying publication.");
85+
await requireHead(current);
7886
const signedLegacy = legacy === undefined ? undefined : await this.signed(legacy);
7987
let next = mergeDescription(current.body ?? "", key, body, previous, signedLegacy);
8088
// Sign a new body or an exact legacy replacement; retain existing signatures elsewhere.
8189
if (!(current.body ?? "").includes(body) && (!current.body || current.body === signedLegacy)) next = await this.signed(next);
8290
assertDescriptionSize(next);
8391
if (next === current.body) return;
8492
const fresh = await read();
85-
if (fresh.state !== "open" || fresh.head.sha !== commit || fresh.body !== current.body) throw new DescriptionConflict("PR changed while its description was being prepared. Retry after inspecting concurrent edits.");
93+
await requireHead(fresh);
94+
if (fresh.body !== current.body) throw new DescriptionConflict("PR description changed while its update was being prepared. Retry after inspecting concurrent edits.");
8695
await this.request(`/repos/${repo}/pulls/${number}`, "PATCH", { body: next });
8796
}
8897
async mergeApproved(repo: string, number: number, commit: string, since: number, authors: string[], options: GithubOptions["autoMerge"]): Promise<boolean> {

0 commit comments

Comments
 (0)