Skip to content

Commit f5859f4

Browse files
mchwangclaude
andcommitted
Close the xhigh review findings on F2d: own merged PR, drafts unsupported, refresh ordering
- A close by the task's own PR or commit, and the task's own merged PR, now count as already fixed; only its own open PR is excluded. - A repository without draft PRs: GitHub's refusal becomes DraftsUnsupported, a definite outcome. Opening drops the opening, refresh drops the pending update, and a matching check reports the ready PR it could not draft (leftReady). No loops, no ready PR for a needs-human task. - The refresh is recorded before the push that moves the open PR's head, so a task change during the push cannot strand a half-updated PR; the new-PR path keeps the guard after the push. - gh gets the Windows variables it needs; GH_PAGER is empty there. - Commit subjects are cut without splitting a surrogate pair, through a shared core/text.ts; the GitHub adapters share github/validate.ts. - markDraft changes the PR straight away and reads it back once. - recordPullRequestOpened is split from recordRefreshConfirmed. - Test Stores are closed after each test. - AGENTS.md: exclusions only in the states they are for; record in-flight ownership before an operation's first external write. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 0be7147 commit f5859f4

12 files changed

Lines changed: 239 additions & 81 deletions

File tree

‎AGENTS.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -67,6 +67,7 @@ Every reproduced race requires a failing-before and passing-after regression. As
6767
- Align subprocess output limits with every payload the schema accepts, or tighten the upstream page and field bounds; valid bounded input must not fail only because the transport budget is smaller.
6868
- Pass text whose size follows user or agent input to a subprocess on stdin, never as an argument: the OS limits one argument's size and cannot pass a NUL, so valid bounded input can fail to spawn.
6969
- Exclude the subject of a duplicate or supersession check by stable identity only. A shared branch name or other mutable attribute does not prove two records are the same subject.
70+
- Exclude the subject's own records only in the states the exclusion is for. A check that skips its own open PR must still count its own merged PR, or its own close of the issue, as done.
7071
- Preserve repository identity with pull request numbers in cross-reference scans. Never resolve or exclude a repository-qualified reference by number alone.
7172
- When a relation can be added and removed (a manually linked PR, a label, an assignment), replay its add and remove events in order and count only its latest state. An add event alone does not prove the relation still holds.
7273
- After the final asynchronous external validation, re-read the local generation immediately before an irreversible action. A generation check performed before that await is insufficient.
@@ -94,6 +95,7 @@ Every reproduced race requires a failing-before and passing-after regression. As
9495
- When a durable external-action attempt is bound to an older snapshot, require approvals or evidence recorded against the replacement generation before another action, whether or not the prior outcome explicitly requested fresh review. A mismatch with the old context is not itself fresh review.
9596
- If the external lifecycle mechanism or mode changes between validation passes, abort before the irreversible command. Create durable lifecycle ownership from the final stable mode, never from an earlier observation.
9697
- When an irreversible command has an ambiguous timeout, cancellation, transport, or unknown outcome, retain durable in-flight ownership and reconcile external state before enabling retry. Only a confirmed refusal may become retryable failure.
98+
- Record in-flight ownership before the first external write of an operation, not before a later step: when a push moves an open PR's head, the refresh it belongs to is already in flight.
9799
- 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.
98100
- 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.
99101
- 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.

‎core/pull-request-body.ts‎

Lines changed: 1 addition & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Plan } from './plan.ts';
2+
import { cutText as cut } from './text.ts';
23

