File size: 7,145 Bytes
914f53d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | import { Octokit } from '@octokit/rest';
import {
MARKER_ORCHESTRATOR,
PrAgentStateSchema,
type PrAgentState,
} from './types.js';
export function createOctokit(token?: string): Octokit {
const auth = token ?? process.env.GITHUB_TOKEN ?? process.env.PR_AGENT_GITHUB_TOKEN;
if (!auth) {
throw new Error('GITHUB_TOKEN or PR_AGENT_GITHUB_TOKEN required');
}
return new Octokit({ auth });
}
export async function listAllIssueComments(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
): Promise<Array<{ id: number; body?: string | null; created_at?: string | null }>> {
const all: Array<{ id: number; body?: string | null; created_at?: string | null }> = [];
let page = 1;
for (;;) {
const { data } = await octokit.issues.listComments({
owner,
repo,
issue_number: issueNumber,
per_page: 100,
page,
});
if (data.length === 0) break;
all.push(...data);
if (data.length < 100) break;
page++;
}
return all;
}
export function parseStateFromComment(body: string): PrAgentState | null {
if (!body.includes(MARKER_ORCHESTRATOR)) return null;
const jsonMatch = body.match(/```json\s*([\s\S]*?)\s*```/);
if (!jsonMatch) return null;
try {
return PrAgentStateSchema.parse(JSON.parse(jsonMatch[1]!));
} catch {
return null;
}
}
export function formatStateComment(state: PrAgentState): string {
return `${MARKER_ORCHESTRATOR}
## PR Agent Orchestrator State
\`\`\`json
${JSON.stringify(state, null, 2)}
\`\`\`
`;
}
export function defaultState(): PrAgentState {
return PrAgentStateSchema.parse({});
}
export async function loadOrCreateState(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
): Promise<{ state: PrAgentState; commentId?: number }> {
// Races between concurrent orchestrator runs (e.g. a workflow_run-triggered
// run on the default branch overlapping a pull_request-triggered run on the
// PR branch) have produced duplicate state comments: a transient list/parse
// failure made one run fall back to a default state, whose save then created
// a second marker comment. Recover deterministically: parse every marker
// comment, adopt the highest revision, and best-effort delete the rest so
// the ledger converges back to a single source of truth.
for (let attempt = 0; attempt < 2; attempt++) {
const comments = await listAllIssueComments(octokit, owner, repo, issueNumber);
const markers = comments.filter((c) => c.body?.includes(MARKER_ORCHESTRATOR));
const parsed = markers
.map((c) => ({ id: c.id, state: c.body ? parseStateFromComment(c.body) : null }))
.filter((x): x is { id: number; state: PrAgentState } => x.state != null);
if (parsed.length > 0) {
parsed.sort((a, b) => (b.state.revision ?? 0) - (a.state.revision ?? 0));
const winner = parsed[0]!;
for (const dup of parsed.slice(1)) {
try {
await octokit.issues.deleteComment({ owner, repo, comment_id: dup.id });
console.log(
`Deleted duplicate state comment ${dup.id} (revision ${dup.state.revision ?? 0} < ${winner.state.revision ?? 0})`,
);
} catch {
// Best-effort: a leftover duplicate is inert as long as the winner sorts first.
}
}
return { state: winner.state, commentId: winner.id };
}
if (markers.length > 0 && attempt === 0) {
// Marker comments exist but none parsed — likely a transient mid-edit
// read. Retry once before falling back: proceeding with a default state
// silently resets the ledger and budget counters.
console.warn('State comment present but unparseable; retrying once before default');
await new Promise((r) => setTimeout(r, 5000));
continue;
}
break;
}
return { state: defaultState() };
}
export async function saveState(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
state: PrAgentState,
commentId?: number,
): Promise<{ wrote: boolean; revision: number }> {
const localRevision = state.revision ?? 0;
if (commentId) {
// Compare-and-swap: refuse to overwrite a newer revision written by a
// concurrent orchestrator run (the #3465 lost-update failure mode).
try {
const { data } = await octokit.issues.getComment({
owner,
repo,
comment_id: commentId,
});
const remote = data.body ? parseStateFromComment(data.body) : null;
const remoteRevision = remote?.revision ?? 0;
if (remote && remoteRevision > localRevision) {
console.log(
`Skipping stale state write: local revision ${localRevision} < remote ${remoteRevision}`,
);
return { wrote: false, revision: remoteRevision };
}
} catch (err) {
console.warn('saveState: failed to re-read state comment before write', err);
}
}
const nextRevision = localRevision + 1;
const nextState: PrAgentState = { ...state, revision: nextRevision };
const body = formatStateComment(nextState);
if (commentId) {
await octokit.issues.updateComment({
owner,
repo,
comment_id: commentId,
body,
});
return { wrote: true, revision: nextRevision };
}
await octokit.issues.createComment({
owner,
repo,
issue_number: issueNumber,
body,
});
return { wrote: true, revision: nextRevision };
}
export async function upsertMarkerComment(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
marker: string,
body: string,
): Promise<void> {
const comments = await listAllIssueComments(octokit, owner, repo, issueNumber);
const existing = comments.find((c) => c.body?.includes(marker));
if (existing) {
await octokit.issues.updateComment({ owner, repo, comment_id: existing.id, body });
return;
}
await octokit.issues.createComment({ owner, repo, issue_number: issueNumber, body });
}
export async function prHasLabel(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
label: string,
): Promise<boolean> {
const { data } = await octokit.issues.get({ owner, repo, issue_number: issueNumber });
return (data.labels ?? []).some((l) => (typeof l === 'string' ? l : l.name) === label);
}
export async function ensureLabel(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
label: string,
): Promise<void> {
const has = await prHasLabel(octokit, owner, repo, issueNumber, label);
if (!has) {
await octokit.issues.addLabels({ owner, repo, issue_number: issueNumber, labels: [label] });
}
}
export async function removeLabel(
octokit: Octokit,
owner: string,
repo: string,
issueNumber: number,
label: string,
): Promise<void> {
try {
await octokit.issues.removeLabel({ owner, repo, issue_number: issueNumber, name: label });
} catch {
// label may not exist
}
}
|