57bd10d6dd
* fix(#15): precompute diff anchors in checkout_pr TOC * test(#15): update TOC snapshot for precomputed diff anchors * chore(tests): skip codex-mini-latest models.dev check + refresh latest-by-provider snapshot * fix(#22): add commitCount and commitLog to checkout_pr return * fix(#21): include PR body in checkout_pr return * fix(#5): force-fetch PR refspec to overwrite stale local branch * fix(#31): rename git tool parameter from subcommand to command * fix(#11): soft-fail post-checkout hook, bump timeout to 10min * fix(#16): strengthen diff file usage guidance Agent was bypassing diffPath and running `git diff` instead. Tighten instructions in `checkout_pr` result and remove the mixed-signal "log, diff" listing in the global Git guidance. `git log` and `git diff --stat` remain allowed for commit-range overview. * fix(#20): drop invalid inline review comments instead of failing review Previously, a single inline comment anchored outside a diff hunk would 422 the entire review submission. Pre-validate comments against the PR file patches via listFiles, drop the invalid ones, and append a note to the review body listing what was skipped. Include the dropped list in the tool response so the agent can retry targeted fixes. * fix(#12): stop MCP server on inner activity kill + filter reconnect noise Inner-activity-kill zombies were burning multi-hour runner time because mcp-proxy's SSE reconnect and provider-error retry lines kept the outer activity timer alive long after the agent subprocess was killed. - Filter [mcp-proxy] / "provider error detected" chunks so they don't count as outer-timer activity. - Add onActivityTimeout callback to spawn + thread through agent runs. - main.ts wires that callback to stop the MCP HTTP server (so reconnects finally fail instead of looping) and arms a 5min safety-net timer that force-rejects the outer timer if the agent promise is still pending. * audit: harden #12 lifecycle + cover #20/#12 with unit tests Bugs found during Ralph audit of the prior run-issues fixes: - main.ts's 5min safety-net setTimeout was never cleared on the happy path; also activityTimeout.stop() didn't null the internal rejectFn, so a late forceReject from the safety-net could still reject a long-resolved promise. Timer now cleared in finally; stop() now disarms forceReject. - mcp server disposal was non-idempotent, so the inner-kill path ran server.stop() twice once the outer `await using` block exited. Made the returned disposer idempotent. Tests: - action/mcp/review.test.ts: 14 tests for commentableLinesForFile (multi-hunk, no-count hunks, no-newline marker, empty) and validateInlineComments (file not in diff, wrong side, out-of-range line and start_line, partitioning batches, default side). - action/utils/activity.test.ts: 6 tests for isActivityNoise covering mcp-proxy lines, provider-error lines, mixed chunks, Buffer input. * audit(#22): cap commitLog at 200 + scope git-diff restriction to PR review - cap git log --oneline at 200 entries so a PR with thousands of commits cannot blow up the MCP tool response; expose commitLogTruncated so callers can warn the agent when the log was clipped - tighten instruction wording so `git diff` / `git diff --cached` remain available for inspecting an agent's own uncommitted changes, while PR review content must still come from diffPath Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#11,#22,#31): surface hook/commit warnings in instructions + polish git tool - append hookWarning + commitLogTruncated advisories to checkout_pr instructions so the agent actually sees the warning inline, not just as a field it may skip - fix stale 'subcommand' wording in git tool redirect for `pull` and in the `command` parameter description; the MCP parameter is named `command` now, and that's what the agent binds to Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix(#20): reassign params.comments even when all inline comments dropped if every inline comment fails pre-validation, the earlier guard skipped reassigning params.comments, so the submission still carried the bad comments and GitHub 422'd on the whole review. always reassign to validation.valid so the downstream 'nothing left to post' skip fires and an otherwise-empty review is no-oped cleanly. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#22): degrade gracefully when base ref isn't resolvable checkout_pr used to assume \`origin/<base>\` is always reachable, but it isn't guaranteed after a shallow fetch that only pulled down the PR head. Failing the whole checkout over metadata we added for ergonomics would be a regression, so wrap the rev-list / log in a try/catch and return empty commit metadata instead. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#12): anchor noise patterns to line start to avoid false positives before this, a line like "agent said: [mcp-proxy] was there" or "context: provider error detected in log" in real agent output would have been treated as noise and failed to reset the outer activity timer. both patterns now anchor at the start of the (optionally debug-timestamped) line, matching only lines mcp-proxy or our own log.info actually emit. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#20): export and unit-test formatDroppedCommentsNote covers single-line `path:N`, multi-line `path:start-end`, and startLine==line fallback so changes to the dropped-comments note format surface in test diffs instead of only in GitHub UI. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#20): cap dropped-comment note to stay under GitHub body limit a pathological run (agent emits hundreds of invalid inline comments on a huge PR and they all get dropped) would push the review body past GitHub's ~65KB limit and fail the whole submission with a body-too-long 422 — the exact all-or-nothing failure #20 was meant to prevent. cap the detail list at 50 entries with a "…and N more" line so the note stays bounded. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#20): distinguish binary/no-patch files in dropped-comment reason previously a comment on a binary file (or pure rename / mode-only change) was dropped with "line X is not inside a diff hunk", which misleads the agent into retrying with different line numbers. call out the no-textual-diff case explicitly so the agent knows to move that feedback to the review body instead. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#11): replace lifecycle timeout string-match with typed sentinel spawn() now rejects with SpawnTimeoutError (code === SPAWN_TIMEOUT_CODE or SPAWN_ACTIVITY_TIMEOUT_CODE) instead of a plain Error. executeLifecycleHook now branches on that code so rewording the error message in subprocess.ts can no longer silently misroute timeouts into the "transient — retry" warning. * audit(#12): route agent hung-vs-failed via typed SpawnTimeoutError claude.ts and opentoad.ts decide between "hung" and "failed" log wording based on the subprocess error. move them off the literal "activity timeout" substring match onto the same SPAWN_ACTIVITY_TIMEOUT_CODE sentinel used by lifecycle.ts so all three call sites agree on the source of truth. * audit(#20): delete leftover pending review when submit fails Why: `createAndSubmitWithFooter` creates a PENDING review first so we can mint Fix-links with the review ID, then submits. If submitReview fails (e.g. 422 from a race where the diff moved between pre-validation and submission), the draft was left on the PR. GitHub only allows one pending review per user, so the agent's retry would then fail with "already has a pending review" — an error the agent has no tools to clean up from. Best-effort cleanup: delete the pending draft on submit failure before re-throwing the original error, so retries start from a clean slate. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#31): point agent to concrete alternative when rebase/bisect blocked Why: in disabled-shell mode, `git rebase` and `git bisect` are blocked as arbitrary-code-execution escape hatches. Previous error messages explained *why* but left the agent without a next step — especially painful right after the `pull` redirect, which suggested "merge or rebase locally." The agent would follow that advice, hit the rebase block, and loop without knowing what to try next. Now: rebase block explicitly says "use 'merge' instead"; bisect block notes that manual bisect is also unavailable through this tool; pull redirect no longer recommends rebase in shell-disabled contexts. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: import security tables into security.test to prevent drift Why: the security tests re-declared AUTH_REQUIRED_REDIRECT, NOSHELL_BLOCKED_SUBCOMMANDS, and NOSHELL_BLOCKED_ARGS inline with hand-copied message strings. When the runtime messages in git.ts were tightened (recent rebase/bisect guidance updates), the test copies drifted and tests validated a stale version of the logic while passing clean. A missing or mistyped entry in git.ts could therefore slip through. Now: export the tables from git.ts and import them into the test file. If a runtime message changes, the tests exercise the new string automatically; if an entry is added or removed, tests covering that command see the change without manual sync. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: widen pending-review cleanup to cover pre-submit throws getApiUrl() (invoked in footer build) can throw if API_URL is misconfigured, which would leak a pending draft between createReview and the previous submitReview try/catch. Move the try/catch to wrap the entire post-create body so any throw routes through deletePendingReview cleanup. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: reject leading-dash refs/branch names to block flag injection git's parseopt accepts options intermixed with positional args, so a ref like "--upload-pack=evil" passed to git_fetch could be parsed as a flag rather than a refspec. Add a narrow rejectIfLeadingDash helper to git_fetch (ref), delete_branch (branchName), and push_branch (branchName). HTTPS remotes ignore --upload-pack server-side, but the hygiene matters for defense in depth (ssh remotes, future code paths). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: validate the resolved branch in push_branch too When branchName is omitted, rev-parse surfaces the current branch name, which could start with '-' if git state was tampered with. Move the leading-dash check to after the branch is resolved so both the explicit and derived paths go through validation. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: cache commentable-lines snapshot at checkout to match review anchor Review comments are anchored to checkoutSha (commit_id), but validation was hitting pulls.listFiles at review time — latest HEAD, not the SHA the agent actually reviewed. If the PR was updated mid-run, valid comments could be silently dropped (or invalid ones admitted). Snapshot the commentable lines during checkout_pr so review-time validation matches the anchor exactly. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#12): route activity monitor's own debug output around the write wrap startProcessOutputMonitor monkey-patches process.stdout.write to mark activity, then called log.debug(...) every 5s to report idle time — which landed right back in its own wrapper, failed isActivityNoise, and called markActivity. with ACTIONS_STEP_DEBUG=true (common on reruns) the idle counter reset every interval and the timeout could never fire, re-creating the #12 zombie-run bug for any debug-enabled run. Fix: capture the original stdout.write and use it directly for the monitor's own diagnostics so they bypass the feedback loop. Added a tight-timeout regression test that asserts the timeout still rejects in debug mode. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#12): noise-filter subprocess.ts monitor logs so outer timer survives debug activity.ts's own monitor output already bypasses the wrap (c35cd3fb), but subprocess.ts's spawn activity timer uses log.debug — which goes straight through process.stdout.write and would still mark activity on every interval when debug logging is enabled. Pattern-filter those '(spawn|process) activity (check|timer|monitor)' lines in both local ([DEBUG] ...) and GH-runner (::debug::...) formats so they don't reset the outer agent-hang timer. Kept scoped to those specific monitor messages — a blanket [DEBUG] filter would silently classify any coincidentally-debug-prefixed agent output as idle, which is a worse failure mode than the one we're fixing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#11): surface spawn ENOENT-style errors in stderr buffer spawn() resolved with exitCode=1 and an empty stderr when the command itself couldn't start (missing binary, bad permissions). lifecycle.ts then reported 'output: (empty)' to the user, who was explicitly told 'retry if the failure looks flaky' — so every run hit the same wall with no diagnostic trail. Append the '[spawn] <cmd>: <node error>' line to stderrBuffer before resolving so the real cause (ENOENT, EACCES, …) flows through to the hook-warning message. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit(#11,#12): cover executeLifecycleHook typed-timeout routing the typed SpawnTimeoutError + sentinel-code branching introduced in d7ee7fd2 / ea8dd2c4 classifies hung vs failed lifecycle hooks — critical for whether agents retry — but had no unit coverage. add tests for all four branches (no script, exit 0, non-zero exit with retry-if-flaky guidance, timeout with do-NOT-retry guidance, transient spawn failure). Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: re-verify clean tree after prepush hook the pre-prepush check guarantees we enter the hook with a clean tree, but if the hook writes tracked files (formatter, type generator, build artifacts), the push still only sends the pre-hook commit — the hook's edits silently disappear from the upstream branch while the tool reports "successfully pushed". add a post-hook status check so the agent sees the dropped mutations and can commit or discard them before retrying. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: reject push_tags refspec injection via ':' in tag name without tag validation, a tag like "foo:refs/heads/main" concatenated into "refs/tags/${tag}" becomes a valid <src>:<dst> refspec — git pushes the local refs/tags/foo's commit to remote main, bypassing push_branch's default-branch guard. same shape blocks leading '-' (flag injection) and other refspec metacharacters (~ ^ ? * [ \) via an allow-list regex. only reachable in push=enabled today, so this is defense-in-depth, but hardens the tool in case push_tags is ever exposed in restricted mode. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: stop pointing agents at an internal constant they can't change the lifecycle-hook timeout warning told agents to "bump LIFECYCLE_HOOK_TIMEOUT_MS" — but that's a hard-coded constant in the action, not something the agent or repo owner can tune. the agent would plausibly loop hunting for where to change it. redirect to the actual lever they control: ask the repo owner to simplify the hook. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: drop inverted inline-comment ranges locally with precise reason validateInlineComments only checked that both line and start_line anchor inside a hunk, not that start_line <= line. an inverted range (e.g. start=44, line=42) would pass local validation and GitHub would 422 with "invalid line numbers" — opaque to the agent and unfixable without reading docs. reject locally with a reason that names the constraint. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: don't let usage-summary write error mask main's outcome writeGitHubUsageSummaryToFile is called in main's finally block. it can throw on ENOSPC / EACCES / missing parent dir. a throw here propagates past the try's successful return or the catch's error return, hiding the actual run outcome behind an I/O failure on a purely informational file. swallow the write error (debug-logged) — the summary is nice-to-have, not load-bearing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: don't mislabel agent handler errors as JSON parse failures the onStdout event loop wrapped both JSON.parse and the handler call in one try/catch that logged every caught error as 'non-JSON stdout line'. if a handler threw (e.g. todowrite state shape drift), the error was silently classified as a parse error, making diagnosis impossible. split the try blocks so JSON errors and handler errors get distinct, identifying log lines. * audit: reject leading-dash PR refs before they reach git commands PR head/base refs come from GitHub and are attacker-controlled on fork PRs (the PR author picks headRef freely). they flow straight into `git fetch origin <ref>`, `git checkout -B <ref>`, and config writes. without a leading-dash check, a ref named like '-upload-pack=evil' could be parsed as a flag instead of a refspec. validate both refs at the top of checkoutPrBranch (before any async work) and cover the two attack shapes with unit tests. * audit: cover ActivityTimeout.stop()'s forceReject disarming main.ts's safety-net-timer path depends on ActivityTimeout.stop() nulling out rejectFn so a late safety-net fire after a successful agent run is a no-op. that behavior had no direct coverage — removing the \`rejectFn = null\` in stop() would silently break the happy path (unhandled rejection / spurious failure) without failing any test. add three tests covering: forceReject rejects with the reason, stop() disarms forceReject, and forceReject after timer rejection is an idempotent no-op. * audit: stabilize activity-timeout idleSec against late stdout race * audit: reject 0ms timeout parses to avoid insta-fail from '0m' * audit: surface raw GitHub error on review 422 instead of assuming anchor cause * audit: key commentable-lines cache by PR number to prevent cross-PR drift * audit: enumerate concrete 422 causes and name checkout_pr in review error * audit: stop shipping ralph-loop runtime state in PR history .claude/ralph-loop.local.md and .claude/ralph-loop-prompt.md were accidentally staged in an earlier audit commit. the .local.md suffix is conventional for gitignored runtime state, and the prompt file is per-run harness config — neither should merge to main. ignore the pattern and untrack the existing entries (files remain on disk so the active loop keeps working). * audit: pin commentable-lines cache to checkoutSha, not just PR number a second checkout_pr(N) call advances toolState.checkoutSha at line 305 or 334, then runs fetchAndFormatPrDiff + cache population at line 549. any throw between those two points (rate limit, 5xx, network blip) left the old snapshot keyed to (pullNumber=N) while checkoutSha now points at a different sha. review_pr(N) would reuse the stale snapshot, silently validating comments against the wrong anchor — the original failure this cache was meant to prevent. track commentableLinesCheckoutSha alongside the pull number and require both to match before returning the cache. if either has moved, fall back to listFiles like any other miss. * audit: auto-clear leftover pending review from killed prior runs a workflow timeout or OOM between createReview PENDING and submitReview leaves GitHub holding a pending draft. the next run hits GitHub's one-pending-per-user-per-PR limit and 422s at pending-create, with no way to recover short of a human cleaning up manually. catch 422 at pending-create, list the PR's reviews (GitHub only exposes our own pending to us, so the filter is safe), delete the leftover, and retry once. 404/422 on the cleanup are treated as no-ops (race with another concurrent cleanup or the draft was submitted); any other cleanup error rethrows so the real cause reaches the caller. * audit: extract + unit-test stranded-pending-review cleanup the recovery branch inside createAndSubmitWithFooter had no direct test coverage. a regression in any of its guards (status check, message match, listReviews filter, 404/422 tolerance, non-retryable rethrow) would silently cause either destructive deletes of unrelated reviews or the old failure mode where a stranded pending draft blocks every retry. extract to clearStrandedPendingReview so the cases can be exercised with a mocked octokit, and add tests for each branch — including the load-bearing negative cases (non-422 passthrough, non-pending-review 422 passthrough, no-leftover-found passthrough, non-retryable cleanup error passthrough). no behavior change at the call site. * audit: document concurrent-run race in clearStrandedPendingReview two runs on the same PR using the same GitHub App installation token would both see each other's PENDING draft via listReviews (GitHub exposes PENDING only to the author, and both runs share authorship). the loser's recovery path would delete the winner's active draft, causing the winner's submitReview to 404. no reliable in-request signal distinguishes a genuinely-stranded prior-run draft from an active peer's draft — PENDING reviews have no created_at, and the user field is the same bot in both cases. the correct fix is workflow-level concurrency (a per-PR concurrency key), not a heuristic here. document the limitation so future readers don't try to bolt on a broken heuristic. * audit: report signal-killed subprocesses as failures, not exit code 0 node's close event delivers (code=null, signal=<name>) when a child is killed by signal (OOM killer, segfault, external SIGTERM). the close handler captured only exitCode and coerced null to 0 via `exitCode || 0`, so lifecycle hooks killed by signal were silently reported as successful — lifecycle.ts's `if (result.exitCode !== 0)` check skipped the warning and callers proceeded as if setup/post-checkout/prepush had completed. now capture signal, append "killed by signal <name>" to stderr, and resolve with exitCode=1 when code is null but signal is set. adds a regression test that spawns `kill -KILL \$\$` and asserts a non-zero exit plus the signal-kill marker in stderr. * audit: untrack RUN_ISSUES*.md ralph-loop working docs same pattern called out in 4f14dbf1: these files are per-run harness state and analysis scratch, not merge-to-main deliverables. the TODO literally opens with "Ralph loop instructions:", so it's unambiguously in the same category as .claude/ralph-loop-prompt.md was. files stay on disk so the active loop keeps working. * audit: block refs/... + symbolic-ref bypass of default-branch guard push_branch's restricted-mode guard compared the resolved remoteBranch against defaultBranch with exact-string equality. an agent passing branchName "refs/heads/main" flowed through: rejectIfLeadingDash passed, getPushDestination's fallback preserved the refs/heads/main string as remoteBranch, so "refs/heads/main" !== "main" and the block was skipped, yet git push happily resolved refs/heads/main to the local main commit and pushed to the remote main branch. symbolic refs (HEAD / FETCH_HEAD / ORIG_HEAD / MERGE_HEAD) are the same class of bypass — they resolve to whatever commit they point at, unconstrained by the name-based guard. add rejectSpecialRef to enforce bare branch names at the tool entry, use it in push_branch and delete_branch. checkout_pr only ever assigns pr-<number> as the local branch, so nothing legitimate relied on the refs/... form here. * audit: keep original 422 visible when listReviews fails during pending-review cleanup if listReviews threw (e.g. transient 502, rate limit) during the stranded pending-review recovery path, the listing failure replaced the original 422 "pending review" error when it propagated up through the tool's outer catch. agents then saw a generic server error with no mention of the real blocker and stopped retrying the cleanup. now the listing failure is logged at debug but does not mask the original 422. the caller's retry re-attempts cleanup, which succeeds if the listing failure was transient. * audit: block default-branch deletion even under push: enabled delete_branch required push: enabled, but within that mode the agent could delete the default branch with no local guard. GitHub branch protection usually catches this at the remote, but not every repo has protection configured — and even when it does, relying on remote config for local safety is wrong. pushing to main is reversible (revert, force-push old HEAD); deleting main is not (reflog recovery only, 30-day window). block deletion of the resolved default_branch in DeleteBranchTool regardless of push permission. push: enabled authorizes pushes, not wholesale removal of the repository's primary branch. * audit: attach no-op catch to agentPromise so a late rejection can't crash cleanup agentPromise raced against activityTimeout.promise (and the --timeout timeoutPromise), both of which had .catch(() => {}) handlers. agentPromise did not. if a timeout won the race, agentPromise became stranded and its subsequent rejection was an unhandled rejection — under node 15+'s default unhandled-rejection policy that terminates the process, which would kill main() mid-cleanup and lose the error-reporting and usage-summary work queued in the catch/finally blocks. the race still sees the rejection (the original promise is shared); this catch only prevents node from treating a post-race rejection as unobserved. * audit: close push_branch refspec-injection via ':' / '+' in branchName rejectSpecialRef only forbade leading-dash, `refs/` prefix, and symbolic refs. git push accepts `[+]src[:dst]` refspec syntax, so an agent under push:restricted could smuggle a full refspec through branchName and bypass the downstream exact-string default-branch guard: "evil:refs/heads/main" → push local 'evil' to remote main ":refs/heads/main" → delete remote main ":other" → delete arbitrary branches (outside grant) "+main" → force-push refspec prefix reject ':', '+', '^', '~', '?', '*', '[', '\\', and whitespace — git's own check-ref-format forbids all of them in branch names, so the allow-list cannot false-positive against a legitimate branch. add regression tests. * audit: stop suggesting blocked 'rebase' in push_rejected advice under shell=disabled Why: when push fails with non-fast-forward, the advice told the agent to run 'git rebase origin/...'. In shell=disabled mode the git MCP tool blocks rebase (as an arbitrary-code-execution escape hatch), so the agent's only path forward was to hit the block, read the fallback message, and try merge — one wasted round trip. Now: under shell=disabled we directly suggest 'git merge origin/...', which always works. Under other modes the advice keeps the rebase/merge choice but leads with merge so the example is copy-pastable either way. * audit: harden includeIf cleanup against shell-injection via subsection names setupGit read `includeif.*` keys via `git config --get-regexp`, split on the first space, and fed the result into `execSync(\`git config --unset "${key}"\`)`. git config subsection values preserve arbitrary characters, so a crafted `[includeIf "gitdir:$(touch${IFS}/tmp/pwn)safe"]` entry round-trips through `--get-regexp` with its `$(...)` command substitution intact, survives the split-on-space filter (IFS-bypass leaves the payload space-free), and gets evaluated when interpolated into the shell command. Confirmed reachable as an RCE sink in local repro. Switch to `--get-regexp -z` (null-terminated, no ambiguity on whitespace) and call `$("git", ["config", "--unset-all", key])` which uses spawn-array and never hands the key to a shell. Extract the logic into `removeIncludeIfEntries` and add regression tests covering the injection payload, whitespace-in-subsection keys, benign entries, and the no-op case. * audit: clear SIGKILL escalator on clean SIGTERM exit the overall-timeout path scheduled a 5s SIGKILL follow-up without capturing the timer id. if the child cooperated with SIGTERM and `close` fired promptly, the escalator stayed pending in the event loop for up to 5s — delaying any subsequent clean shutdown (e.g. the main action exiting after an agent timeout) by that long. capture sigkillEscalatorId alongside timeoutId and clear it in both close and error handlers. regression test asserts the active-timer count does not grow past the pre-spawn baseline after a timed-out child exits on SIGTERM. * audit: correct rebase-availability hints to reflect shell=restricted the MCP git tool only blocks rebase when shell=disabled (NOSHELL_BLOCKED_SUBCOMMANDS check in GitTool). under shell=restricted, git({command: "rebase"}) works fine through the tool — NOSHELL_BLOCKED_SUBCOMMANDS doesn't apply. but two agent-facing messages implied rebase is only available with shell=enabled: - AUTH_REQUIRED_REDIRECT["pull"] said "rebase is only available when shell is enabled" - push-rejected integrateStep (non-disabled branch) said "(or 'rebase' if shell is enabled)" under shell=restricted, agents reading these would wrongly think they had to pick merge — pushing them toward merge commits when rebase would have been cleaner. the push-rejected branch is already ternary-gated on shell !== "disabled", so the qualifier there was just redundant noise. * audit: block difftool/mergetool under shell=disabled git difftool -x <cmd> is the short form of --extcmd. the args blocklist only matches --extcmd / --extcmd=*, so -x slipped through and let an agent run arbitrary commands even when shell=disabled. globally blocking -x would false-positive on git cherry-pick -x, which only appends metadata, so block difftool (and mergetool, same shape via mergetool.<name>.cmd) at the subcommand level instead. agents have no legitimate need for either — diffs go through diff/show and merges are resolved by file edits. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * audit: recover stranded PENDING drafts on no-body createReview too The body path already clears a stranded PENDING draft from a prior crashed run via createAndSubmitWithFooter's own try/catch. The no-body path (approve-with-no-feedback or comments-only) called createReview directly — so a PR whose previous body-path run crashed between createReview(PENDING) and submitReview would permanently 422 any subsequent no-body review with "already has a pending review" until a body-path run happened to clear it. Factored out createReviewWithStrandedRecovery so both paths get the same recovery treatment, and added regression tests covering the no-stranded / stranded-and-retry / non-stranded-422-no-retry cases. * audit: reject timeouts past node's setTimeout ceiling a user-supplied timeout like "999h" parses fine (parseTimeString has no upper cap) but falls off the 2^31-1 ms limit setTimeout clamps to 1ms. the agent run would reject with "timed out after 999h" in a single tick. extract a resolveTimeoutMs helper that centralizes the zero/overflow/ unparseable checks (previously scattered behind inline boolean logic in main.ts) and cover the behavior with unit tests including the boundary value. * fix(#22): replace parameter property in SpawnTimeoutError node --experimental-strip-types rejects readonly/public/private param properties in constructors. tests run via node directly (no tsc), so CI was hitting ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX on every action-agents / action-agnostic job before any test code ran. declare the field and assign in the body instead. * audit: tighten git tool description and delete_branch refspec - `git` tool description previously implied `pull` had a dedicated MCP tool alongside `push_branch`/`git_fetch`. it doesn't — the redirect sends the agent back to the same git tool with `command: "merge"` (or `rebase`). update the description to teach this directly instead of letting agents discover it through the redirect error. - `delete_branch` now passes `refs/heads/${branchName}` to `git push --delete` so a same-named tag can't be silently deleted when both exist on the remote. `rejectSpecialRef` already guarantees the bare-name invariant, so the template construction stays injection-safe. Made-with: Cursor * audit: polish review.ts per anneal findings - drop `as "LEFT" | "RIGHT"` cast in `validateInlineComments` — octokit types `side?: string` at the createReview endpoint, so narrow via `c.side === "LEFT" ? "LEFT" : "RIGHT"`. no cast, no redundant annotation — TS infers the literal union from the ternary. - consolidate `clearStrandedPendingReview` from 3 params to 2 by folding `originalErr` into `params`, per AGENTS.md "max 2 parameters" rule. updates both call sites (`createReviewWithStrandedRecovery`, `createAndSubmitWithFooter`) and all 7 test paths. - upgrade `listReviews`-during-cleanup failure log from `log.debug` to `log.info` so operators not running at debug still see that recovery was attempted before the original 422 bubbles up. message now reads "surfacing original 422" to make the intent unambiguous. Made-with: Cursor * audit: signal partial commit metadata in checkout_pr previously a rev-list/log failure (e.g. shallow fetch where `origin/<base>` isn't reachable) silently returned `commitCount: 0, commitLog: ""` — indistinguishable from "this PR has no commits past base", which could mislead review reasoning about scope. add a `commitLogUnavailable: boolean` field to `CheckoutPrResult`, set when the rev-list/log calls throw. instructions footer now tells the agent to treat the values as "unknown" rather than "no commits" in that case. message phrased to cover the rare case where rev-list succeeds but git log throws (partial, not strictly zero) metadata. Made-with: Cursor * audit: fix parseDiffTocEntries to match production ' · diff-<sha>' TOC suffix the regex required $ right after the line range, but formatFilesWithLineNumbers in checkout.ts appends ` · diff-<sha256>` so agents have the GitHub "Files Changed" anchor precomputed. result: tocEntries was always empty on real PR reviews, breakdown.files was empty, and runDiffCoveragePreflight never fired its one-time "read the diff" nudge. add an optional suffix to the regex and a regression test that uses the exact production TOC shape. Made-with: Cursor * audit(#20): skip empty downgraded-APPROVE reviews before they 422 GitHub rejects `event: "COMMENT"` reviews with no body and no inline comments (HTTP 422 "Unprocessable Entity", verified empirically on repos/pullfrog/preview-546-run-issues-fixes/pulls/1). the runtime `prApproveEnabled` downgrade folds approved=true into event=COMMENT when the repo flag is off, so an agent asking to APPROVE a PR with no other feedback produces exactly that rejected shape — but the existing empty-review skip only fired for !approved cases, so the tool POSTed the doomed COMMENT, octokit returned what looked like a success-with- no-persisted-review shape, and agents reported a phantom reviewId that 404s on any subsequent GET. extract the skip decision into `reviewSkipDecision` and add a second branch for approved + !prApproveEnabled + empty. the function returns null when the review should be submitted, so a real bare APPROVE (approved + prApproveEnabled + empty) still goes through unchanged — GitHub accepts empty APPROVE reviews because the stamp itself is the content. surfaced in the PR #546 preview e2e run 24678139563 (reviewId 4141786854 reported by the agent but absent from every reviews listing). TC13 run 24680349445 re-ran the same scenario with prApproveEnabled=enabled and the review persisted correctly, isolating the cause to the downgrade + empty interaction. * audit(#31): drop misleading rebase mention from pull redirect AUTH_REQUIRED_REDIRECT["pull"] and the git tool's top-level description both said "use git_fetch then this tool with command 'merge' (or 'rebase' unless shell is disabled)". the "(or 'rebase' unless shell is disabled)" qualifier is active misinformation when the agent is already running under shell=disabled: rebase is blocked there by NOSHELL_BLOCKED_SUBCOMMANDS, so the suggestion sends the agent into a second block on the next tool call. 3b83ee97 already fixed this pattern for the push-rejected advice at line 248, but the pull redirect at line 280 and the tool description at line 351 were missed. the right copy isn't a conditional qualifier that agents have to parse against their own shell mode — it's just naming the one alternative that works everywhere (merge). agents under shell=restricted/enabled who want rebase can invoke it directly; the redirect doesn't need to advertise it. verified in preview e2e run 24679728733 (TC8 probe 6) where the agent correctly captured the verbatim redirect message under shell=disabled and explicitly flagged the "(or 'rebase' unless shell is disabled)" clause as confusing — the new test in security.test.ts asserts the message names merge and never rebase in every shell mode. * audit: drop vestigial entry/post references + add preview-546 settings util followup to d79860c6 "refactor: flatten action entrypoints" (Apr 10), which moved action.yml from built `entry`/`post` files to source `entry.ts`/`post.ts` but left three stale references lying around: - .gitignore: `action/run/entry` / `action/dispatch/entry` paths no longer exist anywhere in the build. - .github/workflows/pull-from-action.yml: agent instruction told the upstream sync agent to "Ignore `entry` files (they are built artifacts and .gitignored in this repo)". there are no built entry artifacts anymore — entry.ts is source. - .cursor/settings.json: search.exclude pattern "**/entry" excluded the old built files that no longer exist. none of these were load-bearing on their own, but the same drift had already broken preview e2e end-to-end: the pullfrog/template workflow's three-file copy step (cp .../entry, cp .../post) silently failed with cp: no such file on every preview PR since Apr 10. that template fix went to pullfrog/template@7ec7c8d and the preview-546 mirror at @17ab585, which is what unblocked this PR's full e2e validation. also adds scripts/preview-546-settings.ts, the helper used during the e2e validation to show/set/reset DB-level repo settings on the Neon preview branch (push, shell, prApproveEnabled, hook scripts). scoped to this preview repo ID so it can't accidentally mutate prod. * audit(#11): scope removeIncludeIfEntries to repoDir under inherited GIT_* the function takes `repoDir` as the target, but plain execSync / $(...) inherit GIT_DIR, GIT_WORK_TREE, and GIT_INDEX_FILE from the parent process — and `git config --local` honors GIT_DIR over cwd. when this runs as a child of another git invocation (notably the pre-push hook, but also any future caller embedded inside a git subcommand), the cleanup silently targets the outer repo instead of repoDir. latent today because the real caller is ASKPASS setup, which runs before any git-subcommand ancestor exists, but the function's contract still promised the wrong thing — and the test suite hit exactly this bug when invoked through `git push`. - envScopedToRepo() strips GIT_* before both the get-regexp and unset calls, so cwd wins. - swap the $(...) shell helper for execFileSync on the unset call. $() would merge our scoped env with a "restricted" base that's tuned for hook execution (no tokens) — overkill here and it re-introduces the shell-vs-argv distinction this function was explicitly hardened against in a9aa3b2b. execFileSync with argv is the right tool for a call where the key can contain arbitrary characters. - setup.test.ts also strips GIT_* in its own execSync harness so the suite passes identically under `pnpm vitest run`, `pnpm -r test`, and `git push`'s pre-push hook. --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com> Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
649 lines
25 KiB
TypeScript
649 lines
25 KiB
TypeScript
import { createHash } from "node:crypto";
|
|
import { writeFileSync } from "node:fs";
|
|
import { join } from "node:path";
|
|
import type { Octokit, RestEndpointMethodTypes } from "@octokit/rest";
|
|
import { type } from "arktype";
|
|
import { log } from "../utils/cli.ts";
|
|
import { countLines, createDiffCoverageState } from "../utils/diffCoverage.ts";
|
|
import { $git } from "../utils/gitAuth.ts";
|
|
import { executeLifecycleHook } from "../utils/lifecycle.ts";
|
|
import { computeIncrementalDiff } from "../utils/rangeDiff.ts";
|
|
import { $ } from "../utils/shell.ts";
|
|
import { rejectIfLeadingDash } from "./git.ts";
|
|
import { commentableLinesForFile } from "./review.ts";
|
|
import type { ToolContext } from "./server.ts";
|
|
import { execute, tool } from "./shared.ts";
|
|
|
|
type PullFile = RestEndpointMethodTypes["pulls"]["listFiles"]["response"]["data"][number];
|
|
|
|
export type FormatFilesResult = {
|
|
content: string;
|
|
toc: string;
|
|
};
|
|
|
|
export type FetchAndFormatPrDiffResult = FormatFilesResult & {
|
|
files: PullFile[];
|
|
};
|
|
|
|
/**
|
|
* formats PR files with explicit line numbers for each code line.
|
|
* preserves all original diff info (file headers, hunk headers) and adds:
|
|
* | OLD | NEW | TYPE | code
|
|
* returns both the formatted content and a TOC with line ranges per file.
|
|
*/
|
|
export function formatFilesWithLineNumbers(files: PullFile[]): FormatFilesResult {
|
|
const output: string[] = [];
|
|
const tocEntries: Array<{ filename: string; startLine: number; endLine: number }> = [];
|
|
|
|
// calculate TOC header size: "## Files (N)\n" + N entries + "\n---\n\n"
|
|
const tocHeaderSize = 1 + files.length + 2;
|
|
let currentLine = tocHeaderSize + 1;
|
|
|
|
for (const file of files) {
|
|
const fileStartLine = currentLine;
|
|
|
|
// file header
|
|
output.push(`diff --git a/${file.filename} b/${file.filename}`);
|
|
output.push(`--- a/${file.filename}`);
|
|
output.push(`+++ b/${file.filename}`);
|
|
currentLine += 3;
|
|
|
|
if (!file.patch) {
|
|
output.push("(binary file or no changes)");
|
|
output.push("");
|
|
currentLine += 2;
|
|
tocEntries.push({
|
|
filename: file.filename,
|
|
startLine: fileStartLine,
|
|
endLine: currentLine - 1,
|
|
});
|
|
continue;
|
|
}
|
|
|
|
// parse and format the patch with line numbers
|
|
const lines = file.patch.split("\n");
|
|
let oldLine = 0;
|
|
let newLine = 0;
|
|
|
|
for (const line of lines) {
|
|
// hunk header: @@ -OLD,COUNT +NEW,COUNT @@ optional context
|
|
const hunkMatch = line.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/);
|
|
if (hunkMatch) {
|
|
oldLine = parseInt(hunkMatch[1], 10);
|
|
newLine = parseInt(hunkMatch[2], 10);
|
|
output.push(line); // pass through unchanged
|
|
currentLine++;
|
|
continue;
|
|
}
|
|
|
|
// code lines within hunks
|
|
const changeType = line[0] || " ";
|
|
const code = line.slice(1);
|
|
|
|
if (changeType === "-") {
|
|
// removed line: show old line number, no new line number
|
|
output.push(`| ${padNum(oldLine)} | | - | ${code}`);
|
|
oldLine++;
|
|
} else if (changeType === "+") {
|
|
// added line: no old line number, show new line number
|
|
output.push(`| | ${padNum(newLine)} | + | ${code}`);
|
|
newLine++;
|
|
} else if (changeType === " " || changeType === "\\") {
|
|
// context line or "\ No newline at end of file"
|
|
if (changeType === "\\") {
|
|
output.push(line); // pass through as-is
|
|
} else {
|
|
output.push(`| ${padNum(oldLine)} | ${padNum(newLine)} | | ${code}`);
|
|
oldLine++;
|
|
newLine++;
|
|
}
|
|
} else {
|
|
// unknown line type, pass through
|
|
output.push(line);
|
|
}
|
|
currentLine++;
|
|
}
|
|
output.push(""); // blank line between files
|
|
currentLine++;
|
|
|
|
tocEntries.push({
|
|
filename: file.filename,
|
|
startLine: fileStartLine,
|
|
endLine: currentLine - 1,
|
|
});
|
|
}
|
|
|
|
// build TOC. each entry includes the precomputed sha256 anchor used in
|
|
// github PR Files Changed URLs (#diff-<hex>), so the agent never needs to
|
|
// shell out to sha256sum.
|
|
const tocLines = [`## Files (${files.length})`];
|
|
for (const entry of tocEntries) {
|
|
const anchor = createHash("sha256").update(entry.filename).digest("hex");
|
|
tocLines.push(
|
|
`- ${entry.filename} → lines ${entry.startLine}-${entry.endLine} · diff-${anchor}`
|
|
);
|
|
}
|
|
tocLines.push("");
|
|
tocLines.push("---");
|
|
tocLines.push("");
|
|
|
|
const toc = tocLines.join("\n");
|
|
const content = toc + output.join("\n");
|
|
|
|
return { content, toc };
|
|
}
|
|
|
|
function padNum(n: number): string {
|
|
return n.toString().padStart(4, " ");
|
|
}
|
|
|
|
export const CheckoutPr = type({
|
|
pull_number: type.number.describe("the pull request number to checkout"),
|
|
});
|
|
|
|
export type CheckoutPrResult = {
|
|
success: true;
|
|
number: number;
|
|
title: string;
|
|
body: string | null;
|
|
base: string;
|
|
localBranch: string;
|
|
remoteBranch: string;
|
|
isFork: boolean;
|
|
maintainerCanModify: boolean;
|
|
url: string;
|
|
headRepo: string;
|
|
diffPath: string;
|
|
incrementalDiffPath?: string | undefined;
|
|
toc: string;
|
|
commitCount: number;
|
|
commitLog: string;
|
|
/** true when commitLog was capped because the PR has more commits than we render */
|
|
commitLogTruncated: boolean;
|
|
/** true when commit metadata could not be computed (e.g. base ref unreachable after shallow fetch). commitCount/commitLog are zero/empty in that case, not "no commits". */
|
|
commitLogUnavailable: boolean;
|
|
/** non-fatal warning from the post-checkout lifecycle hook, if any */
|
|
hookWarning?: string | undefined;
|
|
instructions: string;
|
|
};
|
|
|
|
/**
|
|
* fetches PR files from GitHub and formats them with line numbers and TOC.
|
|
* this is the core diff formatting logic, extracted for testability.
|
|
*/
|
|
export async function fetchAndFormatPrDiff(
|
|
ctx: ToolContext,
|
|
pullNumber: number
|
|
): Promise<FetchAndFormatPrDiffResult> {
|
|
const files = await ctx.octokit.paginate(ctx.octokit.rest.pulls.listFiles, {
|
|
owner: ctx.repo.owner,
|
|
repo: ctx.repo.name,
|
|
pull_number: pullNumber,
|
|
per_page: 100,
|
|
});
|
|
return { ...formatFilesWithLineNumbers(files), files };
|
|
}
|
|
|
|
import type { GitContext } from "../utils/setup.ts";
|
|
|
|
export type PrData = {
|
|
number: number;
|
|
headSha: string;
|
|
headRef: string;
|
|
headRepoFullName: string;
|
|
baseRef: string;
|
|
baseRepoFullName: string;
|
|
maintainerCanModify: boolean;
|
|
};
|
|
|
|
type EnsureBeforeShaParams = {
|
|
sha: string;
|
|
octokit: Octokit;
|
|
owner: string;
|
|
repo: string;
|
|
gitToken: string;
|
|
isShallow: boolean;
|
|
};
|
|
|
|
type CreateTempBranchParams = {
|
|
octokit: Octokit;
|
|
owner: string;
|
|
repo: string;
|
|
ref: string;
|
|
sha: string;
|
|
};
|
|
|
|
async function createTempBranch(params: CreateTempBranchParams) {
|
|
const response = await params.octokit.rest.git.createRef({
|
|
owner: params.owner,
|
|
repo: params.repo,
|
|
ref: `refs/heads/${params.ref}`,
|
|
sha: params.sha,
|
|
});
|
|
return {
|
|
data: response.data,
|
|
async [Symbol.asyncDispose]() {
|
|
try {
|
|
await params.octokit.rest.git.deleteRef({
|
|
owner: params.owner,
|
|
repo: params.repo,
|
|
ref: `heads/${params.ref}`,
|
|
});
|
|
log.debug(`» deleted temp branch ${params.ref}`);
|
|
} catch (e) {
|
|
log.debug(
|
|
`» failed to delete temp branch ${params.ref}: ${e instanceof Error ? e.message : String(e)}`
|
|
);
|
|
}
|
|
},
|
|
};
|
|
}
|
|
|
|
async function ensureBeforeShaReachable(params: EnsureBeforeShaParams): Promise<boolean> {
|
|
try {
|
|
$("git", ["cat-file", "-t", params.sha], { log: false });
|
|
log.debug(`» before_sha ${params.sha.slice(0, 7)} is reachable`);
|
|
return true;
|
|
} catch {
|
|
// not available locally — create a temporary branch to fetch it
|
|
}
|
|
|
|
const tempBranch = `pullfrog/tmp/${params.sha.slice(0, 12)}`;
|
|
try {
|
|
log.debug(`» before_sha ${params.sha.slice(0, 7)} not reachable, creating temp branch...`);
|
|
await using _ref = await createTempBranch({
|
|
octokit: params.octokit,
|
|
owner: params.owner,
|
|
repo: params.repo,
|
|
sha: params.sha,
|
|
ref: tempBranch,
|
|
});
|
|
await $git(
|
|
"fetch",
|
|
["--no-tags", ...(params.isShallow ? ["--depth=1"] : []), "origin", tempBranch],
|
|
{ token: params.gitToken }
|
|
);
|
|
log.debug(`» fetched before_sha via temp branch ${tempBranch}`);
|
|
return true;
|
|
} catch (e) {
|
|
log.debug(`» failed to fetch before_sha: ${e instanceof Error ? e.message : String(e)}`);
|
|
return false;
|
|
}
|
|
}
|
|
|
|
type CheckoutPrBranchParams = GitContext & {
|
|
beforeSha?: string | undefined;
|
|
};
|
|
|
|
/**
|
|
* Shared helper to checkout a PR branch and configure fork remotes.
|
|
* Assumes origin remote is already configured with authentication.
|
|
* Updates toolState.issueNumber, toolState.checkoutSha, and toolState.pushUrl (for fork PRs).
|
|
*/
|
|
export async function checkoutPrBranch(
|
|
pr: PrData,
|
|
params: CheckoutPrBranchParams
|
|
): Promise<{ hookWarning?: string | undefined }> {
|
|
const { octokit, owner, name, gitToken, toolState, beforeSha } = params;
|
|
log.info(`» checking out PR #${pr.number}...`);
|
|
|
|
// SECURITY: PR ref names come from GitHub and are attacker-controlled on
|
|
// forks (the PR author picks headRef freely, and baseRef could be a
|
|
// maliciously-named branch on the target repo). reject leading-dash names
|
|
// before they reach any git command — without this, a ref like
|
|
// "-upload-pack=evil" fed into `git fetch origin <ref>` would be parsed as
|
|
// a flag, not a refspec.
|
|
rejectIfLeadingDash(pr.baseRef, "PR base ref");
|
|
rejectIfLeadingDash(pr.headRef, "PR head ref");
|
|
|
|
const isFork = pr.headRepoFullName !== pr.baseRepoFullName;
|
|
|
|
// always use pr-{number} as local branch name for consistency
|
|
// this avoids naming conflicts and makes push config simpler
|
|
const localBranch = `pr-${pr.number}`;
|
|
|
|
const isShallow =
|
|
$("git", ["rev-parse", "--is-shallow-repository"], { log: false }).trim() === "true";
|
|
|
|
toolState.checkoutSha = $("git", ["rev-parse", "HEAD"], { log: false }).trim();
|
|
const alreadyOnBranch = toolState.checkoutSha === pr.headSha;
|
|
|
|
// fetch base branch so origin/<base> exists for diff operations
|
|
log.debug(`» fetching base branch (${pr.baseRef})...`);
|
|
await $git("fetch", ["--no-tags", "origin", pr.baseRef], { token: gitToken });
|
|
|
|
// alreadyOnBranch only matches for repeated checkout_pr calls for the same PR in one session
|
|
// (without the tip moving), or if an external setup already checked out the PR head.
|
|
// normal PR-triggered runs won't match here — actions/checkout lands on a synthesized
|
|
// merge commit whose SHA differs from pr.headSha.
|
|
//
|
|
// so the fetch+checkout block below will almost always execute, and the fetched HEAD
|
|
// might differ from pr.headSha. toolState.checkoutSha is set after to capture the actual SHA.
|
|
if (!alreadyOnBranch) {
|
|
// checkout base branch first to avoid "refusing to fetch into current branch" error
|
|
// -B creates or resets the branch to match origin/baseBranch
|
|
$("git", ["checkout", "-B", pr.baseRef, `origin/${pr.baseRef}`], { log: false });
|
|
|
|
// fetch PR branch using pull/{n}/head refspec (works for both fork and same-repo PRs)
|
|
log.debug(`» fetching PR #${pr.number} (${localBranch})...`);
|
|
await $git("fetch", ["--no-tags", "origin", `+pull/${pr.number}/head:${localBranch}`], {
|
|
token: gitToken,
|
|
});
|
|
|
|
// checkout the branch
|
|
$("git", ["checkout", localBranch], { log: false });
|
|
log.debug(`» checked out PR #${pr.number}`);
|
|
// make sure toolState.checkoutSha is set to the actual checked-out SHA (which might be different from pr.headSha)
|
|
toolState.checkoutSha = $("git", ["rev-parse", "HEAD"], { log: false }).trim();
|
|
}
|
|
|
|
const beforeShaReachable = beforeSha
|
|
? await ensureBeforeShaReachable({
|
|
sha: beforeSha,
|
|
octokit,
|
|
owner,
|
|
repo: name,
|
|
gitToken,
|
|
isShallow,
|
|
})
|
|
: false;
|
|
|
|
// compute deepen depth for shallow clones. actions/checkout uses depth=1
|
|
// by default, which breaks rebase/log because git can't find the merge base.
|
|
// use the GitHub compare API to fetch exactly enough history.
|
|
// computed after checkout so compareCommits uses the actual checked-out SHA.
|
|
if (isShallow) {
|
|
let deepenDepth = 0;
|
|
try {
|
|
// ahead_by = PR commits past merge base, behind_by = base commits past merge base.
|
|
// --deepen extends ALL shallow roots equally (can't deepen a single branch),
|
|
// so we need the max across both the PR head and before_sha to ensure all
|
|
// three points (base, head, before_sha) reach the merge base in a single deepen call.
|
|
const [prComparison, beforeShaComparison] = await Promise.all([
|
|
octokit.rest.repos.compareCommits({
|
|
owner,
|
|
repo: name,
|
|
base: pr.baseRef,
|
|
head: toolState.checkoutSha,
|
|
}),
|
|
beforeSha && beforeShaReachable
|
|
? octokit.rest.repos.compareCommits({
|
|
owner,
|
|
repo: name,
|
|
base: pr.baseRef,
|
|
head: beforeSha,
|
|
})
|
|
: undefined,
|
|
]);
|
|
deepenDepth =
|
|
Math.max(
|
|
prComparison.data.ahead_by,
|
|
prComparison.data.behind_by,
|
|
beforeShaComparison?.data.ahead_by ?? 0,
|
|
beforeShaComparison?.data.behind_by ?? 0
|
|
) + 10;
|
|
log.debug(
|
|
`» PR: ${prComparison.data.ahead_by} ahead / ${prComparison.data.behind_by} behind` +
|
|
(beforeShaComparison
|
|
? `, before_sha: ${beforeShaComparison.data.ahead_by} ahead / ${beforeShaComparison.data.behind_by} behind`
|
|
: "") +
|
|
`, deepen by ${deepenDepth}`
|
|
);
|
|
} catch {
|
|
deepenDepth = 1000;
|
|
log.debug(`» compare API failed, falling back to --deepen=${deepenDepth}`);
|
|
}
|
|
// deepen after both branches are fetched so the merge base is reachable from both sides
|
|
if (deepenDepth) {
|
|
log.debug(`» deepening by ${deepenDepth} to reach merge base...`);
|
|
await $git("fetch", [`--deepen=${deepenDepth}`, "--no-tags", "origin"], {
|
|
token: gitToken,
|
|
});
|
|
}
|
|
}
|
|
|
|
// configure push remote for this branch
|
|
// NOTE: This always runs regardless of alreadyOnBranch, because setupGit doesn't configure
|
|
// fork remotes. This ensures fork PRs can push even when checkout_pr is called after setupGit.
|
|
if (isFork) {
|
|
const remoteName = `pr-${pr.number}`;
|
|
// SECURITY: fork URL without token - auth is injected via GIT_ASKPASS in $git()
|
|
const forkUrl = `https://github.com/${pr.headRepoFullName}.git`;
|
|
|
|
// add fork as a named remote (suppress logging to avoid "error: remote already exists" spam)
|
|
try {
|
|
$("git", ["remote", "add", remoteName, forkUrl], { log: false });
|
|
log.debug(`» added remote '${remoteName}' for fork ${pr.headRepoFullName}`);
|
|
} catch {
|
|
// remote already exists, update its URL
|
|
$("git", ["remote", "set-url", remoteName, forkUrl], { log: false });
|
|
log.debug(`» updated remote '${remoteName}' for fork ${pr.headRepoFullName}`);
|
|
}
|
|
|
|
// set branch push config so `git push` knows where to push
|
|
$("git", ["config", `branch.${localBranch}.pushRemote`, remoteName], { log: false });
|
|
// set merge ref so git knows the remote branch name (may differ from local)
|
|
$("git", ["config", `branch.${localBranch}.merge`, `refs/heads/${pr.headRef}`], { log: false });
|
|
log.debug(`» configured branch '${localBranch}' to push to '${remoteName}/${pr.headRef}'`);
|
|
|
|
// warn if maintainer can't modify (push will likely fail)
|
|
if (!pr.maintainerCanModify) {
|
|
log.warning(
|
|
`» fork PR has maintainer_can_modify=false - push operations will fail. ` +
|
|
`ask the PR author to enable "Allow edits from maintainers" or the fork may be owned by an organization.`
|
|
);
|
|
}
|
|
} else {
|
|
// for same-repo PRs, push to origin
|
|
$("git", ["config", `branch.${localBranch}.pushRemote`, "origin"], { log: false });
|
|
$("git", ["config", `branch.${localBranch}.merge`, `refs/heads/${pr.headRef}`], { log: false });
|
|
}
|
|
|
|
// update toolState
|
|
toolState.issueNumber = pr.number;
|
|
if (isFork) {
|
|
toolState.pushUrl = `https://github.com/${pr.headRepoFullName}.git`;
|
|
}
|
|
|
|
// store push destination so push_branch can use it directly
|
|
// git config is the primary mechanism, but toolState serves as a reliable fallback
|
|
// in case git config reads fail in certain environments
|
|
toolState.pushDest = {
|
|
remoteName: isFork ? `pr-${pr.number}` : "origin",
|
|
remoteBranch: pr.headRef,
|
|
localBranch,
|
|
};
|
|
|
|
// execute post-checkout lifecycle hook. soft-fail: surface the warning
|
|
// to the agent via the tool response instead of throwing, so a flaky or
|
|
// slightly-broken hook doesn't block checkout entirely.
|
|
const postCheckoutHook = await executeLifecycleHook({
|
|
event: "post-checkout",
|
|
script: params.postCheckoutScript,
|
|
});
|
|
return { hookWarning: postCheckoutHook.warning };
|
|
}
|
|
|
|
export function CheckoutPrTool(ctx: ToolContext) {
|
|
return tool({
|
|
name: "checkout_pr",
|
|
description:
|
|
"Checkout a pull request branch locally. This fetches the PR branch and sets up push configuration for fork PRs. " +
|
|
"Returns diffPath pointing to the formatted diff file.",
|
|
parameters: CheckoutPr,
|
|
execute: execute(async ({ pull_number }) => {
|
|
const prResponse = await ctx.octokit.rest.pulls.get({
|
|
owner: ctx.repo.owner,
|
|
repo: ctx.repo.name,
|
|
pull_number,
|
|
});
|
|
|
|
const headRepo = prResponse.data.head.repo;
|
|
if (!headRepo) {
|
|
throw new Error(`PR #${pull_number} source repository was deleted`);
|
|
}
|
|
|
|
const pr: PrData = {
|
|
number: pull_number,
|
|
headSha: prResponse.data.head.sha,
|
|
headRef: prResponse.data.head.ref,
|
|
headRepoFullName: headRepo.full_name,
|
|
baseRef: prResponse.data.base.ref,
|
|
baseRepoFullName: prResponse.data.base.repo.full_name,
|
|
maintainerCanModify: prResponse.data.maintainer_can_modify,
|
|
};
|
|
|
|
const checkoutResult = await checkoutPrBranch(pr, {
|
|
octokit: ctx.octokit,
|
|
owner: ctx.repo.owner,
|
|
name: ctx.repo.name,
|
|
gitToken: ctx.gitToken,
|
|
toolState: ctx.toolState,
|
|
shell: ctx.payload.shell,
|
|
postCheckoutScript: ctx.postCheckoutScript,
|
|
beforeSha: ctx.toolState.beforeSha,
|
|
});
|
|
|
|
const tempDir = process.env.PULLFROG_TEMP_DIR;
|
|
if (!tempDir) {
|
|
throw new Error(
|
|
"PULLFROG_TEMP_DIR not set - checkout_pr must run in pullfrog action context"
|
|
);
|
|
}
|
|
|
|
const headShort = ctx.toolState.checkoutSha!.slice(0, 7);
|
|
|
|
// compute incremental diff if we have a beforeSha to compare against
|
|
let incrementalDiffPath: string | undefined;
|
|
if (ctx.toolState.beforeSha && ctx.toolState.checkoutSha) {
|
|
const beforeShort = ctx.toolState.beforeSha.slice(0, 7);
|
|
const incremental = computeIncrementalDiff({
|
|
baseBranch: pr.baseRef,
|
|
beforeSha: ctx.toolState.beforeSha,
|
|
headSha: ctx.toolState.checkoutSha,
|
|
});
|
|
if (incremental) {
|
|
incrementalDiffPath = join(
|
|
tempDir,
|
|
`pr-${pull_number}-${beforeShort}-${headShort}-incremental.diff`
|
|
);
|
|
writeFileSync(incrementalDiffPath, incremental);
|
|
log.info(
|
|
`» incremental diff computed (${incremental.length} bytes) → ${incrementalDiffPath}`
|
|
);
|
|
}
|
|
}
|
|
|
|
// fetch PR files and format with line numbers
|
|
const formatResult = await fetchAndFormatPrDiff(ctx, pull_number);
|
|
const diffPreview = formatResult.content.split("\n").slice(0, 100).join("\n");
|
|
log.debug(`formatted diff preview (first 100 lines):\n${diffPreview}`);
|
|
const diffPath = join(tempDir, `pr-${pull_number}-${headShort}.diff`);
|
|
writeFileSync(diffPath, formatResult.content);
|
|
log.debug(`wrote diff to ${diffPath} (${formatResult.content.length} bytes)`);
|
|
ctx.toolState.diffCoverage = createDiffCoverageState({
|
|
diffPath,
|
|
totalLines: countLines({ content: formatResult.content }),
|
|
toc: formatResult.toc,
|
|
});
|
|
log.debug(
|
|
`» diff coverage initialized: diffPath=${diffPath}, totalLines=${ctx.toolState.diffCoverage.totalLines}, tocEntries=${ctx.toolState.diffCoverage.tocEntries.length}`
|
|
);
|
|
|
|
// cache commentable-lines snapshot so review-time validation matches what
|
|
// GitHub will anchor to (commit_id=checkoutSha), even if the PR is updated
|
|
// between checkout and review.
|
|
const cached = new Map<string, ReturnType<typeof commentableLinesForFile>>();
|
|
for (const file of formatResult.files) {
|
|
cached.set(file.filename, commentableLinesForFile(file.patch));
|
|
}
|
|
ctx.toolState.commentableLinesByFile = cached;
|
|
ctx.toolState.commentableLinesPullNumber = pull_number;
|
|
ctx.toolState.commentableLinesCheckoutSha = ctx.toolState.checkoutSha;
|
|
|
|
const incrementalInstructions = incrementalDiffPath
|
|
? ` IMPORTANT: incrementalDiffPath contains ONLY the changes since the last reviewed version ` +
|
|
`(computed via range-diff). you MUST read incrementalDiffPath FIRST to understand what changed, ` +
|
|
`then use diffPath for full PR context. do NOT skip the incremental diff.`
|
|
: "";
|
|
|
|
// commit metadata relative to the PR base (e.g. main). use origin/<base>
|
|
// because the local base ref may not exist after a shallow fetch. cap
|
|
// the log so a PR with thousands of commits doesn't blow up the tool
|
|
// response. if the base ref can't be resolved (e.g. shallow fetch that
|
|
// didn't pull down origin/<base>), degrade gracefully rather than
|
|
// failing the whole checkout_pr call over metadata.
|
|
const COMMIT_LOG_MAX = 200;
|
|
const baseRange = `origin/${pr.baseRef}..HEAD`;
|
|
let commitCount = 0;
|
|
let commitLog = "";
|
|
let commitLogUnavailable = false;
|
|
try {
|
|
commitCount = parseInt(
|
|
$("git", ["rev-list", "--count", baseRange], { log: false }).trim() || "0",
|
|
10
|
|
);
|
|
commitLog = $("git", ["log", "--oneline", `--max-count=${COMMIT_LOG_MAX}`, baseRange], {
|
|
log: false,
|
|
});
|
|
} catch (err) {
|
|
commitLogUnavailable = true;
|
|
log.debug(
|
|
`» unable to compute commit metadata for ${baseRange}: ${err instanceof Error ? err.message : String(err)}`
|
|
);
|
|
}
|
|
const commitLogTruncated = commitCount > COMMIT_LOG_MAX;
|
|
|
|
const hookWarningInstructions = checkoutResult.hookWarning
|
|
? ` HOOK WARNING: the post-checkout lifecycle hook reported a non-fatal failure (see hookWarning). ` +
|
|
`decide whether to retry based on the guidance in that field before proceeding.`
|
|
: "";
|
|
|
|
const commitLogInstructions = commitLogUnavailable
|
|
? ` NOTE: commit metadata is partial (base ref unreachable, likely a shallow fetch). ` +
|
|
`commitCount/commitLog may be 0/empty or incomplete; treat them as "unknown" rather than "no commits", ` +
|
|
`and use \`git log\` directly if you need the full history.`
|
|
: commitLogTruncated
|
|
? ` NOTE: commitLog was capped at ${COMMIT_LOG_MAX} entries out of ${commitCount} commits; ` +
|
|
`use \`git log\` directly if you need the full history.`
|
|
: "";
|
|
|
|
return {
|
|
success: true,
|
|
number: prResponse.data.number,
|
|
title: prResponse.data.title,
|
|
body: prResponse.data.body,
|
|
base: pr.baseRef,
|
|
localBranch: `pr-${pull_number}`,
|
|
remoteBranch: `refs/heads/${pr.headRef}`,
|
|
isFork: pr.headRepoFullName !== pr.baseRepoFullName,
|
|
maintainerCanModify: pr.maintainerCanModify,
|
|
url: prResponse.data.html_url,
|
|
headRepo: pr.headRepoFullName,
|
|
diffPath,
|
|
incrementalDiffPath,
|
|
toc: formatResult.toc,
|
|
commitCount,
|
|
commitLog,
|
|
commitLogTruncated,
|
|
commitLogUnavailable,
|
|
hookWarning: checkoutResult.hookWarning,
|
|
instructions:
|
|
`the diff file at diffPath contains a table of contents (TOC) at the top listing every changed file with its line range. ` +
|
|
`use the TOC line ranges as your checklist and read specific files from the diff instead of reading the entire file. ` +
|
|
`for example, if the TOC says "src/foo.ts → lines 5-42", read lines 5-42 from diffPath to see that file's changes. ` +
|
|
`review files selectively based on relevance rather than reading everything sequentially. ` +
|
|
`to inspect the PR's changed files, use diffPath — do NOT run \`git diff <base>..<head>\` to re-derive what's already in diffPath. the formatted diff with line numbers is authoritative. ` +
|
|
`\`git log\` and \`git diff --stat\` are fine for commit-range overview, and \`git diff\` / \`git diff --cached\` are fine for inspecting *your own* uncommitted changes — but PR review content MUST come from diffPath. ` +
|
|
`before your review is submitted, a one-time coverage pre-flight may error listing unread TOC regions. ` +
|
|
`retry the same create_pull_request_review call to proceed — optionally after reading the listed ranges. the pre-flight will not block again this session. ` +
|
|
`the local branch is 'localBranch' (pr-{number}), not the remote branch name. ` +
|
|
`when pushing, omit branchName to use the current branch. do not use remoteBranch as a local branch name.` +
|
|
incrementalInstructions +
|
|
hookWarningInstructions +
|
|
commitLogInstructions,
|
|
} satisfies CheckoutPrResult;
|
|
}),
|
|
});
|
|
}
|