Compare commits
15 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| e4e93ea6d3 | |||
| ae8a634450 | |||
| cd9e00f8d6 | |||
| f87e0f878c | |||
| e2e29a19fc | |||
| 6f76a6a9da | |||
| 366af55f19 | |||
| 4c1413d925 | |||
| 6db4a6d02e | |||
| 3c8b493aee | |||
| 560e27bda5 | |||
| 1e17a76863 | |||
| ada5584737 | |||
| b6e2c61d30 | |||
| e58299740d |
@@ -12,16 +12,14 @@ on:
|
||||
description: Run name
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
actions: read
|
||||
checks: read
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
pullfrog:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
|
||||
@@ -72,16 +72,14 @@ on:
|
||||
description: 'Agent prompt'
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
pull-requests: write
|
||||
issues: write
|
||||
actions: read
|
||||
checks: read
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
pullfrog:
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: read
|
||||
steps:
|
||||
- name: Checkout code
|
||||
uses: actions/checkout@v6
|
||||
@@ -130,11 +128,7 @@ jobs:
|
||||
|
||||
permissions:
|
||||
id-token: write
|
||||
contents: write
|
||||
issues: write
|
||||
pull-requests: write
|
||||
actions: read
|
||||
checks: read
|
||||
contents: read
|
||||
uses: ./.github/workflows/pullfrog.yml
|
||||
with:
|
||||
# pass the full event payload as the prompt
|
||||
|
||||
@@ -36,8 +36,6 @@ outputs:
|
||||
runs:
|
||||
using: "node24"
|
||||
main: "entry.ts"
|
||||
post: "post.ts"
|
||||
post-if: "failure() || cancelled()"
|
||||
|
||||
branding:
|
||||
icon: "code"
|
||||
|
||||
@@ -210,6 +210,7 @@ async function runClaude(params: RunParams): Promise<ClaudeRunResult> {
|
||||
|
||||
let finalOutput = "";
|
||||
let sessionId: string | undefined;
|
||||
let resultErrorSubtype: string | null = null;
|
||||
let accumulatedTokens = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0 };
|
||||
// Claude CLI reports a single end-of-run `total_cost_usd` on the result
|
||||
// event. per-message events don't carry cost, so there's nothing to sum —
|
||||
@@ -367,9 +368,14 @@ async function runClaude(params: RunParams): Promise<ClaudeRunResult> {
|
||||
tokensLogged = true;
|
||||
}
|
||||
} else if (subtype === "error_max_turns") {
|
||||
resultErrorSubtype = subtype;
|
||||
log.info(`» ${params.label} max turns reached: ${JSON.stringify(event)}`);
|
||||
} else if (subtype === "error_during_execution") {
|
||||
resultErrorSubtype = subtype;
|
||||
log.info(`» ${params.label} execution error: ${JSON.stringify(event)}`);
|
||||
} else if (subtype.startsWith("error")) {
|
||||
resultErrorSubtype = subtype;
|
||||
log.info(`» ${params.label} result: subtype=${subtype}, data=${JSON.stringify(event)}`);
|
||||
} else {
|
||||
log.info(`» ${params.label} result: subtype=${subtype}, data=${JSON.stringify(event)}`);
|
||||
}
|
||||
@@ -527,6 +533,16 @@ async function runClaude(params: RunParams): Promise<ClaudeRunResult> {
|
||||
};
|
||||
}
|
||||
|
||||
if (resultErrorSubtype) {
|
||||
return {
|
||||
success: false,
|
||||
output: finalOutput || output,
|
||||
error: `result subtype: ${resultErrorSubtype}`,
|
||||
usage,
|
||||
sessionId,
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, output: finalOutput || output, usage, sessionId };
|
||||
} catch (error) {
|
||||
params.todoTracker?.cancel();
|
||||
@@ -703,6 +719,8 @@ export const claude = agent({
|
||||
initialResult: result,
|
||||
initialUsage: result.usage,
|
||||
stopScript: ctx.stopScript,
|
||||
summaryFilePath: ctx.summaryFilePath,
|
||||
summarySeed: ctx.summarySeed,
|
||||
reflectionPrompt: buildLearningsReflectionPrompt("claude"),
|
||||
canResume: (r) => Boolean(r.sessionId),
|
||||
resume: async (c) => {
|
||||
|
||||
+33
-1
@@ -254,7 +254,13 @@ interface OpenCodeErrorEvent {
|
||||
type: "error";
|
||||
timestamp?: string;
|
||||
sessionID?: string;
|
||||
error?: { name?: string; message?: string; data?: unknown; [key: string]: unknown };
|
||||
// opencode emits the error message under `error.data.message`, not at the
|
||||
// top level. see anomalyco/opencode packages/opencode/src/cli/cmd/run.ts.
|
||||
error?: {
|
||||
name?: string;
|
||||
data?: { message?: string; [key: string]: unknown };
|
||||
[key: string]: unknown;
|
||||
};
|
||||
[key: string]: unknown;
|
||||
}
|
||||
|
||||
@@ -630,6 +636,16 @@ async function runOpenCode(params: RunParams): Promise<AgentResult> {
|
||||
log.debug(withLabel(label, `tool output: ${outputStr}`));
|
||||
}
|
||||
},
|
||||
error: (event: OpenCodeErrorEvent) => {
|
||||
// opencode emits a `type=error` event when a provider call fails (e.g.
|
||||
// 401 Invalid authentication credentials). the underlying CLI still
|
||||
// exits 0 because the error was returned cleanly by the LLM SDK, so
|
||||
// unless we capture this event the run is reported as success.
|
||||
agentErrorEvent = event;
|
||||
const errorName = event.error?.name || "unknown";
|
||||
const errorMessage = event.error?.data?.message || event.error?.name || JSON.stringify(event);
|
||||
log.info(`» ${params.label} error event: ${errorName}: ${errorMessage}`);
|
||||
},
|
||||
result: async (event: OpenCodeResultEvent) => {
|
||||
const status = event.status || "unknown";
|
||||
const duration = event.stats?.duration_ms || 0;
|
||||
@@ -663,6 +679,7 @@ async function runOpenCode(params: RunParams): Promise<AgentResult> {
|
||||
const recentStderr: string[] = [];
|
||||
|
||||
let lastProviderError: string | null = null;
|
||||
let agentErrorEvent: OpenCodeErrorEvent | null = null;
|
||||
|
||||
let output = "";
|
||||
let stdoutBuffer = "";
|
||||
@@ -824,6 +841,19 @@ async function runOpenCode(params: RunParams): Promise<AgentResult> {
|
||||
};
|
||||
}
|
||||
|
||||
if (agentErrorEvent) {
|
||||
const errorEvent: OpenCodeErrorEvent = agentErrorEvent;
|
||||
const errorName = errorEvent.error?.name || "agent error";
|
||||
const errorMessage =
|
||||
errorEvent.error?.data?.message || errorEvent.error?.name || JSON.stringify(errorEvent);
|
||||
return {
|
||||
success: false,
|
||||
output: finalOutput || output,
|
||||
error: `${errorName}: ${errorMessage}`,
|
||||
usage,
|
||||
};
|
||||
}
|
||||
|
||||
return { success: true, output: finalOutput || output, usage };
|
||||
} catch (error) {
|
||||
params.todoTracker?.cancel();
|
||||
@@ -932,6 +962,8 @@ export const opencode = agent({
|
||||
initialResult: result,
|
||||
initialUsage: result.usage,
|
||||
stopScript: ctx.stopScript,
|
||||
summaryFilePath: ctx.summaryFilePath,
|
||||
summarySeed: ctx.summarySeed,
|
||||
reflectionPrompt: buildLearningsReflectionPrompt("opencode"),
|
||||
resume: async (c) =>
|
||||
runOpenCode({
|
||||
|
||||
+82
-3
@@ -1,3 +1,4 @@
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { type AgentId, formatMcpToolRef } from "../external.ts";
|
||||
import { LIFECYCLE_HOOK_TIMEOUT_MS } from "../lifecycle.ts";
|
||||
import { log } from "../utils/cli.ts";
|
||||
@@ -92,13 +93,46 @@ export function buildStopHookPrompt(failure: StopHookFailure): string {
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/** check whether the seeded summary file is byte-identical to its seed.
|
||||
* a missing or unreadable file returns false (don't nudge — the agent
|
||||
* may have legitimately deleted it, or the seed step failed; the read-
|
||||
* back path in main.ts handles both cases by skipping persist). */
|
||||
async function isSummaryUnchanged(filePath: string, seed: string): Promise<boolean> {
|
||||
try {
|
||||
const current = await readFile(filePath, "utf8");
|
||||
return current === seed;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
export function buildSummaryStalePrompt(filePath: string): string {
|
||||
return [
|
||||
`PR SUMMARY UNTOUCHED — the rolling PR summary file at \`${filePath}\` is byte-identical to its seed; this run did not edit it.`,
|
||||
"",
|
||||
"review the diff and update the file in place to reflect what changed in the PR. update intent, key changes, and any risks worth flagging — keep the existing section headings stable so incremental runs produce clean diffs.",
|
||||
"",
|
||||
"if the diff is genuinely too small or noisy to warrant rewriting (e.g. a one-line typo fix, a comment tweak, a formatting-only change), it's fine to leave the structure as-is — but at minimum confirm you considered it by appending one line to the appropriate section noting the run. silence is not an option; the snapshot is what the next review run reads as context.",
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* check the two post-run gates: did the stop hook pass and is the working
|
||||
* tree clean? returns everything that still needs fixing so the caller can
|
||||
* check the post-run gates: did the stop hook pass, is the working tree
|
||||
* clean, and (when applicable) did the agent touch the rolling PR summary
|
||||
* snapshot? returns everything that still needs nudging so the caller can
|
||||
* render a single combined resume prompt.
|
||||
*
|
||||
* the summary-stale check is skipped when `summaryFilePath` / `summarySeed`
|
||||
* are not provided; this is the common case (non-PR runs, runs where the
|
||||
* dispatcher didn't request snapshot generation, runs where the seed step
|
||||
* failed). loop callers also pass these as undefined after the agent has
|
||||
* already been nudged once, to avoid burning the retry budget on a soft
|
||||
* non-blocking gate.
|
||||
*/
|
||||
export async function collectPostRunIssues(params: {
|
||||
stopScript: string | null | undefined;
|
||||
summaryFilePath?: string | undefined;
|
||||
summarySeed?: string | undefined;
|
||||
}): Promise<PostRunIssues> {
|
||||
const issues: PostRunIssues = {};
|
||||
if (params.stopScript) {
|
||||
@@ -107,6 +141,10 @@ export async function collectPostRunIssues(params: {
|
||||
}
|
||||
const status = getGitStatus();
|
||||
if (status) issues.dirtyTree = status;
|
||||
if (params.summaryFilePath && params.summarySeed !== undefined) {
|
||||
const stale = await isSummaryUnchanged(params.summaryFilePath, params.summarySeed);
|
||||
if (stale) issues.summaryStale = { filePath: params.summaryFilePath };
|
||||
}
|
||||
return issues;
|
||||
}
|
||||
|
||||
@@ -114,6 +152,7 @@ export function buildPostRunPrompt(issues: PostRunIssues): string {
|
||||
const parts: string[] = [];
|
||||
if (issues.stopHook) parts.push(buildStopHookPrompt(issues.stopHook));
|
||||
if (issues.dirtyTree) parts.push(buildCommitPrompt(issues.dirtyTree));
|
||||
if (issues.summaryStale) parts.push(buildSummaryStalePrompt(issues.summaryStale.filePath));
|
||||
return parts.join("\n\n---\n\n");
|
||||
}
|
||||
|
||||
@@ -164,6 +203,14 @@ export async function runPostRunRetryLoop<R extends AgentResult>(params: {
|
||||
initialResult: R;
|
||||
initialUsage: AgentUsage | undefined;
|
||||
stopScript: string | null | undefined;
|
||||
/** absolute path to the seeded PR summary file. when set together with
|
||||
* `summarySeed`, the loop checks after each agent attempt whether the
|
||||
* file has been edited; if not, it nudges the agent ONCE via a resume
|
||||
* turn (subsequent iterations skip the check so we don't keep burning
|
||||
* retries on a soft gate when the agent has decided no edit is warranted). */
|
||||
summaryFilePath?: string | undefined;
|
||||
/** exact bytes of the seeded summary file used for the unchanged-check. */
|
||||
summarySeed?: string | undefined;
|
||||
resume: (context: { prompt: string; previousResult: R }) => Promise<R>;
|
||||
canResume?: ((result: R) => boolean) | undefined;
|
||||
reflectionPrompt?: string | undefined;
|
||||
@@ -173,10 +220,21 @@ export async function runPostRunRetryLoop<R extends AgentResult>(params: {
|
||||
let finalIssues: PostRunIssues = {};
|
||||
let gateResumeCount = 0;
|
||||
let pendingReflection = params.reflectionPrompt;
|
||||
// nudge for an untouched summary file fires AT MOST ONCE per run. after
|
||||
// we've delivered the prompt, subsequent gate checks pass undefined so
|
||||
// the loop doesn't keep flagging the same condition — the agent may have
|
||||
// legitimately decided no edit is warranted, and re-prompting would
|
||||
// burn the retry budget without adding signal.
|
||||
let summaryStaleNudged = false;
|
||||
|
||||
while (gateResumeCount < MAX_POST_RUN_RETRIES) {
|
||||
if (!result.success) break;
|
||||
const issues = await collectPostRunIssues({ stopScript: params.stopScript });
|
||||
const issues = await collectPostRunIssues({
|
||||
stopScript: params.stopScript,
|
||||
summaryFilePath: summaryStaleNudged ? undefined : params.summaryFilePath,
|
||||
summarySeed: summaryStaleNudged ? undefined : params.summarySeed,
|
||||
});
|
||||
if (issues.summaryStale) summaryStaleNudged = true;
|
||||
finalIssues = issues;
|
||||
|
||||
if (!hasPostRunIssues(issues)) {
|
||||
@@ -230,8 +288,25 @@ export async function runPostRunRetryLoop<R extends AgentResult>(params: {
|
||||
|
||||
log.info(`» post-run retry (attempt ${gateResumeCount + 1}/${MAX_POST_RUN_RETRIES})`);
|
||||
const prompt = buildPostRunPrompt(issues);
|
||||
// summary-stale is a soft gate that must never flip a successful run to
|
||||
// failed. when it's the only issue and the resume itself errors out,
|
||||
// restore the pre-resume successful result and break — persistSummary
|
||||
// detects the unchanged file via its seed comparison and skips the DB
|
||||
// write on its own, so no further coordination is needed here.
|
||||
const onlySummaryStale =
|
||||
issues.summaryStale !== undefined &&
|
||||
issues.stopHook === undefined &&
|
||||
issues.dirtyTree === undefined;
|
||||
const preResume = result;
|
||||
result = await params.resume({ prompt, previousResult: result });
|
||||
aggregatedUsage = mergeAgentUsage(aggregatedUsage, result.usage);
|
||||
if (!result.success && onlySummaryStale) {
|
||||
log.warning(
|
||||
`» summary-stale resume turn failed (${result.error ?? "unknown error"}), preserving prior successful result`
|
||||
);
|
||||
result = preResume;
|
||||
break;
|
||||
}
|
||||
gateResumeCount++;
|
||||
}
|
||||
|
||||
@@ -242,6 +317,10 @@ export async function runPostRunRetryLoop<R extends AgentResult>(params: {
|
||||
// already observed a clean state we skip: re-running the hook risks flaky
|
||||
// false-positive failures right after it just passed.
|
||||
if (gateResumeCount > 0 && result.success && hasPostRunIssues(finalIssues)) {
|
||||
// re-check the gates that can actually fail the run (stop hook /
|
||||
// dirty tree). summary-stale is intentionally NOT re-checked here:
|
||||
// we already delivered the one-shot nudge, and a still-unchanged
|
||||
// file at this point is the agent's deliberate choice.
|
||||
finalIssues = await collectPostRunIssues({ stopScript: params.stopScript });
|
||||
}
|
||||
|
||||
|
||||
+28
-1
@@ -42,13 +42,26 @@ export interface StopHookFailure {
|
||||
output: string;
|
||||
}
|
||||
|
||||
export interface SummaryStale {
|
||||
/** absolute path to the seeded snapshot file the agent was meant to edit. */
|
||||
filePath: string;
|
||||
}
|
||||
|
||||
export interface PostRunIssues {
|
||||
stopHook?: StopHookFailure;
|
||||
dirtyTree?: string;
|
||||
/** populated when the rolling PR summary file is byte-identical to its
|
||||
* seed, i.e. the agent never touched it. soft gate — nudges once via a
|
||||
* resume turn but never fails the run, parallel to dirtyTree semantics. */
|
||||
summaryStale?: SummaryStale;
|
||||
}
|
||||
|
||||
export function hasPostRunIssues(issues: PostRunIssues): boolean {
|
||||
return issues.stopHook !== undefined || issues.dirtyTree !== undefined;
|
||||
return (
|
||||
issues.stopHook !== undefined ||
|
||||
issues.dirtyTree !== undefined ||
|
||||
issues.summaryStale !== undefined
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,6 +119,20 @@ export interface AgentRunContext {
|
||||
* guidance. null when the repo has no stop hook configured.
|
||||
*/
|
||||
stopScript?: string | null | undefined;
|
||||
/**
|
||||
* absolute path to the rolling PR summary tmpfile, when one was seeded
|
||||
* for this run (Review / IncrementalReview / pr-summary Task). enables
|
||||
* a post-run sanity nudge that prompts the agent if the file is still
|
||||
* byte-identical to its seed.
|
||||
*/
|
||||
summaryFilePath?: string | undefined;
|
||||
/**
|
||||
* exact bytes of the seeded summary file. compared against the current
|
||||
* file content after each agent attempt to detect "agent forgot to edit
|
||||
* the summary" — particularly common with smaller models that lose
|
||||
* track of multi-step instructions.
|
||||
*/
|
||||
summarySeed?: string | undefined;
|
||||
/**
|
||||
* called synchronously when the agent subprocess is killed for inner
|
||||
* activity timeout. lets main.ts tear down shared resources (MCP HTTP
|
||||
|
||||
+52
-26
@@ -2,8 +2,6 @@ import { dirname } from "node:path";
|
||||
import * as core from "@actions/core";
|
||||
import arg from "arg";
|
||||
import { main } from "../main.ts";
|
||||
import { log } from "../utils/cli.ts";
|
||||
import { runPostCleanup } from "../utils/postCleanup.ts";
|
||||
import { acquireInstallationToken, revokeInstallationToken } from "../utils/token.ts";
|
||||
|
||||
// GitHub Actions runs the action entry point with the node24 binary specified
|
||||
@@ -31,16 +29,6 @@ async function runMain(): Promise<void> {
|
||||
}
|
||||
}
|
||||
|
||||
async function runPost(): Promise<void> {
|
||||
log.debug(`[post] script started at ${new Date().toISOString()}`);
|
||||
try {
|
||||
await runPostCleanup();
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
log.error(`[post] unexpected error: ${message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async function tokenMain(): Promise<void> {
|
||||
const reposInput = core.getInput("repos");
|
||||
const additionalRepos = reposInput
|
||||
@@ -73,7 +61,7 @@ async function tokenPost(): Promise<void> {
|
||||
}
|
||||
|
||||
function printGhaUsage(params: { stream: typeof console.log; prog: string }): void {
|
||||
params.stream(`usage: ${params.prog} gha [token] [--post]\n`);
|
||||
params.stream(`usage: ${params.prog} gha [subcommand]\n`);
|
||||
params.stream("run the github action runtime flow.");
|
||||
params.stream("");
|
||||
params.stream("subcommands:");
|
||||
@@ -81,10 +69,31 @@ function printGhaUsage(params: { stream: typeof console.log; prog: string }): vo
|
||||
params.stream("");
|
||||
params.stream("options:");
|
||||
params.stream(" -h, --help show help");
|
||||
params.stream(" --post run post-cleanup flow");
|
||||
}
|
||||
|
||||
function printGhaTokenUsage(params: { stream: typeof console.log; prog: string }): void {
|
||||
params.stream(`usage: ${params.prog} gha token [--post]\n`);
|
||||
params.stream("acquire a github app installation token, or revoke it in the post step.");
|
||||
params.stream("");
|
||||
params.stream("options:");
|
||||
params.stream(" -h, --help show help");
|
||||
params.stream(" --post revoke the previously-acquired token (post-step usage only)");
|
||||
}
|
||||
|
||||
function parseGhaArgs(args: string[]) {
|
||||
return arg(
|
||||
{
|
||||
"--help": Boolean,
|
||||
"-h": "--help",
|
||||
},
|
||||
{
|
||||
argv: args,
|
||||
stopAtPositional: true,
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function parseGhaTokenArgs(args: string[]) {
|
||||
return arg(
|
||||
{
|
||||
"--help": Boolean,
|
||||
@@ -118,27 +127,46 @@ export async function runCli(params: GhaCliParams): Promise<void> {
|
||||
return;
|
||||
}
|
||||
|
||||
const normalizedArgs = ["gha"];
|
||||
const positional = parsed._;
|
||||
const subcommand = positional[0];
|
||||
|
||||
if (positional.length > 1) {
|
||||
console.error(`unexpected positional arguments for gha: ${positional.slice(1).join(" ")}\n`);
|
||||
if (!subcommand) {
|
||||
await run(["gha"]);
|
||||
return;
|
||||
}
|
||||
|
||||
if (subcommand !== "token") {
|
||||
console.error(`unknown gha subcommand: ${subcommand}\n`);
|
||||
printGhaUsage({ stream: console.error, prog: params.prog });
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (positional[0] === "token") {
|
||||
normalizedArgs.push("token");
|
||||
} else if (positional[0]) {
|
||||
console.error(`unknown gha subcommand: ${positional[0]}\n`);
|
||||
printGhaUsage({ stream: console.error, prog: params.prog });
|
||||
// gha token [--post]
|
||||
let tokenParsed: ReturnType<typeof parseGhaTokenArgs>;
|
||||
try {
|
||||
tokenParsed = parseGhaTokenArgs(positional.slice(1));
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`${message}\n`);
|
||||
printGhaTokenUsage({ stream: console.error, prog: params.prog });
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
if (parsed["--post"]) {
|
||||
if (tokenParsed["--help"]) {
|
||||
printGhaTokenUsage({ stream: console.log, prog: params.prog });
|
||||
return;
|
||||
}
|
||||
|
||||
if (tokenParsed._.length > 0) {
|
||||
console.error(`unexpected positional arguments for gha token: ${tokenParsed._.join(" ")}\n`);
|
||||
printGhaTokenUsage({ stream: console.error, prog: params.prog });
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const normalizedArgs = ["gha", "token"];
|
||||
if (tokenParsed["--post"]) {
|
||||
normalizedArgs.push("--post");
|
||||
}
|
||||
|
||||
await run(normalizedArgs);
|
||||
}
|
||||
|
||||
@@ -150,8 +178,6 @@ export async function run(args: string[]) {
|
||||
} else {
|
||||
await tokenMain();
|
||||
}
|
||||
} else if (args.includes("--post")) {
|
||||
await runPost();
|
||||
} else {
|
||||
await runMain();
|
||||
}
|
||||
|
||||
+4
-2
@@ -279,8 +279,10 @@ export interface WriteablePayload {
|
||||
timeout?: string | undefined;
|
||||
/** working directory for the agent */
|
||||
cwd?: string | undefined;
|
||||
/** pre-created progress comment ID for updating status */
|
||||
progressCommentId?: string | undefined;
|
||||
/** pre-created progress comment (ID + type) for updating status */
|
||||
progressComment?: { id: string; type: "issue" | "review" } | undefined;
|
||||
/** when true, seed the PR summary tmpfile + persist edits at run end */
|
||||
generateSummary?: boolean | undefined;
|
||||
}
|
||||
|
||||
// immutable payload type for agent execution
|
||||
|
||||
@@ -40,6 +40,21 @@ export {
|
||||
stripExistingFooter,
|
||||
} from "../utils/buildPullfrogFooter.ts";
|
||||
export type { ResourceUsage, UsageSummary } from "../utils/github.ts";
|
||||
export {
|
||||
isLeapingIntoActionCommentBody,
|
||||
LEAPING_INTO_ACTION_PREFIX,
|
||||
} from "../utils/leapingComment.ts";
|
||||
export type {
|
||||
CreateProgressCommentTarget,
|
||||
ProgressComment,
|
||||
ProgressCommentType,
|
||||
} from "../utils/progressComment.ts";
|
||||
export {
|
||||
createLeapingProgressComment,
|
||||
deleteProgressCommentApi,
|
||||
getProgressComment,
|
||||
updateProgressComment,
|
||||
} from "../utils/progressComment.ts";
|
||||
export {
|
||||
isValidTimeString,
|
||||
parseTimeString,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
// changes to tool permissions should be reflected in wiki/granular-tools.md
|
||||
|
||||
import { existsSync, readdirSync } from "node:fs";
|
||||
import { readFile } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import * as core from "@actions/core";
|
||||
import { deleteProgressComment, reportProgress } from "./mcp/comment.ts";
|
||||
@@ -34,8 +35,10 @@ import { executeLifecycleHook } from "./utils/lifecycle.ts";
|
||||
import { normalizeEnv } from "./utils/normalizeEnv.ts";
|
||||
import { aggregateUsage, patchWorkflowRunFields } from "./utils/patchWorkflowRunFields.ts";
|
||||
import { resolvePayload, resolvePromptInput } from "./utils/payload.ts";
|
||||
import { readSummaryFile, seedSummaryFile } from "./utils/prSummary.ts";
|
||||
import { postReviewCleanup } from "./utils/reviewCleanup.ts";
|
||||
import { handleAgentResult } from "./utils/run.ts";
|
||||
import { type AccountPlan, isInfraCovered } from "./utils/runContext.ts";
|
||||
import { resolveRunContextData } from "./utils/runContextData.ts";
|
||||
import { setEnvAllowlist } from "./utils/secrets.ts";
|
||||
import { createTempDirectory, setupGit } from "./utils/setup.ts";
|
||||
@@ -111,6 +114,142 @@ interface OidcCredentials {
|
||||
requestToken: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Billing-layer error surfaced from `/api/proxy-token` as a 402. User-actionable
|
||||
* — distinct from TransientError (503 / transient sync issue) so the job
|
||||
* summary + PR comment can use affirmative "you need to do X" copy rather than
|
||||
* the ambiguous "billing error" label that makes transient outages look like
|
||||
* the user's fault.
|
||||
*
|
||||
* `code` is a server-side discriminator: `router_requires_card` (no card + no
|
||||
* wallet balance on Router), or null for unclassified. `declineCode` is
|
||||
* Stripe's more specific sub-reason on `card_declined` (e.g.
|
||||
* `insufficient_funds`, `lost_card`). `needsReauthentication` is the 3DS case
|
||||
* broken out for convenience.
|
||||
*/
|
||||
class BillingError extends Error {
|
||||
code: string | null;
|
||||
declineCode: string | null;
|
||||
needsReauthentication: boolean;
|
||||
|
||||
constructor(
|
||||
message: string,
|
||||
opts: {
|
||||
code?: string | null;
|
||||
declineCode?: string | null;
|
||||
needsReauthentication?: boolean;
|
||||
} = {}
|
||||
) {
|
||||
super(message);
|
||||
this.name = "BillingError";
|
||||
this.code = opts.code ?? null;
|
||||
this.declineCode = opts.declineCode ?? null;
|
||||
this.needsReauthentication = opts.needsReauthentication ?? false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Transient service failures from `/api/proxy-token` (503: partial OpenRouter
|
||||
* usage sync, DB flake, in-flight payment intent). Not the user's fault — the
|
||||
* summary uses "temporarily unavailable" framing, and the non-zero exit lets
|
||||
* GH Actions apply whatever retry policy the workflow has configured.
|
||||
*/
|
||||
class TransientError extends Error {
|
||||
constructor(message: string) {
|
||||
super(message);
|
||||
this.name = "TransientError";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Deep link into the right console section for the failing account. Anchors
|
||||
* are defined in `app/console/[owner]/page.tsx` (`#billing`, `#model-access`).
|
||||
* `owner` is the GitHub login of the repo's account — i.e. the org or user
|
||||
* that pays for this repo's runs, which is the right scope for billing.
|
||||
*/
|
||||
function billingConsoleUrl(owner: string, anchor: "billing" | "model-access"): string {
|
||||
return `https://pullfrog.com/console/${encodeURIComponent(owner)}#${anchor}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a BillingError as user-facing markdown (shared between GH job summary
|
||||
* and the PR progress comment). Goals:
|
||||
*
|
||||
* - quiet, not alarmist — bold first line instead of an `### ❌` H3, since
|
||||
* the comment already has Pullfrog branding in the footer
|
||||
* - actionable — every branch ends in a single CTA deep-linked to the
|
||||
* correct section of the owner's console
|
||||
* - honest — say what actually went wrong (card declined vs. balance
|
||||
* empty vs. 3DS required), don't lump them under "billing error"
|
||||
*
|
||||
* Branches:
|
||||
* - `router_requires_card`: user is on Router mode with no card AND no
|
||||
* wallet balance. Lead with the carrot ($20 free credit), link to
|
||||
* `#model-access` where the Add Card flow lives.
|
||||
* - `needsReauthentication`: issuer requires 3DS on every off-session
|
||||
* charge. Re-adding the card won't help — the only escape is a manual
|
||||
* top-up where 3DS runs interactively in Stripe Checkout.
|
||||
* - `declineCode` set: Stripe declined a real charge. Show the sub-code
|
||||
* so support can act on it; tell the user we'll retry on next dispatch.
|
||||
* - default: balance hit zero with no in-flight charge (auto-reload off
|
||||
* or amount below threshold). Direct them to top up or enable auto-reload.
|
||||
*/
|
||||
function formatBillingErrorSummary(error: BillingError, owner: string): string {
|
||||
if (error.code === "router_requires_card") {
|
||||
return [
|
||||
"**Add a card to start using Pullfrog Router.**",
|
||||
"",
|
||||
"Router proxies OpenRouter at raw cost — no platform markup, and your first $20 of usage is on us.",
|
||||
"",
|
||||
`[Add a card →](${billingConsoleUrl(owner, "model-access")})`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
if (error.needsReauthentication) {
|
||||
const code = error.declineCode ?? "authentication_required";
|
||||
return [
|
||||
`**Your card issuer requires 3D Secure on every charge** (\`${code}\`).`,
|
||||
"",
|
||||
"Pullfrog can't complete a 3DS challenge from inside a workflow. Top up your Router balance once in Stripe Checkout — subsequent runs draw from the prepaid balance without re-triggering 3DS.",
|
||||
"",
|
||||
`[Top up balance →](${billingConsoleUrl(owner, "billing")})`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
if (error.declineCode) {
|
||||
return [
|
||||
`**Your card was declined** (\`${error.declineCode}\`).`,
|
||||
"",
|
||||
"Update your payment method and Pullfrog will retry on the next run.",
|
||||
"",
|
||||
`[Update payment method →](${billingConsoleUrl(owner, "billing")})`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
return [
|
||||
"**Your Pullfrog balance is empty.**",
|
||||
"",
|
||||
"Top up your balance or enable auto-reload to keep runs flowing.",
|
||||
"",
|
||||
`[Manage billing →](${billingConsoleUrl(owner, "billing")})`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a TransientError as user-facing markdown. Distinct framing from
|
||||
* BillingError so the user doesn't read an alarm and assume their card
|
||||
* failed — this branch is "our fault, retry shortly", not theirs.
|
||||
*/
|
||||
function formatTransientErrorSummary(error: TransientError, owner: string): string {
|
||||
return [
|
||||
"**Pullfrog billing is temporarily unavailable.**",
|
||||
"",
|
||||
error.message,
|
||||
"",
|
||||
`Usually transient — the next dispatch should succeed. If it persists, check [status.pullfrog.com](https://status.pullfrog.com) or [your console](${billingConsoleUrl(owner, "billing")}).`,
|
||||
].join("\n");
|
||||
}
|
||||
|
||||
async function mintProxyKey(ctx: { oidcCredentials: OidcCredentials }): Promise<string | null> {
|
||||
try {
|
||||
process.env.ACTIONS_ID_TOKEN_REQUEST_URL = ctx.oidcCredentials.requestUrl;
|
||||
@@ -125,6 +264,31 @@ async function mintProxyKey(ctx: { oidcCredentials: OidcCredentials }): Promise<
|
||||
headers: { Authorization: `Bearer ${oidcToken}` },
|
||||
});
|
||||
|
||||
if (response.status === 402) {
|
||||
const body = (await response.json().catch(() => null)) as {
|
||||
error?: string;
|
||||
code?: string;
|
||||
declineCode?: string;
|
||||
needsReauthentication?: boolean;
|
||||
} | null;
|
||||
throw new BillingError(body?.error ?? "insufficient balance", {
|
||||
code: body?.code ?? null,
|
||||
declineCode: body?.declineCode ?? null,
|
||||
needsReauthentication: body?.needsReauthentication ?? false,
|
||||
});
|
||||
}
|
||||
|
||||
// 503 = transient sync issue (partial OpenRouter failure, DB flake,
|
||||
// in-flight top-up). Not the user's fault — TransientError renders a
|
||||
// "temporarily unavailable" summary instead of the "billing error"
|
||||
// label that BillingError uses.
|
||||
if (response.status === 503) {
|
||||
const body = (await response.json().catch(() => null)) as { error?: string } | null;
|
||||
throw new TransientError(
|
||||
body?.error ?? "billing service temporarily unavailable — retry shortly"
|
||||
);
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
log.warning(`proxy key mint failed (${response.status})`);
|
||||
return null;
|
||||
@@ -133,6 +297,8 @@ async function mintProxyKey(ctx: { oidcCredentials: OidcCredentials }): Promise<
|
||||
const data = (await response.json()) as { key: string };
|
||||
return data.key;
|
||||
} catch (error) {
|
||||
if (error instanceof BillingError) throw error;
|
||||
if (error instanceof TransientError) throw error;
|
||||
log.warning(`proxy key mint error: ${error instanceof Error ? error.message : String(error)}`);
|
||||
return null;
|
||||
} finally {
|
||||
@@ -144,29 +310,90 @@ async function mintProxyKey(ctx: { oidcCredentials: OidcCredentials }): Promise<
|
||||
async function resolveProxyModel(ctx: {
|
||||
payload: ResolvedPayload;
|
||||
oss: boolean;
|
||||
plan: AccountPlan;
|
||||
proxyModel?: string | undefined;
|
||||
oidcCredentials: OidcCredentials | null;
|
||||
}): Promise<void> {
|
||||
// env override = BYOK escape hatch, don't proxy
|
||||
if (process.env.PULLFROG_MODEL?.trim()) return;
|
||||
|
||||
// OSS: server decided the model
|
||||
if (ctx.oss && ctx.proxyModel) {
|
||||
if (!ctx.oidcCredentials) {
|
||||
log.warning("» oss repo but no OIDC credentials available — skipping proxy");
|
||||
return;
|
||||
}
|
||||
const key = await mintProxyKey({ oidcCredentials: ctx.oidcCredentials });
|
||||
if (!key) return;
|
||||
const needsProxy = isInfraCovered({ isOss: ctx.oss, plan: ctx.plan }) && ctx.proxyModel;
|
||||
if (!needsProxy) return;
|
||||
|
||||
process.env.OPENROUTER_API_KEY = key;
|
||||
core.setSecret(key);
|
||||
ctx.payload.proxyModel = ctx.proxyModel;
|
||||
log.info(`» proxy: oss → ${ctx.proxyModel}`);
|
||||
if (!ctx.oidcCredentials) {
|
||||
log.warning("» proxy requested but no OIDC credentials available — skipping");
|
||||
return;
|
||||
}
|
||||
|
||||
// managed billing will add its path here later
|
||||
const key = await mintProxyKey({ oidcCredentials: ctx.oidcCredentials });
|
||||
if (!key) return;
|
||||
|
||||
process.env.OPENROUTER_API_KEY = key;
|
||||
core.setSecret(key);
|
||||
ctx.payload.proxyModel = ctx.proxyModel;
|
||||
const label = ctx.oss ? "oss" : "router";
|
||||
log.info(`» proxy: ${label} → ${ctx.proxyModel}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the most recent persisted PR summary snapshot for this PR.
|
||||
* Returns null on first-time PRs, when summary is disabled, or on any error.
|
||||
* Best-effort: a transient API failure should not block the run.
|
||||
*/
|
||||
async function fetchPreviousSnapshot(ctx: ToolContext, prNumber: number): Promise<string | null> {
|
||||
if (!ctx.githubInstallationToken) return null;
|
||||
try {
|
||||
const response = await apiFetch({
|
||||
path: `/api/repo/${ctx.repo.owner}/${ctx.repo.name}/pr/${prNumber}/summary-comment`,
|
||||
method: "GET",
|
||||
headers: { authorization: `Bearer ${ctx.githubInstallationToken}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
if (!response.ok) return null;
|
||||
const data = (await response.json()) as { snapshot?: string | null };
|
||||
return typeof data.snapshot === "string" && data.snapshot.length > 0 ? data.snapshot : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the agent-edited PR summary tmpfile and persist to `WorkflowRun.summarySnapshot`.
|
||||
*
|
||||
* Best-effort: any failure is logged and does not affect the run's success
|
||||
* status. Skips the PATCH when the file is byte-identical to its seed —
|
||||
* persisting the seed verbatim would either re-write what the DB already has
|
||||
* (on incremental runs) or serialize the placeholder scaffold (on first
|
||||
* runs), neither of which is useful.
|
||||
*/
|
||||
async function persistSummary(ctx: ToolContext): Promise<void> {
|
||||
const filePath = ctx.toolState.summaryFilePath;
|
||||
if (!filePath) return;
|
||||
// already-completed guard: the error-path call (success path persisted,
|
||||
// then a late step threw) and the SIGINT/SIGTERM handler all funnel
|
||||
// through here; the first one to arrive wins.
|
||||
if (ctx.toolState.summaryPersistAttempted) return;
|
||||
ctx.toolState.summaryPersistAttempted = true;
|
||||
const snapshot = await readSummaryFile(filePath);
|
||||
if (!snapshot) {
|
||||
log.debug(`pr summary tmpfile missing or invalid at ${filePath} — skipping persist`);
|
||||
return;
|
||||
}
|
||||
// soft gate: agent never touched the seeded file. saving the seed back
|
||||
// is a no-op at best (incremental run — DB already has it) and a bug at
|
||||
// worst (first run — serializes the placeholder italics). log a warning
|
||||
// so the failure mode is visible in CI without flipping the run to
|
||||
// failed.
|
||||
const seed = ctx.toolState.summarySeed?.trim();
|
||||
if (seed !== undefined && snapshot === seed) {
|
||||
log.warning(
|
||||
"» pr summary tmpfile unchanged from seed — skipping persist (agent did not edit it)"
|
||||
);
|
||||
return;
|
||||
}
|
||||
await patchWorkflowRunFields(ctx, { summarySnapshot: snapshot }).catch((err) => {
|
||||
log.debug(`pr summary persist failed: ${err instanceof Error ? err.message : String(err)}`);
|
||||
});
|
||||
}
|
||||
|
||||
async function writeJobSummary(toolState: ToolState): Promise<void> {
|
||||
@@ -191,12 +418,12 @@ export async function main(): Promise<MainResult> {
|
||||
let activityTimeout: ActivityTimeout | null = null;
|
||||
let safetyNetTimer: NodeJS.Timeout | undefined;
|
||||
|
||||
// parse prompt early to extract progressCommentId for toolState
|
||||
// parse prompt early to extract progressComment for toolState
|
||||
const resolvedPromptInput = resolvePromptInput();
|
||||
|
||||
const toolState = initToolState({
|
||||
progressCommentId:
|
||||
typeof resolvedPromptInput !== "string" ? resolvedPromptInput.progressCommentId : undefined,
|
||||
progressComment:
|
||||
typeof resolvedPromptInput !== "string" ? resolvedPromptInput.progressComment : undefined,
|
||||
});
|
||||
|
||||
// resolve and fingerprint git binary before any agent code runs
|
||||
@@ -251,13 +478,39 @@ export async function main(): Promise<MainResult> {
|
||||
delete process.env.ACTIONS_ID_TOKEN_REQUEST_TOKEN;
|
||||
}
|
||||
|
||||
// proxy decision: mint an OpenRouter key for OSS repos (or later, managed billing)
|
||||
await resolveProxyModel({
|
||||
payload,
|
||||
oss: runContext.oss,
|
||||
proxyModel: runContext.proxyModel,
|
||||
oidcCredentials,
|
||||
});
|
||||
// Proxy decision: mint an OpenRouter key for OSS repos or managed billing
|
||||
// accounts. BillingError (402) and TransientError (503) both surface here.
|
||||
// Handle explicitly so the user sees an actionable message (job summary +
|
||||
// PR progress comment when one exists) — otherwise the error unwinds past
|
||||
// the main try/catch (which needs toolState) and lands in runMain with only
|
||||
// a generic core.setFailed.
|
||||
try {
|
||||
await resolveProxyModel({
|
||||
payload,
|
||||
oss: runContext.oss,
|
||||
plan: runContext.plan,
|
||||
proxyModel: runContext.proxyModel,
|
||||
oidcCredentials,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof BillingError) {
|
||||
const summary = formatBillingErrorSummary(error, runContext.repo.owner);
|
||||
await writeSummary(summary).catch(() => {});
|
||||
// Mirror to the PR progress comment if the trigger created one
|
||||
// (mention / PR event). Without this, auto-reload declines are only
|
||||
// visible in the job summary — users rarely open that, so the agent
|
||||
// just appears to silently stop mid-run.
|
||||
await reportErrorToComment({ toolState, error: summary }).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
if (error instanceof TransientError) {
|
||||
const summary = formatTransientErrorSummary(error, runContext.repo.owner);
|
||||
await writeSummary(summary).catch(() => {});
|
||||
await reportErrorToComment({ toolState, error: summary }).catch(() => {});
|
||||
throw error;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
|
||||
// create octokit with MCP token for GitHub API calls
|
||||
const octokit = createOctokit(tokenRef.mcpToken);
|
||||
@@ -350,6 +603,8 @@ export async function main(): Promise<MainResult> {
|
||||
jobId: runInfo.jobId,
|
||||
mcpServerUrl: "",
|
||||
tmpdir,
|
||||
oss: runContext.oss,
|
||||
plan: runContext.plan,
|
||||
resolvedModel,
|
||||
};
|
||||
await using mcpHttpServer = await startMcpHttpServer(toolContext, { outputSchema });
|
||||
@@ -357,6 +612,40 @@ export async function main(): Promise<MainResult> {
|
||||
log.info(`» MCP server started at ${mcpHttpServer.url}`);
|
||||
timer.checkpoint("mcpServer");
|
||||
|
||||
// seed the rolling PR summary tmpfile when the dispatcher requested it.
|
||||
// gated on event being a PR — issue/workflow_dispatch runs have no
|
||||
// summarySnapshot to maintain. file path is exposed to the agent via
|
||||
// the select_mode response addendum (action/mcp/selectMode.ts).
|
||||
if (payload.generateSummary && payload.event.is_pr && payload.event.issue_number) {
|
||||
const previousSnapshot = await fetchPreviousSnapshot(toolContext, payload.event.issue_number);
|
||||
const filePath = await seedSummaryFile({ tmpdir, previousSnapshot });
|
||||
toolState.summaryFilePath = filePath;
|
||||
// capture the exact bytes the agent will see at startup. used by
|
||||
// the post-run retry loop to detect the agent forgetting to edit
|
||||
// the file (byte-identical to seed → nudge once via resume turn)
|
||||
// and by persistSummary to skip the DB write when nothing changed.
|
||||
// we just wrote the file, so the read shouldn't fail; the catch
|
||||
// leaves summarySeed unset (its default), in which case the unchanged
|
||||
// checks downstream are simply skipped.
|
||||
try {
|
||||
toolState.summarySeed = await readFile(filePath, "utf8");
|
||||
} catch {
|
||||
// intentionally empty — summarySeed stays undefined
|
||||
}
|
||||
log.info(
|
||||
`» summary snapshot seeded at ${filePath} (previous=${previousSnapshot ? "yes" : "no"})`
|
||||
);
|
||||
// on SIGINT/SIGTERM we still want to persist whatever the agent has
|
||||
// written so far. handler is best-effort: any failure inside is
|
||||
// swallowed by Promise.allSettled in exitHandler.ts, and the
|
||||
// summaryPersistAttempted guard prevents double-execution if the
|
||||
// signal arrives after the normal path already persisted. capture a
|
||||
// narrowed reference so the closure doesn't depend on the outer
|
||||
// `toolContext` variable being defined later.
|
||||
const ctxForExit = toolContext;
|
||||
onExitSignal(() => persistSummary(ctxForExit));
|
||||
}
|
||||
|
||||
startInstallation(toolContext);
|
||||
|
||||
const modelForLog = resolveModelForLog({ payload, resolvedModel });
|
||||
@@ -421,6 +710,16 @@ export async function main(): Promise<MainResult> {
|
||||
});
|
||||
toolState.todoTracker = todoTracker;
|
||||
|
||||
// on cancellation, stop scheduling new tracker writes immediately. without this, a
|
||||
// debounced write queued just before SIGTERM could land at GitHub *after* the
|
||||
// workflow_run.completed webhook has already replaced the comment with the
|
||||
// "This run was cancelled" body, clobbering it back to the task list. we can't
|
||||
// await in-flight writes (the process is exiting), but cancelling the timer
|
||||
// shrinks the race window.
|
||||
onExitSignal(() => {
|
||||
todoTracker?.cancel();
|
||||
});
|
||||
|
||||
// when the agent subprocess is killed for inner activity timeout, stop
|
||||
// the MCP HTTP server so mcp-proxy's SSE reconnect attempts don't keep
|
||||
// the outer activity timer alive. start a short safety-net timer — if
|
||||
@@ -459,6 +758,8 @@ export async function main(): Promise<MainResult> {
|
||||
instructions,
|
||||
todoTracker,
|
||||
stopScript: runContext.repoSettings.stopScript,
|
||||
summaryFilePath: toolState.summaryFilePath,
|
||||
summarySeed: toolState.summarySeed,
|
||||
onActivityTimeout: onInnerActivityTimeout,
|
||||
onToolUse: (event) => {
|
||||
const wasTracked = recordDiffReadFromToolUse({
|
||||
@@ -540,20 +841,27 @@ export async function main(): Promise<MainResult> {
|
||||
});
|
||||
}
|
||||
|
||||
// clean up stranded progress comments. two cases:
|
||||
// 1. wasUpdated=false: nothing wrote to the comment ("Leaping into action" orphan)
|
||||
// 2. tracker published a checklist but the agent never wrote a final summary
|
||||
// (hasPublished=true, finalSummaryWritten=false).
|
||||
// in both cases, delete the comment so it doesn't linger with stale content.
|
||||
// wasUpdated is intentionally NOT set here — cleanup is not a real progress update.
|
||||
// uses finalSummaryWritten (not todoTracker.enabled) so cleanup survives API failures
|
||||
// in report_progress where cancel() ran but the write didn't succeed.
|
||||
const trackerWasLastWriter = todoTracker?.hasPublished && !toolState.finalSummaryWritten;
|
||||
if (
|
||||
toolContext &&
|
||||
toolState.progressCommentId &&
|
||||
(!toolState.wasUpdated || trackerWasLastWriter)
|
||||
) {
|
||||
// read the agent-edited summary tmpfile and persist to the DB. happens
|
||||
// after the agent exits so the file is in its final state.
|
||||
if (toolContext) {
|
||||
await persistSummary(toolContext);
|
||||
}
|
||||
|
||||
// clean up stranded progress comments. the comment is stale unless
|
||||
// report_progress wrote a final summary to it — three sub-cases all reduce
|
||||
// to !finalSummaryWritten:
|
||||
// 1. nothing wrote to the comment ("Leaping into action" orphan)
|
||||
// 2. tracker published a checklist but the agent never finalized it
|
||||
// 3. the agent produced a substantive artifact via another MCP write tool
|
||||
// (create_issue_comment, update_pull_request_body, reply_to_review_comment)
|
||||
// and skipped report_progress — wasUpdated is true, but the progress
|
||||
// comment itself was never touched.
|
||||
// create_pull_request_review owns its own deletion (see action/mcp/review.ts),
|
||||
// so progressComment is already null by the time we get here for that path.
|
||||
// uses finalSummaryWritten (not todoTracker.enabled or wasUpdated) so cleanup
|
||||
// survives API failures in report_progress where cancel() ran but the write
|
||||
// didn't succeed, and isn't fooled by writes to *other* artifacts.
|
||||
if (toolContext && toolState.progressComment && !toolState.finalSummaryWritten) {
|
||||
await deleteProgressComment(toolContext).catch((error) => {
|
||||
log.debug(`stranded progress comment cleanup failed: ${error}`);
|
||||
});
|
||||
@@ -600,6 +908,13 @@ export async function main(): Promise<MainResult> {
|
||||
});
|
||||
}
|
||||
|
||||
// best-effort summary persist on the error path: if the agent successfully
|
||||
// edited the summary file before timing out / crashing, those edits are
|
||||
// worth keeping for the next incremental run.
|
||||
if (toolContext) {
|
||||
await persistSummary(toolContext);
|
||||
}
|
||||
|
||||
return {
|
||||
success: false,
|
||||
error: errorMessage,
|
||||
|
||||
@@ -0,0 +1,110 @@
|
||||
{
|
||||
"owner": "pullfrog",
|
||||
"name": "scratch",
|
||||
"pullNumber": 49,
|
||||
"reviewId": 3485940013,
|
||||
"review": {
|
||||
"body": "### This is the final PR Bugbot will review for you during this billing cycle\n\nYour free Bugbot reviews will reset on November 30\n\n<details>\n<summary>Details</summary>\n\nYour team is on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle for each member of your team.\n\nTo receive Bugbot reviews on all of your PRs, visit the [Cursor dashboard](https://www.cursor.com/dashboard?tab=bugbot) to activate Pro and start your 14-day free trial.\n</details>\n\n",
|
||||
"user": {
|
||||
"login": "cursor[bot]"
|
||||
}
|
||||
},
|
||||
"threads": [
|
||||
{
|
||||
"id": "PRRT_kwDOPaxxp85iysVl",
|
||||
"path": ".github/workflows/test.yml",
|
||||
"line": null,
|
||||
"startLine": null,
|
||||
"diffSide": "RIGHT",
|
||||
"isResolved": true,
|
||||
"isOutdated": true,
|
||||
"comments": {
|
||||
"nodes": [
|
||||
{
|
||||
"fullDatabaseId": "2544544046",
|
||||
"body": "### Bug: GitHub Actions workflow triggered for wrong branch\n\n<!-- **High Severity** -->\n\n<!-- DESCRIPTION START -->\nThe `pull_request` trigger specifies `branches: [mainc]`, but the `push` trigger specifies `branches: [main]`. This mismatch means pull requests will only trigger tests if targeting a non-existent `mainc` branch rather than the actual `main` development branch, preventing CI from running on most pull requests.\n<!-- DESCRIPTION END -->\n\n<!-- LOCATIONS START\n.github/workflows/test.yml#L6-L7\nLOCATIONS END -->\n<a href=\"https://cursor.com/open?data=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImJ1Z2JvdC12MSJ9.eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9DVVJTT1IiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjllMTgyY2U2LWY0YWMtNDAwNS1hMzQ4LWIyYzJkZTk4OGM1ZSIsImVuY3J5cHRpb25LZXkiOiJmSW93NEdsUGUwYlYtd3M2UC1UNHdHT1JmMGZjakxfWVZEdC00SWNveXo0IiwiYnJhbmNoIjoiZGl2aWRlIn0sImlhdCI6MTc2MzYyMDgxOSwiZXhwIjoxNzY0MjI1NjE5fQ.BjkWsTqiNriojI5v10JcveUY2M50f9eflTNDgWAdjdW9w7E0EEY4GJfyzBrA72neco3qAlc34WipASNuEQbTD1fZvwtJY-TeNTDzoKmwA6gtwICB8t7qT87GPvcbDrdGGWdC8kW1jf-LntTmD0k7gt0AeENRAdRSiD3dbqYFN0huXHaB8f2Y48mpmLcnnUpoaaZe7By-Y0DnILyHppwx3AH75nKE_ZeAee3rQNGX4cwcHgB5emTSM93pMDQhT1vbIRYHMaFkOaW2-kDOA8H2QqxD4mT8VzY3skvxIo5HNZCvqE84NtEygHqkBv88g2EEijOPAAeskfsdp087yIzV9g\"><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"https://cursor.com/fix-in-cursor-dark.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"https://cursor.com/fix-in-cursor-light.svg\"><img alt=\"Fix in Cursor\" src=\"https://cursor.com/fix-in-cursor.svg\"></picture></a> <a href=\"https://cursor.com/agents?data=eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCIsImtpZCI6ImJ1Z2JvdC12MSJ9.eyJ2ZXJzaW9uIjoxLCJ0eXBlIjoiQlVHQk9UX0ZJWF9JTl9XRUIiLCJkYXRhIjp7InJlZGlzS2V5IjoiYnVnYm90OjllMTgyY2U2LWY0YWMtNDAwNS1hMzQ4LWIyYzJkZTk4OGM1ZSIsImVuY3J5cHRpb25LZXkiOiJmSW93NEdsUGUwYlYtd3M2UC1UNHdHT1JmMGZjakxfWVZEdC00SWNveXo0IiwiYnJhbmNoIjoiZGl2aWRlIiwicmVwb093bmVyIjoicHVsbGZyb2dhaSIsInJlcG9OYW1lIjoic2NyYXRjaCIsInByTnVtYmVyIjo0OSwiY29tbWl0U2hhIjoiNThiOGJmNmQ1MWE1Mjg4OGFjNGFkNzA5YWVmYTk2MWFkZDMyNDBiMSJ9LCJpYXQiOjE3NjM2MjA4MTksImV4cCI6MTc2NDIyNTYxOX0.SFDZe8R9uwhPjS55J4i_mV2ybsSZoQYM6YzdUOava4IKy1IK2OrVkVsG3-8p4rRaMBXdDZZ4ObPbtk70KqdAiLEDKBqaFcWqELc49lr0XRKUmu4F6EhESFQOvt7MLSVDIOgee8YRlhS6xtoPDqsRiV2KGOwyLEdCeYdrYz9i1DanIswWSoMRVvkjxZ6GUBYVAUg_JsgAXoKVJ-L9Q5Ygho6acVAr5NlGeBp2f6g49GX4GfDOPeV3SORQS1CjxQVRbjI-g0rW55NIisBEl8279VwG6-dTISNbyasZOB6R3eEmC4vmyAAGJjUsMwqhMPw1oaMMmYNSbtZLDESxME9IUg\"><picture><source media=\"(prefers-color-scheme: dark)\" srcset=\"https://cursor.com/fix-in-web-dark.svg\"><source media=\"(prefers-color-scheme: light)\" srcset=\"https://cursor.com/fix-in-web-light.svg\"><img alt=\"Fix in Web\" src=\"https://cursor.com/fix-in-web.svg\"></picture></a>\n\n",
|
||||
"createdAt": "2025-11-20T06:40:19Z",
|
||||
"diffHunk": "@@ -0,0 +1,36 @@\n+name: Test\n+\n+on:\n+ push:\n+ branches: [main]\n+ pull_request:\n+ branches: [mainc]",
|
||||
"line": null,
|
||||
"startLine": null,
|
||||
"originalLine": 7,
|
||||
"originalStartLine": null,
|
||||
"author": {
|
||||
"login": "cursor"
|
||||
},
|
||||
"pullRequestReview": {
|
||||
"databaseId": 3485940013,
|
||||
"author": {
|
||||
"login": "cursor"
|
||||
}
|
||||
},
|
||||
"reactionGroups": [
|
||||
{
|
||||
"content": "THUMBS_UP",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "THUMBS_DOWN",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "LAUGH",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "HOORAY",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "CONFUSED",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "HEART",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "ROCKET",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
},
|
||||
{
|
||||
"content": "EYES",
|
||||
"reactors": {
|
||||
"nodes": []
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"prFiles": [
|
||||
{
|
||||
"filename": ".github/workflows/test.yml",
|
||||
"patch": "@@ -0,0 +1,36 @@\n+name: Test\n+\n+on:\n+ push:\n+ branches: [main]\n+ pull_request:\n+ branches: [main]\n+\n+jobs:\n+ test:\n+ runs-on: ubuntu-latest\n+\n+ strategy:\n+ matrix:\n+ node-version: [22.x]\n+\n+ steps:\n+ - name: Checkout code\n+ uses: actions/checkout@v4\n+\n+ - name: Setup pnpm\n+ uses: pnpm/action-setup@v2\n+ with:\n+ version: 8\n+\n+ - name: Setup Node.js ${{ matrix.node-version }}\n+ uses: actions/setup-node@v4\n+ with:\n+ node-version: ${{ matrix.node-version }}\n+ cache: 'pnpm'\n+\n+ - name: Install dependencies\n+ run: pnpm install\n+\n+ - name: Run tests\n+ run: pnpm test"
|
||||
},
|
||||
{
|
||||
"filename": "index.test.ts",
|
||||
"patch": "@@ -1,5 +1,5 @@\n import { describe, it, expect } from 'vitest'\n-import { add } from './index.js'\n+import { add, multiply, subtract, divide } from './index.js'\n \n describe('add function', () => {\n it('should add two positive numbers correctly', () => {\n@@ -25,3 +25,51 @@ describe('add function', () => {\n expect(add(0.1, 0.2)).toBeCloseTo(0.3)\n })\n })\n+\n+describe('multiply function', () => {\n+ it('should multiply two positive numbers correctly', () => {\n+ expect(multiply(3, 4)).toBe(12)\n+ })\n+\n+ it('should multiply negative numbers correctly', () => {\n+ expect(multiply(-2, 3)).toBe(-6)\n+ expect(multiply(-2, -3)).toBe(6)\n+ })\n+\n+ it('should handle zero correctly', () => {\n+ expect(multiply(5, 0)).toBe(0)\n+ expect(multiply(0, 5)).toBe(0)\n+ })\n+})\n+\n+describe('subtract function', () => {\n+ it('should subtract two positive numbers correctly', () => {\n+ expect(subtract(10, 3)).toBe(7)\n+ })\n+\n+ it('should handle negative numbers correctly', () => {\n+ expect(subtract(5, -3)).toBe(8)\n+ expect(subtract(-5, 3)).toBe(-8)\n+ })\n+\n+ it('should handle zero correctly', () => {\n+ expect(subtract(5, 0)).toBe(5)\n+ expect(subtract(0, 5)).toBe(-5)\n+ })\n+})\n+\n+describe('divide function', () => {\n+ it('should divide two positive numbers correctly', () => {\n+ expect(divide(10, 2)).toBe(5)\n+ })\n+\n+ it('should handle negative numbers correctly', () => {\n+ expect(divide(-10, 2)).toBe(-5)\n+ expect(divide(10, -2)).toBe(-5)\n+ })\n+\n+ it('should handle decimal results correctly', () => {\n+ expect(divide(10, 3)).toBeCloseTo(3.333, 2)\n+ expect(divide(7, 2)).toBe(3.5)\n+ })\n+})"
|
||||
},
|
||||
{
|
||||
"filename": "index.ts",
|
||||
"patch": "@@ -3,11 +3,13 @@ export function add(a: number, b: number) {\n }\n \n export function multiply(a: number, b: number) {\n- // Bug: accidentally adding 1 to the result\n- return a * b + 1;\n+ return a * b;\n }\n \n export function subtract(a: number, b: number) {\n- // Bug: accidentally adding instead of subtracting\n- return a + b;\n+ return a - b;\n+}\n+\n+export function divide(a: number, b: number) {\n+ return a / b;\n }"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"owner": "pullfrog",
|
||||
"name": "scratch",
|
||||
"pullNumber": 64,
|
||||
"reviewId": 3531000326,
|
||||
"review": {
|
||||
"body": "This PR looks great. The retry logic is well-implemented and the tests are comprehensive.",
|
||||
"user": {
|
||||
"login": "pullfrog[bot]"
|
||||
}
|
||||
},
|
||||
"threads": [],
|
||||
"prFiles": []
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
{
|
||||
"owner": "pullfrog",
|
||||
"name": "test-repo",
|
||||
"pullNumber": 1,
|
||||
"files": [
|
||||
{
|
||||
"sha": "a2d9c355792f1883c26d43d219db006b05781e4c",
|
||||
"filename": "src/format.ts",
|
||||
"status": "modified",
|
||||
"additions": 12,
|
||||
"deletions": 2,
|
||||
"changes": 14,
|
||||
"blob_url": "https://github.com/pullfrog/test-repo/blob/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fformat.ts",
|
||||
"raw_url": "https://github.com/pullfrog/test-repo/raw/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fformat.ts",
|
||||
"contents_url": "https://api.github.com/repos/pullfrog/test-repo/contents/src%2Fformat.ts?ref=0311c0fb58fc7faa46e51c174394a4468f379681",
|
||||
"patch": "@@ -1,7 +1,17 @@\n-export function formatCurrency(amount: number) {\n- return `$${amount.toFixed(2)}`;\n+export function formatCurrency(amount: number, currency = \"USD\") {\n+ return new Intl.NumberFormat(\"en-US\", {\n+ style: \"currency\",\n+ currency,\n+ }).format(amount);\n }\n \n export function formatPercent(value: number) {\n return `${(value * 100).toFixed(1)}%`;\n }\n+\n+export function formatNumber(value: number, decimals = 2) {\n+ return new Intl.NumberFormat(\"en-US\", {\n+ minimumFractionDigits: decimals,\n+ maximumFractionDigits: decimals,\n+ }).format(value);\n+}"
|
||||
},
|
||||
{
|
||||
"sha": "0786b9ce6870e65c644673745266e87eef057ce4",
|
||||
"filename": "src/math.ts",
|
||||
"status": "modified",
|
||||
"additions": 5,
|
||||
"deletions": 2,
|
||||
"changes": 7,
|
||||
"blob_url": "https://github.com/pullfrog/test-repo/blob/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fmath.ts",
|
||||
"raw_url": "https://github.com/pullfrog/test-repo/raw/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fmath.ts",
|
||||
"contents_url": "https://api.github.com/repos/pullfrog/test-repo/contents/src%2Fmath.ts?ref=0311c0fb58fc7faa46e51c174394a4468f379681",
|
||||
"patch": "@@ -3,13 +3,16 @@ export function add(a: number, b: number) {\n }\n \n export function subtract(a: number, b: number) {\n- return a + b; // bug: should be a - b\n+ return a - b;\n }\n \n export function multiply(a: number, b: number) {\n- return a * b + 1; // bug: off by one\n+ return a * b;\n }\n \n export function divide(a: number, b: number) {\n+ if (b === 0) {\n+ throw new Error(\"division by zero\");\n+ }\n return a / b;\n }"
|
||||
},
|
||||
{
|
||||
"sha": "cf92d8f6562c1be779506fec1049f38c9206c869",
|
||||
"filename": "src/old-module.ts",
|
||||
"status": "removed",
|
||||
"additions": 0,
|
||||
"deletions": 4,
|
||||
"changes": 4,
|
||||
"blob_url": "https://github.com/pullfrog/test-repo/blob/91ef1048326ef786fbcf95f29b3e2555506d2d54/src%2Fold-module.ts",
|
||||
"raw_url": "https://github.com/pullfrog/test-repo/raw/91ef1048326ef786fbcf95f29b3e2555506d2d54/src%2Fold-module.ts",
|
||||
"contents_url": "https://api.github.com/repos/pullfrog/test-repo/contents/src%2Fold-module.ts?ref=91ef1048326ef786fbcf95f29b3e2555506d2d54",
|
||||
"patch": "@@ -1,4 +0,0 @@\n-// this module is deprecated and will be removed\n-export function legacyHelper() {\n- return \"old\";\n-}"
|
||||
},
|
||||
{
|
||||
"sha": "a5bfb8a1be72e4f0816a5c4c83ee784a06559629",
|
||||
"filename": "src/validate.ts",
|
||||
"status": "added",
|
||||
"additions": 11,
|
||||
"deletions": 0,
|
||||
"changes": 11,
|
||||
"blob_url": "https://github.com/pullfrog/test-repo/blob/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fvalidate.ts",
|
||||
"raw_url": "https://github.com/pullfrog/test-repo/raw/0311c0fb58fc7faa46e51c174394a4468f379681/src%2Fvalidate.ts",
|
||||
"contents_url": "https://api.github.com/repos/pullfrog/test-repo/contents/src%2Fvalidate.ts?ref=0311c0fb58fc7faa46e51c174394a4468f379681",
|
||||
"patch": "@@ -0,0 +1,11 @@\n+export function isPositive(n: number) {\n+ return n > 0;\n+}\n+\n+export function isInRange(value: number, min: number, max: number) {\n+ return value >= min && value <= max;\n+}\n+\n+export function isInteger(n: number) {\n+ return Number.isInteger(n);\n+}"
|
||||
},
|
||||
{
|
||||
"sha": "5815895211d8e3355fdb77b9e216e73a248644d9",
|
||||
"filename": "test/math.test.ts",
|
||||
"status": "modified",
|
||||
"additions": 4,
|
||||
"deletions": 0,
|
||||
"changes": 4,
|
||||
"blob_url": "https://github.com/pullfrog/test-repo/blob/0311c0fb58fc7faa46e51c174394a4468f379681/test%2Fmath.test.ts",
|
||||
"raw_url": "https://github.com/pullfrog/test-repo/raw/0311c0fb58fc7faa46e51c174394a4468f379681/test%2Fmath.test.ts",
|
||||
"contents_url": "https://api.github.com/repos/pullfrog/test-repo/contents/test%2Fmath.test.ts?ref=0311c0fb58fc7faa46e51c174394a4468f379681",
|
||||
"patch": "@@ -17,4 +17,8 @@ describe(\"math\", () => {\n it(\"divides\", () => {\n expect(divide(10, 2)).toBe(5);\n });\n+\n+ it(\"throws on division by zero\", () => {\n+ expect(() => divide(1, 0)).toThrow(\"division by zero\");\n+ });\n });"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`fetchAndFormatPrDiff > generates accurate TOC line numbers for pullfrog/test-repo#1 > content 1`] = `
|
||||
exports[`formatFilesWithLineNumbers > generates accurate TOC line numbers for pullfrog/test-repo#1 > content 1`] = `
|
||||
"## Files (5)
|
||||
- src/format.ts → lines 9-32 · diff-41c7b3ac268a3a1ae5c7be92f1230f600013b7170e44a693570ccbdb183ea36b
|
||||
- src/math.ts → lines 33-55 · diff-9c6e445a719b33e276684bdf95c69e617f0303638d44cf90d61295f2720ecc63
|
||||
@@ -96,7 +96,7 @@ diff --git a/test/math.test.ts b/test/math.test.ts
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`fetchAndFormatPrDiff > generates accurate TOC line numbers for pullfrog/test-repo#1 > toc 1`] = `
|
||||
exports[`formatFilesWithLineNumbers > generates accurate TOC line numbers for pullfrog/test-repo#1 > toc 1`] = `
|
||||
"## Files (5)
|
||||
- src/format.ts → lines 9-32 · diff-41c7b3ac268a3a1ae5c7be92f1230f600013b7170e44a693570ccbdb183ea36b
|
||||
- src/math.ts → lines 33-55 · diff-9c6e445a719b33e276684bdf95c69e617f0303638d44cf90d61295f2720ecc63
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html
|
||||
|
||||
exports[`getFormattedReviewThreads > formats body-only review > content 1`] = `
|
||||
exports[`formatReviewData > formats body-only review > content 1`] = `
|
||||
"# Review Threads (0) for PR #64 - Review 3531000326 by pullfrog[bot]
|
||||
|
||||
## Review Body
|
||||
@@ -11,9 +11,9 @@ This PR looks great. The retry logic is well-implemented and the tests are compr
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`getFormattedReviewThreads > formats body-only review > toc 1`] = `""`;
|
||||
exports[`formatReviewData > formats body-only review > toc 1`] = `""`;
|
||||
|
||||
exports[`getFormattedReviewThreads > formats thread blocks with TOC and correct line numbers > content 1`] = `
|
||||
exports[`formatReviewData > formats thread blocks with TOC and correct line numbers > content 1`] = `
|
||||
"# Review Threads (1) for PR #49 - Review 3485940013 by cursor[bot]
|
||||
|
||||
## TOC
|
||||
@@ -68,4 +68,4 @@ LOCATIONS END -->
|
||||
"
|
||||
`;
|
||||
|
||||
exports[`getFormattedReviewThreads > formats thread blocks with TOC and correct line numbers > toc 1`] = `"- .github/workflows/test.yml:7 → lines 25-52"`;
|
||||
exports[`formatReviewData > formats thread blocks with TOC and correct line numbers > toc 1`] = `"- .github/workflows/test.yml:7 → lines 25-52"`;
|
||||
|
||||
+42
-52
@@ -1,8 +1,7 @@
|
||||
import type { RestEndpointMethodTypes } from "@octokit/rest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { acquireNewToken, createOctokit } from "../utils/github.ts";
|
||||
import { fetchAndFormatPrDiff } from "./checkout.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { type FormatFilesResult, formatFilesWithLineNumbers } from "./checkout.ts";
|
||||
|
||||
/**
|
||||
* parses TOC entries like "- src/math.ts → lines 7-42 · diff-<hex>" into structured data.
|
||||
@@ -22,59 +21,50 @@ function parseTocEntries(toc: string) {
|
||||
return entries;
|
||||
}
|
||||
|
||||
async function getToken(): Promise<string> {
|
||||
// prefer explicit GH_TOKEN, fall back to acquiring one via GitHub App credentials
|
||||
if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
|
||||
return await acquireNewToken();
|
||||
// fixture captured by action/scripts/refresh-test-fixtures.ts. running
|
||||
// the formatter against checked-in JSON keeps this test offline and
|
||||
// deterministic — re-fetch the fixture (with creds) when GitHub's
|
||||
// pulls.listFiles response shape changes, then review the snapshot diff.
|
||||
type DiffFixture = {
|
||||
owner: string;
|
||||
name: string;
|
||||
pullNumber: number;
|
||||
files: Parameters<typeof formatFilesWithLineNumbers>[0];
|
||||
};
|
||||
|
||||
function loadFixture<T>(file: string): T {
|
||||
return JSON.parse(readFileSync(resolve(import.meta.dirname, "__fixtures__", file), "utf-8")) as T;
|
||||
}
|
||||
|
||||
describe("fetchAndFormatPrDiff", () => {
|
||||
it(
|
||||
"generates accurate TOC line numbers for pullfrog/test-repo#1",
|
||||
{ timeout: 30000 },
|
||||
async () => {
|
||||
const token = await getToken();
|
||||
const octokit = createOctokit(token);
|
||||
const ctx = {
|
||||
octokit,
|
||||
repo: {
|
||||
owner: "pullfrog",
|
||||
name: "test-repo",
|
||||
data: {} as RestEndpointMethodTypes["repos"]["get"]["response"]["data"],
|
||||
},
|
||||
} as ToolContext;
|
||||
const result = await fetchAndFormatPrDiff(ctx, 1);
|
||||
describe("formatFilesWithLineNumbers", () => {
|
||||
it("generates accurate TOC line numbers for pullfrog/test-repo#1", () => {
|
||||
const fx = loadFixture<DiffFixture>("pullfrog-test-repo-pr-1.diff.json");
|
||||
const result: FormatFilesResult = formatFilesWithLineNumbers(fx.files);
|
||||
|
||||
// verify content includes TOC at the start
|
||||
expect(result.content.startsWith(result.toc)).toBe(true);
|
||||
expect(result.content.startsWith(result.toc)).toBe(true);
|
||||
|
||||
// parse TOC and validate every entry's line numbers against actual content
|
||||
const contentLines = result.content.split("\n");
|
||||
const tocEntries = parseTocEntries(result.toc);
|
||||
expect(tocEntries.length).toBeGreaterThan(0);
|
||||
const contentLines = result.content.split("\n");
|
||||
const tocEntries = parseTocEntries(result.toc);
|
||||
expect(tocEntries.length).toBeGreaterThan(0);
|
||||
|
||||
for (const entry of tocEntries) {
|
||||
// line numbers are 1-indexed, arrays are 0-indexed
|
||||
const firstLine = contentLines[entry.startLine - 1];
|
||||
expect(firstLine).toBeDefined();
|
||||
// first line of each file section should be the diff header
|
||||
expect(firstLine).toBe(`diff --git a/${entry.filename} b/${entry.filename}`);
|
||||
for (const entry of tocEntries) {
|
||||
// line numbers are 1-indexed, arrays are 0-indexed
|
||||
const firstLine = contentLines[entry.startLine - 1];
|
||||
expect(firstLine).toBeDefined();
|
||||
// first line of each file section should be the diff header
|
||||
expect(firstLine).toBe(`diff --git a/${entry.filename} b/${entry.filename}`);
|
||||
|
||||
// endLine should be within bounds
|
||||
expect(entry.endLine).toBeLessThanOrEqual(contentLines.length);
|
||||
}
|
||||
|
||||
// verify adjacent files don't overlap and are contiguous
|
||||
for (let i = 1; i < tocEntries.length; i++) {
|
||||
const prev = tocEntries[i - 1];
|
||||
const curr = tocEntries[i];
|
||||
// current file starts right after previous file ends
|
||||
expect(curr.startLine).toBe(prev.endLine + 1);
|
||||
}
|
||||
|
||||
// snapshot the full output for regression detection
|
||||
expect(result.toc).toMatchSnapshot("toc");
|
||||
expect(result.content).toMatchSnapshot("content");
|
||||
expect(entry.endLine).toBeLessThanOrEqual(contentLines.length);
|
||||
}
|
||||
);
|
||||
|
||||
// verify adjacent files don't overlap and are contiguous
|
||||
for (let i = 1; i < tocEntries.length; i++) {
|
||||
const prev = tocEntries[i - 1];
|
||||
const curr = tocEntries[i];
|
||||
expect(curr.startLine).toBe(prev.endLine + 1);
|
||||
}
|
||||
|
||||
expect(result.toc).toMatchSnapshot("toc");
|
||||
expect(result.content).toMatchSnapshot("content");
|
||||
});
|
||||
});
|
||||
|
||||
+41
-1
@@ -1,5 +1,5 @@
|
||||
import { createHash } from "node:crypto";
|
||||
import { writeFileSync } from "node:fs";
|
||||
import { statSync, unlinkSync, writeFileSync } from "node:fs";
|
||||
import { join } from "node:path";
|
||||
import type { Octokit, RestEndpointMethodTypes } from "@octokit/rest";
|
||||
import { type } from "arktype";
|
||||
@@ -275,6 +275,39 @@ type CheckoutPrBranchParams = GitContext & {
|
||||
beforeSha?: string | undefined;
|
||||
};
|
||||
|
||||
// stale lock files left over from a crashed/cancelled prior git process block
|
||||
// every subsequent fetch with `Unable to create '<path>': File exists`. only
|
||||
// sweep locks older than this threshold so we never race a concurrent
|
||||
// legitimate git op that's holding the lock.
|
||||
const STALE_LOCK_AGE_MS = 30_000;
|
||||
|
||||
const GIT_LOCK_PATHS = [
|
||||
".git/shallow.lock",
|
||||
".git/index.lock",
|
||||
".git/objects/maintenance.lock",
|
||||
] as const;
|
||||
|
||||
function cleanupStaleGitLocks(): void {
|
||||
const now = Date.now();
|
||||
for (const relPath of GIT_LOCK_PATHS) {
|
||||
let mtimeMs: number;
|
||||
try {
|
||||
mtimeMs = statSync(relPath).mtimeMs;
|
||||
} catch {
|
||||
continue;
|
||||
}
|
||||
if (now - mtimeMs < STALE_LOCK_AGE_MS) continue;
|
||||
try {
|
||||
unlinkSync(relPath);
|
||||
log.warning(`» removed stale ${relPath} from prior run`);
|
||||
} catch (e) {
|
||||
log.debug(
|
||||
`» failed to remove stale ${relPath}: ${e instanceof Error ? e.message : String(e)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared helper to checkout a PR branch and configure fork remotes.
|
||||
* Assumes origin remote is already configured with authentication.
|
||||
@@ -296,6 +329,12 @@ export async function checkoutPrBranch(
|
||||
rejectIfLeadingDash(pr.baseRef, "PR base ref");
|
||||
rejectIfLeadingDash(pr.headRef, "PR head ref");
|
||||
|
||||
// self-hosted runners and cancelled jobs frequently leave stale .git/*.lock
|
||||
// files behind. without this sweep, the first fetch below aborts with
|
||||
// `Unable to create '.git/shallow.lock': File exists` and the agent has to
|
||||
// shell out to `rm -f` (issue #564).
|
||||
cleanupStaleGitLocks();
|
||||
|
||||
const isFork = pr.headRepoFullName !== pr.baseRepoFullName;
|
||||
|
||||
// always use pr-{number} as local branch name for consistency
|
||||
@@ -545,6 +584,7 @@ export function CheckoutPrTool(ctx: ToolContext) {
|
||||
diffPath,
|
||||
totalLines: countLines({ content: formatResult.content }),
|
||||
toc: formatResult.toc,
|
||||
previous: ctx.toolState.diffCoverage,
|
||||
});
|
||||
log.debug(
|
||||
`» diff coverage initialized: diffPath=${diffPath}, totalLines=${ctx.toolState.diffCoverage.totalLines}, tocEntries=${ctx.toolState.diffCoverage.tocEntries.length}`
|
||||
|
||||
+74
-112
@@ -4,21 +4,19 @@ import { buildPullfrogFooter, stripExistingFooter } from "../utils/buildPullfrog
|
||||
import { log } from "../utils/cli.ts";
|
||||
import { fixDoubleEscapedString } from "../utils/fixDoubleEscapedString.ts";
|
||||
import { patchWorkflowRunFields } from "../utils/patchWorkflowRunFields.ts";
|
||||
import {
|
||||
createLeapingProgressComment,
|
||||
deleteProgressCommentApi,
|
||||
updateProgressComment,
|
||||
} from "../utils/progressComment.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
/**
|
||||
* The prefix text for the initial "leaping into action" comment.
|
||||
* This is used to identify if a comment is still in its initial state
|
||||
* and hasn't been updated with progress or error messages.
|
||||
*/
|
||||
export const LEAPING_INTO_ACTION_PREFIX = "Leaping into action";
|
||||
|
||||
export function isLeapingIntoActionCommentBody(body: string): boolean {
|
||||
const content = stripExistingFooter(body).trimStart();
|
||||
const firstLine = content.split(/\r?\n/, 1)[0]?.trimEnd() ?? "";
|
||||
return new RegExp(`(^|\\s)${LEAPING_INTO_ACTION_PREFIX}(\\.\\.\\.)?$`).test(firstLine);
|
||||
}
|
||||
// re-export for backward compat with anything importing the leaping helpers from mcp/comment
|
||||
export {
|
||||
isLeapingIntoActionCommentBody,
|
||||
LEAPING_INTO_ACTION_PREFIX,
|
||||
} from "../utils/leapingComment.ts";
|
||||
|
||||
function buildCommentFooter(ctx: ToolContext, customParts?: string[]): string {
|
||||
const runId = ctx.runId;
|
||||
@@ -58,10 +56,8 @@ export const Comment = type({
|
||||
issueNumber: type.number.describe("the issue number to comment on"),
|
||||
body: type.string.describe("the comment body content"),
|
||||
type: type
|
||||
.enumerated("Plan", "Summary", "Comment")
|
||||
.describe(
|
||||
"Plan: record as the plan for this run. Summary: record as the PR summary comment (one per PR, updated in place). Comment: regular comment (default)."
|
||||
)
|
||||
.enumerated("Plan", "Comment")
|
||||
.describe("Plan: record as the plan for this run. Comment: regular comment (default).")
|
||||
.optional(),
|
||||
});
|
||||
|
||||
@@ -69,35 +65,11 @@ export function CreateCommentTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "create_issue_comment",
|
||||
description:
|
||||
"Create a comment on a GitHub issue or PR. For progress/plan updates on the current run use report_progress instead. Use type: 'Plan' for plan comments, type: 'Summary' for PR summary comments.",
|
||||
"Create a comment on a GitHub issue or PR. For progress/plan updates on the current run use report_progress instead. Use type: 'Plan' for plan comments.",
|
||||
parameters: Comment,
|
||||
execute: execute(async ({ issueNumber, body, type: commentType }) => {
|
||||
const bodyWithFooter = addFooter(ctx, body);
|
||||
|
||||
// if a summary comment already exists (found by select_mode), update instead of creating
|
||||
if (commentType === "Summary" && ctx.toolState.existingSummaryCommentId) {
|
||||
log.info(
|
||||
`» redirecting create_issue_comment(Summary) to update existing comment ${ctx.toolState.existingSummaryCommentId}`
|
||||
);
|
||||
const result = await ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
comment_id: ctx.toolState.existingSummaryCommentId,
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
if (result.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { summaryCommentNodeId: result.data.node_id });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
commentId: result.data.id,
|
||||
url: result.data.html_url,
|
||||
body: result.data.body,
|
||||
};
|
||||
}
|
||||
|
||||
const result = await ctx.octokit.rest.issues.createComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
@@ -105,6 +77,8 @@ export function CreateCommentTool(ctx: ToolContext) {
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
if (commentType === "Plan") {
|
||||
if (result.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: result.data.node_id });
|
||||
@@ -129,10 +103,6 @@ export function CreateCommentTool(ctx: ToolContext) {
|
||||
};
|
||||
}
|
||||
|
||||
if (commentType === "Summary" && result.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { summaryCommentNodeId: result.data.node_id });
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
commentId: result.data.id,
|
||||
@@ -184,12 +154,15 @@ export const ReportProgress = type({
|
||||
/**
|
||||
* Report progress to a GitHub comment.
|
||||
*
|
||||
* progressCommentId has three states:
|
||||
* progressComment has three states:
|
||||
* - undefined: no comment yet — will create one if an issue/PR target exists
|
||||
* - number: active comment — will update it in place
|
||||
* - object: active comment — will update it in place via the right REST endpoint for its type
|
||||
* - null: deliberately deleted (e.g. after submitting a PR review) — skips silently
|
||||
*
|
||||
* The body is always tracked in lastProgressBody for the job summary regardless of comment state.
|
||||
*
|
||||
* The "existing plan comment" path always targets a top-level issue comment (plan comments are
|
||||
* created by create_issue_comment with type:"Plan", never as review-thread replies).
|
||||
*/
|
||||
export async function reportProgress(
|
||||
ctx: ToolContext,
|
||||
@@ -204,7 +177,7 @@ export async function reportProgress(
|
||||
// always track the body for job summary
|
||||
ctx.toolState.lastProgressBody = body;
|
||||
|
||||
// silent events (e.g., auto-label, PR summary) should never create or update progress comments.
|
||||
// silent events (e.g., auto-label, pr-summary Task) should never create or update progress comments.
|
||||
// the body is still tracked above for the GitHub Actions job summary.
|
||||
if (ctx.payload.event.silent) {
|
||||
return { body, action: "skipped" };
|
||||
@@ -212,6 +185,7 @@ export async function reportProgress(
|
||||
|
||||
const issueNumber = ctx.payload.event.issue_number ?? ctx.toolState.issueNumber;
|
||||
const isPlanMode = ctx.toolState.selectedMode === "Plan";
|
||||
const apiCtx = { octokit: ctx.octokit, owner: ctx.repo.owner, repo: ctx.repo.name };
|
||||
|
||||
// when editing existing plan: update the plan comment from tool state (set by select_mode)
|
||||
if (target_plan_comment === true && ctx.toolState.existingPlanCommentId === undefined) {
|
||||
@@ -225,63 +199,57 @@ export async function reportProgress(
|
||||
const footer = buildCommentFooter(ctx, customParts);
|
||||
const bodyWithFooter = `${bodyWithoutFooter}${footer}`;
|
||||
|
||||
const result = await ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
comment_id: commentId,
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
const result = await updateProgressComment(
|
||||
apiCtx,
|
||||
{ id: commentId, type: "issue" },
|
||||
bodyWithFooter
|
||||
);
|
||||
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
if (isPlanMode && result.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: result.data.node_id });
|
||||
if (isPlanMode && result.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: result.node_id });
|
||||
}
|
||||
|
||||
return {
|
||||
commentId: result.data.id,
|
||||
url: result.data.html_url,
|
||||
body: result.data.body || "",
|
||||
commentId: result.id,
|
||||
url: result.html_url,
|
||||
body: result.body || "",
|
||||
action: "updated",
|
||||
};
|
||||
}
|
||||
|
||||
const existingCommentId = ctx.toolState.progressCommentId;
|
||||
const existingComment = ctx.toolState.progressComment;
|
||||
|
||||
// if we already have a progress comment, update it
|
||||
if (existingCommentId) {
|
||||
if (existingComment) {
|
||||
const customParts =
|
||||
isPlanMode && issueNumber !== undefined
|
||||
? [buildImplementPlanLink(ctx, issueNumber, existingCommentId)]
|
||||
? [buildImplementPlanLink(ctx, issueNumber, existingComment.id)]
|
||||
: undefined;
|
||||
|
||||
const bodyWithoutFooter = stripExistingFooter(body);
|
||||
const footer = buildCommentFooter(ctx, customParts);
|
||||
const bodyWithFooter = `${bodyWithoutFooter}${footer}`;
|
||||
|
||||
const result = await ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
comment_id: existingCommentId,
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
const result = await updateProgressComment(apiCtx, existingComment, bodyWithFooter);
|
||||
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
if (isPlanMode && result.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: result.data.node_id });
|
||||
if (isPlanMode && result.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: result.node_id });
|
||||
}
|
||||
|
||||
return {
|
||||
commentId: result.data.id,
|
||||
url: result.data.html_url,
|
||||
body: result.data.body || "",
|
||||
commentId: result.id,
|
||||
url: result.html_url,
|
||||
body: result.body || "",
|
||||
action: "updated",
|
||||
};
|
||||
}
|
||||
|
||||
// null = progress comment was deleted by stranded-comment cleanup in main.ts
|
||||
if (existingCommentId === null) {
|
||||
if (existingComment === null) {
|
||||
return { body, action: "skipped" };
|
||||
}
|
||||
|
||||
@@ -294,49 +262,43 @@ export async function reportProgress(
|
||||
}
|
||||
|
||||
// for new comments, we need to create first, then update with Plan link if in Plan mode
|
||||
// self-created progress comments are always top-level issue comments — review-reply
|
||||
// progress comments only originate from the dispatch path and arrive pre-created.
|
||||
const initialBody = addFooter(ctx, body);
|
||||
const created = await createLeapingProgressComment(
|
||||
apiCtx,
|
||||
{ kind: "issue", issueNumber },
|
||||
initialBody
|
||||
);
|
||||
|
||||
const result = await ctx.octokit.rest.issues.createComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
issue_number: issueNumber,
|
||||
body: initialBody,
|
||||
});
|
||||
|
||||
// store the comment ID for future updates
|
||||
ctx.toolState.progressCommentId = result.data.id;
|
||||
ctx.toolState.progressComment = created.comment;
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
// if Plan mode, update the comment to add the "Implement plan" link
|
||||
if (isPlanMode) {
|
||||
const customParts = [buildImplementPlanLink(ctx, issueNumber, result.data.id)];
|
||||
const customParts = [buildImplementPlanLink(ctx, issueNumber, created.comment.id)];
|
||||
const bodyWithoutFooter = stripExistingFooter(body);
|
||||
const footer = buildCommentFooter(ctx, customParts);
|
||||
const bodyWithPlanLink = `${bodyWithoutFooter}${footer}`;
|
||||
|
||||
const updateResult = await ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
comment_id: result.data.id,
|
||||
body: bodyWithPlanLink,
|
||||
});
|
||||
const updateResult = await updateProgressComment(apiCtx, created.comment, bodyWithPlanLink);
|
||||
|
||||
if (updateResult.data.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: updateResult.data.node_id });
|
||||
if (updateResult.node_id) {
|
||||
await patchWorkflowRunFields(ctx, { planCommentNodeId: updateResult.node_id });
|
||||
}
|
||||
|
||||
return {
|
||||
commentId: updateResult.data.id,
|
||||
url: updateResult.data.html_url,
|
||||
body: updateResult.data.body || "",
|
||||
commentId: updateResult.id,
|
||||
url: updateResult.html_url,
|
||||
body: updateResult.body || "",
|
||||
action: "created",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
commentId: result.data.id,
|
||||
url: result.data.html_url,
|
||||
body: result.data.body || "",
|
||||
commentId: created.comment.id,
|
||||
url: created.html_url,
|
||||
body: created.body || "",
|
||||
action: "created",
|
||||
};
|
||||
}
|
||||
@@ -369,10 +331,6 @@ export function ReportProgressTool(ctx: ToolContext) {
|
||||
}
|
||||
const result = await reportProgress(ctx, reportParams);
|
||||
|
||||
if (!params.target_plan_comment) {
|
||||
ctx.toolState.finalSummaryWritten = true;
|
||||
}
|
||||
|
||||
if (result.action === "skipped") {
|
||||
return {
|
||||
success: true,
|
||||
@@ -381,6 +339,10 @@ export function ReportProgressTool(ctx: ToolContext) {
|
||||
};
|
||||
}
|
||||
|
||||
if (!params.target_plan_comment) {
|
||||
ctx.toolState.finalSummaryWritten = true;
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
...result,
|
||||
@@ -393,20 +355,19 @@ export function ReportProgressTool(ctx: ToolContext) {
|
||||
* Delete the progress comment if it exists.
|
||||
* Used by main.ts for stranded-comment cleanup (orphaned "Leaping into action" or
|
||||
* checklist left by the todo tracker when the agent didn't call report_progress).
|
||||
* Sets progressCommentId to null so subsequent report_progress calls are no-ops.
|
||||
* Sets progressComment to null so subsequent report_progress calls are no-ops.
|
||||
*/
|
||||
export async function deleteProgressComment(ctx: ToolContext): Promise<boolean> {
|
||||
const existingCommentId = ctx.toolState.progressCommentId;
|
||||
if (!existingCommentId) {
|
||||
const existing = ctx.toolState.progressComment;
|
||||
if (!existing) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
await ctx.octokit.rest.issues.deleteComment({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
comment_id: existingCommentId,
|
||||
});
|
||||
await deleteProgressCommentApi(
|
||||
{ octokit: ctx.octokit, owner: ctx.repo.owner, repo: ctx.repo.name },
|
||||
existing
|
||||
);
|
||||
} catch (error) {
|
||||
// ignore 404 - comment already deleted
|
||||
if (error instanceof Error && error.message.includes("Not Found")) {
|
||||
@@ -417,7 +378,7 @@ export async function deleteProgressComment(ctx: ToolContext): Promise<boolean>
|
||||
}
|
||||
|
||||
// set to null (not undefined) so report_progress skips instead of creating a new comment
|
||||
ctx.toolState.progressCommentId = null;
|
||||
ctx.toolState.progressComment = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -447,7 +408,8 @@ export function ReplyToReviewCommentTool(ctx: ToolContext) {
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
// mark progress as updated so post script doesn't think the run failed
|
||||
// mark progress as updated so error reporting + run-result handling know
|
||||
// a substantive write happened (used by reportErrorToComment / handleAgentResult)
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
return {
|
||||
|
||||
+121
@@ -1,4 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { classifyPushError } from "./git.ts";
|
||||
|
||||
// re-export the normalizeUrl function for testing
|
||||
// note: in a real scenario, we'd export this from git.ts or move to a shared utils file
|
||||
@@ -61,3 +62,123 @@ describe("push URL validation", () => {
|
||||
expect(pushUrlNormalized).toBe(actualUrlNormalized);
|
||||
});
|
||||
});
|
||||
|
||||
describe("classifyPushError", () => {
|
||||
describe("concurrent-push", () => {
|
||||
it("matches client-side non-fast-forward (`fetch first`)", () => {
|
||||
const msg =
|
||||
"git push failed (exit 1): To https://github.com/o/r.git\n" +
|
||||
" ! [rejected] feature -> feature (fetch first)\n" +
|
||||
"error: failed to push some refs to 'https://github.com/o/r.git'\n" +
|
||||
"hint: Updates were rejected because the remote contains work";
|
||||
expect(classifyPushError(msg)).toBe("concurrent-push");
|
||||
});
|
||||
|
||||
it("matches client-side `non-fast-forward` wording", () => {
|
||||
const msg = "! [rejected] main -> main (non-fast-forward)";
|
||||
expect(classifyPushError(msg)).toBe("concurrent-push");
|
||||
});
|
||||
|
||||
it("matches server-side `cannot lock ref` (the case from #571)", () => {
|
||||
const msg =
|
||||
"remote: error: cannot lock ref 'refs/heads/feature': is at " +
|
||||
"abc123 but expected def456\n" +
|
||||
" ! [remote rejected] feature -> feature (cannot lock ref ...)";
|
||||
expect(classifyPushError(msg)).toBe("concurrent-push");
|
||||
});
|
||||
});
|
||||
|
||||
describe("transient", () => {
|
||||
it("matches RPC failed with HTTP 502", () => {
|
||||
expect(
|
||||
classifyPushError(
|
||||
"fatal: unable to access 'https://github.com/o/r.git/': The requested URL returned error: 502"
|
||||
)
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("matches early EOF mid-pack", () => {
|
||||
expect(
|
||||
classifyPushError("fatal: the remote end hung up unexpectedly\nfatal: early EOF")
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("matches RPC failed", () => {
|
||||
expect(
|
||||
classifyPushError("fatal: RPC failed; curl 56 OpenSSL SSL_read: Connection reset by peer")
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("matches HTTP/2 stream not closed cleanly", () => {
|
||||
expect(
|
||||
classifyPushError("fatal: HTTP/2 stream 7 was not closed cleanly: PROTOCOL_ERROR (err 1)")
|
||||
).toBe("transient");
|
||||
});
|
||||
|
||||
it("matches DNS resolution failure", () => {
|
||||
expect(classifyPushError("fatal: Could not resolve host: github.com")).toBe("transient");
|
||||
});
|
||||
|
||||
it("matches unexpected disconnect during sideband read", () => {
|
||||
expect(classifyPushError("fatal: unexpected disconnect while reading sideband packet")).toBe(
|
||||
"transient"
|
||||
);
|
||||
});
|
||||
|
||||
it("classifies HTTP 429 (rate-limit / abuse detection) as transient", () => {
|
||||
// 429 is the documented exception to the otherwise-permanent 4xx class —
|
||||
// GitHub's abuse detection occasionally surfaces it on git push.
|
||||
expect(
|
||||
classifyPushError(
|
||||
"fatal: unable to access 'https://github.com/o/r.git/': The requested URL returned error: 429"
|
||||
)
|
||||
).toBe("transient");
|
||||
expect(classifyPushError("remote: HTTP 429: too many requests")).toBe("transient");
|
||||
});
|
||||
});
|
||||
|
||||
describe("unknown", () => {
|
||||
it("does NOT classify auth/403 as transient", () => {
|
||||
// permission denied is permanent within a run — retrying just wastes
|
||||
// time. must NOT match the HTTP-5xx regex.
|
||||
expect(
|
||||
classifyPushError(
|
||||
"remote: Permission to o/r.git denied to bot.\n" +
|
||||
"fatal: unable to access 'https://github.com/o/r.git/': The requested URL returned error: 403"
|
||||
)
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("does NOT classify protected-branch rejection as concurrent-push", () => {
|
||||
expect(
|
||||
classifyPushError(
|
||||
" ! [remote rejected] main -> main (push declined due to repository rule violations)"
|
||||
)
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("does NOT classify 404 as transient", () => {
|
||||
expect(
|
||||
classifyPushError(
|
||||
"fatal: unable to access 'https://github.com/o/r.git/': The requested URL returned error: 404"
|
||||
)
|
||||
).toBe("unknown");
|
||||
});
|
||||
|
||||
it("returns unknown for an empty message", () => {
|
||||
expect(classifyPushError("")).toBe("unknown");
|
||||
});
|
||||
});
|
||||
|
||||
describe("ordering", () => {
|
||||
it("prefers concurrent-push over transient when both signals appear", () => {
|
||||
// a server-side cannot-lock-ref response that also includes an HTTP
|
||||
// 5xx in the libcurl envelope should still route to the recovery
|
||||
// path, not a blind retry.
|
||||
const msg =
|
||||
"remote: error: cannot lock ref 'refs/heads/feature': is at A but expected B\n" +
|
||||
"fatal: unable to access ...: The requested URL returned error: 500";
|
||||
expect(classifyPushError(msg)).toBe("concurrent-push");
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
+145
-26
@@ -153,6 +153,62 @@ export const PushBranch = type({
|
||||
force: type.boolean.describe("Force push (use with caution)").default(false),
|
||||
});
|
||||
|
||||
// classify an error from `$git("push", ...)` to decide retry vs. recovery
|
||||
// vs. rethrow. exported for tests.
|
||||
//
|
||||
// - `concurrent-push`: server-side compare-and-swap failed because the ref
|
||||
// advanced between fetch and push. recovery is fetch + integrate + retry.
|
||||
// matches both the client-side detection (`fetch first` /
|
||||
// `non-fast-forward`) and the server-side detection (`cannot lock ref`
|
||||
// with `is at <SHA1> but expected <SHA2>`).
|
||||
// - `transient`: network or upstream server hiccup (RPC failed mid-stream,
|
||||
// HTTP 5xx, early EOF, reset, timeout, dns flake). push is idempotent so
|
||||
// verbatim retry with backoff is safe.
|
||||
// - `unknown`: anything else (including auth/permission/protected-branch
|
||||
// rejections). retrying these wastes time; surface to the caller.
|
||||
//
|
||||
// kept conservative: a misclassification of `unknown` -> `transient` would
|
||||
// cause two extra round-trips on a permanently-failing push, while the
|
||||
// reverse (true transient labeled `unknown`) just falls back to current
|
||||
// behavior. so we only mark as transient when the error string is
|
||||
// unambiguously a network/server-side fault, not a refusal.
|
||||
export type PushErrorKind = "concurrent-push" | "transient" | "unknown";
|
||||
|
||||
const CONCURRENT_PUSH_PATTERNS = ["fetch first", "non-fast-forward", "cannot lock ref"] as const;
|
||||
|
||||
const TRANSIENT_PATTERNS: RegExp[] = [
|
||||
/RPC failed/i,
|
||||
/early EOF/,
|
||||
/the remote end hung up unexpectedly/,
|
||||
/Connection reset/i,
|
||||
/Could not resolve host/i,
|
||||
/Operation timed out/i,
|
||||
/HTTP\/2 stream \d+ was not closed cleanly/i,
|
||||
/unexpected disconnect while reading sideband packet/i,
|
||||
// libcurl HTTP 5xx surfaced by git over https. matches both the
|
||||
// libcurl-style "The requested URL returned error: 502" and the more
|
||||
// recent "HTTP 502" wording. most 4xx is intentionally excluded —
|
||||
// 401/403/404 indicate auth/permission problems that are not
|
||||
// retry-safe — but 429 (rate-limited / abuse detection) IS retry-safe
|
||||
// and GitHub occasionally surfaces it on git push, so it's included
|
||||
// explicitly below.
|
||||
/HTTP 5\d\d/,
|
||||
/returned error: 5\d\d/i,
|
||||
/HTTP 429/,
|
||||
/returned error: 429/i,
|
||||
];
|
||||
|
||||
export function classifyPushError(msg: string): PushErrorKind {
|
||||
if (CONCURRENT_PUSH_PATTERNS.some((p) => msg.includes(p))) return "concurrent-push";
|
||||
if (TRANSIENT_PATTERNS.some((p) => p.test(msg))) return "transient";
|
||||
return "unknown";
|
||||
}
|
||||
|
||||
// backoff delays before retry attempts 2 and 3. attempt 1 is the original
|
||||
// push. total worst-case added latency: ~7s. small enough that the agent
|
||||
// rarely notices, large enough to ride out most upstream hiccups.
|
||||
const TRANSIENT_RETRY_DELAYS_MS = [2000, 5000];
|
||||
|
||||
export function PushBranchTool(ctx: ToolContext) {
|
||||
const defaultBranch = ctx.repo.data.default_branch || "main";
|
||||
const pushPermission = ctx.payload.push;
|
||||
@@ -234,30 +290,65 @@ export function PushBranchTool(ctx: ToolContext) {
|
||||
log.warning(`force pushing - this will overwrite remote history`);
|
||||
}
|
||||
|
||||
try {
|
||||
await $git("push", pushArgs, {
|
||||
token: ctx.gitToken,
|
||||
});
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
if (msg.includes("fetch first") || msg.includes("non-fast-forward")) {
|
||||
// git rebase is blocked through the MCP tool when shell is disabled
|
||||
// (rebase --exec can execute arbitrary code). merge always works and
|
||||
// integrates remote changes cleanly, so suggest it as the default.
|
||||
const integrateStep =
|
||||
ctx.payload.shell === "disabled"
|
||||
? `2. use the git tool to merge the remote branch into yours: git({ command: "merge", args: ["origin/${pushDest.remoteBranch}"] })`
|
||||
: `2. use the git tool to rebase or merge your changes on top: git({ command: "merge", args: ["origin/${pushDest.remoteBranch}"] }) (or 'rebase')`;
|
||||
throw new Error(
|
||||
`push rejected: the remote branch '${pushDest.remoteBranch}' has new commits you don't have locally.\n\n` +
|
||||
`to resolve this:\n` +
|
||||
`1. use git_fetch to fetch the remote branch: git_fetch({ ref: "${pushDest.remoteBranch}" })\n` +
|
||||
`${integrateStep}\n` +
|
||||
`3. resolve any merge conflicts if needed\n` +
|
||||
`4. retry push_branch`
|
||||
);
|
||||
// retry transient network/server errors (RPC failed, early EOF, 5xx,
|
||||
// connection reset, etc) with backoff. push is idempotent: if the remote
|
||||
// never received the pack, retry creates the ref; if it did, the retry
|
||||
// is a no-op fast-forward to the same SHA. concurrent-push rejections
|
||||
// and permission errors are NOT retried — they need user intervention.
|
||||
let lastErr: unknown;
|
||||
let pushed = false;
|
||||
for (let attempt = 0; attempt <= TRANSIENT_RETRY_DELAYS_MS.length; attempt++) {
|
||||
try {
|
||||
await $git("push", pushArgs, {
|
||||
token: ctx.gitToken,
|
||||
});
|
||||
if (attempt > 0) {
|
||||
log.info(`push succeeded on attempt ${attempt + 1}`);
|
||||
}
|
||||
pushed = true;
|
||||
break;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const kind = classifyPushError(msg);
|
||||
|
||||
if (kind === "concurrent-push") {
|
||||
// git rebase is blocked through the MCP tool when shell is disabled
|
||||
// (rebase --exec can execute arbitrary code). merge always works and
|
||||
// integrates remote changes cleanly, so suggest it as the default.
|
||||
const integrateStep =
|
||||
ctx.payload.shell === "disabled"
|
||||
? `2. use the git tool to merge the remote branch into yours: git({ command: "merge", args: ["origin/${pushDest.remoteBranch}"] })`
|
||||
: `2. use the git tool to rebase or merge your changes on top: git({ command: "merge", args: ["origin/${pushDest.remoteBranch}"] }) (or 'rebase')`;
|
||||
throw new Error(
|
||||
`push rejected: the remote branch '${pushDest.remoteBranch}' has new commits you don't have locally (often a concurrent push to the same branch).\n\n` +
|
||||
`to resolve this:\n` +
|
||||
`1. use git_fetch to fetch the remote branch: git_fetch({ ref: "${pushDest.remoteBranch}" })\n` +
|
||||
`${integrateStep}\n` +
|
||||
`3. resolve any merge conflicts if needed\n` +
|
||||
`4. retry push_branch`
|
||||
);
|
||||
}
|
||||
|
||||
if (kind === "transient" && attempt < TRANSIENT_RETRY_DELAYS_MS.length) {
|
||||
// jitter avoids lockstep retries when several agents are hit by the
|
||||
// same upstream blip simultaneously — without it, all retries land
|
||||
// on the same recovering server at the same instant.
|
||||
const baseDelay = TRANSIENT_RETRY_DELAYS_MS[attempt] ?? 5000;
|
||||
const delay = Math.round(baseDelay * (0.75 + Math.random() * 0.5));
|
||||
log.info(
|
||||
`push attempt ${attempt + 1} failed (transient), retrying in ${delay}ms: ${msg.slice(0, 300)}`
|
||||
);
|
||||
await new Promise((r) => setTimeout(r, delay));
|
||||
continue;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
if (!pushed) {
|
||||
// safety net — loop should always either break with success or throw.
|
||||
throw lastErr instanceof Error ? lastErr : new Error(String(lastErr));
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -408,6 +499,21 @@ const GitFetch = type({
|
||||
depth: type.number.describe("Fetch depth (for shallow clones)").optional(),
|
||||
});
|
||||
|
||||
// when an agent-supplied depth is too shallow to reach the merge base, git
|
||||
// surfaces "Could not read <sha>" and "remote did not send all necessary
|
||||
// objects". detect both wordings so a single deepen retry can recover before
|
||||
// the error reaches the agent (issue #564). git emits the full OID via
|
||||
// oid_to_hex, so the bound is 40 (SHA-1) or 64 (SHA-256).
|
||||
const SHALLOW_UNREACHABLE_PATTERNS: RegExp[] = [
|
||||
/Could not read [a-f0-9]{40,64}/,
|
||||
/remote did not send all necessary objects/,
|
||||
];
|
||||
|
||||
// large enough to clear the merge base on most real-world PRs without
|
||||
// downloading the full history; matches the fallback used by checkoutPrBranch
|
||||
// when the compare API is unavailable.
|
||||
const DEEPEN_RETRY_DEPTH = 1000;
|
||||
|
||||
export function GitFetchTool(ctx: ToolContext) {
|
||||
return tool({
|
||||
name: "git_fetch",
|
||||
@@ -419,9 +525,22 @@ export function GitFetchTool(ctx: ToolContext) {
|
||||
if (params.depth !== undefined) {
|
||||
fetchArgs.push(`--depth=${params.depth}`);
|
||||
}
|
||||
await $git("fetch", fetchArgs, {
|
||||
token: ctx.gitToken,
|
||||
});
|
||||
try {
|
||||
await $git("fetch", fetchArgs, { token: ctx.gitToken });
|
||||
} catch (err) {
|
||||
const msg = err instanceof Error ? err.message : String(err);
|
||||
const isShallowUnreachable = SHALLOW_UNREACHABLE_PATTERNS.some((p) => p.test(msg));
|
||||
const isShallow =
|
||||
isShallowUnreachable &&
|
||||
$("git", ["rev-parse", "--is-shallow-repository"], { log: false }).trim() === "true";
|
||||
if (!isShallow) throw err;
|
||||
log.info(
|
||||
`» git_fetch hit shallow-unreachable error, retrying with --deepen=${DEEPEN_RETRY_DEPTH}`
|
||||
);
|
||||
await $git("fetch", [`--deepen=${DEEPEN_RETRY_DEPTH}`, "--no-tags", "origin", params.ref], {
|
||||
token: ctx.gitToken,
|
||||
});
|
||||
}
|
||||
return { success: true, ref: params.ref };
|
||||
}),
|
||||
});
|
||||
|
||||
@@ -49,6 +49,8 @@ export function UpdatePullRequestBodyTool(ctx: ToolContext) {
|
||||
body: bodyWithFooter,
|
||||
});
|
||||
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
return {
|
||||
success: true,
|
||||
number: result.data.number,
|
||||
|
||||
+2
-2
@@ -648,8 +648,8 @@ describe("reviewSkipDecision", () => {
|
||||
describe("duplicateReviewDecision", () => {
|
||||
// regression: colinhacks/zod#5897 had two reviews submitted from the same
|
||||
// workflow run 8 seconds apart — a substantive review followed by an empty
|
||||
// "Reviewed — no issues found." follow-up. the agent re-classified the
|
||||
// first review's non-blocking observations as "no actionable issues" and
|
||||
// "No new issues found." follow-up. the agent re-classified the first
|
||||
// review's non-blocking observations as "no actionable issues" and
|
||||
// submitted the canonical body per modes.ts. this guard makes the second
|
||||
// call a no-op without burning a GitHub API call or polluting the PR.
|
||||
|
||||
|
||||
+5
-3
@@ -187,8 +187,8 @@ export type DuplicateReviewDecision = {
|
||||
* the agent is instructed to call create_pull_request_review exactly once per
|
||||
* Review-mode session (see action/modes.ts), but in practice it sometimes
|
||||
* submits twice — once with substantive feedback, then again with the
|
||||
* canonical "Reviewed — no issues found." body when the prompt's branch
|
||||
* logic re-classifies non-blocking observations. the second submission is
|
||||
* canonical "No new issues found." body when the prompt's branch logic
|
||||
* re-classifies non-blocking observations. the second submission is
|
||||
* always redundant: the first review is the record, and the duplicate just
|
||||
* adds noise to the PR.
|
||||
*
|
||||
@@ -537,10 +537,12 @@ export function CreatePullRequestReviewTool(ctx: ToolContext) {
|
||||
reviewedSha: actuallyReviewedSha,
|
||||
};
|
||||
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
// a submitted review obsoletes the progress comment — the review IS the
|
||||
// durable artifact. owned here (not in main.ts) so cleanup is atomic with
|
||||
// submission and survives any path out of the run (success, timeout,
|
||||
// crash). deleteProgressComment sets progressCommentId = null, so a later
|
||||
// crash). deleteProgressComment sets progressComment = null, so a later
|
||||
// report_progress call short-circuits to a no-op.
|
||||
// best-effort: a cleanup failure must not turn a successful review into
|
||||
// a tool-call failure visible to the agent.
|
||||
|
||||
+30
-33
@@ -1,43 +1,40 @@
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { acquireNewToken } from "../utils/github.ts";
|
||||
import { getReviewData } from "./reviewComments.ts";
|
||||
import { type FormatReviewDataInput, formatReviewData } from "./reviewComments.ts";
|
||||
|
||||
async function getToken(): Promise<string> {
|
||||
if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
|
||||
return await acquireNewToken();
|
||||
// fixtures captured by action/scripts/refresh-test-fixtures.ts; re-run
|
||||
// (with creds) when GitHub's review/threads/listFiles response shape
|
||||
// changes, then review the snapshot diff.
|
||||
type ReviewFixture = FormatReviewDataInput & {
|
||||
owner: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
function loadFixture(file: string): ReviewFixture {
|
||||
return JSON.parse(
|
||||
readFileSync(resolve(import.meta.dirname, "__fixtures__", file), "utf-8")
|
||||
) as ReviewFixture;
|
||||
}
|
||||
|
||||
describe("getFormattedReviewThreads", () => {
|
||||
it("formats thread blocks with TOC and correct line numbers", { timeout: 30000 }, async () => {
|
||||
const token = await getToken();
|
||||
const octokit = new Octokit({ auth: token });
|
||||
describe("formatReviewData", () => {
|
||||
it("formats thread blocks with TOC and correct line numbers", () => {
|
||||
const fx = loadFixture("pullfrog-scratch-pr-49-review-3485940013.json");
|
||||
const result = formatReviewData(fx);
|
||||
expect(result).toBeDefined();
|
||||
if (!result) return;
|
||||
|
||||
const { formatted } = (await getReviewData({
|
||||
octokit,
|
||||
owner: "pullfrog",
|
||||
name: "scratch",
|
||||
pullNumber: 49,
|
||||
reviewId: 3485940013,
|
||||
}))!;
|
||||
|
||||
expect(formatted.toc).toMatchSnapshot("toc");
|
||||
expect(formatted.content).toMatchSnapshot("content");
|
||||
expect(result.formatted.toc).toMatchSnapshot("toc");
|
||||
expect(result.formatted.content).toMatchSnapshot("content");
|
||||
});
|
||||
|
||||
it("formats body-only review", { timeout: 30000 }, async () => {
|
||||
const token = await getToken();
|
||||
const octokit = new Octokit({ auth: token });
|
||||
it("formats body-only review", () => {
|
||||
const fx = loadFixture("pullfrog-scratch-pr-64-review-3531000326.json");
|
||||
const result = formatReviewData(fx);
|
||||
expect(result).toBeDefined();
|
||||
if (!result) return;
|
||||
|
||||
const { formatted } = (await getReviewData({
|
||||
octokit,
|
||||
owner: "pullfrog",
|
||||
name: "scratch",
|
||||
pullNumber: 64,
|
||||
reviewId: 3531000326,
|
||||
}))!;
|
||||
|
||||
expect(formatted.toc).toMatchSnapshot("toc");
|
||||
expect(formatted.content).toMatchSnapshot("content");
|
||||
expect(result.formatted.toc).toMatchSnapshot("toc");
|
||||
expect(result.formatted.content).toMatchSnapshot("content");
|
||||
});
|
||||
});
|
||||
|
||||
+76
-28
@@ -497,6 +497,67 @@ interface GetReviewDataInput {
|
||||
approvedBy?: string | undefined;
|
||||
}
|
||||
|
||||
// pure formatter: takes already-fetched GitHub responses and produces the
|
||||
// review data the MCP tool returns. extracted from getReviewData so tests
|
||||
// can drive it from checked-in fixtures without live API access.
|
||||
//
|
||||
// `prFiles` may be empty when `threads` is empty — callers that hit the
|
||||
// network should skip the listFiles call in that case as a perf
|
||||
// optimization. when both are empty and `review.body` is also empty, the
|
||||
// formatter returns undefined just like getReviewData.
|
||||
export interface FormatReviewDataInput {
|
||||
review: ReviewResponse;
|
||||
threads: ReviewThread[];
|
||||
prFiles: ReviewPrFile[];
|
||||
pullNumber: number;
|
||||
reviewId: number;
|
||||
}
|
||||
|
||||
export type ReviewResponse = {
|
||||
body: string | null | undefined;
|
||||
user: { login: string } | null | undefined;
|
||||
};
|
||||
|
||||
export type ReviewPrFile = {
|
||||
filename: string;
|
||||
patch?: string | undefined;
|
||||
};
|
||||
|
||||
export function formatReviewData(input: FormatReviewDataInput):
|
||||
| {
|
||||
threadBlocks: Array<{ path: string; lineRange: string; content: string[] }>;
|
||||
reviewer: string;
|
||||
formatted: { toc: string; content: string };
|
||||
}
|
||||
| undefined {
|
||||
const rawReviewBody = input.review.body;
|
||||
const reviewBody = rawReviewBody ? stripExistingFooter(rawReviewBody) : "";
|
||||
const reviewer = input.review.user?.login ?? "unknown";
|
||||
|
||||
if (input.threads.length === 0 && !reviewBody) return undefined;
|
||||
|
||||
let threadBlocks: Array<{ path: string; lineRange: string; content: string[] }> = [];
|
||||
|
||||
if (input.threads.length > 0) {
|
||||
const filePatchMap = new Map<string, ParsedHunk[]>();
|
||||
for (const file of input.prFiles) {
|
||||
if (file.patch) {
|
||||
filePatchMap.set(file.filename, parseFilePatches(file.patch));
|
||||
}
|
||||
}
|
||||
threadBlocks = buildThreadBlocks(input.threads, filePatchMap, input.reviewId);
|
||||
}
|
||||
|
||||
const formatted = formatReviewThreads(threadBlocks, {
|
||||
pullNumber: input.pullNumber,
|
||||
reviewId: input.reviewId,
|
||||
reviewer,
|
||||
reviewBody,
|
||||
});
|
||||
|
||||
return { threadBlocks, reviewer, formatted };
|
||||
}
|
||||
|
||||
export async function getReviewData(input: GetReviewDataInput): Promise<
|
||||
| {
|
||||
threadBlocks: Array<{ path: string; lineRange: string; content: string[] }>;
|
||||
@@ -515,38 +576,25 @@ export async function getReviewData(input: GetReviewDataInput): Promise<
|
||||
getReviewThreads(input),
|
||||
]);
|
||||
|
||||
const rawReviewBody = review.data.body;
|
||||
const reviewBody = rawReviewBody ? stripExistingFooter(rawReviewBody) : "";
|
||||
const reviewer = review.data.user?.login ?? "unknown";
|
||||
// skip listFiles when there are no threads — prFiles is only used for
|
||||
// building thread blocks, and an empty array short-circuits below.
|
||||
const prFiles =
|
||||
threads.length > 0
|
||||
? await input.octokit.paginate(input.octokit.rest.pulls.listFiles, {
|
||||
owner: input.owner,
|
||||
repo: input.name,
|
||||
pull_number: input.pullNumber,
|
||||
per_page: 100,
|
||||
})
|
||||
: [];
|
||||
|
||||
if (threads.length === 0 && !reviewBody) return undefined;
|
||||
|
||||
let threadBlocks: Array<{ path: string; lineRange: string; content: string[] }> = [];
|
||||
|
||||
if (threads.length > 0) {
|
||||
const prFiles = await input.octokit.paginate(input.octokit.rest.pulls.listFiles, {
|
||||
owner: input.owner,
|
||||
repo: input.name,
|
||||
pull_number: input.pullNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const filePatchMap = new Map<string, ParsedHunk[]>();
|
||||
for (const file of prFiles) {
|
||||
if (file.patch) {
|
||||
filePatchMap.set(file.filename, parseFilePatches(file.patch));
|
||||
}
|
||||
}
|
||||
threadBlocks = buildThreadBlocks(threads, filePatchMap, input.reviewId);
|
||||
}
|
||||
|
||||
const formatted = formatReviewThreads(threadBlocks, {
|
||||
return formatReviewData({
|
||||
review: review.data,
|
||||
threads,
|
||||
prFiles,
|
||||
pullNumber: input.pullNumber,
|
||||
reviewId: input.reviewId,
|
||||
reviewer,
|
||||
reviewBody,
|
||||
});
|
||||
|
||||
return { threadBlocks, reviewer, formatted };
|
||||
}
|
||||
|
||||
export function GetReviewCommentsTool(ctx: ToolContext) {
|
||||
|
||||
+39
-61
@@ -1,14 +1,13 @@
|
||||
import { type } from "arktype";
|
||||
import { formatMcpToolRef } from "../external.ts";
|
||||
import { type Mode, PR_SUMMARY_FORMAT } from "../modes.ts";
|
||||
import type { Mode } from "../modes.ts";
|
||||
import { apiFetch } from "../utils/apiFetch.ts";
|
||||
import { log } from "../utils/log.ts";
|
||||
import type { ToolContext } from "./server.ts";
|
||||
import { execute, tool } from "./shared.ts";
|
||||
|
||||
export const SelectModeParams = type({
|
||||
mode: type.string.describe(
|
||||
"the name of the mode to select (e.g., 'Build', 'Plan', 'Review', 'IncrementalReview', 'Fix', 'AddressReviews', 'Task', 'ResolveConflicts', 'Summarize')"
|
||||
"the name of the mode to select (e.g., 'Build', 'Plan', 'Review', 'IncrementalReview', 'Fix', 'AddressReviews', 'Task', 'ResolveConflicts')"
|
||||
),
|
||||
"issue_number?": type("number").describe(
|
||||
"optional issue number; when provided with Plan mode, used to look up an existing plan comment for this issue (edit vs create)"
|
||||
@@ -32,18 +31,6 @@ An existing plan comment was found for this issue. Update that comment with the
|
||||
- produce a structured plan with clear milestones
|
||||
3. Call \`${t("report_progress")}\` with the full revised plan text and \`{ target_plan_comment: true }\` so it updates the existing plan comment (not the progress comment).
|
||||
4. Then post a short note to the progress comment (e.g. "Plan has been updated in the comment above.") via \`${t("report_progress")}\` so it is not left as "Leaping...".`,
|
||||
|
||||
SummaryUpdate: `### Checklist (updating existing summary)
|
||||
|
||||
An existing summary comment was found for this PR. Update it rather than creating a new one.
|
||||
|
||||
1. Use \`previousSummaryBody\` from this response as the current summary to revise.
|
||||
2. Checkout the PR via \`${t("checkout_pr")}\` — this returns PR metadata and a \`diffPath\`.
|
||||
3. Read the diff using the TOC to selectively read relevant sections. Produce an updated summary reflecting the current state of the PR, using the existing summary (\`previousSummaryBody\`) as a starting point. If EVENT INSTRUCTIONS specify a custom format, follow that instead of the default format below.
|
||||
4. Call \`${t("edit_issue_comment")}\` with \`commentId: existingSummaryCommentId\` (from this response) and the updated summary body.
|
||||
5. Call \`${t("report_progress")}\` with a brief note (e.g., "Updated PR summary.").
|
||||
|
||||
${PR_SUMMARY_FORMAT}`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -78,10 +65,7 @@ function buildOrchestratorGuidance(
|
||||
// matches the API response for /repo/[owner]/[repo]/issue/[issueNumber]/plan-comment
|
||||
export type PlanCommentResponsePayload = { error: string } | { commentId: number; body: string };
|
||||
|
||||
// matches the API response for /repo/[owner]/[repo]/pr/[prNumber]/summary-comment
|
||||
export type SummaryCommentResponsePayload = { error: string } | { commentId: number; body: string };
|
||||
|
||||
// IMPORTANT: these routes authenticate via GitHub installation token (getEnrichedRepo),
|
||||
// IMPORTANT: this route authenticates via GitHub installation token (getEnrichedRepo),
|
||||
// NOT the Pullfrog API JWT (ctx.apiToken). use ctx.githubInstallationToken here.
|
||||
// see wiki/api-auth.md for the two auth patterns.
|
||||
async function fetchExistingPlanComment(
|
||||
@@ -103,33 +87,30 @@ async function fetchExistingPlanComment(
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchExistingSummaryComment(
|
||||
ctx: ToolContext,
|
||||
prNumber: number
|
||||
): Promise<Extract<SummaryCommentResponsePayload, { commentId: number }> | null> {
|
||||
if (!ctx.githubInstallationToken) {
|
||||
log.warning("fetchExistingSummaryComment: no token, skipping");
|
||||
return null;
|
||||
}
|
||||
const path = `/api/repo/${ctx.repo.owner}/${ctx.repo.name}/pr/${prNumber}/summary-comment`;
|
||||
try {
|
||||
const response = await apiFetch({
|
||||
path,
|
||||
method: "GET",
|
||||
headers: { authorization: `Bearer ${ctx.githubInstallationToken}` },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
const data = (await response.json()) as SummaryCommentResponsePayload;
|
||||
if (response.ok && "commentId" in data) {
|
||||
return data;
|
||||
}
|
||||
const errMsg = "error" in data ? data.error : "(no error body)";
|
||||
log.warning(`fetchExistingSummaryComment: ${response.status} ${path} — ${errMsg}`);
|
||||
return null;
|
||||
} catch (error) {
|
||||
log.warning("fetchExistingSummaryComment failed:", error);
|
||||
return null;
|
||||
}
|
||||
const SUMMARY_MODES = new Set(["Review", "IncrementalReview", "Task"]);
|
||||
|
||||
/** modes that gain the PR summary edit step when toolState.summaryFilePath is set.
|
||||
*
|
||||
* NOTE: this snapshot is an internal artifact consumed by future agent runs. it is
|
||||
* deliberately NOT shaped by user-supplied summary instructions — those would warp
|
||||
* the durable agent context. user-facing summarization (e.g. the review body's
|
||||
* "Reviewed changes" section) is governed by review-mode prompts and review
|
||||
* instructions, separately from this snapshot. */
|
||||
function buildSummaryAddendum(t: (name: string) => string, ctx: ToolContext): string {
|
||||
const filePath = ctx.toolState.summaryFilePath;
|
||||
if (!filePath) return "";
|
||||
return `### PR summary snapshot — required step
|
||||
|
||||
A rolling PR summary lives at \`${filePath}\`. It is your durable cross-run agent context — a functional summary of what this PR does, the subsystems and files it touches, the material behavior of its changes, and any risks or open questions worth carrying forward. It is NOT a chronological log of past review runs; commit-level history can already be reconstructed from \`${t("list_pull_request_reviews")}\`.
|
||||
|
||||
How to use it:
|
||||
|
||||
- read \`${filePath}\` at the START of the run, alongside the diff. it represents what previous agent runs already understood about this PR — absorb it before picking lenses or crafting subagent dispatch prompts. if it's a fresh seed (file is one or two lines), this is a first review and you'll be filling it in from the diff.
|
||||
- let the snapshot inform triage and dispatch. when it already tracks a risk, your lens prompts to subagents are stronger when they reference that context (e.g. "the JSDoc explicitly scopes to code points — do not flag grapheme-cluster issues" if the snapshot already documents that contract). when something the snapshot tracks is now resolved by new commits, note that. when new commits introduce something the snapshot doesn't yet describe, that's exactly where your fan-out should focus.
|
||||
- update the file in place to reflect the PR's CURRENT state. revise stale claims, drop resolved risks, add new behavior or risks. accuracy over breadth — every claim must be grounded in the diff. write for the next agent run, not for a human.
|
||||
- structure however serves THIS PR. there is no required section template. a refactor might organize by renamed export and call-site impact; a feature by capability; a billing change by money path. a compact note of which commit ranges have been reviewed should always be present so future runs scope correctly, but the rest is your call. when the structure works across runs, keep it stable so range-diffs are clean; when the PR's character changes (e.g. scope expands), reshape.
|
||||
|
||||
Do NOT call \`${t("create_issue_comment")}\` for the summary — the server reads this file at end-of-run and persists it. The file edit is mandatory regardless of whether a review is submitted; the snapshot feeds the next run.`;
|
||||
}
|
||||
|
||||
export function SelectModeTool(ctx: ToolContext) {
|
||||
@@ -180,22 +161,19 @@ export function SelectModeTool(ctx: ToolContext) {
|
||||
}
|
||||
}
|
||||
|
||||
if (selectedMode.name === "Summarize") {
|
||||
const prNumber = ctx.payload.event.issue_number;
|
||||
if (prNumber !== undefined) {
|
||||
const existing = await fetchExistingSummaryComment(ctx, prNumber);
|
||||
if (existing !== null) {
|
||||
ctx.toolState.existingSummaryCommentId = existing.commentId;
|
||||
return {
|
||||
...buildOrchestratorGuidance(ctx, selectedMode, overrides.SummaryUpdate),
|
||||
existingSummaryCommentId: existing.commentId,
|
||||
previousSummaryBody: existing.body,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const summaryAddendum = SUMMARY_MODES.has(selectedMode.name)
|
||||
? buildSummaryAddendum(t, ctx)
|
||||
: "";
|
||||
|
||||
return buildOrchestratorGuidance(ctx, selectedMode);
|
||||
const base = buildOrchestratorGuidance(ctx, selectedMode);
|
||||
if (summaryAddendum.length > 0) {
|
||||
return {
|
||||
...base,
|
||||
orchestratorGuidance: `${base.orchestratorGuidance}\n\n${summaryAddendum}`,
|
||||
summaryFilePath: ctx.toolState.summaryFilePath,
|
||||
};
|
||||
}
|
||||
return base;
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
+36
-11
@@ -12,6 +12,12 @@ import { log } from "../utils/cli.ts";
|
||||
import type { DiffCoverageState } from "../utils/diffCoverage.ts";
|
||||
import type { OctokitWithPlugins } from "../utils/github.ts";
|
||||
import type { ResolvedPayload } from "../utils/payload.ts";
|
||||
import {
|
||||
type ProgressComment,
|
||||
type ProgressCommentType,
|
||||
parseProgressComment,
|
||||
} from "../utils/progressComment.ts";
|
||||
import type { AccountPlan } from "../utils/runContext.ts";
|
||||
import type { RunContextData } from "../utils/runContextData.ts";
|
||||
import type { TodoTracker } from "../utils/todoTracking.ts";
|
||||
import { CheckoutPrTool } from "./checkout.ts";
|
||||
@@ -109,8 +115,8 @@ export interface ToolState {
|
||||
promise: Promise<PrepResult[]> | undefined;
|
||||
results: PrepResult[] | undefined;
|
||||
};
|
||||
// undefined = no comment yet, number = active comment, null = deliberately deleted
|
||||
progressCommentId: number | null | undefined;
|
||||
// undefined = no comment yet, object = active comment, null = deliberately deleted
|
||||
progressComment: ProgressComment | null | undefined;
|
||||
// immutable snapshot: true if a progress comment was pre-created at init time.
|
||||
// survives deleteProgressComment so handleAgentResult can still detect "expected but never reported".
|
||||
hadProgressComment: boolean;
|
||||
@@ -122,8 +128,21 @@ export interface ToolState {
|
||||
// set by select_mode when Plan + issue_number and plan-comment API returns existing plan (for report_progress target_plan_comment)
|
||||
existingPlanCommentId?: number;
|
||||
previousPlanBody?: string;
|
||||
// set by select_mode when Summarize mode and summary-comment API returns existing summary
|
||||
existingSummaryCommentId?: number;
|
||||
// absolute path to the PR summary markdown file the agent edits in place.
|
||||
// seeded by main.ts before the agent starts when payload.generateSummary is set;
|
||||
// read back at end-of-run to persist to DB.
|
||||
summaryFilePath?: string;
|
||||
// exact bytes of the seeded snapshot file at run start. compared against
|
||||
// the file content at end-of-run to detect "agent never touched it" — in
|
||||
// that case persistSummary skips the DB write (saving the seed verbatim
|
||||
// would either re-write what the DB already has, on incremental runs, or
|
||||
// serialize the placeholder scaffold, on first runs).
|
||||
summarySeed?: string;
|
||||
// set to true after persistSummary completes once. prevents the error-path
|
||||
// call (which exists so a successful agent edit before a crash still gets
|
||||
// persisted) from redundantly re-running the DB PATCH on the
|
||||
// success-then-late-throw path.
|
||||
summaryPersistAttempted?: boolean;
|
||||
output?: string;
|
||||
usageEntries: AgentUsage[];
|
||||
model?: string | undefined;
|
||||
@@ -132,20 +151,19 @@ export interface ToolState {
|
||||
}
|
||||
|
||||
interface InitToolStateParams {
|
||||
progressCommentId: string | undefined;
|
||||
progressComment: { id: string; type: ProgressCommentType } | undefined;
|
||||
}
|
||||
|
||||
export function initToolState(params: InitToolStateParams): ToolState {
|
||||
const parsed = params.progressCommentId ? parseInt(params.progressCommentId, 10) : NaN;
|
||||
const resolvedId = Number.isNaN(parsed) || parsed <= 0 ? undefined : parsed;
|
||||
const resolved = parseProgressComment(params.progressComment);
|
||||
|
||||
if (resolvedId) {
|
||||
log.info(`» using pre-created progress comment: ${resolvedId}`);
|
||||
if (resolved) {
|
||||
log.info(`» using pre-created progress comment: ${resolved.id} (${resolved.type})`);
|
||||
}
|
||||
|
||||
return {
|
||||
progressCommentId: resolvedId,
|
||||
hadProgressComment: !!resolvedId,
|
||||
progressComment: resolved,
|
||||
hadProgressComment: !!resolved,
|
||||
backgroundProcesses: new Map(),
|
||||
usageEntries: [],
|
||||
};
|
||||
@@ -169,6 +187,13 @@ export interface ToolContext {
|
||||
jobId: string | undefined;
|
||||
mcpServerUrl: string;
|
||||
tmpdir: string;
|
||||
// repo-level OSS flag + account-level billing plan. together they decide
|
||||
// whether pullfrog is paying for marginal infra — see isInfraCovered in
|
||||
// utils/runContext.ts. plan gating for things like update_learnings is
|
||||
// enforced server-side via 402, so we pass plan along mostly for future
|
||||
// use / observability. see wiki/pricing.md.
|
||||
oss: boolean;
|
||||
plan: AccountPlan;
|
||||
// resolved upstream model specifier (e.g. "google/gemini-3.1-pro-preview").
|
||||
// undefined when payload.proxyModel is set or when the alias is unresolvable.
|
||||
// used by the schema sanitizer to detect Gemini-routed traffic.
|
||||
|
||||
@@ -140,14 +140,14 @@ export const providers = {
|
||||
models: {
|
||||
grok: {
|
||||
displayName: "Grok",
|
||||
resolve: "xai/grok-4",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4",
|
||||
resolve: "xai/grok-4.3",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4.3",
|
||||
preferred: true,
|
||||
},
|
||||
"grok-fast": {
|
||||
displayName: "Grok Fast",
|
||||
resolve: "xai/grok-4-fast",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4-fast",
|
||||
resolve: "xai/grok-4-1-fast",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4.1-fast",
|
||||
},
|
||||
"grok-code-fast": {
|
||||
displayName: "Grok Code Fast",
|
||||
@@ -354,8 +354,8 @@ export const providers = {
|
||||
},
|
||||
grok: {
|
||||
displayName: "Grok",
|
||||
resolve: "openrouter/x-ai/grok-4",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4",
|
||||
resolve: "openrouter/x-ai/grok-4.3",
|
||||
openRouterResolve: "openrouter/x-ai/grok-4.3",
|
||||
},
|
||||
"deepseek-pro": {
|
||||
displayName: "DeepSeek Pro",
|
||||
|
||||
@@ -10,6 +10,12 @@ export interface Mode {
|
||||
prompt?: string | undefined;
|
||||
}
|
||||
|
||||
// Default user-facing summary format embedded in Review mode review bodies.
|
||||
// Deliberately scoped to Review (initial PR review). IncrementalReview keeps
|
||||
// its own terser bullet-list "Reviewed changes" shape since re-review bodies
|
||||
// are deltas, not introductions. Distinct from the agent-internal snapshot
|
||||
// (action/utils/prSummary.ts) which has its own stable scaffold and is never
|
||||
// shaped by user instructions — see selectMode.ts for the firewall.
|
||||
export const PR_SUMMARY_FORMAT = `### Default format
|
||||
|
||||
Follow this structure exactly:
|
||||
@@ -112,7 +118,7 @@ export function computeModes(agentId: AgentId): Mode[] {
|
||||
- Do NOT defect-hunt the diff yourself in parallel with the subagent. Your role is dispatch + evaluation; doing the review yourself reintroduces the implementation bias the subagent is meant to mitigate.
|
||||
- For diffs that rely on third-party API contracts, SDK semantics, framework directives, or DB engine specifics, instruct the subagent to verify load-bearing claims via web search and quote source URLs rather than trust training data — this is the single most common review-quality failure mode.
|
||||
|
||||
Review the findings, address valid points, and discard nitpicks or false positives. The reviewer is fallible — it biases toward *recommending additions* (defensive checks for impossible cases, extra logging, new abstractions used once, comments restating code, tests asserting tautologies, "just-in-case" guards). For each finding, ask: would applying it leave the code more sound, correct, AND elegant? Two-out-of-three is not enough — a fix that improves correctness while degrading elegance still degrades the codebase. Reject bloat-shaped findings without applying them, and after applying the rest re-read your diff and be discerning about what *you just changed*: if any fix turned out to be bloat in context, revert it. The goal is code that is sound and correct *while remaining elegant*; the smallest diff that fixes the real defect almost always wins. Then verify only intended changes are present, no debug artifacts or commented-out code remain, no unrelated files were modified. Commit locally via shell (\`git add . && git commit -m "..."\`).
|
||||
Review the findings, address valid points, and discard nitpicks or false positives. The reviewer is fallible — it biases toward *recommending additions* (defensive checks for impossible cases, extra logging, new abstractions used once, comments restating code, tests asserting tautologies, "just-in-case" guards). For each finding, ask: would applying it leave the code more sound, correct, AND elegant? Two-out-of-three is usually a signal to look harder for a fix that gets all three before settling for one that trades elegance for correctness. Reject bloat-shaped findings without applying them, and after applying the rest re-read your diff and be discerning about what *you just changed*: if any fix turned out to be bloat in context, revert it. The goal is code that is sound and correct *while remaining elegant*; the smallest diff that fixes the real defect almost always wins. Then verify only intended changes are present, no debug artifacts or commented-out code remain, no unrelated files were modified. Commit locally via shell (\`git add . && git commit -m "..."\`).
|
||||
|
||||
5. **finalize**:
|
||||
- confirm a clean working tree, then push via \`${t("push_branch")}\` (see *SYSTEM* Git rules if this fails — prepush errors are usually the repo's tests/lint, not infra timeouts)
|
||||
@@ -137,7 +143,7 @@ For simple, well-defined tasks, skip the plan phase and go straight to build.`,
|
||||
|
||||
3. For each comment:
|
||||
- understand the feedback
|
||||
- evaluate whether applying it would leave the code more **sound, correct, AND elegant**. reviewers are fallible and bias toward *recommending additions* (defensive checks for impossible cases, extra abstractions, comments restating obvious code, tests asserting tautologies, "just-in-case" guards). if a request would add bloat — ceremony without commensurate correctness benefit — push back in your reply rather than mechanically applying it. two-out-of-three is not enough; improving correctness while degrading elegance still degrades the code.
|
||||
- evaluate whether applying it would leave the code more **sound, correct, AND elegant**. reviewers are fallible and bias toward *recommending additions* (defensive checks for impossible cases, extra abstractions, comments restating obvious code, tests asserting tautologies, "just-in-case" guards). if a request would add bloat — ceremony without commensurate correctness benefit — push back in your reply rather than mechanically applying it. two-out-of-three is usually a signal to look harder for a fix that gets all three before settling.
|
||||
- if the request stands, make the code change using your native tools; otherwise reply explaining why
|
||||
- record what was done (or why nothing was done)
|
||||
|
||||
@@ -175,7 +181,7 @@ ${learningsStep(t, 6)}`,
|
||||
|
||||
2. **triage**: orient yourself on the PR — identify *what kind of thing this is* (domain it touches, seams it crosses, external contracts it depends on, user-facing surfaces it changes). orientation only — defer specific defect-hunting to the subagents; pre-reviewing biases the lenses you pick. use \`${t("get_pull_request")}\` and other read-only GitHub tools for additional context if needed.
|
||||
|
||||
if the PR is **genuinely trivial**, skip steps 3–4 entirely and submit \`Reviewed — no issues found.\` per step 5. there's no value in dispatching even one lens for a typo.
|
||||
if the PR is **genuinely trivial**, skip steps 3–4 entirely and submit a \`No new issues found.\` review per step 5. there's no value in dispatching even one lens for a typo.
|
||||
|
||||
"Genuinely trivial" (skip):
|
||||
- single-word doc typo, whitespace/format-only, comment-only across any number of files
|
||||
@@ -243,26 +249,28 @@ ${learningsStep(t, 6)}`,
|
||||
|
||||
note: the first create_pull_request_review submission may error with a one-time diff-coverage nudge listing unread TOC regions. retry the same call to proceed — optionally after reading the listed ranges. the pre-flight will not block again this session.
|
||||
|
||||
The review body is structured as: \`[optional alert blockquote]\` → \`[PR summary using the default format below]\`. Inline comments are passed via the \`comments\` parameter, not in the body.
|
||||
|
||||
- **critical issues** (blocks merge — bugs, security, data loss):
|
||||
\`approved: false\`. Body begins with a GitHub alert blockquote, e.g.:
|
||||
\`> [!CAUTION]\\n> This PR introduces a race condition in ...\`
|
||||
Follow with a brief summary if needed. Include all inline comments.
|
||||
\`approved: false\`. Body opens with \`> [!CAUTION]\\n> This PR introduces ...\`, followed by the PR summary. Include all inline comments via \`comments\`.
|
||||
- **recommended changes** (non-critical):
|
||||
\`approved: false\`. Body begins with a GitHub alert blockquote, e.g.:
|
||||
\`> [!IMPORTANT]\\n> Consider adding input validation for ...\`
|
||||
Follow with a brief summary if needed. Include all inline comments.
|
||||
\`approved: false\`. Body opens with \`> [!IMPORTANT]\\n> Consider ...\`, followed by the PR summary. Include all inline comments via \`comments\`.
|
||||
- **no actionable issues**:
|
||||
\`approved: true\`, body: "Reviewed — no issues found."`,
|
||||
\`approved: true\`. Body opens with \`No new issues found.\` followed by the PR summary.
|
||||
|
||||
${PR_SUMMARY_FORMAT}`,
|
||||
},
|
||||
// IncrementalReview shares Review's multi-lens orchestrator pattern but
|
||||
// scopes the target to the incremental diff and adds prior-review-feedback
|
||||
// tracking. The "issues must be NEW since the last Pullfrog review" filter
|
||||
// lives at aggregation time (step 5), NOT in the subagent prompt — pushing
|
||||
// the filter into subagents matches the canonical anneal anti-pattern of
|
||||
// "list known pre-existing failures — don't flag these" and suppresses
|
||||
// signal on regressions the new commits amplified. The body-format rules
|
||||
// (Reviewed changes / Prior review feedback) are unchanged from the prior
|
||||
// version. Same severity-table omission as Review.
|
||||
// scopes the target to the incremental diff. The "issues must be NEW
|
||||
// since the last Pullfrog review" filter lives at aggregation time
|
||||
// (step 5), NOT in the subagent prompt — pushing the filter into
|
||||
// subagents matches the canonical anneal anti-pattern of "list known
|
||||
// pre-existing failures — don't flag these" and suppresses signal on
|
||||
// regressions the new commits amplified. The review body is just
|
||||
// "Reviewed changes" — a separate "Prior review feedback" checklist
|
||||
// would duplicate the rolling PR summary snapshot's record of what
|
||||
// earlier runs already addressed and add noise to the user-facing
|
||||
// body. Same severity-table omission as Review.
|
||||
{
|
||||
name: "IncrementalReview",
|
||||
description:
|
||||
@@ -273,7 +281,7 @@ ${learningsStep(t, 6)}`,
|
||||
|
||||
2. **incremental scope**: if \`incrementalDiffPath\` is present, read it to see what changed since the last review. this is a range-diff that isolates the net changes, filtering out base branch noise. if not present, fall back to reviewing the full PR diff and determine what changed since Pullfrog's most recent review.
|
||||
|
||||
3. **prior feedback**: fetch previous reviews via \`${t("list_pull_request_reviews")}\`. for the most recent Pullfrog review, call \`${t("get_review_comments")}\` with the review ID to retrieve specific prior line-level feedback. you'll need this in step 6 to track which prior comments were addressed.
|
||||
3. **prior feedback**: fetch previous reviews via \`${t("list_pull_request_reviews")}\`. for the most recent Pullfrog review, call \`${t("get_review_comments")}\` with the review ID to retrieve specific prior line-level feedback. you'll use this to filter your aggregation in step 5 — anything already flagged in a prior review and not changed by the new commits should not be re-raised. you do NOT need to render this in the review body; the rolling PR summary snapshot is the durable record of what's been addressed.
|
||||
|
||||
4. **triage & fan out**: orient on the *incremental* changes — domain, seams, external contracts, user-facing surfaces.
|
||||
|
||||
@@ -302,20 +310,14 @@ ${learningsStep(t, 6)}`,
|
||||
|
||||
5. **aggregate, draft, self-critique**: merge findings; de-dup overlaps; trace each finding yourself. drop praise, style preferences, speculative/unverified claims, findings about pre-existing code unrelated to the new commits, anything not actionable, and anything that re-states prior review feedback (heuristic: if the finding's root cause lives in lines the *new commits* added or modified, it's in scope; otherwise drop). also drop **bloat-shaped findings** — proposed fixes that would add defensive checks for cases that can't happen, abstractions used once, comments restating obvious code, tests asserting tautologies, or "just-in-case" guards. subagents are fallible and bias toward recommending changes; the bar for an actionable inline comment is sound + correct + elegant. recommending a change that improves only one of the three (or degrades elegance to nominally improve correctness) makes the codebase worse, not better. To compute "lines the new commits added or modified": if \`incrementalDiffPath\` from step 1 is present, use it directly. Otherwise, take the prior Pullfrog review's \`commit_id\` (returned alongside each entry from \`${t("list_pull_request_reviews")}\` in step 3) and run \`git diff <prior-review-sha>..HEAD\` to isolate the lines added since that review. draft inline comments with NEW line numbers from the full PR diff — every comment must be actionable, 2-3 sentences max.
|
||||
|
||||
then check: which prior review comments were addressed by the new commits? track the addressed ones for step 6b.
|
||||
6. **build the review body** — a single "Reviewed changes" section: summarize at the logical-change level, not per-file. each bullet starts with a past-tense verb (e.g. \`- Extracted shared CLI runtime into a single module\`, \`- Renamed package to pullfrog\`). avoid file paths unless they add clarity. if the changes can be described in one sentence, use one sentence — no bullets needed. do NOT include a separate "Prior review feedback" checklist; that's tracked in the rolling PR summary snapshot for the next agent run, and surfacing it in the user-facing body is noise (changes that addressed prior feedback are already covered by the Reviewed-changes bullets). in some cases you may receive a complete diff for the whole pull request instead of an incremental one — when this happens, you will need to determine what changes have happened since Pullfrog's most recent review.
|
||||
|
||||
6. **build the review body** — two distinct sections:
|
||||
a. **Reviewed changes**: summarize at the logical-change level, not per-file. each bullet starts with a past-tense verb (e.g. \`- Extracted shared CLI runtime into a single module\`, \`- Renamed package to pullfrog\`). avoid file paths unless they add clarity. if the changes can be described in one sentence, use one sentence — no bullets needed.
|
||||
b. **Prior review feedback** (only if any were addressed): list only the prior review comments that WERE addressed by the new commits (\`- [x] safeParse instead of parse — addressed\`). omit unaddressed comments. omit this entire section if nothing was addressed. a change can appear in both sections.
|
||||
- no headings, no tables, no prose paragraphs in either section — just bullets
|
||||
- in some cases you may receive a complete diff for the whole pull request instead of an incremental one. when this happens, you will need to determine what changes have happened since Pullfrog's most recent review.
|
||||
|
||||
7. Submit — Do NOT call \`report_progress\` or \`create_issue_comment\` — the review is the final record and the progress comment will be cleaned up automatically. the review body always includes the reviewed changes from step 6a. append \`Prior review feedback:\\n\` with the checklist from step 6b only if any prior comments were addressed. Follow these rules:
|
||||
7. Submit — Do NOT call \`report_progress\` or \`create_issue_comment\` — the review is the final record and the progress comment will be cleaned up automatically. Follow these rules:
|
||||
- note: the first create_pull_request_review submission may error with a one-time diff-coverage nudge listing unread TOC regions. retry the same call to proceed — optionally after reading the listed ranges. the pre-flight will not block again this session.
|
||||
- IF NO NEW ISSUES, NON-SUBSTANTIVE CHANGES ONLY (trivial formatting, import reordering, comment tweaks): do NOT submit a review. Do NOT call \`report_progress\`. Exit — the progress comment will be cleaned up automatically.
|
||||
- ELSE IF NEW CRITICAL ISSUES (blocks merge): call \`${t("create_pull_request_review")}\` with \`approved: false\`, all comments, and the review body. body opens with a GitHub alert blockquote (e.g. \`> [!CAUTION]\\n> This PR introduces ...\`), then the reviewed changes summary and prior feedback (if any).
|
||||
- ELSE IF NEW RECOMMENDED CHANGES (non-critical): call \`${t("create_pull_request_review")}\` with \`approved: false\`, all comments, and the review body. body opens with \`> [!IMPORTANT]\\n> ...\` alert, then the reviewed changes summary and prior feedback (if any).
|
||||
- ELSE IF NO NEW ISSUES, SUBSTANTIVE CHANGES (new functionality, behavior changes, or fixes to prior review feedback): call \`${t("create_pull_request_review")}\` to create a PR review. If all previous reviews have been properly addressed and no new issues were discovered, you can set \`approved: true\`. body opens with \`No new issues. Reviewed the following changes:\\n\`, then the reviewed changes summary and prior feedback (if any).`,
|
||||
- ELSE IF NEW CRITICAL ISSUES (blocks merge): call \`${t("create_pull_request_review")}\` with \`approved: false\`, all comments, and the review body. body opens with a GitHub alert blockquote (e.g. \`> [!CAUTION]\\n> This PR introduces ...\`), then the Reviewed-changes summary.
|
||||
- ELSE IF NEW RECOMMENDED CHANGES (non-critical): call \`${t("create_pull_request_review")}\` with \`approved: false\`, all comments, and the review body. body opens with \`> [!IMPORTANT]\\n> ...\` alert, then the Reviewed-changes summary.
|
||||
- ELSE IF NO NEW ISSUES, SUBSTANTIVE CHANGES (new functionality, behavior changes, or fixes to prior review feedback): call \`${t("create_pull_request_review")}\` to create a PR review. If all previous reviews have been properly addressed and no new issues were discovered, you can set \`approved: true\`. body opens with \`No new issues. Reviewed the following changes:\\n\`, then the Reviewed-changes summary.`,
|
||||
},
|
||||
{
|
||||
name: "Plan",
|
||||
@@ -405,19 +407,6 @@ ${learningsStep(t, 6)}`,
|
||||
|
||||
${learningsStep(t, 4)}`,
|
||||
},
|
||||
{
|
||||
name: "Summarize",
|
||||
description:
|
||||
"Summarize a PR with a structured comment that is updated in place on subsequent pushes",
|
||||
prompt: `### Checklist
|
||||
|
||||
1. Checkout the PR via \`${t("checkout_pr")}\` — this returns PR metadata and a \`diffPath\`.
|
||||
2. Read the diff using the TOC to selectively read relevant sections (not the entire file). Produce a structured summary. If EVENT INSTRUCTIONS specify a custom format, follow that instead of the default format below.
|
||||
3. Call \`${t("create_issue_comment")}\` with \`type: "Summary"\` and the summary body.
|
||||
4. Call \`${t("report_progress")}\` with a brief note (e.g., "Posted PR summary.").
|
||||
|
||||
${PR_SUMMARY_FORMAT}`,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "pullfrog",
|
||||
"version": "0.0.203",
|
||||
"version": "0.0.205",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
"pullfrog": "dist/cli.mjs",
|
||||
|
||||
@@ -12,7 +12,6 @@ import { log } from "./utils/cli.ts";
|
||||
import { runInDocker } from "./utils/docker.ts";
|
||||
import { ensureGitHubToken } from "./utils/github.ts";
|
||||
import { isInsideDocker } from "./utils/globals.ts";
|
||||
import { runPostCleanup } from "./utils/postCleanup.ts";
|
||||
import { setupTestRepo } from "./utils/setup.ts";
|
||||
|
||||
/**
|
||||
@@ -78,13 +77,7 @@ export async function run(inputsOrPrompt: Inputs | string): Promise<AgentResult>
|
||||
}
|
||||
}
|
||||
|
||||
// wrap main() so post cleanup runs even on failure (mirrors action.yml post-if: "failure() || cancelled()")
|
||||
let result: AgentResult;
|
||||
try {
|
||||
result = await main();
|
||||
} finally {
|
||||
await runPostCleanup();
|
||||
}
|
||||
const result: AgentResult = await main();
|
||||
|
||||
process.chdir(originalCwd);
|
||||
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { runPullfrogCli } from "./runCli.ts";
|
||||
|
||||
runPullfrogCli({
|
||||
cliArgs: ["gha", "--post"],
|
||||
swallowErrors: true,
|
||||
});
|
||||
@@ -7,7 +7,6 @@ const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const entryPoints = [
|
||||
resolve(scriptDir, "../entry.ts"),
|
||||
resolve(scriptDir, "../post.ts"),
|
||||
resolve(scriptDir, "../get-installation-token/entry.ts"),
|
||||
resolve(scriptDir, "../get-installation-token/post.ts"),
|
||||
];
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* refresh checked-in test fixtures for mcp/checkout.test.ts and
|
||||
* mcp/reviewComments.test.ts.
|
||||
*
|
||||
* those tests used to hit live GitHub on every run, which made them
|
||||
* cred-gated (GH_TOKEN or GITHUB_APP_ID + GITHUB_PRIVATE_KEY) and
|
||||
* non-deterministic. they now read from action/mcp/__fixtures__/*.json,
|
||||
* which this script regenerates on demand.
|
||||
*
|
||||
* run with creds set (locally via .env, or in a CI cron with secrets):
|
||||
*
|
||||
* GH_TOKEN=… node action/scripts/refresh-test-fixtures.ts
|
||||
* # or
|
||||
* GITHUB_APP_ID=… GITHUB_PRIVATE_KEY=… node action/scripts/refresh-test-fixtures.ts
|
||||
*
|
||||
* commit the resulting fixture changes; review the diff before merging
|
||||
* (anything unexpected indicates real GitHub API drift).
|
||||
*/
|
||||
|
||||
import { mkdirSync, writeFileSync } from "node:fs";
|
||||
import { dirname, resolve } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { Octokit } from "@octokit/rest";
|
||||
import { config as loadDotenv } from "dotenv";
|
||||
import {
|
||||
REVIEW_THREADS_QUERY,
|
||||
type ReviewThread,
|
||||
type ReviewThreadsQueryResponse,
|
||||
} from "../mcp/reviewComments.ts";
|
||||
import { acquireNewToken } from "../utils/github.ts";
|
||||
|
||||
const scriptDir = dirname(fileURLToPath(import.meta.url));
|
||||
const repoRoot = resolve(scriptDir, "../..");
|
||||
const fixturesDir = resolve(scriptDir, "../mcp/__fixtures__");
|
||||
|
||||
loadDotenv({ path: resolve(repoRoot, ".env") });
|
||||
|
||||
type DiffFixture = {
|
||||
owner: string;
|
||||
name: string;
|
||||
pullNumber: number;
|
||||
files: unknown;
|
||||
};
|
||||
|
||||
type ReviewFixture = {
|
||||
owner: string;
|
||||
name: string;
|
||||
pullNumber: number;
|
||||
reviewId: number;
|
||||
review: { body: string | null | undefined; user: { login: string } | null | undefined };
|
||||
threads: ReviewThread[];
|
||||
prFiles: Array<{ filename: string; patch?: string | undefined }>;
|
||||
};
|
||||
|
||||
const DIFF_TARGETS: Array<Pick<DiffFixture, "owner" | "name" | "pullNumber">> = [
|
||||
{ owner: "pullfrog", name: "test-repo", pullNumber: 1 },
|
||||
];
|
||||
|
||||
const REVIEW_TARGETS: Array<Pick<ReviewFixture, "owner" | "name" | "pullNumber" | "reviewId">> = [
|
||||
{ owner: "pullfrog", name: "scratch", pullNumber: 49, reviewId: 3485940013 },
|
||||
{ owner: "pullfrog", name: "scratch", pullNumber: 64, reviewId: 3531000326 },
|
||||
];
|
||||
|
||||
async function getToken(): Promise<string> {
|
||||
if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
|
||||
return await acquireNewToken();
|
||||
}
|
||||
|
||||
async function refreshDiffFixture(
|
||||
octokit: Octokit,
|
||||
target: (typeof DIFF_TARGETS)[number]
|
||||
): Promise<void> {
|
||||
const files = await octokit.paginate(octokit.rest.pulls.listFiles, {
|
||||
owner: target.owner,
|
||||
repo: target.name,
|
||||
pull_number: target.pullNumber,
|
||||
per_page: 100,
|
||||
});
|
||||
const fixture: DiffFixture = { ...target, files };
|
||||
const path = resolve(
|
||||
fixturesDir,
|
||||
`${target.owner}-${target.name}-pr-${target.pullNumber}.diff.json`
|
||||
);
|
||||
writeFileSync(path, `${JSON.stringify(fixture, null, 2)}\n`);
|
||||
console.log(`wrote ${path}`);
|
||||
}
|
||||
|
||||
async function refreshReviewFixture(
|
||||
octokit: Octokit,
|
||||
target: (typeof REVIEW_TARGETS)[number]
|
||||
): Promise<void> {
|
||||
const [review, threadsResp] = await Promise.all([
|
||||
octokit.rest.pulls.getReview({
|
||||
owner: target.owner,
|
||||
repo: target.name,
|
||||
pull_number: target.pullNumber,
|
||||
review_id: target.reviewId,
|
||||
}),
|
||||
octokit.graphql<ReviewThreadsQueryResponse>(REVIEW_THREADS_QUERY, {
|
||||
owner: target.owner,
|
||||
name: target.name,
|
||||
prNumber: target.pullNumber,
|
||||
}),
|
||||
]);
|
||||
|
||||
const allThreads = threadsResp.repository?.pullRequest?.reviewThreads?.nodes ?? [];
|
||||
const threads = allThreads.filter((thread): thread is ReviewThread => {
|
||||
if (!thread?.comments?.nodes) return false;
|
||||
return thread.comments.nodes.some((c) => c?.pullRequestReview?.databaseId === target.reviewId);
|
||||
});
|
||||
|
||||
// skip listFiles entirely when there are no threads — prFiles is only
|
||||
// used for thread blocks, so an empty array short-circuits in the
|
||||
// formatter. mirrors getReviewData's runtime perf optimization and
|
||||
// keeps body-only-review fixtures small.
|
||||
const prFiles =
|
||||
threads.length > 0
|
||||
? await octokit.paginate(octokit.rest.pulls.listFiles, {
|
||||
owner: target.owner,
|
||||
repo: target.name,
|
||||
pull_number: target.pullNumber,
|
||||
per_page: 100,
|
||||
})
|
||||
: [];
|
||||
|
||||
// strip prFiles down to the fields the formatter actually reads. keeps
|
||||
// fixtures small and avoids capturing volatile fields (sha, blob_url,
|
||||
// contents_url, etc.) that would churn unrelated to formatter behavior.
|
||||
const trimmedFiles = prFiles.map((f) => ({
|
||||
filename: f.filename,
|
||||
...(f.patch ? { patch: f.patch } : {}),
|
||||
}));
|
||||
|
||||
const fixture: ReviewFixture = {
|
||||
...target,
|
||||
review: {
|
||||
body: review.data.body,
|
||||
user: review.data.user ? { login: review.data.user.login } : null,
|
||||
},
|
||||
threads,
|
||||
prFiles: trimmedFiles,
|
||||
};
|
||||
const path = resolve(
|
||||
fixturesDir,
|
||||
`${target.owner}-${target.name}-pr-${target.pullNumber}-review-${target.reviewId}.json`
|
||||
);
|
||||
writeFileSync(path, `${JSON.stringify(fixture, null, 2)}\n`);
|
||||
console.log(`wrote ${path}`);
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
const token = await getToken();
|
||||
const octokit = new Octokit({ auth: token });
|
||||
mkdirSync(fixturesDir, { recursive: true });
|
||||
|
||||
for (const t of DIFF_TARGETS) await refreshDiffFixture(octokit, t);
|
||||
for (const t of REVIEW_TARGETS) await refreshReviewFixture(octokit, t);
|
||||
}
|
||||
|
||||
await main();
|
||||
@@ -11,8 +11,8 @@ exports[`latest model per provider snapshot > matches snapshot 1`] = `
|
||||
"releaseDate": "2026-04-24",
|
||||
},
|
||||
"google": {
|
||||
"modelId": "gemma-4-31b-it",
|
||||
"releaseDate": "2026-04-02",
|
||||
"modelId": "gemini-3.1-flash-lite",
|
||||
"releaseDate": "2026-05-07",
|
||||
},
|
||||
"moonshotai": {
|
||||
"modelId": "kimi-k2.6",
|
||||
@@ -27,8 +27,8 @@ exports[`latest model per provider snapshot > matches snapshot 1`] = `
|
||||
"releaseDate": "2026-04-24",
|
||||
},
|
||||
"openrouter": {
|
||||
"modelId": "poolside/laguna-xs.2:free",
|
||||
"releaseDate": "2026-04-28",
|
||||
"modelId": "x-ai/grok-4.3",
|
||||
"releaseDate": "2026-05-01",
|
||||
},
|
||||
"xai": {
|
||||
"modelId": "grok-4.3",
|
||||
|
||||
@@ -98,6 +98,24 @@ describe("diff coverage line checker", () => {
|
||||
]);
|
||||
});
|
||||
|
||||
it("carries forward coveragePreflightRan from a previous state across checkout refreshes", () => {
|
||||
const previous = createDiffCoverageState({ diffPath, totalLines: 30, toc });
|
||||
previous.coveragePreflightRan = true;
|
||||
previous.coveredRanges = [{ startLine: 5, endLine: 10 }];
|
||||
|
||||
const next = createDiffCoverageState({ diffPath, totalLines: 50, toc, previous });
|
||||
|
||||
expect(next.coveragePreflightRan).toBe(true);
|
||||
// coveredRanges are tied to the previous diff content and must not leak forward
|
||||
expect(next.coveredRanges).toEqual([]);
|
||||
expect(next.totalLines).toBe(50);
|
||||
});
|
||||
|
||||
it("defaults coveragePreflightRan to false when no previous state is provided", () => {
|
||||
const state = createDiffCoverageState({ diffPath, totalLines: 30, toc });
|
||||
expect(state.coveragePreflightRan).toBe(false);
|
||||
});
|
||||
|
||||
it("computes per-file unread ranges from tracked reads", () => {
|
||||
const state = createDiffCoverageState({
|
||||
diffPath,
|
||||
|
||||
@@ -78,13 +78,17 @@ export function createDiffCoverageState(params: {
|
||||
diffPath: string;
|
||||
totalLines: number;
|
||||
toc: string;
|
||||
previous?: DiffCoverageState | undefined;
|
||||
}): DiffCoverageState {
|
||||
return {
|
||||
diffPath: params.diffPath,
|
||||
totalLines: params.totalLines,
|
||||
tocEntries: parseDiffTocEntries({ toc: params.toc }),
|
||||
coveredRanges: [],
|
||||
coveragePreflightRan: false,
|
||||
// carry forward across checkout_pr refreshes so the nudge stays "once per
|
||||
// review session". coveredRanges are intentionally not carried because
|
||||
// line numbers are tied to the previous diff's content.
|
||||
coveragePreflightRan: params.previous?.coveragePreflightRan ?? false,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@ import type { ToolState } from "../mcp/server.ts";
|
||||
import { getApiUrl } from "./apiUrl.ts";
|
||||
import { buildPullfrogFooter } from "./buildPullfrogFooter.ts";
|
||||
import { createOctokit, parseRepoContext } from "./github.ts";
|
||||
import { updateProgressComment } from "./progressComment.ts";
|
||||
import { getGitHubInstallationToken } from "./token.ts";
|
||||
|
||||
interface ReportErrorParams {
|
||||
@@ -13,8 +14,8 @@ interface ReportErrorParams {
|
||||
export async function reportErrorToComment(ctx: ReportErrorParams): Promise<void> {
|
||||
const formattedError = ctx.title ? `${ctx.title}\n\n${ctx.error}` : ctx.error;
|
||||
|
||||
const commentId = ctx.toolState.progressCommentId;
|
||||
if (!commentId) {
|
||||
const comment = ctx.toolState.progressComment;
|
||||
if (!comment) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -39,12 +40,11 @@ export async function reportErrorToComment(ctx: ReportErrorParams): Promise<void
|
||||
model: ctx.toolState.model,
|
||||
});
|
||||
|
||||
await octokit.rest.issues.updateComment({
|
||||
owner: repoContext.owner,
|
||||
repo: repoContext.name,
|
||||
comment_id: commentId,
|
||||
body: `${formattedError}${footer}`,
|
||||
});
|
||||
await updateProgressComment(
|
||||
{ octokit, owner: repoContext.owner, repo: repoContext.name },
|
||||
comment,
|
||||
`${formattedError}${footer}`
|
||||
);
|
||||
|
||||
// mark as updated so exit handler doesn't try to update again
|
||||
ctx.toolState.wasUpdated = true;
|
||||
|
||||
+13
-2
@@ -154,8 +154,19 @@ export async function $git(
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
const stderr = result.stderr.trim();
|
||||
log.info(`git ${subcommand} failed: ${stderr}`);
|
||||
throw new Error(`git ${subcommand} failed: ${stderr}`);
|
||||
const stdout = result.stdout.trim();
|
||||
// stderr is the primary channel for git diagnostics, but in rare cases
|
||||
// (e.g. some HTTPS smart-protocol failures) the only useful detail is
|
||||
// on stdout — without it the agent / operator sees an empty error.
|
||||
// include exit code so we can distinguish e.g. signal-killed (1 with
|
||||
// empty output) from a genuine git-level rejection.
|
||||
const detail =
|
||||
stderr && stdout
|
||||
? `${stderr}\n--- stdout ---\n${stdout}`
|
||||
: stderr || stdout || "(no output)";
|
||||
const message = `git ${subcommand} failed (exit ${result.exitCode}): ${detail}`;
|
||||
log.info(message);
|
||||
throw new Error(message);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -289,7 +289,7 @@ When embedding images (e.g. uploaded screenshots) in comments or PR bodies, alwa
|
||||
|
||||
**\`report_progress\`**: call this exactly once at the end of every run with a brief final summary (1-3 sentences) unless the mode guidance instructs otherwise. Never call it for intermediate status updates (e.g., "Checking for changes...", "Starting review...") — the task list handles live progress automatically. Calling \`report_progress\` replaces the task list with your summary and preserves the current task list in a collapsible section. Keep the summary concise — do not repeat what the task list already shows. Focus on the outcome (what was accomplished, links to artifacts) rather than listing individual steps. If something failed, include the tool's error text even when that makes the summary longer.
|
||||
|
||||
Never use \`create_issue_comment\` for task progress — that creates duplicate comments and leaves the progress comment stuck in its initial state. \`create_issue_comment\` is only for standalone comments unrelated to your current task (e.g., Plan comments, PR Summary comments).
|
||||
Never use \`create_issue_comment\` for task progress — that creates duplicate comments and leaves the progress comment stuck in its initial state. \`create_issue_comment\` is only for standalone comments unrelated to your current task (e.g., Plan comments).
|
||||
|
||||
### If you get stuck
|
||||
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
import { stripExistingFooter } from "./buildPullfrogFooter.ts";
|
||||
|
||||
/**
|
||||
* The prefix text for the initial "leaping into action" comment.
|
||||
* Used to detect whether a progress comment is still in its initial state
|
||||
* and hasn't been updated with real progress or error messages.
|
||||
*
|
||||
* Lives in `utils/` (not `mcp/`) so it can be re-exported via `pullfrog/internal`
|
||||
* without dragging the MCP server's transitive imports into the Next.js app's
|
||||
* type-check graph.
|
||||
*/
|
||||
export const LEAPING_INTO_ACTION_PREFIX = "Leaping into action";
|
||||
|
||||
export function isLeapingIntoActionCommentBody(body: string): boolean {
|
||||
const content = stripExistingFooter(body).trimStart();
|
||||
const firstLine = content.split(/\r?\n/, 1)[0]?.trimEnd() ?? "";
|
||||
return new RegExp(`(^|\\s)${LEAPING_INTO_ACTION_PREFIX}(\\.\\.\\.)?$`).test(firstLine);
|
||||
}
|
||||
@@ -14,7 +14,8 @@ export type WorkflowRunArtifactPatchKey =
|
||||
| "issueNodeId"
|
||||
| "reviewNodeId"
|
||||
| "planCommentNodeId"
|
||||
| "summaryCommentNodeId";
|
||||
| "summaryCommentNodeId"
|
||||
| "summarySnapshot";
|
||||
|
||||
/**
|
||||
* Usage fields — aggregated across all agent calls and PATCHed once at
|
||||
@@ -38,6 +39,7 @@ const STRING_KEYS: WorkflowRunArtifactPatchKey[] = [
|
||||
"reviewNodeId",
|
||||
"planCommentNodeId",
|
||||
"summaryCommentNodeId",
|
||||
"summarySnapshot",
|
||||
];
|
||||
|
||||
const NUMBER_KEYS: WorkflowRunUsagePatchKey[] = [
|
||||
|
||||
+7
-2
@@ -23,7 +23,11 @@ export const JsonPayload = type({
|
||||
"eventInstructions?": "string",
|
||||
"event?": "object",
|
||||
"timeout?": "string | undefined",
|
||||
"progressCommentId?": "string | undefined",
|
||||
"progressComment?": type({
|
||||
id: "string",
|
||||
type: "'issue' | 'review'",
|
||||
}).or("undefined"),
|
||||
"generateSummary?": "boolean | undefined",
|
||||
});
|
||||
|
||||
// permission levels that indicate collaborator status (have push access)
|
||||
@@ -156,7 +160,8 @@ export function resolvePayload(
|
||||
event,
|
||||
timeout: inputs.timeout ?? jsonPayload?.timeout,
|
||||
cwd: resolveCwd(inputs.cwd),
|
||||
progressCommentId: jsonPayload?.progressCommentId,
|
||||
progressComment: jsonPayload?.progressComment,
|
||||
generateSummary: jsonPayload?.generateSummary,
|
||||
|
||||
// permissions: inputs > repoSettings > fallbacks
|
||||
push: inputs.push ?? repoSettings.push ?? "restricted",
|
||||
|
||||
@@ -1,185 +0,0 @@
|
||||
import { isLeapingIntoActionCommentBody } from "../mcp/comment.ts";
|
||||
import { getApiUrl } from "./apiUrl.ts";
|
||||
import { buildPullfrogFooter } from "./buildPullfrogFooter.ts";
|
||||
import { log } from "./cli.ts";
|
||||
import { createOctokit, parseRepoContext } from "./github.ts";
|
||||
import { type ResolvedPromptInput, resolvePromptInput } from "./payload.ts";
|
||||
import { getJobToken } from "./token.ts";
|
||||
|
||||
type JsonPromptInput = Extract<ResolvedPromptInput, object>; // not string
|
||||
|
||||
interface PostCleanupContext {
|
||||
repoContext: ReturnType<typeof parseRepoContext>;
|
||||
octokit: ReturnType<typeof createOctokit>;
|
||||
runId: number | undefined;
|
||||
promptInput: JsonPromptInput | null;
|
||||
}
|
||||
|
||||
// controls whether the script should check the reason for the workflow termination.
|
||||
// it can be either canceled or failed.
|
||||
// YAML file cannot supply it (not in ENV), so an extra request is required to check it.
|
||||
const SHOULD_CHECK_REASON = true;
|
||||
|
||||
function buildErrorCommentBody(ctx: PostCleanupContext, isCancellation: boolean): string {
|
||||
let errorMessage = isCancellation
|
||||
? `This run was cancelled 🛑\n\nThe workflow was cancelled before completion.`
|
||||
: `This run croaked 😵\n\nThe workflow encountered an error before any progress could be reported.`;
|
||||
|
||||
if (ctx.runId) {
|
||||
errorMessage += " Please check the link below for details.";
|
||||
}
|
||||
|
||||
const customParts: string[] = [];
|
||||
if (!isCancellation && ctx.runId) {
|
||||
const apiUrl = getApiUrl();
|
||||
customParts.push(
|
||||
`[Rerun failed job ➔](${apiUrl}/trigger/${ctx.repoContext.owner}/${ctx.repoContext.name}/${ctx.runId}?action=rerun)`
|
||||
);
|
||||
}
|
||||
const footer = buildPullfrogFooter({
|
||||
triggeredBy: true,
|
||||
workflowRun: ctx.runId
|
||||
? {
|
||||
owner: ctx.repoContext.owner,
|
||||
repo: ctx.repoContext.name,
|
||||
runId: ctx.runId,
|
||||
}
|
||||
: undefined,
|
||||
customParts,
|
||||
});
|
||||
return `${errorMessage}${footer}`;
|
||||
}
|
||||
|
||||
async function validateStuckProgressComment(ctx: PostCleanupContext): Promise<number | null> {
|
||||
if (!ctx.promptInput?.progressCommentId) {
|
||||
log.info("[post] no progressCommentId in prompt input, skipping cleanup");
|
||||
return null;
|
||||
}
|
||||
|
||||
const commentId = parseInt(ctx.promptInput.progressCommentId, 10);
|
||||
log.info(`[post] validating progressCommentId from prompt input: ${commentId}`);
|
||||
|
||||
try {
|
||||
const commentResult = await ctx.octokit.rest.issues.getComment({
|
||||
owner: ctx.repoContext.owner,
|
||||
repo: ctx.repoContext.name,
|
||||
comment_id: commentId,
|
||||
});
|
||||
|
||||
const body = commentResult.data.body ?? "";
|
||||
|
||||
if (isLeapingIntoActionCommentBody(body)) {
|
||||
log.info(`[post] comment ${commentId} is stuck on "Leaping into action"`);
|
||||
return commentId;
|
||||
}
|
||||
|
||||
// detect stranded todo checklists left by the tracker when the process was killed
|
||||
// before the agent could call report_progress with a final summary
|
||||
if (/^- \[[ x]\] |^- \*\*→\*\* |^- ~~/.test(body)) {
|
||||
log.info(`[post] comment ${commentId} is stuck on a todo checklist`);
|
||||
return commentId;
|
||||
}
|
||||
|
||||
log.info(`[post] comment ${commentId} is not stuck (already updated or different content)`);
|
||||
return null;
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
log.info(`[post] failed to get comment ${commentId}: ${errorMessage}`);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function getIsCancelled(ctx: PostCleanupContext): Promise<boolean> {
|
||||
if (!ctx.runId) return false; // can't check without a run ID — assume failure
|
||||
try {
|
||||
const jobsResult = await ctx.octokit.rest.actions.listJobsForWorkflowRun({
|
||||
owner: ctx.repoContext.owner,
|
||||
repo: ctx.repoContext.name,
|
||||
run_id: ctx.runId,
|
||||
});
|
||||
|
||||
// find current job by matching GITHUB_JOB env var.
|
||||
// GITHUB_JOB is the job ID (yaml key), but job.name is the display name.
|
||||
// for matrix jobs, the name includes matrix values like "build (ubuntu-latest, node-18)"
|
||||
// so we match jobs that START with the job ID
|
||||
const currentJobName = process.env.GITHUB_JOB;
|
||||
const currentJob = currentJobName
|
||||
? jobsResult.data.jobs.find(
|
||||
(j) => j.name === currentJobName || j.name.startsWith(`${currentJobName} (`)
|
||||
)
|
||||
: jobsResult.data.jobs[0]; // fallback to first job
|
||||
|
||||
if (!currentJob) {
|
||||
log.warning("[post] could not find current job");
|
||||
return false;
|
||||
}
|
||||
|
||||
log.info(`[post] job status: ${currentJob.status}, conclusion: ${currentJob.conclusion}`);
|
||||
if (currentJob.conclusion === "cancelled") return true; // whole job explicit cancellation
|
||||
|
||||
// but if it's still null, check steps for cancellation:
|
||||
const cancelledStep = currentJob.steps?.find((step) => step.conclusion === "cancelled");
|
||||
if (cancelledStep) {
|
||||
log.info(`[post] found cancelled step: ${cancelledStep.name}`);
|
||||
return true;
|
||||
}
|
||||
log.info("[post] no cancellation found, assuming failure");
|
||||
} catch (error) {
|
||||
log.info(
|
||||
`[post] failed to get job status: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
return false; // assuming failure
|
||||
}
|
||||
|
||||
export async function runPostCleanup(): Promise<void> {
|
||||
log.info("» [post] starting post cleanup");
|
||||
|
||||
const runId = process.env.GITHUB_RUN_ID
|
||||
? Number.parseInt(process.env.GITHUB_RUN_ID, 10)
|
||||
: undefined;
|
||||
|
||||
// resolve prompt input once and use it for both issue number and comment ID extraction
|
||||
// only use the object form (JSON payload), not plain string prompts
|
||||
let promptInput: JsonPromptInput | null = null;
|
||||
try {
|
||||
const resolved = resolvePromptInput();
|
||||
if (typeof resolved !== "string") promptInput = resolved;
|
||||
} catch (error) {
|
||||
log.info(
|
||||
`[post] failed to resolve prompt input: ${error instanceof Error ? error.message : String(error)}`
|
||||
);
|
||||
}
|
||||
|
||||
// get job token for API calls
|
||||
const token = getJobToken();
|
||||
const repoContext = parseRepoContext();
|
||||
const octokit = createOctokit(token);
|
||||
|
||||
const ctx: PostCleanupContext = { repoContext, octokit, runId, promptInput };
|
||||
|
||||
const commentId = await validateStuckProgressComment(ctx);
|
||||
|
||||
if (!commentId) return log.info("» [post] no stuck progress comment to update, skipping cleanup");
|
||||
|
||||
log.info(`» [post] validated stuck comment: ${commentId}, updating with error message`);
|
||||
|
||||
try {
|
||||
const body = buildErrorCommentBody(
|
||||
ctx,
|
||||
SHOULD_CHECK_REASON ? await getIsCancelled(ctx) : false
|
||||
);
|
||||
|
||||
await ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.repoContext.owner,
|
||||
repo: ctx.repoContext.name,
|
||||
comment_id: commentId,
|
||||
body,
|
||||
});
|
||||
|
||||
log.info("» [post] successfully updated progress comment");
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : String(error);
|
||||
log.info(`[post] failed to update comment: ${errorMessage}`);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
|
||||
/**
|
||||
* The PR-level summary snapshot is a markdown file the agent edits in place
|
||||
* during a Review / IncrementalReview run. The server seeds the file with
|
||||
* either the previous run's snapshot (incremental) or a stub scaffold (first
|
||||
* run), lets the agent edit it with its native file-editing tools, then
|
||||
* reads it back at end-of-run and persists it to `WorkflowRun.summarySnapshot`.
|
||||
*
|
||||
* The snapshot is an internal artifact — it is consumed by future agent runs
|
||||
* as durable cross-run context, not surfaced to humans. User-visible summary
|
||||
* content lives in the Review / IncrementalReview review bodies, governed by
|
||||
* `action/modes.ts`.
|
||||
*
|
||||
* Edit-in-place avoids the output-token tax of a tool call that regurgitates
|
||||
* the full snapshot, and gives incremental runs a clean surface that
|
||||
* range-diffs cleanly across runs because the section headings are stable.
|
||||
*/
|
||||
|
||||
export const SUMMARY_FILE_NAME = "pullfrog-summary.md";
|
||||
|
||||
/**
|
||||
* minimal seed for first-run PRs. just a header + a one-line note about
|
||||
* what this file is for. structure is intentionally NOT prescribed —
|
||||
* different PRs warrant different organization, and the agent should pick
|
||||
* a shape that fits this PR. the agent's prompt (see selectMode.ts
|
||||
* `buildSummaryAddendum`) carries the actual instructions for what to
|
||||
* capture and how.
|
||||
*
|
||||
* keeping the seed short also makes the unchanged-from-seed gate more
|
||||
* sensitive — any meaningful edit moves the file off the seed, so
|
||||
* `persistSummary` can reliably skip the DB write when the agent didn't
|
||||
* touch the file.
|
||||
*/
|
||||
export const SUMMARY_SCAFFOLD = `# PR summary
|
||||
|
||||
<!-- durable cross-run context. edit in place; the next agent run reads this
|
||||
before reviewing new commits. structure however serves the PR best. -->
|
||||
`;
|
||||
|
||||
const MIN_SNAPSHOT_LENGTH = 60;
|
||||
/** PG TEXT can hold ~1GB but a sane cap protects the DB / API payloads. */
|
||||
const MAX_SNAPSHOT_LENGTH = 32_768;
|
||||
|
||||
export function summaryFilePath(tmpdir: string): string {
|
||||
return join(tmpdir, SUMMARY_FILE_NAME);
|
||||
}
|
||||
|
||||
/** seed the summary file with previous snapshot (incremental) or scaffold (first run). */
|
||||
export async function seedSummaryFile(params: {
|
||||
tmpdir: string;
|
||||
previousSnapshot: string | null;
|
||||
}): Promise<string> {
|
||||
const path = summaryFilePath(params.tmpdir);
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
const seed =
|
||||
params.previousSnapshot && params.previousSnapshot.trim().length >= MIN_SNAPSHOT_LENGTH
|
||||
? params.previousSnapshot
|
||||
: SUMMARY_SCAFFOLD;
|
||||
await writeFile(path, seed, "utf8");
|
||||
return path;
|
||||
}
|
||||
|
||||
/** read + validate the summary file written by the agent.
|
||||
* returns null when the file is missing or fails sanity checks. */
|
||||
export async function readSummaryFile(path: string): Promise<string | null> {
|
||||
let raw: string;
|
||||
try {
|
||||
raw = await readFile(path, "utf8");
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
const trimmed = raw.trim();
|
||||
if (trimmed.length < MIN_SNAPSHOT_LENGTH) return null;
|
||||
if (trimmed.length > MAX_SNAPSHOT_LENGTH) return trimmed.slice(0, MAX_SNAPSHOT_LENGTH);
|
||||
return trimmed;
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
/**
|
||||
* Single source of truth for reading, updating, deleting, and creating "progress comments" —
|
||||
* the GitHub comments Pullfrog uses to surface a run's status.
|
||||
*
|
||||
* A progress comment can be one of two distinct GitHub entities with non-overlapping IDs and
|
||||
* distinct REST endpoints:
|
||||
* - "issue": a top-level issue/PR timeline comment (octokit.rest.issues.*Comment)
|
||||
* - "review": an inline PR review-thread comment (octokit.rest.pulls.*ReviewComment)
|
||||
*
|
||||
* Callers carry a `ProgressComment` (id + type) value end-to-end so the right endpoint is always
|
||||
* picked. Adding a third comment type later means one new branch in this file, not six.
|
||||
*/
|
||||
|
||||
export type ProgressCommentType = "issue" | "review";
|
||||
|
||||
export type ProgressComment = {
|
||||
id: number;
|
||||
type: ProgressCommentType;
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse the on-the-wire `{ id: string; type }` shape (the form carried in `JsonPayload`)
|
||||
* into the in-memory `ProgressComment` shape. Returns undefined when the id isn't a
|
||||
* positive integer so callers can short-circuit cleanly. Callers handle logging.
|
||||
*/
|
||||
export function parseProgressComment(
|
||||
raw: { id: string; type: ProgressCommentType } | null | undefined
|
||||
): ProgressComment | undefined {
|
||||
if (!raw?.id) return undefined;
|
||||
const id = parseInt(raw.id, 10);
|
||||
if (Number.isNaN(id) || id <= 0) return undefined;
|
||||
return { id, type: raw.type };
|
||||
}
|
||||
|
||||
// minimal Octokit shape needed by the progress-comment helpers. structural so the helper
|
||||
// can be called from both the action package (@octokit/rest v22) and the root project
|
||||
// (@octokit/rest v21) without a nominal type clash. only the methods used here are listed.
|
||||
interface CommentResponse {
|
||||
data: { id: number; body?: string | null | undefined; html_url: string; node_id?: string };
|
||||
}
|
||||
export interface ProgressCommentOctokit {
|
||||
rest: {
|
||||
issues: {
|
||||
createComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
issue_number: number;
|
||||
body: string;
|
||||
}) => Promise<CommentResponse>;
|
||||
getComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
}) => Promise<CommentResponse>;
|
||||
updateComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
body: string;
|
||||
}) => Promise<CommentResponse>;
|
||||
deleteComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
}) => Promise<unknown>;
|
||||
};
|
||||
pulls: {
|
||||
createReplyForReviewComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
pull_number: number;
|
||||
comment_id: number;
|
||||
body: string;
|
||||
}) => Promise<CommentResponse>;
|
||||
getReviewComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
}) => Promise<CommentResponse>;
|
||||
updateReviewComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
body: string;
|
||||
}) => Promise<CommentResponse>;
|
||||
deleteReviewComment: (params: {
|
||||
owner: string;
|
||||
repo: string;
|
||||
comment_id: number;
|
||||
}) => Promise<unknown>;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
interface ApiCtx {
|
||||
octokit: ProgressCommentOctokit;
|
||||
owner: string;
|
||||
repo: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a progress comment via the appropriate REST endpoint for its type.
|
||||
* Returns the common subset of fields callers actually use.
|
||||
*/
|
||||
export async function getProgressComment(
|
||||
ctx: ApiCtx,
|
||||
comment: ProgressComment
|
||||
): Promise<{ id: number; body: string | undefined; html_url: string }> {
|
||||
const result = await (comment.type === "review"
|
||||
? ctx.octokit.rest.pulls.getReviewComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
})
|
||||
: ctx.octokit.rest.issues.getComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
}));
|
||||
return {
|
||||
id: result.data.id,
|
||||
body: result.data.body ?? undefined,
|
||||
html_url: result.data.html_url,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a progress comment in place via the appropriate REST endpoint.
|
||||
* Returns the common subset of fields callers actually use.
|
||||
*/
|
||||
export async function updateProgressComment(
|
||||
ctx: ApiCtx,
|
||||
comment: ProgressComment,
|
||||
body: string
|
||||
): Promise<{
|
||||
id: number;
|
||||
body: string | undefined;
|
||||
html_url: string;
|
||||
node_id: string | undefined;
|
||||
}> {
|
||||
const result = await (comment.type === "review"
|
||||
? ctx.octokit.rest.pulls.updateReviewComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
body,
|
||||
})
|
||||
: ctx.octokit.rest.issues.updateComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
body,
|
||||
}));
|
||||
return {
|
||||
id: result.data.id,
|
||||
body: result.data.body ?? undefined,
|
||||
html_url: result.data.html_url,
|
||||
node_id: result.data.node_id,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a progress comment via the appropriate REST endpoint.
|
||||
* Lower-level than `deleteProgressComment` in mcp/comment.ts — that one also clears
|
||||
* tool state. Callers that don't have a ToolContext (post cleanup, error handlers)
|
||||
* should use this directly; the higher-level wrapper delegates here.
|
||||
*/
|
||||
export async function deleteProgressCommentApi(
|
||||
ctx: ApiCtx,
|
||||
comment: ProgressComment
|
||||
): Promise<void> {
|
||||
if (comment.type === "review") {
|
||||
await ctx.octokit.rest.pulls.deleteReviewComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
});
|
||||
return;
|
||||
}
|
||||
await ctx.octokit.rest.issues.deleteComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
comment_id: comment.id,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Discriminated target for `createLeapingProgressComment`. The two variants map to the two
|
||||
* distinct GitHub create endpoints; review-reply additionally needs the parent comment ID.
|
||||
*/
|
||||
export type CreateProgressCommentTarget =
|
||||
| { kind: "issue"; issueNumber: number }
|
||||
| { kind: "reviewReply"; pullNumber: number; replyToCommentId: number };
|
||||
|
||||
export interface CreatedProgressComment {
|
||||
comment: ProgressComment;
|
||||
body: string | undefined;
|
||||
html_url: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create the initial "Leaping into action..." progress comment.
|
||||
*
|
||||
* Reliability: when `kind: "reviewReply"` fails (e.g. the parent comment was deleted or the
|
||||
* thread is otherwise unreachable), falls back to a top-level issue comment on the same PR
|
||||
* rather than leaving the run with no progress surface. The fallback is logged.
|
||||
*
|
||||
* (PR # === issue # in GitHub's number space, so `pullNumber` doubles as the fallback target.)
|
||||
*/
|
||||
export async function createLeapingProgressComment(
|
||||
ctx: ApiCtx,
|
||||
target: CreateProgressCommentTarget,
|
||||
body: string
|
||||
): Promise<CreatedProgressComment> {
|
||||
if (target.kind === "reviewReply") {
|
||||
try {
|
||||
const result = await ctx.octokit.rest.pulls.createReplyForReviewComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
pull_number: target.pullNumber,
|
||||
comment_id: target.replyToCommentId,
|
||||
body,
|
||||
});
|
||||
return {
|
||||
comment: { id: result.data.id, type: "review" },
|
||||
body: result.data.body ?? undefined,
|
||||
html_url: result.data.html_url,
|
||||
};
|
||||
} catch (error) {
|
||||
// console.warn (not the action-flavored log.warning) because this helper runs in
|
||||
// both the action runtime and the Next.js webhook context, and we don't want a
|
||||
// ::warning:: GitHub Actions annotation leaking into Vercel logs.
|
||||
console.warn(
|
||||
`[progressComment] review reply failed (parent ${target.replyToCommentId} on PR #${target.pullNumber}), falling back to issue comment:`,
|
||||
error
|
||||
);
|
||||
const fallback = await ctx.octokit.rest.issues.createComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
issue_number: target.pullNumber,
|
||||
body,
|
||||
});
|
||||
return {
|
||||
comment: { id: fallback.data.id, type: "issue" },
|
||||
body: fallback.data.body ?? undefined,
|
||||
html_url: fallback.data.html_url,
|
||||
};
|
||||
}
|
||||
}
|
||||
const result = await ctx.octokit.rest.issues.createComment({
|
||||
owner: ctx.owner,
|
||||
repo: ctx.repo,
|
||||
issue_number: target.issueNumber,
|
||||
body,
|
||||
});
|
||||
return {
|
||||
comment: { id: result.data.id, type: "issue" },
|
||||
body: result.data.body ?? undefined,
|
||||
html_url: result.data.html_url,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import { detectProviderError } from "./providerErrors.ts";
|
||||
|
||||
describe("detectProviderError", () => {
|
||||
describe("false positives previously seen in production", () => {
|
||||
it("returns null for commit SHAs containing 429", () => {
|
||||
expect(detectProviderError("hash=7a46d89f505b36df49b4f54429daffa1a9459b11")).toBeNull();
|
||||
expect(detectProviderError("commit f609cc89e84596ab125d60dac568bfb2ef398396 429")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for x-ratelimit-* response headers in 401 error JSON", () => {
|
||||
const stderr = JSON.stringify({
|
||||
error: { name: "APIError", statusCode: 401, message: "Invalid authentication credentials" },
|
||||
headers: {
|
||||
"x-ratelimit-limit-requests": 50,
|
||||
"x-ratelimit-remaining-requests": 49,
|
||||
"x-ratelimit-reset-tokens": "2025-01-01T00:00:00Z",
|
||||
},
|
||||
});
|
||||
expect(detectProviderError(stderr)).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for INTERNAL_SERVER_ERROR substring", () => {
|
||||
expect(detectProviderError("HTTP/1.1 500 INTERNAL_SERVER_ERROR")).toBeNull();
|
||||
expect(detectProviderError("expected: not INTERNAL_SERVER_ERROR")).toBeNull();
|
||||
});
|
||||
|
||||
it("returns null for INTERNALS substring", () => {
|
||||
expect(detectProviderError("debugging INTERNALS of the parser")).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe("real provider errors", () => {
|
||||
it("detects 429 only when adjacent to a status key", () => {
|
||||
expect(detectProviderError('{"statusCode": 429}')).toBe("rate limited (429)");
|
||||
expect(detectProviderError('{"status_code": 429, "message": "..."}')).toBe(
|
||||
"rate limited (429)"
|
||||
);
|
||||
expect(detectProviderError("http_status: 429")).toBe("rate limited (429)");
|
||||
expect(detectProviderError("status=429")).toBe("rate limited (429)");
|
||||
});
|
||||
|
||||
it("detects rate_limit_error and rate_limit_exceeded", () => {
|
||||
expect(detectProviderError('{"type":"rate_limit_error"}')).toBe("rate limited");
|
||||
expect(detectProviderError("rate_limit_exceeded")).toBe("rate limited");
|
||||
expect(detectProviderError("plain rate limit reached")).toBe("rate limited");
|
||||
});
|
||||
|
||||
it("detects rate-limit phrasing with trailing inflection", () => {
|
||||
expect(detectProviderError("Error: rate limited by provider")).toBe("rate limited");
|
||||
expect(detectProviderError("rate limits exceeded for this key")).toBe("rate limited");
|
||||
});
|
||||
|
||||
it("detects RESOURCE_EXHAUSTED", () => {
|
||||
expect(detectProviderError('"status": "RESOURCE_EXHAUSTED"')).toBe("quota exhausted");
|
||||
});
|
||||
|
||||
it("detects gRPC INTERNAL status as a whole word", () => {
|
||||
expect(detectProviderError('"status": "INTERNAL"')).toBe("provider internal error");
|
||||
});
|
||||
|
||||
it("detects UNAVAILABLE as a whole word", () => {
|
||||
expect(detectProviderError('"status": "UNAVAILABLE"')).toBe("provider unavailable");
|
||||
});
|
||||
|
||||
it("detects 500 / 503 only when adjacent to a status key", () => {
|
||||
expect(detectProviderError('"statusCode": 500')).toBe("provider 500 error");
|
||||
expect(detectProviderError('"statusCode": 503')).toBe("provider unavailable (503)");
|
||||
expect(detectProviderError("v1.503.0 release notes")).toBeNull();
|
||||
});
|
||||
|
||||
it("detects quota and zero-quota responses", () => {
|
||||
expect(detectProviderError('"message": "quota exceeded"')).toBe("quota error");
|
||||
expect(detectProviderError('{"code":"insufficient_quota"}')).toBe("quota error");
|
||||
expect(detectProviderError('"error":"quota_exceeded"')).toBe("quota error");
|
||||
expect(detectProviderError('{"reason":"quotaExceeded"}')).toBe("quota error");
|
||||
expect(detectProviderError('{"limit": 0, "remaining": 0}')).toBe("zero quota");
|
||||
expect(detectProviderError('"time_limit": 0')).toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
+31
-11
@@ -1,18 +1,38 @@
|
||||
const PROVIDER_ERROR_PATTERNS = [
|
||||
{ pattern: "429", label: "rate limited (429)" },
|
||||
{ pattern: "RESOURCE_EXHAUSTED", label: "quota exhausted" },
|
||||
{ pattern: "quota", label: "quota error" },
|
||||
{ pattern: "status: 500", label: "provider 500 error" },
|
||||
{ pattern: "INTERNAL", label: "provider internal error" },
|
||||
{ pattern: "status: 503", label: "provider unavailable (503)" },
|
||||
{ pattern: "UNAVAILABLE", label: "provider unavailable" },
|
||||
{ pattern: "rate limit", label: "rate limited" },
|
||||
{ pattern: "limit: 0", label: "zero quota" },
|
||||
type ProviderErrorPattern = { regex: RegExp; label: string };
|
||||
|
||||
// status codes are only treated as provider errors when they are adjacent to
|
||||
// a recognised status key. this rejects commit SHAs that happen to contain
|
||||
// "429", version strings, file hashes, etc.
|
||||
const statusKey = `\\b(?:status[_ ]?code|http[_ ]?status|status)["']?\\s*[:=]\\s*["']?`;
|
||||
|
||||
const PROVIDER_ERROR_PATTERNS: ProviderErrorPattern[] = [
|
||||
{ regex: new RegExp(`${statusKey}429\\b`, "i"), label: "rate limited (429)" },
|
||||
{ regex: new RegExp(`${statusKey}500\\b`, "i"), label: "provider 500 error" },
|
||||
{ regex: new RegExp(`${statusKey}503\\b`, "i"), label: "provider unavailable (503)" },
|
||||
// matches `rate limit`, `rate limited`, `rate limits exceeded`,
|
||||
// `rate_limit_error`, `rate_limit_exceeded`. the leading `\b` + `[_ ]`
|
||||
// separator rejects `x-ratelimit-*` / `anthropic-ratelimit-*` response
|
||||
// headers (no separator between "rate" and "limit") which routinely
|
||||
// appear in dumped 401 / 4xx error JSON.
|
||||
{ regex: /\brate[_ ]limit/i, label: "rate limited" },
|
||||
{ regex: /\bRESOURCE_EXHAUSTED\b/, label: "quota exhausted" },
|
||||
// Google gRPC `INTERNAL` status. word-boundary anchors reject
|
||||
// `INTERNAL_SERVER_ERROR` (HTTP 500 message that may appear in unrelated
|
||||
// log lines) and identifiers like `INTERNALS`.
|
||||
{ regex: /\bINTERNAL\b/, label: "provider internal error" },
|
||||
{ regex: /\bUNAVAILABLE\b/, label: "provider unavailable" },
|
||||
// matches `quota`, `insufficient_quota`, `quota_exceeded`, `quotaExceeded`.
|
||||
// word-character lookarounds would reject `_quota` / `quotaX`; `quota` is
|
||||
// specific enough that a plain substring match is safe.
|
||||
{ regex: /quota/i, label: "quota error" },
|
||||
// explicit zero-quota response, e.g. `{"limit": 0}`. the `\b` anchor
|
||||
// around `limit` rejects keys like `time_limit` or `field_limit`.
|
||||
{ regex: /["']?\blimit\b["']?\s*:\s*0\b/, label: "zero quota" },
|
||||
];
|
||||
|
||||
export function detectProviderError(text: string): string | null {
|
||||
for (const entry of PROVIDER_ERROR_PATTERNS) {
|
||||
if (text.includes(entry.pattern)) return entry.label;
|
||||
if (entry.regex.test(text)) return entry.label;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
+12
-1
@@ -88,8 +88,19 @@ async function dispatchFollowUpReReview(ctx: ToolContext, reviewedSha: string):
|
||||
await ctx.octokit.rest.actions.createWorkflowDispatch({
|
||||
owner: ctx.repo.owner,
|
||||
repo: ctx.repo.name,
|
||||
workflow_id: "pullfrog.yml",
|
||||
workflow_id: getCurrentWorkflowFilename(),
|
||||
ref: pr.data.base.repo.default_branch,
|
||||
inputs: { prompt: JSON.stringify(payload) },
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* derive the running workflow's filename from `GITHUB_WORKFLOW_REF`, which has the form
|
||||
* `<owner>/<repo>/.github/workflows/<filename>@<ref>` (e.g. `.../pullfrog.yaml@refs/heads/main`).
|
||||
* falls back to `pullfrog.yml` if the env var is missing or malformed (shouldn't happen in CI).
|
||||
*/
|
||||
function getCurrentWorkflowFilename(): string {
|
||||
const ref = process.env.GITHUB_WORKFLOW_REF ?? "";
|
||||
const match = ref.match(/\/([^/]+)@/);
|
||||
return match?.[1] ?? "pullfrog.yml";
|
||||
}
|
||||
|
||||
+8
-8
@@ -19,14 +19,14 @@ export async function handleAgentResult(ctx: HandleAgentResultParams): Promise<M
|
||||
};
|
||||
}
|
||||
|
||||
// Review and IncrementalReview modes intentionally never set wasUpdated:
|
||||
// the prompt forbids report_progress (the review IS the durable record),
|
||||
// and IncrementalReview's non-substantive path produces no review at
|
||||
// all by design. wasUpdated staying false is also load-bearing for the
|
||||
// stranded-comment cleanup in main.ts which deletes the "Leaping into
|
||||
// action" orphan via `(!wasUpdated || trackerWasLastWriter)`. Skip the
|
||||
// strict completion check for these modes — the agent's exit code is
|
||||
// the completion signal, not a progress-comment write.
|
||||
// IncrementalReview's non-substantive path exits cleanly without
|
||||
// submitting any review, so no MCP write tool flips wasUpdated and the
|
||||
// strict completion check below would otherwise fail the run. The
|
||||
// isReviewMode skip is load-bearing for that path: the agent's exit
|
||||
// code is the completion signal, not a progress-comment write.
|
||||
// (Review mode that submits a real review now flips wasUpdated via
|
||||
// create_pull_request_review, so the skip is redundant for the
|
||||
// substantive-review path but kept for symmetry with IncrementalReview.)
|
||||
// See plans/review_progress_comment_cleanup_b0120f6c.plan.md.
|
||||
const mode = ctx.toolState.selectedMode;
|
||||
const isReviewMode = mode === "Review" || mode === "IncrementalReview";
|
||||
|
||||
@@ -24,10 +24,27 @@ export interface RepoSettings {
|
||||
envAllowlist: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Account-level billing plan. Orthogonal to repo-level OSS status. Mirrors
|
||||
* the server's `AccountPlan` in `utils/billing.ts`. `"none"` = free tier,
|
||||
* `"payg"` = card on file / pay-as-you-go.
|
||||
*/
|
||||
export type AccountPlan = "none" | "payg";
|
||||
|
||||
/**
|
||||
* "Is Pullfrog absorbing marginal infra cost for this repo?" — composite
|
||||
* predicate over the two orthogonal dimensions (repo-level OSS, account-level
|
||||
* plan). Mirrors `isInfraCovered` in the server's `utils/billing.ts`.
|
||||
*/
|
||||
export function isInfraCovered(params: { isOss: boolean; plan: AccountPlan }): boolean {
|
||||
return params.isOss || params.plan === "payg";
|
||||
}
|
||||
|
||||
export interface RunContext {
|
||||
settings: RepoSettings;
|
||||
apiToken: string;
|
||||
oss: boolean;
|
||||
plan: AccountPlan;
|
||||
proxyModel?: string | undefined;
|
||||
dbSecrets?: Record<string, string> | undefined;
|
||||
}
|
||||
@@ -51,6 +68,7 @@ const defaultRunContext: RunContext = {
|
||||
settings: defaultSettings,
|
||||
apiToken: "",
|
||||
oss: false,
|
||||
plan: "none",
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -92,6 +110,7 @@ export async function fetchRunContext(params: {
|
||||
settings: RepoSettings | null;
|
||||
apiToken: string;
|
||||
oss?: boolean;
|
||||
plan?: AccountPlan;
|
||||
proxyModel?: string;
|
||||
dbSecrets?: Record<string, string>;
|
||||
} | null;
|
||||
@@ -112,6 +131,7 @@ export async function fetchRunContext(params: {
|
||||
},
|
||||
apiToken: data.apiToken,
|
||||
oss: data.oss ?? false,
|
||||
plan: data.plan ?? "none",
|
||||
proxyModel: data.proxyModel,
|
||||
dbSecrets: data.dbSecrets,
|
||||
};
|
||||
|
||||
@@ -3,7 +3,7 @@ import type { Octokit } from "@octokit/rest";
|
||||
import packageJson from "../package.json" with { type: "json" };
|
||||
import { log } from "./cli.ts";
|
||||
import { type OctokitWithPlugins, parseRepoContext } from "./github.ts";
|
||||
import { fetchRunContext, type RepoSettings } from "./runContext.ts";
|
||||
import { type AccountPlan, fetchRunContext, type RepoSettings } from "./runContext.ts";
|
||||
|
||||
export interface RunContextData {
|
||||
repo: {
|
||||
@@ -14,6 +14,7 @@ export interface RunContextData {
|
||||
repoSettings: RepoSettings;
|
||||
apiToken: string;
|
||||
oss: boolean;
|
||||
plan: AccountPlan;
|
||||
proxyModel?: string | undefined;
|
||||
dbSecrets?: Record<string, string> | undefined;
|
||||
}
|
||||
@@ -54,6 +55,7 @@ export async function resolveRunContextData(
|
||||
repoSettings: runContext.settings,
|
||||
apiToken: runContext.apiToken,
|
||||
oss: runContext.oss,
|
||||
plan: runContext.plan,
|
||||
proxyModel: runContext.proxyModel,
|
||||
dbSecrets: runContext.dbSecrets,
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user