Skip to content

Commit 9980445

Browse files
mchwangclaude
andcommitted
Close handed-off review findings on F2d: references, adoption, ProjectV2, order
- Neutralise issue references in the PR title, plan and problems, since GitHub closes issues from keywords in default-branch commit messages, which fences do not protect. - Look up the branch PR with the markers of every earlier opening, abandoned ones included, before the check; adopt an abandoned opening's PR (and count it as own) instead of getting stuck behind GitHub's one-open-PR-per-branch refusal. - Treat a ProjectV2 closer as a closing by someone else, not unknown. - Refuse a PR-number mismatch before the push. - Run the timeline and base-commit reads together; the first failure aborts the other. - Cut titles and problems by UTF-16 unit without splitting a surrogate pair; an empty summary becomes "codeboost plan". - AGENTS.md: three rules from these findings. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 6b26e65 commit 9980445

9 files changed

Lines changed: 202 additions & 63 deletions

File tree

‎AGENTS.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ Every reproduced race requires a failing-before and passing-after regression. As
7575
- Budget a multi-stage validation across all sequential stages; giving each stage the full request allowance does not create an overall deadline.
7676
- Preserve the distinction between an explicit unbound identity and missing or malformed authorization metadata. Missing or malformed identities must fail closed.
7777
- Validate every field used to classify an external record as clear, including enum values and required nullable fields. Partial records and malformed policy objects must fail closed.
78+
- Select every member the API documents for a union or enum you classify (for example every GraphQL `Closer` type). Fail closed only on types outside that list; a missing known member turns every result into a false unknown.
7879
- Validate coupled lifecycle fields as allowed combinations. A terminal-looking conclusion must not override an active or unknown status.
7980
- Treat a successful external command as the transition it actually performed. If it can enqueue or schedule work, model and verify that lifecycle before reporting the final action as complete.
8081
- For safety-critical API responses, require and validate every requested field before any early return, including terminal-success paths. Treat an omitted field differently from an explicit `null` allowed by the API contract.
@@ -91,6 +92,7 @@ Every reproduced race requires a failing-before and passing-after regression. As
9192
- 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.
9293
- 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.
9394
- 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.
95+
- 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.
9496
- 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.
9597
- 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.
9698

@@ -106,6 +108,7 @@ Every reproduced race requires a failing-before and passing-after regression. As
106108

107109
- When a subprocess reports a problem only as a warning and carries on, decide pass or fail by what each message means for the result, not by whether anything was printed: fail on messages that mean it did less than it should (for example could not read a path), and let through messages about harmless input the agent controls. Test both a benign case and a failing case, and filter the output as it arrives so that no volume of benign messages can push a failure out of a bounded buffer.
108110
- Quote or escape agent-controlled text (file names, paths, branch names) wherever it lands in output that people or tools parse, such as diffs, notices, logs or reports, so it cannot forge that output's structure.
111+
- Neutralise issue references (`#N`, `GH-N`, `owner/repo#N`, issue URLs) in any text codeboost writes that can become a commit message, such as a PR title or description. Code fences do not protect commit messages, and GitHub closes issues from closing keywords in default-branch commits.
109112
- Never spread a collection whose size follows unbounded input into function arguments (`Math.max(...runs)`); engines limit the argument count, so use a loop.
110113
- A hardened Git invocation must also keep Git out of nested repositories and populated submodules, whose own config and hooks are the agent's: pass `--ignore-submodules` on the command line (the config default does not bind plumbing or override `.gitmodules`), and never run Git with a nested repository as its working directory.
111114

‎core/pull-request-body.ts‎

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,23 @@ export function fenced(text: string): string {
1818
return `${fence}text\n${text.replace(/\r\n?/g, '\n')}\n${fence}`;
1919
}
2020

