Skip to content

Commit 59e2d44

Browse files
feat(repair): add safe author-wide PR intake (#335)
Co-authored-by: Joao Carreiro <[email protected]>
1 parent 39239e7 commit 59e2d44

4 files changed

Lines changed: 295 additions & 65 deletions

File tree

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ checkpoint, and status-only commits are intentionally omitted.
99

1010
### Added
1111

12+
- Added author-wide PR repair intake across configured public repositories, with private and unsupported repositories excluded before job generation. Thanks @Jhacarreiro.
13+
1214
### Changed
1315

1416
### Fixed

‎README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -103,6 +103,13 @@ exact-head review, and run a bounded Codex review/fix loop. Codex handles the
103103
code repair and local validation loop; deterministic executor steps own every
104104
GitHub mutation, branch push, label update, and final merge gate.
105105

106+
Operators can create repair-only jobs for one author's blocked pull requests in
107+
one repository with `pnpm repair:pr-intake -- --repo owner/name --author login`,
108+
or across all configured public repositories with
109+
`pnpm repair:pr-intake -- --author login --all-open`. Author-wide discovery
110+
skips private, unsupported, and unverifiable repositories without persisting
111+
their names. Generated jobs cannot close or merge their source pull requests.
112+
106113
Automerge waits for exact-head review, required checks, mergeability, and policy
107114
gates. If repair was needed, the mutable status comment records each review,
108115
repair, re-review, and merge step with timing and links. The final merge result

‎src/repair/pr-repair-intake.ts‎

Lines changed: 170 additions & 65 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { ghJson } from "./github-cli.js";
66
import { renderJobIntentFrontmatter } from "./job-intent.js";
77
import { parseArgs, parseJob, repoRoot, validateJob } from "./lib.js";
88
import { slug } from "./text-utils.js";
9+
import { repositoryProfileFor } from "../repository-profiles.js";
910

1011
type Signal = {
1112
kind: string;
@@ -27,9 +28,19 @@ type Candidate = {
2728
updatedAt?: string;
2829
};
2930

31+
type AuthorSearchPullRequest = {
32+
repository?: { nameWithOwner?: string };
33+
};
34+
35+
type AuthorWideRepositoryDecision = {
36+
repo?: string;
37+
reason?: "private" | "metadata_unavailable" | "unsupported_profile";
38+
};
39+
3040
const args = parseArgs(process.argv.slice(2));
31-
const repo = stringArg("repo", "");
41+
const requestedRepo = stringArg("repo", "");
3242
const author = stringArg("author", "");
43+
const allOpen = truthy(args["all-open"] ?? args.all_open);
3344
const limit = numberArg("limit", 50);
3445
const outDirArg = stringArg("out-dir", stringArg("out_dir", ""));
3546
const dryRun = truthy(args["dry-run"] ?? args.dry_run);
@@ -58,70 +69,164 @@ query($owner:String!, $name:String!, $number:Int!) {
5869
}
5970
`;
6071

61-
if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo)) die("--repo owner/name is required");
6272
if (!author.trim()) die("--author is required");
6373

64-
const owner = repo.split("/")[0] ?? "unknown";
65-
const outDir = path.resolve(repoRoot(), outDirArg || `jobs/${owner}/inbox`);
66-
const prs = fetchOpenPullRequests({ repo, author, limit });
67-
const results = prs
68-
.map((pr) => candidateResult(pr))
69-
.filter((result) => result.signals.length >= minSignals);
70-
71-
if (!dryRun) fs.mkdirSync(outDir, { recursive: true });
72-
73-
const written: LooseRecord[] = [];
74-
for (const result of results) {
75-
const clusterId = slug(`repair-pr-${repo.replace("/", "-")}-${result.number}`);
76-
const jobPath = path.join(outDir, `${clusterId}.md`);
77-
const relativeJobPath = path.relative(repoRoot(), jobPath);
78-
const branch = `clawsweeper/${clusterId}`;
79-
const body = renderJob({ result, clusterId, branch });
80-
if (dryRun) {
74+
if (/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(requestedRepo)) {
75+
console.log(JSON.stringify(runRepoIntake(requestedRepo, repoModeOutDir(requestedRepo)), null, 2));
76+
} else if (allOpen) {
77+
console.log(JSON.stringify(runAuthorWideIntake(), null, 2));
78+
} else {
79+
die("--repo owner/name is required unless --all-open is set");
80+
}
81+
82+
function runAuthorWideIntake() {
83+
const pullRequests = fetchAuthorOpenPullRequests({ author, limit });
84+
const discoveredRepositories = Array.from(
85+
new Set(pullRequests.map((pr) => repoNameWithOwner(pr)).filter(Boolean)),
86+
).sort();
87+
const decisions = discoveredRepositories.map(authorWideRepositoryDecision);
88+
const repositories = decisions.flatMap((decision) => (decision.repo ? [decision.repo] : []));
89+
const summaries = repositories.map((targetRepo) =>
90+
runRepoIntake(targetRepo, authorWideOutDir(targetRepo)),
91+
);
92+
93+
return {
94+
status: "ok",
95+
mode: "author-wide",
96+
author,
97+
state: "open",
98+
searched: pullRequests.length,
99+
repos_discovered: discoveredRepositories.length,
100+
repos_scanned: summaries.length,
101+
skipped_repositories: skippedRepositoryCounts(decisions),
102+
scanned: summaries.reduce((sum, summary) => sum + Number(summary.scanned ?? 0), 0),
103+
candidates: summaries.reduce((sum, summary) => sum + Number(summary.candidates ?? 0), 0),
104+
dry_run: dryRun,
105+
jobs: summaries.flatMap((summary) => (Array.isArray(summary.jobs) ? summary.jobs : [])),
106+
repositories: summaries,
107+
};
108+
}
109+
110+
function runRepoIntake(targetRepo: string, outDir: string): LooseRecord {
111+
const prs = fetchOpenPullRequests({ repo: targetRepo, author, limit });
112+
const results = prs
113+
.map((pr) => candidateResult(targetRepo, pr))
114+
.filter((result) => result.signals.length >= minSignals);
115+
116+
if (!dryRun) fs.mkdirSync(outDir, { recursive: true });
117+
118+
const written: LooseRecord[] = [];
119+
for (const result of results) {
120+
const clusterId = slug(`repair-pr-${targetRepo.replace("/", "-")}-${result.number}`);
121+
const jobPath = path.join(outDir, `${clusterId}.md`);
122+
const relativeJobPath = path.relative(repoRoot(), jobPath);
123+
const branch = `clawsweeper/${clusterId}`;
124+
const body = renderJob({ targetRepo, result, clusterId, branch });
125+
if (dryRun) {
126+
written.push({
127+
status: "planned",
128+
job: relativeJobPath,
129+
number: result.number,
130+
signals: result.signals,
131+
});
132+
continue;
133+
}
134+
if (fs.existsSync(jobPath) && !force) {
135+
written.push({
136+
status: "exists",
137+
job: relativeJobPath,
138+
number: result.number,
139+
signals: result.signals,
140+
});
141+
continue;
142+
}
143+
fs.writeFileSync(jobPath, body, "utf8");
144+
const parsed = parseJob(jobPath);
145+
const errors = validateJob(parsed);
146+
if (errors.length > 0)
147+
die(`generated invalid job ${relativeJobPath}:\n- ${errors.join("\n- ")}`);
81148
written.push({
82-
status: "planned",
149+
status: "written",
83150
job: relativeJobPath,
84151
number: result.number,
85152
signals: result.signals,
86153
});
87-
continue;
88154
}
89-
if (fs.existsSync(jobPath) && !force) {
90-
written.push({
91-
status: "exists",
92-
job: relativeJobPath,
93-
number: result.number,
94-
signals: result.signals,
95-
});
96-
continue;
155+
156+
return {
157+
status: "ok",
158+
repo: targetRepo,
159+
author,
160+
scanned: prs.length,
161+
candidates: results.length,
162+
dry_run: dryRun,
163+
jobs: written,
164+
};
165+
}
166+
167+
function repoModeOutDir(targetRepo: string): string {
168+
const owner = targetRepo.split("/")[0] ?? "unknown";
169+
return path.resolve(repoRoot(), outDirArg || `jobs/${owner}/inbox`);
170+
}
171+
172+
function authorWideOutDir(targetRepo: string): string {
173+
const root = outDirArg
174+
? path.resolve(repoRoot(), outDirArg)
175+
: path.resolve(repoRoot(), "jobs", "author", slug(author));
176+
return path.join(root, slug(targetRepo), "inbox");
177+
}
178+
179+
function fetchAuthorOpenPullRequests({
180+
author,
181+
limit,
182+
}: {
183+
author: string;
184+
limit: number;
185+
}): AuthorSearchPullRequest[] {
186+
return ghJson<AuthorSearchPullRequest[]>([
187+
"search",
188+
"prs",
189+
"--author",
190+
author,
191+
"--state",
192+
"open",
193+
"--limit",
194+
String(limit),
195+
"--json",
196+
"repository",
197+
]);
198+
}
199+
200+
function repoNameWithOwner(pr: AuthorSearchPullRequest): string {
201+
return String(pr.repository?.nameWithOwner ?? "");
202+
}
203+
204+
function authorWideRepositoryDecision(targetRepo: string): AuthorWideRepositoryDecision {
205+
try {
206+
repositoryProfileFor(targetRepo);
207+
} catch {
208+
return { reason: "unsupported_profile" };
209+
}
210+
try {
211+
const metadata = ghJson<LooseRecord>(["repo", "view", targetRepo, "--json", "isPrivate"]);
212+
if (metadata.isPrivate === true) return { reason: "private" };
213+
return metadata.isPrivate === false ? { repo: targetRepo } : { reason: "metadata_unavailable" };
214+
} catch {
215+
return { reason: "metadata_unavailable" };
97216
}
98-
fs.writeFileSync(jobPath, body, "utf8");
99-
const parsed = parseJob(jobPath);
100-
const errors = validateJob(parsed);
101-
if (errors.length > 0) die(`generated invalid job ${relativeJobPath}:\n- ${errors.join("\n- ")}`);
102-
written.push({
103-
status: "written",
104-
job: relativeJobPath,
105-
number: result.number,
106-
signals: result.signals,
107-
});
108217
}
109218

110-
console.log(
111-
JSON.stringify(
112-
{
113-
status: "ok",
114-
repo,
115-
author,
116-
scanned: prs.length,
117-
candidates: results.length,
118-
dry_run: dryRun,
119-
jobs: written,
120-
},
121-
null,
122-
2,
123-
),
124-
);
219+
function skippedRepositoryCounts(decisions: AuthorWideRepositoryDecision[]) {
220+
const counts = {
221+
private: 0,
222+
metadata_unavailable: 0,
223+
unsupported_profile: 0,
224+
};
225+
for (const decision of decisions) {
226+
if (decision.reason) counts[decision.reason] += 1;
227+
}
228+
return counts;
229+
}
125230

126231
function fetchOpenPullRequests({
127232
repo,
@@ -160,7 +265,7 @@ function fetchOpenPullRequests({
160265
]);
161266
}
162267

163-
function candidateResult(pr: Candidate) {
268+
function candidateResult(targetRepo: string, pr: Candidate) {
164269
const blockingSignals: Signal[] = [];
165270
const contextSignals: Signal[] = [];
166271
const mergeState = String(pr.mergeStateStatus ?? "").toUpperCase();
@@ -178,7 +283,7 @@ function candidateResult(pr: Candidate) {
178283
if (signal) blockingSignals.push(signal);
179284
}
180285

181-
const reviewThreadSignals = unresolvedReviewThreadSignals(pr.number);
286+
const reviewThreadSignals = unresolvedReviewThreadSignals(targetRepo, pr.number);
182287
blockingSignals.push(...reviewThreadSignals);
183288

184289
if (includeComments) {
@@ -217,15 +322,15 @@ function candidateResult(pr: Candidate) {
217322
};
218323
}
219324

220-
function unresolvedReviewThreadSignals(number: number): Signal[] {
325+
function unresolvedReviewThreadSignals(targetRepo: string, number: number): Signal[] {
221326
try {
222327
const data = ghJson<LooseRecord>([
223328
"api",
224329
"graphql",
225330
"-f",
226-
`owner=${repo.split("/")[0]}`,
331+
`owner=${targetRepo.split("/")[0]}`,
227332
"-f",
228-
`name=${repo.split("/")[1]}`,
333+
`name=${targetRepo.split("/")[1]}`,
229334
"-F",
230335
`number=${number}`,
231336
"-f",
@@ -301,12 +406,12 @@ function actionableTextSignal(kind: string, entry: LooseRecord): Signal | null {
301406
};
302407
}
303408

304-
function renderJob({ result, clusterId, branch }: LooseRecord) {
409+
function renderJob({ targetRepo, result, clusterId, branch }: LooseRecord) {
305410
const ref = `#${result.number}`;
306411
const sourcePr = String(result.url);
307-
const prompt = renderPrompt(result);
412+
const prompt = renderPrompt(targetRepo, result);
308413
return `---
309-
repo: ${repo}
414+
repo: ${targetRepo}
310415
cluster_id: ${clusterId}
311416
mode: autonomous
312417
${renderJobIntentFrontmatter("pr_repair")}
@@ -338,7 +443,7 @@ target_branch: ${branch}
338443
source: pr-repair-intake
339444
---
340445
341-
# Repair-only PR intake for ${repo}${ref}
446+
# Repair-only PR intake for ${targetRepo}${ref}
342447
343448
This job was created by deterministic repair-only intake. It does not represent a full ClawSweeper review verdict and must not close or merge the source PR.
344449
@@ -369,9 +474,9 @@ ${prompt}
369474
`;
370475
}
371476

372-
function renderPrompt(result: LooseRecord) {
477+
function renderPrompt(targetRepo: JsonValue, result: LooseRecord) {
373478
const lines = [
374-
`Repair source PR ${result.url} (${repo}#${result.number}): ${result.title}`,
479+
`Repair source PR ${result.url} (${targetRepo}#${result.number}): ${result.title}`,
375480
"",
376481
"The PR has objective repair signals and should be made merge-ready if possible.",
377482
"Use read-only GitHub inspection to review the PR diff, checks, comments, reviews, and latest head/base state before editing.",

0 commit comments

Comments
 (0)