34
/** GitHub refuses a PR description longer than 65,536 characters; stay below it with room for the frame. */
45
export const MAX_BODY = 60_000;
@@ -27,13 +28,6 @@ export function fenced(text: string): string {
2728
export function neutralizeReferences(text: string): string {
2829
return text.replace(/#(?=\d)/g, '#').replace(/\b(GH)-(?=\d)/gi, '$1‑').replace(/\/(issues|pull)\/(?=\d)/gi, '/$1∕');
2930
}
30-
/** Cut to at most `max` UTF-16 units (the unit every length bound here counts), never inside a surrogate pair. */
31-
function cut(text: string, max: number): string {
32-
if (text.length <= max) return text;
33-
let end = max - 1;
34-
if (/[\ud800-\udbff]/.test(text[end - 1] ?? '')) end--;
35-
return `${text.slice(0, end)}…`;
36-
}
3731

3832
function planText(plan: Plan, full: boolean): string {
3933
return plan.items.map(item => {

‎core/text.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
/** Cut to at most `max` UTF-16 units (the unit every length bound here counts), never inside a surrogate pair. */
2+
export function cutText(text: string, max: number): string {
3+
if (text.length <= max) return text;
4+
let end = max - 1;
5+
if (/[\ud800-\udbff]/.test(text[end - 1] ?? '')) end--;
6+
return `${text.slice(0, end)}…`;
7+
}

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

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -29,8 +29,8 @@ The check matches when any of these is true:
2929

3030
| Signal | Source | Not a match |
3131
|---|---|---|
32-
| Something other than this task closed the issue. | The issue state and its latest close event (GraphQL). The closer is a PR, a commit, or a Projects workflow (closed by the project, so a match). | Closed by an own PR or an own commit. A reopened issue. |
33-
| Another open or merged PR links to the issue. | Cross-reference events, and manual links: "connected" and "disconnected" events replayed in order. | Own PRs, matched by repository and number. Closed, unmerged PRs. A manual link whose latest event is a disconnect. |
32+
| The issue is closed. | The issue state and its latest close event (GraphQL). The closer is a PR, a commit, or a Projects workflow. A close by the task's own PR or own commit also counts: it means that PR merged, so the fix is already in. | A reopened issue. |
33+
| Another open or merged PR links to the issue. | Cross-reference events, and manual links: "connected" and "disconnected" events replayed in order. | The task's own open PRs, matched by repository and number (its own merged PR is a match). Closed, unmerged PRs. A manual link whose latest event is a disconnect. |
3434
| A new commit on the base branch mentions the issue. | The commits from the task's base to the current base branch head. | Own commits. `#123` when the issue is `#12`. `other/repo#12`. |
3535

3636
A commit mentions the issue with `#12`, `GH-12`, `owner/repo#12`, or the issue URL. A PR in another repository that links the issue counts as a match. It is not excluded by number, because its number belongs to another repository.
@@ -54,7 +54,7 @@ Only one publish runs per task at a time; a second one is refused. A publish who
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.
5555
3. **Find the earlier PR.** If the task has an opened or abandoned opening on the same branch, ask GitHub for the branch's open PR and which opening's marker it carries. A PR with an opened record's marker but another number is refused here, before the push. 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.
57-
5. **Push.** Push, straight after the check's transaction with no await in between, 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.
57+
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.
5959
7. **Open or reuse.** Open a new PR, or update the open earlier PR (found in step 3 with the markers of every earlier opening, abandoned ones included; an abandoned opening's PR is adopted in the same transaction that records the update) and mark it ready (or a draft). An update is recorded before it starts. If its confirmation is lost, the next publish drops the record in step 1 and repeats the update after a new check; the update is idempotent. Record the result.
6060

@@ -89,6 +89,16 @@ Titles and problems are cut by code point, never inside a surrogate pair. An emp
8989

9090
The description stays under 60,000 characters. If the full plan is too long, only item IDs and titles are listed. At most 20 open problems are shown, each cut to 2,000 characters.
9191

92+
## Repositories without draft PRs
93+
94+
Some repositories do not support draft PRs (for example private repositories on GitHub Free). GitHub's refusal is a definite outcome, so nothing is left in flight:
95+
96+
| Case | Result |
97+
|---|---|
98+
| A needs-human task has no PR yet | No PR is opened; the opening is marked `abandoned`; publish returns `draft unsupported`. A ready PR is never opened instead, because it would invite review of work that needs a person. |
99+
| A needs-human task has an open ready PR | The update is dropped; the PR is left as it was; publish returns `draft unsupported` with its number. |
100+
| The check matches and the earlier PR is ready | The result is recorded as usual; publish reports the PR it could not make a draft as `leftReady`. |
101+
92102
## What this slice does not do
93103

94104
- **Push.** `BranchPusher` is injected. The real push needs D's commit export (#66) and a runner-owned host repository.

‎github/already-fixed.ts‎

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import type { RunGh } from './merge.ts';
22
import { ghEnvironment } from './gh-env.ts';
33
import { runWithInput } from './run-with-input.ts';
4+
import { BRANCH, REPOSITORY, SHA } from './validate.ts';
5+
import { cutText } from '../core/text.ts';
46

57
/**
68
* The pre-PR "already fixed" check (design, "Checking whether the issue is already fixed"). It reports a match when
@@ -60,7 +62,6 @@ const TIMELINE_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
6062
}`;
6163

6264
class Unknown extends Error {}
63-
const SHA = /^[a-f0-9]{40}$/;
6465
const object = (value: unknown, label: string): Record<string, unknown> => {
6566
if (!value || typeof value !== 'object' || Array.isArray(value)) throw new Unknown(`GitHub returned an invalid ${label}.`);
6667
return value as Record<string, unknown>;
@@ -71,7 +72,7 @@ const positive = (value: unknown, label: string): number => {
7172
};
7273
const repositoryName = (value: unknown): string => {
7374
const name = object(value, 'repository').nameWithOwner;
74-
if (typeof name !== 'string' || !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(name)) throw new Unknown('GitHub returned an invalid repository name.');
75+
if (typeof name !== 'string' || !REPOSITORY.test(name)) throw new Unknown('GitHub returned an invalid repository name.');
7576
return name;
7677
};
7778
const escape = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -96,7 +97,7 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
9697
readonly run: RunGh;
9798
readonly deadlineMs: number;
9899
constructor(config: GhAlreadyFixedConfig, run?: RunGh) {
99-
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(config.repository)) throw new Error('A GitHub repository is required for the already-fixed check.');
100+
if (!REPOSITORY.test(config.repository)) throw new Error('A GitHub repository is required for the already-fixed check.');
100101
if (config.deadlineMs !== undefined && (!Number.isSafeInteger(config.deadlineMs) || config.deadlineMs < 1)) throw new Error('Invalid check deadline.');
101102
this.repository = config.repository;
102103
this.deadlineMs = config.deadlineMs ?? DEFAULT_CHECK_DEADLINE_MS;
@@ -113,7 +114,7 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
113114
async check(input: AlreadyFixedInput, signal?: AbortSignal): Promise<AlreadyFixedResult> {
114115
if (!Number.isSafeInteger(input.issue) || input.issue < 1) throw new Error('Invalid issue number.');
115116
if (!SHA.test(input.taskBase)) throw new Error('Invalid task base commit.');
116-
if (!/^(?!-)(?!.*\.\.)(?!.*\/\/)[A-Za-z0-9._/-]+(?<![./])$/.test(input.baseBranch)) throw new Error('Invalid base branch name.');
117+
if (!BRANCH.test(input.baseBranch)) throw new Error('Invalid base branch name.');
117118
if (input.ownPullRequests.some(number => !Number.isSafeInteger(number) || number < 1)) throw new Error('Invalid pull request number.');
118119
// Every stage shares one deadline; reaching it aborts the running `gh` call and makes the check unknown.
119120
// The two stages are independent and run together. The first failure stops the other, and the check still waits for
@@ -128,7 +129,7 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
128129
const [matches, { baseHead, commits }] = settled.map(result => (result as PromiseFulfilledResult<unknown>).value) as [AlreadyFixedMatch[], { baseHead: string; commits: { sha: string; message: string }[] }];
129130
for (const commit of commits) {
130131
if (input.ownCommits.has(commit.sha) || !mentionsIssue(commit.message, this.repository, input.issue)) continue;
131-
matches.push({ kind: 'commit', sha: commit.sha, subject: commit.message.split('\n', 1)[0]!.slice(0, 200) });
132+
matches.push({ kind: 'commit', sha: commit.sha, subject: cutText(commit.message.split('\n', 1)[0]!, 200) });
132133
}
133134
return matches.length ? { outcome: 'found', baseHead, matches } : { outcome: 'clear', baseHead };
134135
} catch (error) {
@@ -164,11 +165,12 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
164165
if (node.closer === null) { lastCloser = 'a person, without a linked PR or commit'; continue; }
165166
const closer = object(node.closer, 'closer');
166167
if (closer.__typename === 'PullRequest') {
168+
// A close always counts, even by this task's own PR or commit: that PR merged, so the issue is fixed.
167169
const repo = repositoryName(closer.repository), number = positive(closer.number, 'pull request number');
168-
lastCloser = isOwn(repo, number) ? null : `${repo}#${number}`;
170+
lastCloser = isOwn(repo, number) ? `${repo}#${number} (this task's own PR, already merged)` : `${repo}#${number}`;
169171
} else if (closer.__typename === 'Commit') {
170172
if (typeof closer.oid !== 'string' || !SHA.test(closer.oid)) throw new Unknown('GitHub returned an invalid closing commit.');
171-
lastCloser = input.ownCommits.has(closer.oid) ? null : `commit ${closer.oid}`;
173+
lastCloser = input.ownCommits.has(closer.oid) ? `commit ${closer.oid} (this task's own commit, already on the default branch)` : `commit ${closer.oid}`;
172174
} else if (closer.__typename === 'ProjectV2') lastCloser = 'a project workflow';
173175
else throw new Unknown('GitHub returned an unknown closer.');
174176
continue;
@@ -180,7 +182,8 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
180182
if (source.__typename !== 'PullRequest') throw new Unknown('GitHub returned an unknown linked item.');
181183
const repo = repositoryName(source.repository), number = positive(source.number, 'pull request number');
182184
if (!['OPEN', 'CLOSED', 'MERGED'].includes(source.state as string) || typeof source.isDraft !== 'boolean') throw new Unknown('GitHub returned an invalid pull request state.');
183-
if (isOwn(repo, number)) continue;
185+
// The task's own open PR is not a match; its own merged PR is: the fix is already in.
186+
if (isOwn(repo, number) && source.state !== 'MERGED') continue;
184187
const key = `${repo.toLowerCase()}#${number}`;
185188
const match: AlreadyFixedMatch | null = source.state === 'CLOSED' ? null : { kind: 'pull request', repository: repo, number, state: source.state as 'OPEN' | 'MERGED', draft: source.isDraft };
186189
if (node.__typename === 'DisconnectedEvent') connected.set(key, null);

‎github/gh-env.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,11 +9,14 @@ export const GH_ENV_ALLOWLIST = [
99
// On Linux, gh reads a token kept in the system keyring over the D-Bus session bus.
1010
'DBUS_SESSION_BUS_ADDRESS', 'XDG_RUNTIME_DIR',
1111
'HTTPS_PROXY', 'HTTP_PROXY', 'NO_PROXY', 'https_proxy', 'http_proxy', 'no_proxy', 'SSL_CERT_FILE', 'SSL_CERT_DIR',
12+
// Windows: process creation, gh's config and credential store, and executable lookup.
13+
'SYSTEMROOT', 'SystemRoot', 'APPDATA', 'LOCALAPPDATA', 'USERPROFILE', 'PATHEXT', 'COMSPEC',
1214
] as const;
1315

14-
export function ghEnvironment(source: NodeJS.ProcessEnv = process.env): NodeJS.ProcessEnv {
16+
export function ghEnvironment(source: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): NodeJS.ProcessEnv {
1517
const env: NodeJS.ProcessEnv = {};
1618
for (const name of GH_ENV_ALLOWLIST) if (source[name] !== undefined) env[name] = source[name];
1719
// Never prompt, open a pager or check for updates inside a server.
18-
return { ...env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', GH_PAGER: 'cat', NO_COLOR: '1' };
20+
// `cat` does not exist on Windows; there an empty GH_PAGER turns the pager off.
21+
return { ...env, GH_PROMPT_DISABLED: '1', GH_NO_UPDATE_NOTIFIER: '1', GH_PAGER: platform === 'win32' ? '' : 'cat', NO_COLOR: '1' };
1922
}

0 commit comments

Comments
 (0)