Skip to content

Commit 3569490

Browse files
feat: add local-review command for offline branch review
Adds a 'local-review' CLI command that reviews the current branch diff against a base branch using Codex, without requiring a GitHub PR. Includes all prerequisites for local runs: - CODEX_BIN env var support (Windows .cmd wrapper compatibility) - shell: true on win32 for all Codex spawn sites - CLAWSWEEPER_CODEX_LOGIN_METHOD for ChatGPT Pro OAuth login - Applied to all 4 Codex subprocess launchers - Clears stale output before each review run Merge order: this PR subsumes #250 (Windows spawn) and #251 (OAuth login). If this lands first, close those as superseded. If either lands first, this PR needs a trivial rebase (identical changes).
1 parent 74f63a0 commit 3569490

5 files changed

Lines changed: 307 additions & 12 deletions

File tree

‎src/clawsweeper.ts‎

Lines changed: 137 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ import {
2424
repositoryProfileForSlug,
2525
type RepositoryProfile,
2626
} from "./repository-profiles.js";
27-
import { codexEnv } from "./codex-env.js";
27+
import { codexEnv, codexLoginMethodConfig } from "./codex-env.js";
2828
import {
2929
ghRetryKind,
3030
ghRetryWaitMs,
@@ -66,7 +66,7 @@ import {
6666
} from "./clawsweeper-args.js";
6767
import { escapeRegExp, safeOutputTail, trimMiddle, truncateText } from "./clawsweeper-text.js";
6868

69-
export { codexEnv } from "./codex-env.js";
69+
export { codexEnv, resolveCodexLoginMethod, codexLoginMethodConfig } from "./codex-env.js";
7070
export { parseGhJson, parseGhJsonLines } from "./github-json.js";
7171
export { itemNumbersArg } from "./clawsweeper-args.js";
7272
export { safeOutputTail } from "./clawsweeper-text.js";
@@ -6174,12 +6174,14 @@ function runCodex(options: {
61746174
}
61756175
const codexConfig = [
61766176
`model_reasoning_effort="${options.reasoningEffort}"`,
6177-
'forced_login_method="api"',
6177+
codexLoginMethodConfig(),
61786178
'approval_policy="never"',
61796179
];
61806180
if (options.serviceTier) codexConfig.splice(1, 0, `service_tier="${options.serviceTier}"`);
6181+
const codexBin = process.env.CODEX_BIN ?? "codex";
6182+
const useShell = process.platform === "win32";
61816183
const result = spawnSync(
6182-
"codex",
6184+
codexBin,
61836185
[
61846186
"exec",
61856187
"-m",
@@ -6207,6 +6209,7 @@ function runCodex(options: {
62076209
input: prompt,
62086210
maxBuffer: 128 * 1024 * 1024,
62096211
timeout: options.timeoutMs,
6212+
...(useShell ? { shell: true } : {}),
62106213
},
62116214
);
62126215
const dirtyAfter = openclawDirtyStatus(options.openclawDir);
@@ -6434,11 +6437,13 @@ function runCodexAssist(options: {
64346437
writeFileSync(promptPath, prompt, "utf8");
64356438
const codexConfig = [
64366439
`model_reasoning_effort="${options.reasoningEffort}"`,
6437-
'forced_login_method="api"',
6440+
codexLoginMethodConfig(),
64386441
'approval_policy="never"',
64396442
];
6443+
const codexBin = process.env.CODEX_BIN ?? "codex";
6444+
const useShell = process.platform === "win32";
64406445
const result = spawnSync(
6441-
"codex",
6446+
codexBin,
64426447
[
64436448
"exec",
64446449
"-m",
@@ -6457,6 +6462,7 @@ function runCodexAssist(options: {
64576462
input: prompt,
64586463
maxBuffer: 32 * 1024 * 1024,
64596464
timeout: options.timeoutMs,
6465+
...(useShell ? { shell: true } : {}),
64606466
},
64616467
);
64626468
if (result.error || result.status !== 0 || !existsSync(outputPath)) {
@@ -16908,6 +16914,130 @@ function checkCommand(): void {
1690816914
console.log("ok");
1690916915
}
1691016916

16917+
function localReviewCommand(args: Args): void {
16918+
const targetDir = resolve(stringArg(args.target_dir, "."));
16919+
const targetRepoArg = stringArg(args.repo, "");
16920+
const baseBranch = stringArg(args.base, "main");
16921+
const model = stringArg(args.codex_model, DEFAULT_CODEX_MODEL);
16922+
const reasoningEffort = stringArg(args.codex_reasoning_effort, DEFAULT_REASONING_EFFORT);
16923+
const sandboxMode = stringArg(args.codex_sandbox, "read-only");
16924+
const serviceTier = stringArg(args.codex_service_tier, DEFAULT_SERVICE_TIER);
16925+
const timeoutMs = numberArg(args.codex_timeout_ms, 600_000);
16926+
const outputDir = resolve(stringArg(args.output_dir, join(homedir(), ".clawsweeper-local-reviews")));
16927+
ensureDir(outputDir);
16928+
16929+
const repoName =
16930+
targetRepoArg ||
16931+
run("git", ["remote", "get-url", "origin"], { cwd: targetDir })
16932+
.replace(/.*github\.com[:/]/, "")
16933+
.replace(/\.git\s*$/, "")
16934+
.trim();
16935+
16936+
const diff = run("git", ["diff", `${baseBranch}...HEAD`], { cwd: targetDir });
16937+
if (!diff.trim()) {
16938+
console.error("[local-review] no diff against " + baseBranch);
16939+
process.exit(1);
16940+
}
16941+
16942+
const commitTitle = run("git", ["log", "--format=%s", "-1"], { cwd: targetDir }).trim();
16943+
const commitBody = run("git", ["log", "--format=%b", "-1"], { cwd: targetDir }).trim();
16944+
const author = run("git", ["log", "--format=%an", "-1"], { cwd: targetDir }).trim();
16945+
const headSha = run("git", ["rev-parse", "HEAD"], { cwd: targetDir }).trim();
16946+
const baseSha = run("git", ["rev-parse", baseBranch], { cwd: targetDir }).trim();
16947+
const changedFiles = run("git", ["diff", "--name-only", `${baseBranch}...HEAD`], { cwd: targetDir })
16948+
.trim()
16949+
.split("\n")
16950+
.filter(Boolean);
16951+
16952+
const prBodyFile = stringArg(args.pr_body_file, "");
16953+
let prBodyOverride = "";
16954+
if (prBodyFile) {
16955+
const resolvedBodyFile = resolve(prBodyFile);
16956+
if (!existsSync(resolvedBodyFile)) {
16957+
throw new Error(`--pr-body-file not found: ${resolvedBodyFile}`);
16958+
}
16959+
prBodyOverride = readFileSync(resolvedBodyFile, "utf8").trim();
16960+
}
16961+
const prBody = prBodyOverride || commitBody || commitTitle;
16962+
16963+
const now = new Date().toISOString();
16964+
const item: Item = {
16965+
repo: repoName,
16966+
number: 0,
16967+
kind: "pull_request",
16968+
title: commitTitle,
16969+
url: `local://${repoName}@${headSha.slice(0, 8)}`,
16970+
createdAt: now,
16971+
updatedAt: now,
16972+
closedAt: null,
16973+
author,
16974+
authorAssociation: "CONTRIBUTOR",
16975+
labels: [],
16976+
locked: false,
16977+
activeLockReason: null,
16978+
};
16979+
16980+
const context: ItemContext = {
16981+
issue: { title: commitTitle, body: prBody, user: { login: author }, state: "open" },
16982+
comments: [],
16983+
timeline: [],
16984+
pullRequest: {
16985+
title: commitTitle,
16986+
body: prBody,
16987+
head: { sha: headSha, ref: "HEAD" },
16988+
base: { sha: baseSha, ref: baseBranch },
16989+
diff,
16990+
changed_files: changedFiles.length,
16991+
additions: diff.split("\n").filter((l: string) => l.startsWith("+") && !l.startsWith("+++")).length,
16992+
deletions: diff.split("\n").filter((l: string) => l.startsWith("-") && !l.startsWith("---")).length,
16993+
mergeable: true,
16994+
user: { login: author },
16995+
},
16996+
pullFiles: changedFiles.map((f: string) => ({ filename: f, status: "modified", patch: "" })),
16997+
pullCommits: [{ sha: headSha, commit: { message: commitTitle + "\n\n" + commitBody } }],
16998+
pullReviewComments: [],
16999+
counts: { comments: 0, timeline: 0 },
17000+
};
17001+
17002+
const git: GitInfo = { mainSha: baseSha, latestRelease: null };
17003+
17004+
try {
17005+
setTargetRepo(repoName);
17006+
} catch {
17007+
setTargetRepo("openclaw/openclaw");
17008+
}
17009+
17010+
console.error(
17011+
`[local-review] repo=${repoName} base=${baseBranch} files=${changedFiles.length} diff=${diff.length} chars`,
17012+
);
17013+
console.error(`[local-review] title: ${commitTitle}`);
17014+
console.error(`[local-review] model=${model} reasoning=${reasoningEffort}`);
17015+
17016+
const staleOutputPath = join(outputDir, `${item.number}.json`);
17017+
if (existsSync(staleOutputPath)) {
17018+
unlinkSync(staleOutputPath);
17019+
}
17020+
17021+
const decision = runCodex({
17022+
item,
17023+
context,
17024+
git,
17025+
model,
17026+
openclawDir: targetDir,
17027+
reasoningEffort,
17028+
sandboxMode,
17029+
serviceTier,
17030+
timeoutMs,
17031+
workDir: outputDir,
17032+
additionalPrompt: `This is a LOCAL review of staged changes, not a GitHub PR. The diff is from git diff ${baseBranch}...HEAD. Focus on code correctness, not PR metadata.`,
17033+
});
17034+
17035+
const outputPath = join(outputDir, "local-review.json");
17036+
writeFileSync(outputPath, JSON.stringify(decision, null, 2), "utf8");
17037+
console.error(`[local-review] decision written to ${outputPath}`);
17038+
console.log(JSON.stringify(decision, null, 2));
17039+
}
17040+
1691117041
export async function main(argv = process.argv.slice(2)): Promise<void> {
1691217042
const args = parseArgs(argv);
1691317043
const command = args._[0] ?? "review";
@@ -16927,6 +17057,7 @@ export async function main(argv = process.argv.slice(2)): Promise<void> {
1692717057
} else if (command === "status") statusCommand(args);
1692817058
else if (command === "assist") assistCommand(args);
1692917059
else if (command === "check") checkCommand();
17060+
else if (command === "local-review") localReviewCommand(args);
1693017061
else {
1693117062
console.error(`Unknown command: ${command}`);
1693217063
process.exit(1);

‎src/codex-env.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,17 @@
1+
const VALID_LOGIN_METHODS = new Set(["api", "chatgpt"]);
2+
3+
export function resolveCodexLoginMethod(): string {
4+
const value = process.env.CLAWSWEEPER_CODEX_LOGIN_METHOD?.trim().toLowerCase();
5+
if (value && VALID_LOGIN_METHODS.has(value)) {
6+
return value;
7+
}
8+
return "api";
9+
}
10+
11+
export function codexLoginMethodConfig(): string {
12+
return `forced_login_method="${resolveCodexLoginMethod()}"`;
13+
}
14+
115
export type CodexEnvOptions = {
216
ghToken?: string | undefined;
317
};

‎src/commit-sweeper.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@ import {
1111
import { publishCheckFromReport, splitFrontMatter } from "./commit-checks.js";
1212
import { argBool, argNumber, argString, parseArgs, type Args } from "./clawsweeper-args.js";
1313
import { safeOutputTail } from "./clawsweeper-text.js";
14-
import { codexEnv } from "./codex-env.js";
14+
import { codexEnv, codexLoginMethodConfig } from "./codex-env.js";
1515
import { runText } from "./command.js";
1616
import { ghRetryKind, ghRetryWaitMs } from "./github-retry.js";
1717
import { DEFAULT_TARGET_REPO, repositoryProfileFor } from "./repository-profiles.js";
@@ -296,12 +296,14 @@ function runCodex(options: {
296296
);
297297
const codexConfig = [
298298
`model_reasoning_effort="${options.reasoningEffort}"`,
299-
'forced_login_method="api"',
299+
codexLoginMethodConfig(),
300300
'approval_policy="never"',
301301
];
302302
if (options.serviceTier) codexConfig.splice(1, 0, `service_tier="${options.serviceTier}"`);
303+
const codexBin = process.env.CODEX_BIN ?? "codex";
304+
const useShell = process.platform === "win32";
303305
const result = spawnSync(
304-
"codex",
306+
codexBin,
305307
[
306308
"exec",
307309
"-m",
@@ -322,6 +324,7 @@ function runCodex(options: {
322324
input: readFileSync(promptPath, "utf8"),
323325
maxBuffer: 128 * 1024 * 1024,
324326
timeout: options.timeoutMs,
327+
...(useShell ? { shell: true } : {}),
325328
},
326329
);
327330
if (result.error || result.status !== 0 || !existsSync(outputPath)) {

‎src/pr-close-coverage-proof.ts‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
import { spawnSync } from "node:child_process";
22
import { existsSync, mkdirSync, readFileSync, unlinkSync, writeFileSync } from "node:fs";
33
import { join } from "node:path";
4-
import { codexEnv } from "./codex-env.js";
4+
import { codexEnv, codexLoginMethodConfig } from "./codex-env.js";
55
import { safeOutputTail, truncateText } from "./clawsweeper-text.js";
66

77
export type PrCloseCoverageProofModelDecision = "covered" | "keep_open";
@@ -252,14 +252,16 @@ export function runPrCloseCoverageProofModel(options: {
252252
if (existsSync(outputPath)) unlinkSync(outputPath);
253253
const codexConfig = [
254254
`model_reasoning_effort="${options.runtime.reasoningEffort}"`,
255-
'forced_login_method="api"',
255+
codexLoginMethodConfig(),
256256
'approval_policy="never"',
257257
];
258258
if (options.runtime.serviceTier) {
259259
codexConfig.splice(1, 0, `service_tier="${options.runtime.serviceTier}"`);
260260
}
261+
const codexBin = process.env.CODEX_BIN ?? "codex";
262+
const useShell = process.platform === "win32";
261263
const result = spawnSync(
262-
"codex",
264+
codexBin,
263265
[
264266
"exec",
265267
"-m",
@@ -282,6 +284,7 @@ export function runPrCloseCoverageProofModel(options: {
282284
input: prompt,
283285
maxBuffer: 64 * 1024 * 1024,
284286
timeout: options.runtime.timeoutMs,
287+
...(useShell ? { shell: true } : {}),
285288
},
286289
);
287290
if (result.error) {

0 commit comments

Comments
 (0)