21+
/**
22+
* GitHub also reads closing keywords ("Fixes #7") in commit messages on the default branch, fenced or not, and a squash
23+
* or merge commit can carry the PR title and description. So every issue reference in plan text and problems is
24+
* neutralised: `#7` becomes `#7`, `GH-7` becomes `GH‑7` (non-breaking hyphen), and `/issues/7` or `/pull/7` in a URL gets a
25+
* division slash. The text stays readable, and no merge method can close another issue through it.
26+
*/
27+
export function neutralizeReferences(text: string): string {
28+
return text.replace(/#(?=\d)/g, '#').replace(/\b(GH)-(?=\d)/gi, '$1‑').replace(/\/(issues|pull)\/(?=\d)/gi, '/$1∕');
29+
}
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+
}
37+
2138
function planText(plan: Plan, full: boolean): string {
2239
return plan.items.map(item => {
2340
const lines = [`${item.id}: ${item.title}`];
@@ -30,12 +47,13 @@ function planText(plan: Plan, full: boolean): string {
3047
return lines.join('\n');
3148
}).join('\n\n');
3249
}
50+
const planTextSafe = (plan: Plan, full: boolean) => neutralizeReferences(planText(plan, full));
3351

34-
/** Single line, no control characters, bounded. */
52+
/** Single line, no control characters, no issue references except its own, bounded in code points. */
3553
export function pullRequestTitle(plan: Plan): string {
36-
const summary = plan.summary.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim();
54+
const summary = neutralizeReferences(plan.summary.replace(/[\u0000-\u001f\u007f]+/g, ' ').replace(/\s+/g, ' ').trim()) || 'codeboost plan';
3755
const suffix = ` (#${plan.issue})`;
38-
return (summary.length + suffix.length > MAX_TITLE ? `${summary.slice(0, MAX_TITLE - suffix.length - 1)}…` : summary) + suffix;
56+
return cut(summary, MAX_TITLE - suffix.length) + suffix;
3957
}
4058

4159
/**
@@ -45,7 +63,7 @@ export function pullRequestTitle(plan: Plan): string {
4563
export function pullRequestBody(input: { plan: Plan; marker: string; problems?: readonly string[] }): string {
4664
const { plan, marker } = input;
4765
// The full problems stay in codeboost; the description shows a bounded summary of them.
48-
const all = input.problems ?? [], shown = all.slice(0, MAX_PROBLEMS).map(problem => problem.length > MAX_PROBLEM ? `${problem.slice(0, MAX_PROBLEM)}…` : problem);
66+
const all = input.problems ?? [], shown = all.slice(0, MAX_PROBLEMS).map(problem => neutralizeReferences(cut(problem, MAX_PROBLEM + 1)));
4967
const problems = all.length > shown.length ? [...shown, `(${all.length - shown.length} more in codeboost)`] : shown;
5068
const build = (full: boolean) => [
5169
marker,
@@ -56,7 +74,7 @@ export function pullRequestBody(input: { plan: Plan; marker: string; problems?:
5674
'',
5775
full ? '**Plan**' : '**Plan** (items only; the full plan is too long for this description)',
5876
'',
59-
fenced(planText(plan, full)),
77+
fenced(planTextSafe(plan, full)),
6078
].join('\n');
6179
const body = build(true);
6280
if (body.length <= MAX_BODY) return body;

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

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ 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). | Closed by an own PR or an own commit. A reopened issue. |
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. |
3333
| 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. |
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

@@ -50,13 +50,13 @@ 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 an open PR from the task branch whose description has its marker. If one exists, record it as opened. 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 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. **Check.** Run the check. Record the result, and any status change, in one transaction. That transaction refuses if the task changed during the check.
56-
4. **Find the earlier PR.** If the task has an opened PR on the same branch, ask GitHub whether it is still open.
57-
5. **Push.** Re-read the task as in step 6, then 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.
55+
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.
56+
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.
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.
59-
7. **Open or reuse.** Open a new PR, or update the open earlier PR 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.
59+
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

6161
Each opening or refresh owns the task state version at the moment it passed step 6. The PR is always recorded. The status changes only when the task still has that version. Every status change, admission and context change increases the version. So a response that arrives after the task changed never moves it.
6262

@@ -75,7 +75,11 @@ The adapter refuses any answer for a PR that is not open. A PR closed between th
7575

7676
The description starts with the marker and `Fixes #<issue>`. The plan follows, inside a fenced code block. A draft also lists its open problems inside a fenced code block.
7777

78-
GitHub ignores closing keywords and @-mentions inside code. So plan text or agent output cannot close other issues or notify people. The fence is longer than any run of backticks in the text, so the text cannot end the block.
78+
GitHub ignores closing keywords and @-mentions inside code. So plan text or agent output cannot notify people from the description, and cannot end the block: the fence is longer than any run of backticks in the text.
79+
80+
Fences do not protect commit messages. A squash or merge commit can carry the PR title and description, and GitHub acts on closing keywords in default-branch commit messages. So every issue reference in the title's summary, the plan and the problems is neutralised: `#7` becomes `#7`, `GH-7` gets a non-breaking hyphen, and `/issues/7` or `/pull/7` gets a division slash. Only the task's own `Fixes #<issue>` line and the title's `(#<issue>)` remain real references.
81+
82+
Titles and problems are cut by code point, never inside a surrogate pair. An empty summary becomes `codeboost plan`.
7983

8084
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.
8185

‎github/already-fixed.ts‎

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,7 @@ const TIMELINE_QUERY = `query($owner: String!, $name: String!, $number: Int!) {
4747
pageInfo { hasNextPage }
4848
nodes {
4949
__typename
50-
... on ClosedEvent { closer { __typename ... on PullRequest { number repository { nameWithOwner } } ... on Commit { oid } } }
50+
... on ClosedEvent { closer { __typename ... on PullRequest { number repository { nameWithOwner } } ... on Commit { oid } ... on ProjectV2 { number } } }
5151
... on CrossReferencedEvent { source { __typename ... on PullRequest { number state isDraft repository { nameWithOwner } } } }
5252
... on ConnectedEvent { subject { __typename ... on PullRequest { number state isDraft repository { nameWithOwner } } } }
5353
... on DisconnectedEvent { subject { __typename ... on PullRequest { number state isDraft repository { nameWithOwner } } } }
@@ -113,10 +113,12 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
113113
if (!/^(?!-)(?!.*\.\.)(?!.*\/\/)[A-Za-z0-9._/-]+(?<![./])$/.test(input.baseBranch)) throw new Error('Invalid base branch name.');
114114
if (input.ownPullRequests.some(number => !Number.isSafeInteger(number) || number < 1)) throw new Error('Invalid pull request number.');
115115
// Every stage shares one deadline; reaching it aborts the running `gh` call and makes the check unknown.
116-
const deadline = AbortSignal.timeout(this.deadlineMs), stages = signal ? AbortSignal.any([signal, deadline]) : deadline;
116+
// The two stages are independent and run together; the first failure stops the other.
117+
const deadline = AbortSignal.timeout(this.deadlineMs), failed = new AbortController();
118+
const stages = AbortSignal.any([...(signal ? [signal] : []), deadline, failed.signal]);
119+
const stop = (error: unknown) => { failed.abort(); throw error; };
117120
try {
118-
const matches = await this.#timeline(input, stages);
119-
const { baseHead, commits } = await this.#baseCommits(input, stages);
121+
const [matches, { baseHead, commits }] = await Promise.all([this.#timeline(input, stages).catch(stop), this.#baseCommits(input, stages).catch(stop)]);
120122
for (const commit of commits) {
121123
if (input.ownCommits.has(commit.sha) || !mentionsIssue(commit.message, this.repository, input.issue)) continue;
122124
matches.push({ kind: 'commit', sha: commit.sha, subject: commit.message.split('\n', 1)[0]!.slice(0, 200) });
@@ -160,7 +162,8 @@ export class GhAlreadyFixedGateway implements AlreadyFixedGateway {
160162
} else if (closer.__typename === 'Commit') {
161163
if (typeof closer.oid !== 'string' || !SHA.test(closer.oid)) throw new Unknown('GitHub returned an invalid closing commit.');
162164
lastCloser = input.ownCommits.has(closer.oid) ? null : `commit ${closer.oid}`;
163-
} else throw new Unknown('GitHub returned an unknown closer.');
165+
} else if (closer.__typename === 'ProjectV2') lastCloser = 'a project workflow';
166+
else throw new Unknown('GitHub returned an unknown closer.');
164167
continue;
165168
}
166169
const field = node.__typename === 'CrossReferencedEvent' ? 'source' : node.__typename === 'ConnectedEvent' || node.__typename === 'DisconnectedEvent' ? 'subject' : null;

0 commit comments

Comments
 (0)