102 Commits

Author SHA1 Message Date
wolfy 0dc0f7eb53 feat: add read_file tool 2026-05-31 12:11:10 -05:00
wolfy 3f0d9a80c7 fix: issue with shell calls 2026-05-31 12:03:06 -05:00
wolfy 19671c6299 feat: branch protection + deps caching 2026-05-31 03:18:19 -05:00
wolfy 2aca1a3aa3 feat: adapt pullfrog for gitea + ollama 2026-05-31 03:16:29 -05:00
Colin McDonnell 8dff91ac49 router: fix unspendable signup credit on no-card private repos (#792)
* router: fix unspendable signup credit on no-card private repos (#791)

The bug
-------
`run-context/route.ts` gated `proxyModel` minting on `isInfraCovered`,
which is `oss || hasCard`. So a no-card account with positive wallet
balance (signup credit, top-up, etc.) on a private repo would never
get a `proxyModel` set on the run context. The action runtime then
fell through to whatever provider keys happened to be in the workflow
env — using the user's BYOK keys without their knowledge if any were
configured, or failing the run entirely otherwise.

Meanwhile `proxy-token/route.ts` already gated correctly on
`oss || hasCard || balance > 0`. The two routes disagreed, with
run-context being strictly more restrictive, so the agent never even
attempted to call proxy-token for these accounts. The wiki at
`billing.md:1052` documented the *intended* behavior ("a Router usage
row can debit a wallet with no card on file"), aspirational against
the actual code.

The action side had a parallel bug at `action/utils/proxy.ts:151` —
it re-derived `isInfraCovered({ isOss, plan })` and short-circuited
mint even when the server set `proxyModel`. Belt-and-suspenders that
was strictly more restrictive than the server.

Production impact
-----------------
Queried 55 router-mode no-card accounts holding signup credit:
- ALL have wallet balance = exactly $10.00 (untouched)
- ALL have 0 router proxy keys ever minted, 0 hwm usage
- ~25 have successful runs (using BYOK env vars from their workflow,
  unaware their credit isn't being touched)
- The rest have zero successes; some accumulated 25+ failures
  (e.g. `onechannelpe`: 25 failures, 0 successes, no card, $10 credit).

The fix
-------
- `run-context/route.ts`: widen `useRouter` to match proxy-token's
  gate. OSS short-circuits as before. Otherwise: router mode + card
  on file → mint; router mode + no card + positive balance → fetch
  balance, mint if > 0. Skip the balance read when a card is on file
  (auto-reload covers it without needing pre-flight balance — keeps
  the hot path single-query).
- `action/utils/proxy.ts`: drop the redundant `isInfraCovered` check.
  `ctx.proxyModel` IS the signal — the server is the authority on
  funding decisions; the action just trusts and mints.
- `wiki/pricing.md`: correct the Router proxy key minting gate row
  + add a paragraph explaining why this gate diverges from
  `isInfraCovered`.
- `wiki/billing.md`: rewrite the misleading "proxy-token returns 402"
  paragraph to describe what actually happens at both routes.

`isInfraCovered` is unchanged. It still gates Pullfrog-paid features
(learnings writes, indexing). The bug was in conflating "Pullfrog
pays for marginal infra" with "user can fund a Router run via wallet"
— different concerns, now untangled.

* action: drop dead isInfraCovered + plan param post-fix

Cleanup the action-side dead code introduced by the previous commit's
removal of the redundant `isInfraCovered` re-derivation in proxy.ts:

- delete `isInfraCovered` from action/utils/runContext.ts (was the only
  callsite; mirror in server's utils/billing.ts is unchanged and still
  load-bearing for learnings/indexing)
- drop unused `plan: AccountPlan` param from `resolveProxyModel` /
  `runProxyResolution` (and the corresponding `AccountPlan` import +
  the `plan: runContext.plan` arg at the main.ts call site)
- update the action/mcp/server.ts comment that pointed at the now-gone
  action mirror to reference the server-side `utils/billing.ts` instead

`AccountPlan` itself is still load-bearing (mcp/server, runContextData,
run-context fetch), only `isInfraCovered` and the dead `plan` parameter
go away.
2026-05-20 02:10:29 +00:00
Colin McDonnell 8e36f76cfa postrun: thread AgentRunContext through the retry loop instead of repackaging (#652)
* postrun: thread AgentRunContext through the retry loop instead of repackaging

drop the per-gate plumbing in `runPostRunRetryLoop`: the loop now receives
`ctx: AgentRunContext` whole and reads `ctx.stopScript` + `ctx.toolState.*`
directly. `getUnsubmittedReview` becomes a pure utility in postRun.ts
instead of a closure shipped over `AgentRunContext`. `AgentRunContext`
loses 4 fields that duplicated `toolState` (`summaryFilePath`,
`summarySeed`, `learningsFilePath`, `getUnsubmittedReview`) and gains
`toolState: ToolState`. both harness call sites collapse from 11 lines to
7; main.ts deletes the inline closure.

`ToolState` and friends move from `action/mcp/server.ts` to
`action/toolState.ts` so non-MCP code (agents, post-run loop) stops
importing run-state types from the MCP server module.

no behavior change. 503/503 tests green.

* toolState: relocate `CommentableLines` to break dep cycle with mcp/review

`action/toolState.ts` was importing `CommentableLines` from
`mcp/review.ts`, which pulled the entire MCP server compile graph (24
files) into any consumer of `ToolState` — including `cf-worker-indexing`
via the `pullfrog/internal` re-export chain through `utils/log.ts` →
`agents/shared.ts` → `toolState.ts`. that exposed a pre-existing TS
error in `mcp/issueEvents.ts` (octokit types resolve differently under
cf-worker's `moduleResolution: bundler`).

move `CommentableLines` (a small `{ RIGHT: Set<number>; LEFT: Set<number> }`
state-shape type) to `toolState.ts` where it's used; re-export from
`mcp/review.ts` for back-compat with test and call-site imports. cuts
cf-worker's mcp/ compile inclusion from 24 files back to 0.

* postRun: drop mock-heavy retry-loop tests; keep pure gate predicate

`runPostRunRetryLoop` and `executeStopHook` were covered by ~560 lines
of mock-heavy regression-gate tests that stubbed `spawn` / `getGitStatus`
and fabricated `AgentRunContext` to drive orchestration paths. per
AGENTS.md ("prefer no test over a mock-heavy test that only catches the
most obvious form of regression") and the empirical track record — the
one real production failure of this code path (#646) was a missing npm
release, not a logic bug a unit test could catch — the value-to-ceremony
ratio is poor. delete them.

keep only the pure predicate: `getUnsubmittedReview(toolState)` is a
decision function whose four input conditions have user-visible
consequences when wrong. 5 assertions, no mocks, no ctx fabrication.

488 tests still pass.

* toolState: import PrepResult from prep/types.ts, not the barrel

same dep-cycle class as the previous CommentableLines fix. importing
PrepResult from prep/index.ts pulled prep/installNodeDependencies.ts
into the Next.js production build's typecheck graph (via
pullfrog/internal → utils/log.ts → agents/shared.ts → toolState.ts →
prep/index.ts → installNodeDependencies.ts), and Next.js's stricter
NODE_ENV-required ProcessEnv shape rejected an existing
`env: { PATH: ... }` literal.

prep/types.ts is a leaf module with zero imports — re-routing the type
import severs the chain. Vercel preview deploy goes from Error → Ready;
preview-sync stops racing the deploy.
2026-05-11 18:47:08 +00:00
David Blass 10aeaf8c11 action: dedupe identical reply_to_review_comment calls within a session (#623)
* action: dedupe identical reply_to_review_comment calls within a session

PR #610 reproduced a Kimi K2 stutter where the agent's tool_use surface
showed one `pullfrog_reply_to_review_comment` call but GitHub recorded
two byte-identical POSTs 3s apart, leaving a duplicate response on
`action/mcp/review.ts:14`.

Add `duplicateReplyDecision` (mirrors `duplicateReviewDecision`) and
track per-session replies on `ToolState.reviewReplies`, keyed by
parent `comment_id` + `bodyWithFooter`. Identical re-emissions short
circuit with `{ skipped: true, reason }` instead of POSTing again.
Body-keyed (not just id-keyed) so legitimate follow-up replies with
different content still go through.

Tighten `AddressReviews` step 5 to say *exactly once per comment* and
note that the runtime dedupes identical bodies, so the agent has both
prompt-level guidance and a server-side guarantee.

Co-authored-by: Cursor <cursoragent@cursor.com>

* address review: drop stale file ref in dedupe comment; soften tool description

* remove comment.test.ts

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-05-09 00:30:51 +00:00
Colin McDonnell 85d25a6fe6 post-run gate: fail review-mode runs that don't submit a review or progress (#638)
* post-run gate: fail the run when review mode finishes without a review or progress

review-mode runs that ended in a text-only assistant turn ("now I have enough
to draft the review...") were silently swallowed: the progress comment was
deleted by stranded-comment cleanup and no review appeared on the PR. user-
visible result was identical to "the agent never ran." caught in
https://github.com/pullfrog/app/actions/runs/25583698781.

new post-run gate alongside stopHook / dirtyTree / summaryStale: derived
inline from toolState (selectedMode in {Review, IncrementalReview} && !review
&& !finalSummaryWritten && hadProgressComment) — no parallel toolState flag.
when it fires, the resume prompt nudges the agent to call either
create_pull_request_review or report_progress; persistent failure after
MAX_POST_RUN_RETRIES surfaces as AgentResult.error.

also: when the post-run loop returns success=false, write the error to the
progress comment before the stranded-comment cleanup runs, and skip the
delete in that case. previously a !success run from the loop would lose the
error message into the void.

IncrementalReview's trivial-skip branch now calls report_progress with a
brief "no review warranted" note instead of exiting silently — keeps the
contract symmetric with the gate and gives the user a visible signal even
on no-op review runs.

documents the literal-record design rule on the ToolState interface so
future fields don't drift back into derived/absence-encoding state.

* review feedback: mode-aware nudge, gate-error preservation, prompt order

addresses three findings from the auto-review on this PR:

1. Review mode nudge no longer offers `report_progress` as an exit. Review
   mode's contract (modes.ts step 5) forbids it; the gate previously sent
   contradictory copy. IncrementalReview's nudge still offers both since
   its trivial-skip path legitimately allows `report_progress`.

2. `writeJobSummary` is now wrapped in try/catch on the success-path
   cleanup. without this, a throw there jumped to the outer catch and
   overwrote the gate's failure message in the progress comment with the
   (less actionable) writeJobSummary error — restoring exactly the
   invisible-failure UX this PR fixes. step-summary writes are
   informational; let them fail silently.

3. `buildPostRunPrompt` reorders gates to match the terminal hard-fail
   order: `stopHook` → `unsubmittedReview` → `dirtyTree` → `summaryStale`.
   when both hard-fail gates co-fire (rare in review modes), the prompt's
   emphasis now matches the user-visible failure message.

new test asserts the IncrementalReview nudge offers both exits while the
Review nudge offers only `create_pull_request_review`. e2e validation
already passed against pullfrog/preview-638-review-stop-hook PR #1
(gate fired once; agent recovered on second turn).

* mode-aware terminal error copy

second auto-review caught a residual contradiction: the terminal hard-fail
error string reported "create_pull_request_review or report_progress" for
both modes, even though the new mode-aware nudge tells Review-mode agents
"Review mode does not have a no-submit exit". the error message now mirrors
the nudge — Review names only `create_pull_request_review`,
IncrementalReview lists both. additional Review-mode hard-fail test asserts
the absence of `report_progress` in the error.
2026-05-09 00:14:31 +00:00
Colin McDonnell d6de1c369a learnings: edit-in-place tmpfile (drop update_learnings tool) (#635)
* learnings: edit-in-place tmpfile (drop update_learnings tool)

learnings now follow the PR-summary file pattern: server seeds
`pullfrog-learnings.md` from `Repo.learnings` at startup, agent reads
it as part of context, may edit in place during the post-run reflection
turn, server reads back at end-of-run and PATCHes if changed.

motivation: `update_learnings` required the agent to pass the FULL
merged list as a string parameter — an output-token tax that grew
linearly with the learnings size, and a constant prompt-context
expansion since the contents were also inlined into the LEARNINGS
section. for repos with mature learnings the prompt was getting
visibly noisy in CI logs.

key changes:
- new `action/utils/learnings.ts` (seed/read helpers + 10k cap)
- `main.ts`: always seed; `persistLearnings` mirrors `persistSummary`
  (success path, error path, exit-signal handler, idempotent guard,
  byte-trim equality skip); forwards `model` for `LearningsRevision.model`
- `LEARNINGS` prompt section now contains only the file path + a
  one-line "read it" instruction (no contents inlined)
- `update_learnings` MCP tool deleted; `action/mcp/learnings.ts` removed
- reflection turn (`buildLearningsReflectionPrompt`) reframed around
  file editing with explicit prune-stale + leave-alone-if-nothing-new
  framing
- `learningsStep` removed from every mode checklist — surface lives only
  in the LEARNINGS prompt section + the reflection turn now

* learnings: harden seed step + refresh stale docs (review feedback)

Three findings from PR review, all implemented:

1. wrap learnings seed in best-effort try/catch (action/main.ts) —
   the always-on seed block ran unconditionally and an unwrapped
   `seedLearningsFile` (mkdir + writeFile) failure (ENOSPC, EACCES,
   hostile sandbox) would unwind into the outer main() catch and flip
   an otherwise-successful run to " Pullfrog failed" before the
   agent even started. asymmetric with `persistLearnings`'s own
   best-effort contract. wrap and log on failure; downstream
   consumers (`persistLearnings`, agent harnesses, `resolveInstructions`)
   already handle `learningsFilePath: undefined` cleanly.

2. refresh wiki/main.md — `resolveInstructions` parameter renamed
   from `learnings` to `learningsFilePath` in this PR; the data-flow
   diagram and the resolver dependency table both still showed the
   pre-refactor signature.

3. drop deleted `learnings.ts` from ROADMAP.md + RESEARCH.md
   "missing MCP tool tests" bullets — `action/mcp/learnings.ts` was
   removed in this PR; the bullets are otherwise still accurate.
2026-05-08 22:45:26 +00:00
Colin McDonnell e4e93ea6d3 PR summary as agent-edited tmpfile snapshot (#568)
* PR summary as agent-edited tmpfile snapshot

Replaces the comment-based PR summary path (and the in-progress
update_pr_summary tool from #534) with a snapshot file the agent edits in
place during Review / IncrementalReview / pr-summary Task runs.

The server seeds the tmpfile with the previous snapshot (incremental) or a
stable scaffold (first run), exposes the path via select_mode, and reads it
back at end-of-run to persist to WorkflowRun.summarySnapshot and (when the
prSummaryComment toggle is on) splice into the PR description body.

Why a tmpfile rather than a tool call: incremental snapshot edits are
output-token-cheap when the agent uses native file-editing tools, and
range-diff cleanly across runs because section headings are stable. The
agent never has to regurgitate the full snapshot to update it.

Gating: snapshot generation is opt-in via either prSummaryComment="enabled"
(splice into PR body) or prReReview="enabled" (snapshot feeds future
incremental review runs as context). Users who disable both pay nothing
end-to-end — no seeding, DB write, or body splice.

Behavior changes:
- Drop the Summarize mode and the Summary comment type entirely; the
  rolling summary is no longer a separate run shape.
- pull_request_synchronize with re-review off and summary on still
  dispatches a silent pr-summary Task, but it edits the snapshot file
  instead of posting a fresh comment.
- /api/repo/.../pr/.../summary-comment now returns
  { snapshot: string | null } from the DB instead of fetching a comment via
  GraphQL. URL kept stable so deployed older actions degrade gracefully.
- summaryCommentNodeId is retained on WorkflowRun for legacy data and a
  future backfill of pre-snapshot comment-based summaries.

Supersedes #534. The commit-tool/sub-agent direction in that PR is
abandoned in favor of this file-based shape.

* address review pass #1: synchronize fallback, splice idempotency, docs

* address review pass #2: in-flight skip should not race summary fallback

* address review pass #3: signal-handler flush, doc clarifications

* address review pass #4: in-flight persist promise + bounded body-splice timeout

* address review pass #5: defensive catch on persist worker, doc nit

* add summary-stale post-run gate

When generateSummary is set, we capture the bytes of the seeded snapshot
file and pass them to the agent's post-run loop alongside the file path.
After each agent attempt, the loop diffs the current file against the
seed; if they're byte-identical the agent never touched it, and we nudge
once via a resume turn (similar to the dirty-tree gate, but soft and
fire-once so smaller models that legitimately decide no edit is warranted
don't burn the retry budget).

Mostly defends against forgetful smaller models on the Review path —
their mode prompt asks them to edit the snapshot file, but the
multi-step instruction can fall through when the diff is large.

* trigger: retry vercel preview build

* fix(action): drop unused re-export that pulled node:fs/promises into next bundle

action/internal/index.ts was re-exporting DEFAULT_PR_SUMMARY_INSTRUCTIONS
from action/utils/prSummary.ts, but nothing in the next.js app imports
it. prSummary.ts uses node:fs/promises, and pullfrog/internal is aliased
into the next bundle by next.config.ts, which made turbopack try to
resolve node:fs/promises in client chunks and fail with:

  the chunking context (unknown) does not support external modules
  (request: node:fs/promises)

drop the re-export — selectMode.ts (the only real consumer) already
imports it directly from action/utils/prSummary.ts.

* firewall PR summary snapshot from user instructions; resurrect rich format for Review

The agent-internal snapshot (the markdown file the agent edits in place across
runs) is exclusively durable context for future agent runs — user-supplied
summarization instructions warp it and degrade that context. Drop the
prSummaryCommentInstructions read path end-to-end:

- handleWebhook: stop reading prSummaryCommentInstructions, stop passing
  prSummaryInstructions through dispatch options
- action payload + ToolState + selectMode addendum: drop the instructions
  appendix; the snapshot prompt is fixed, not user-shaped
- TriggersSettings: drop the InstructionsEditor for prSummaryCommentInstructions
- prSummary.ts: reframe DEFAULT_PR_SUMMARY_INSTRUCTIONS as agent-targeted
  (durable context, not human-facing prose)

Prisma columns (prSummaryComment, prSummaryCommentInstructions) and the
matching zod schema entry stay for graceful retreat.

Separately, resurrect PR_SUMMARY_FORMAT (deleted along with the Summarize mode
in the original PR) and wire it into Review mode only. Initial PR reviews now
include a structured summary section in the review body using the rich format
(TL;DR, key changes, ## sections with before/after, file-link trails).
IncrementalReview keeps its existing terser bullet-list shape since re-review
bodies are deltas, not introductions. The user-facing review summary and the
agent-internal snapshot are deliberately separate artifacts with separate
prompts and zero shared content.

* address review comments: prompt self-consistency + stale-doc cleanup

PR 568 self-review (4232488109) flagged a self-contradiction the firewall
commit introduced and three stale doc references that survived.

- action/modes.ts: Review-mode step 2's trivial-PR shortcut said `submit
  "Reviewed — no issues found." per step 5`, but step 5's rewrite removed
  exactly that preamble. Aligned both: trivial PRs and no-actionable-issues
  PRs now produce a body that opens with "No new issues found." followed by
  the PR summary, so the user gets the headline up front and still sees what
  was reviewed.
- docs/pr-reviews.mdx: dropped the "customize the summary style with Summary
  instructions in the console" sentence (the editor was removed in the
  firewall commit). Replaced with a note that the snapshot uses Pullfrog's
  built-in format and is not user-customizable.
- wiki/prompt.md, wiki/modes.md: rewrote the snapshot-prompt entries to
  reflect the firewall — DEFAULT_PR_SUMMARY_INSTRUCTIONS is the entire
  prompt, prSummaryCommentInstructions is no longer wired in.

* drop orphaned prSummaryCommentInstructions column

Prod audit (455 repos): 5 non-null rows on a single account, all containing the
literal placeholder text from the InstructionsEditor we removed in the firewall
commit. No account has an intentional preference set, so silent-ignore (the
keep-for-retreat option) costs us nothing meaningful while leaving an orphan
column in the schema. Drop it.

- prisma/schema.prisma: remove the column
- prisma/migrations/20260506000000_drop_pr_summary_comment_instructions:
  ALTER TABLE ... DROP COLUMN
- utils/schemas/triggers.ts: drop the matching zod entry

* drop body splicing; snapshot is internal-only

User-visible PR summarization continues to ship in Review and IncrementalReview
review bodies (which already render PR_SUMMARY_FORMAT and "Reviewed changes"
respectively). The snapshot tmpfile is now purely durable cross-run agent
context — seed, edit-in-place, save to DB, feed the next run. Massive
simplification: the body splice mechanics, the two-toggle gating matrix, the
summaryHandlingCovered race tracking, and the synchronize summary-only Task
fallback all go away.

Code:
- prSummary.ts: drop splice/strip/marker code (`splicePrSummary`,
  `stripExistingSummaryBlock`, `buildSummaryBlock`, `extractPrSummary`,
  PULLFROG_SUMMARY_START/END). keep scaffold, instructions, seed/read.
- main.ts: rename persistAndPostSummary -> persistSummary; collapse to a
  single DB PATCH. drop pulls.get/pulls.update, drop AbortSignal timeout,
  drop in-flight promise machinery, drop prSummaryToBody plumbing.
- ToolState: add summarySeed (replaces local var in main.ts so persist can
  compare). drop prSummaryToBody and summaryPersistInFlight.
- persistSummary now compares against the seed and skips the DB write
  with a warning when unchanged — saving the seed verbatim is either a
  no-op or persists the placeholder scaffold, neither useful.
- postRun.ts: when summary-stale is the only failing gate and the resume
  turn itself fails, restore the pre-resume successful result and break.
  symmetric with the existing reflection-failure preservation. summary-stale
  can no longer flip a successful run to failed.

Webhook:
- pull_request_opened: generateSummary follows prReReview only (the snapshot
  has no consumer when re-review is off).
- pull_request_synchronize: collapses to "if prReReview enabled, dispatch
  IncrementalReview". the summaryHandlingCovered flag, the same-SHA/in-flight
  coordination it was protecting, and the summary-only Task fallback all
  delete cleanly.

UI / config:
- drop SummarizePRsTrigger (the toggle gated body splice; with that gone
  it has no behavior). drop sidebar entry, console import, Text icon import.
- drop prSummaryComment from triggers zod schema, prisma schema, preview
  settings script.

Migration: squash the two existing migrations into one timestamped
20260507000000_pr_summary_snapshot covering all three column changes
(add summarySnapshot on workflow_runs, drop prSummaryCommentInstructions
and prSummaryComment on repos). repo convention is one migration per PR.

Action: bump 0.0.203 -> 0.0.205 (payload contract changed: prSummaryToBody
removed; main is at 0.0.204).

Out-of-diff cleanup:
- review.ts:190 + review.test.ts:651 — "Reviewed — no issues found." ->
  "No new issues found." to match the canonical body in modes.ts.

Verified: pnpm typecheck clean, pnpm lint clean, postRun + review tests
pass, dev DB reset against production and the squashed migration applied
cleanly (summarySnapshot present, prSummaryComment / prSummaryCommentInstructions
both gone).

* re-orient snapshot toward functional summary; drop prior-review-feedback section

Empirical audit on preview-568 PR #5 showed the snapshot IS load-bearing
for the orchestrator: lens-dispatch prompts on incremental runs carried
forward context from the snapshot's risk register (e.g. "the JSDoc
explicitly scopes to code points — do not flag grapheme-cluster issues"
on the surrogate-pair fix run, "consistency with native padStart" on the
padStart-added run). The orchestrator was reading the snapshot, reasoning
about it, and using it to anti-prime / focus subagents — exactly the
high-leverage path. My earlier "snapshot is write-only" claim was wrong.

The shape, however, was steering it toward review-history-log instead of
functional summary. This commit re-orients:

- prSummary.ts: replace the four-section scaffold (~580 chars of placeholder
  italics under "What this PR does / Key changes / Risk / Reviewed in prior
  runs") with a minimal seed (~150 chars: just a header + a one-line
  comment about what the file is for). different PRs warrant different
  organization; forcing a refactor and a feature into the same template
  is procrustean. minimal seed also makes the unchanged-from-seed gate
  in persistSummary more sensitive.

- selectMode.ts addendum: rewrite around three principles. (1) the snapshot
  is a FUNCTIONAL summary of what the PR does and the risks it carries,
  not a chronological review log — commit history can already be
  reconstructed from list_pull_request_reviews. (2) the orchestrator should
  USE the snapshot during triage and dispatch — concrete example given of
  carrying snapshot context into subagent lens prompts. (3) structure is
  the agent's call; stable headings make snapshots range-diff cleanly when
  they fit, but riff when they don't.

- modes.ts IncrementalReview: drop the "Prior review feedback" checklist
  from the user-facing review body (step 6b gone, step 7 ELSE IFs cleaned
  up). It duplicated content that's already covered by the Reviewed-changes
  bullets and tracked durably in the snapshot for the next agent run; in
  the user-facing body it was noise. step 3 still fetches prior reviews
  but its role is now just filtering aggregation in step 5, not rendering.

- AGENTS.md: codify "no follow-ups" rule. when an issue is identified
  during code review, fix it in this PR — PR scope does not constrain
  quality. follow-up TODOs are forbidden as a substitute for doing the
  work now.

Empirical evidence supporting the re-orientation:

- Run 25568912293 (PR#5 incr1, surrogate-pair fix): orchestrator's
  correctness lens dispatch said "Do NOT flag grapheme-cluster issues
  — the JSDoc scopes to code points." The grapheme-cluster framing was
  not in the diff; it was downstream of the snapshot's prior risk-section
  framing of truncate's contract. Snapshot influencing dispatch.

- Run 25569054779 (PR#5 incr2, padStart added): orchestrator's correctness
  lens dispatch enumerated edge cases including "consistency with native
  String.prototype.padStart contract" and "fill = multi-code-point string
  (e.g. emoji)". Both threads carried over from the snapshot's prior
  truncate code-point-vs-code-unit discussion. Snapshot informing the
  shape of what was looked for.

The cost of maintaining the snapshot (~800 tokens, ~$0.005/run) is
trivially affordable when it materially improves orchestrator triage
on the 1-5 lenses dispatched per review.
2026-05-08 19:28:24 +00:00
Colin McDonnell 560e27bda5 refactor progress comments into a bundled type + helper module (#567)
* refactor progress comments into a single bundled type + helper module

introduce ProgressComment ({ id, type: "issue" | "review" }) as the canonical handle for
the GitHub comment a run uses to report progress, and route every read/update/delete/create
through a single helper module (action/utils/progressComment.ts). previously every site that
touched the progress comment hardcoded octokit.rest.issues.*Comment, which made adding a
second comment type (review-thread replies) require duplicating the same branch in 6+ places
— the same shape that bit pullfrog/app#445.

new capability: when the address-reviews trigger fires for a one-off review comment, the
"Leaping into action" comment is now posted as a reply in that review thread instead of as
a top-level PR timeline comment. the helper handles failure (e.g. parent comment deleted)
by silently falling back to a top-level issue comment, so the run never loses its progress
surface.

changes:

- action/utils/progressComment.ts (new) — ProgressComment type + getProgressComment,
  updateProgressComment, deleteProgressCommentApi, createLeapingProgressComment. uses a
  structural Octokit interface to bridge the @octokit/rest version mismatch between the
  action package (v22) and the root project (v21).
- action/internal/index.ts — re-export the new types and helpers for cross-boundary use.
- action/external.ts, action/utils/payload.ts — replace progressCommentId: string with
  progressComment: { id: string, type: "issue" | "review" } in WriteablePayload + JsonPayload.
  wire-format breaking, no legacy fallback (in-flight runs across the deploy lose their
  progress comment, fine).
- action/mcp/server.ts — ToolState.progressCommentId becomes
  progressComment: ProgressComment | null | undefined (same tristate semantics).
- action/main.ts, action/mcp/comment.ts, action/utils/errorReport.ts,
  action/utils/postCleanup.ts — every issues.*Comment call against the progress comment
  routes through the helper module. zero hardcoded API branching outside the helper.
- utils/github/triggerWorkflow.ts — drop createLeapingComment + updateCommentToLeaping;
  dispatchAndTrackWorkflow gains a resolution chain (existingComment → replyToReviewComment
  → triggeringIssue → none) and an existingComment: ProgressComment param plus
  replyToReviewComment: { pullNumber, commentId }.
- utils/webhooks/handleWebhook.ts — dispatch closure threads replyToReviewComment through;
  the one-off review comment branch passes it and skips the now-redundant eyes reaction
  on the comment we're about to reply to.
- app/trigger/[owner]/[repo]/[number]/page.tsx, utils/github/runActionLocal.ts,
  app/api/cli/dispatch/route.ts, app/api/dispatch-workflow/route.ts — call sites updated to
  new shape.

no schema or DB column changes. the existing WorkflowRun.progressCommentId column is still
written by id only; type lives only on the in-flight payload, which is sufficient for
runtime since it's the only thing that needs to know which API to call.

* anneal pass 1: fallback visibility + stale doc/comment updates

- progressComment.ts: when reviewReply→issue fallback fires, prepend a [!NOTE] callout
  with a permalink back to the original review comment. without this, the parent comment
  showed no eyes reaction (deliberately skipped) and no reply, leaving the user with no
  signal that anything happened.
- wiki/post-cleanup.md: update progressCommentId references to progressComment, document
  the new helper-based dispatch by type.
- wiki/main.md: update initToolState({ progressCommentId }) → ({ progressComment })
  in the resolver-chain diagram.
- action/main.ts, action/mcp/review.ts: update two stale comments that referenced the
  old field name.

* anneal pass 2: post-cleanup detection through fallback notice + log cleanup

- isLeapingIntoActionCommentBody: strip a leading GFM blockquote/alert before
  testing the leaping prefix. without this, the [!NOTE] callout that the
  reviewReply→issue fallback prepends would prevent post-cleanup from
  recognizing the stuck "Leaping into action..." comment, leaving it permanently
  on the PR timeline if the workflow died before any progress update.
- progressComment helper: switch from log.warning (action-flavored, emits a
  ::warning:: GitHub Actions annotation) to console.warn so the helper doesn't
  pollute Vercel logs when invoked from the webhook context.
- triggerWorkflow.ts: drop the duplicate caller-side log on review-reply
  failure — the helper already speaks loudly. Reword the catch-branch log to
  reflect that it now only fires when both the reply AND the helper's internal
  fallback failed.
- progressComment.ts: document that the [!NOTE] fallback notice is overwritten
  on the first report_progress call, and explain the trade-off vs persisting
  it through the action payload + ToolState.

* debloat: drop the [!NOTE] fallback callout

Reverting two pieces from the prior anneal pass:

- progressComment.ts: drop the [!NOTE] callout that the reviewReply→issue fallback
  prepended to the leaping body. It disappeared on the agent's first report_progress
  call, which made it half-committed to visibility — worse than either properly
  persisting it (real engineering) or leaving the fallback silent (current choice).
  The console.warn diagnostic and the workflow-run footer link in the leaping
  comment itself give us enough signal for the rare case where both API endpoints
  fail at once.
- isLeapingIntoActionCommentBody: revert the leading-blockquote stripping; only
  needed to compensate for the [!NOTE] callout.

Keeping: the console.warn-vs-log.warning fix (real cross-runtime concern), the
duplicate-log drop in triggerWorkflow.ts, the wiki updates, and the two stale
source-comment fixes.

* fix: prevent stranded task list overwriting post-cleanup message

When a run is cancelled, the action's todoTracker may have an HTTP write in
flight to GitHub when SIGTERM lands. The action process dies, but the request
data has already left the socket — GitHub processes it and updates the comment
body to the (stale) task list. Meanwhile post-cleanup, running in a separate
process, writes the "This run was cancelled 🛑" message. If the tracker's
in-flight write happens to land *after* post-cleanup's write, the user never
sees the cancellation message.

Two-layer fix:
- Action side: cancel the tracker in the SIGTERM signal handler so no new
  debounced writes get scheduled. This shrinks the race window but can't
  un-send a request already on the wire.
- Post-cleanup side: after writing, verify the body landed and re-issue if
  another write clobbered ours. Loops up to 3× with a 3s settle delay so
  delayed in-flight writes from the dying action have time to arrive before
  our read-back check decides whether to retry.

* lint: import createLeapingProgressComment from pullfrog/internal in test script

* address bot review findings: reply-target root, version bump, GET error handling

Three real findings from the bot reviews on #567 plus a small DRY pass:

1. handleWebhook reply-target: `newComments[0]` may be a reply, not a
   top-level review comment. `getReviewCommentsWithReplies` returns root +
   replies for any thread the review touched, and `pull_request_review_id`
   filtering only narrows by *which review submitted*, not *root vs reply*.
   When a user submits a single reply as their entire review (e.g. replying
   to someone else's comment to ping @pullfrog), the reply ID flowed through
   to `createReplyForReviewComment`, which 422s on replies-to-replies and
   degraded to a top-level issue comment — exactly the polluted-PR-timeline
   behavior this PR was built to remove. Walk up `in_reply_to` from the
   already-fetched thread data to find the root and reply there instead.

2. action/package.json: bumped 0.0.202 → 0.0.204. main is at 0.0.203 and
   our wire format changed; without a bump validateCompatibility can't
   surface the mismatch on the deploy boundary, and the merge would have
   gone backwards.

3. postCleanup writeAndVerify: distinguish a thrown verify-GET from a
   "body got overwritten" mismatch. Treating a transient 5xx/rate-limit GET
   the same as a clobber wasted PUT attempts and printed a misleading
   "in-flight writes kept clobbering us" warning. We trust our PUT (which
   returned 200) and exit instead of amplifying writes against a flaky API.

4. Small DRY: extracted parseProgressComment for the
   `{ id: string; type } -> ProgressComment` parse that had drifted across
   server.ts and postCleanup.ts.
2026-05-06 01:50:58 +00:00
Colin McDonnell e58299740d Merge pull request #545 from pullfrog/billing
managed billing + stripe v1
2026-05-05 19:33:46 +00:00
David Blass 57bd10d6dd run-issues fixes: #5, #11, #12, #15, #16/#25, #20, #21, #22, #31 (#546)
* 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>
2026-04-20 21:12:17 +00:00
Colin McDonnell c608051b79 sanitize mcp schemas for Gemini; fix gpt-codex-mini alias; add matrix filter
Gemini's generateContent API rejects arktype's `{anyOf:[{enum:[...]}]}` string-enum
encoding, `$schema` metadata, and `anyOf` with sibling fields. Port the old
sanitizer back as an isolated module (action/mcp/geminiSanitizer.ts) and gate it
on `isGeminiRouted(ctx)` so non-gemini routes see the original schema. Wires
`resolvedModel` onto ToolContext so the sanitizer can see the upstream specifier.

Also bumps `openai/gpt-codex-mini` alias from the deprecated `codex-mini-latest`
to `gpt-5.1-codex-mini`, matching the openrouter resolve.

Adds a `filter` workflow_dispatch input + MATRIX_FILTER env that restricts the
models-live matrix to aliases matching a substring, so we can iterate on a
single provider (e.g. `filter=gemini`) without paying to run every model.
2026-04-16 23:09:32 +00:00
Colin McDonnell 56a5d29598 add diff coverage preflight for PR review submissions (#544)
* add one-time diff coverage preflight for PR reviews

track diff read coverage from agent tool-use events and run a one-time pre-flight before review submission, with explicit coverage skip reasons for low-value files like lockfiles.

Made-with: Cursor

* add manual dispatch fallback for preview deploy workflow

allow preview repo and preview sync jobs to be run via workflow_dispatch with explicit PR number and branch inputs, so preview provisioning can be retriggered when pull_request events fail to fire.

Made-with: Cursor

* fix manual preview dispatch PR input wiring

use normalized PR number and branch env values for comment creation and script env wiring so workflow_dispatch preview runs can create and update PR-specific preview resources.

Made-with: Cursor

* remove obsolete snapshots invalidated by checkout instructions change

* fix diff coverage read offset handling and add local sanity-check guidance

normalize read offset semantics for diff coverage tracking, reuse shared range counting in review preflight, add focused diff coverage unit tests, and document the local play.ts testing workflow in AGENTS.md.

Made-with: Cursor

* add regenerated mcp test snapshots

capture snapshot files generated by the review comment and checkout formatting tests during pre-push validation so the branch remains clean and reproducible.

Made-with: Cursor

* add diff coverage preflight instrumentation logs

log diff coverage initialization in checkout_pr and emit preflight state/breakdown diagnostics in create_pull_request_review to debug missing coverage enforcement in preview e2e runs.

Made-with: Cursor

* add env override to force local cli execution in action runtime

support explicit local-cli execution via PULLFROG_FORCE_LOCAL_CLI so preview workflows can run branch action code instead of the npm fallback package during e2e debugging.

Made-with: Cursor

* add preview e2e debugging learnings for action runtime validation

capture the preview execution-path gotchas and one-time preflight verification pattern in AGENTS.md so future investigations validate the real runtime and avoid npm fallback confusion.

Made-with: Cursor

* reduce diff coverage log noise while preserving failure visibility

downgrade verbose diff coverage lifecycle diagnostics to debug, keep a concise info-level pre-flight failure signal, and document preview runtime debugging learnings in AGENTS.md.

Made-with: Cursor

* WIP

* tune sync.md: ff override + softer overlap verification

Made-with: Cursor

* chore: bump models snapshot for claude-opus-4-7

Made-with: Cursor

* rip out coverage_skips waiver from diff coverage pre-flight

Made-with: Cursor

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-04-16 21:51:44 +00:00
Colin McDonnell b9b6503315 reorder prompt sections: task-first with dynamic TOC (#513)
* reorder prompt sections: task-first with dynamic TOC

put the actual task at the top of the prompt for primacy, add a
dynamic table of contents, and push system/runtime metadata to the end.

new section order: TOC → YOUR TASK → PROCEDURE → EVENT CONTEXT →
SYSTEM → LEARNINGS → RUNTIME

Made-with: Cursor

* enforce clean working tree: continue session if agent leaves uncommitted changes

after each agent run, check `git status --porcelain`. if dirty, resume
the same session with instructions to commit on a new branch, push, and
open a PR. retries up to 3 times before giving up.

- claude code: capture session_id from result event, use --resume <id>
- opencode: use --continue to resume the last session
- remove --no-session-persistence from claude (needed for --resume)
- update Task mode to clarify branch/push/PR is the default finalize step

Made-with: Cursor

* log full prompt in collapsible group for debugging

Made-with: Cursor

* fix: format tool refs in buildCommitPrompt via formatMcpToolRef

* enforce clean git status: general instructions, stop hook, and Task mode

Made-with: Cursor

* fix: rename stale titleBody references after body leak fix

Made-with: Cursor

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-04-04 19:37:44 +00:00
Mateusz Burzyński a7b8dcbced Rework incremental diffing (#499)
* Improve our deepening logic

* Use consistent SHA for PR-related operations in CheckoutPrTool

* compute `deepenDepth` at more appropriate time

* fix stale comment

* add comments for `alreadyOnBranch`

* ensure before sha is available

* small cleanup

* computeIncrementalDiff

* move the util

* improve algorithm

* improve algorithm further

* get rid of temp result array

* add comment

* compute incremental diff and updte instructions

* add comment

* update stale comment

* get rid of redundant rev-parse call

* improve comment

* strenghten the instructions

* make diff paths unique
2026-03-27 16:09:13 +00:00
Colin McDonnell cb8e33360c feat: add prepush lifecycle hook (#498)
* feat: add prepush lifecycle hook

Add `prepushScript` configuration — an optional shell script that runs
automatically before pushing code to the remote repository. Reuses the
existing `executeLifecycleHook` infrastructure (bash execution, 2-min
timeout, error propagation on non-zero exit). When unconfigured the
hook is a no-op.

Made-with: Cursor

* fix: add prepushScript to run-context API response, fix UI separator

Include prepushScript in the settings returned by the run-context
endpoint so the hook actually fires in production. Also fix the
separator pattern in AgentSettings to match the existing convention
(spacer + hr + spacer instead of margin).

Made-with: Cursor
2026-03-26 04:28:24 +00:00
Mateusz Burzyński c0f6f9ef2a Browser skill (#485)
* Add `BrowserTool`

* add some logging

* go with npm install -g

* remove dep changes since the switch to npm install -g

* tweak

* tweak

* tweak

* tweak

* tweak timeout

* tweak

* remove logs

* skill investigation doc

* wip

* wip

* tweak

* lock agent-browser version

* tweak

* logs

* logs

* more logs

* more debug stuff

* try this

* try this

* try this

* fix PATH

* try this

* tweak

* tweak

* tweak

* update wiki entries

* update wiki once again

* lint fix

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-03-25 19:36:13 +00:00
David Blass 6b18b6730b live todo tracking, collapsible task list in final progress, hide set_output outside standalone (#492)
* fix false "without reporting progress" error + live todo tracking

clean up orphaned progress comments when review is skipped or only
set_output is used, preventing the false positive in handleAgentResult.

parse todowrite events from OpenCode's NDJSON stream and render a
live markdown checklist in the PR progress comment (2s debounce).
agent's explicit report_progress always takes priority.

Made-with: Cursor

* fix contradictory review/progress prompting

align Review and IncrementalReview mode prompts with their guidance —
mode prompts said "always submit" while guidance said "skip if clean."
remove the empty-approval submission that was silently dropped by the
tool. make progress comment lifecycle explicit: created on first call,
updated in place, removed after review submission.

Made-with: Cursor

* centralize todo tracking into shared TodoTracker module

extract inline todo tracking logic (~95 lines) from opentoad.ts into
action/utils/todoTracking.ts. the tracker is created once in main.ts
and passed to agents via AgentRunContext.todoTracker, making it
agent-agnostic and reusable for future agent implementations.

Made-with: Cursor

* fix todoTracker optional type to match file convention

add | undefined to todoTracker in AgentRunContext, matching every
other optional property in the same interface.

Made-with: Cursor

* instruct agents to always maintain a task list for live progress

system prompt now tells agents to create an internal task list at
the start of every run. the tracker renders it to the progress
comment automatically. report_progress is reserved for final
results only — no more intermediate "Checking..." messages that
cancel the tracker and leave stale text on the comment.

Made-with: Cursor

* require report_progress summary at end of every run

agents must always call report_progress with a final summary —
the completed task list should never be the end state of the
progress comment. updated all review mode prompts to call
report_progress after submitting (or not submitting) a review.

Made-with: Cursor

* keep progress comment after review with final summary

stop deleting the progress comment after review submission —
the agent now always calls report_progress with a summary at
the end, and that summary should persist as a record of what
was done.

Made-with: Cursor

* harden stranded progress comment cleanup

- main.ts: detect when tracker was last writer (agent never called
  report_progress) and delete the stranded checklist instead of
  leaving it as the final comment state
- postCleanup.ts: expand stuck-comment detection to also catch
  stranded todo checklists (regex match for checklist patterns)
  when the process is killed before normal cleanup runs
- modes.ts + selectMode.ts: add report_progress step to Summarize
  and SummaryUpdate modes (only modes that were missing it)

Made-with: Cursor

* fix stale comments, typo, and build mode redundancy

- comment.ts: update deleteProgressComment docstring and inline comment
  to reflect current usage (stranded-comment cleanup, not post-review)
- modes.ts: merge duplicate report_progress steps (8 + 10) into single
  step 9, fix "optimizatfixons" typo
- wiki/post-cleanup.md: document checklist detection regex

Made-with: Cursor

* collapsible completed todos in final progress, hide set_output outside standalone mode

- add renderCollapsible() to TodoTracker, append completed task list as
  <details> section when agent calls report_progress
- cancel tracker after agent's final report_progress so it doesn't
  overwrite with raw checklist
- conditionally register SetOutputTool only in standalone mode or when
  output_schema is provided
- remove unconditional set_output instruction from orchestrator task section
- update Summarize/SummaryUpdate mode guidance to not reference set_output

Made-with: Cursor

* show completion count in collapsible task list summary

Made-with: Cursor

* only count completed (not cancelled) in collapsible task list summary

Made-with: Cursor

* reinforce concise summary prompting across system prompt, modes, and tool description

Made-with: Cursor

* address review feedback: wasUpdated bypass, tracker false-positive, race condition

- remove wasUpdated=true from cleanup paths so handleAgentResult correctly
  detects genuinely silent runs
- add hadProgressComment to ToolState as immutable snapshot for the safety check
- use todoTracker.hasPublished instead of enabled for stranded-comment cleanup
- serialize onUpdate calls via inflightPromise chain with post-cancel guard
- add settled() to wait for in-flight updates before writing final summary

Made-with: Cursor

* address round-2 review: hasPublished after success, finalSummaryWritten flag

- set hasPublished only after onUpdate resolves (not before) so failed
  writes are not counted as published
- add finalSummaryWritten flag to ToolState, set after successful
  non-plan reportProgress; decouple cleanup detection from
  todoTracker.enabled so it survives API failures where cancel() ran
  but the write didn't succeed

Made-with: Cursor
2026-03-25 19:35:31 +00:00
David Blass 64f2238316 Repo Intelligence: agent-managed per-repo learnings with revision history (#487)
* add repo learnings feature with edit history

introduces a new "Learnings" section in the repo console where agents can
persist operational knowledge (setup steps, test commands, conventions) at
the end of runs via an MCP tool. users can also edit learnings manually.

- add `learnings` field to Repo model and `LearningsRevision` audit table
- add `update_learnings` MCP tool for agents to persist repo knowledge
- integrate learnings into prompt assembly as REPO LEARNINGS section
- add learnings step to mode guidance (Build, AddressReviews, Plan, Fix, Task)
- add PATCH /api/repo/[owner]/[repo]/learnings endpoint (JWT auth)
- add GET /api/repo/[owner]/[repo]/learnings/history endpoint (Clerk auth)
- add LearningsSection component with textarea, save-on-blur, and history modal
- record revision history with actor tracking (agent vs user) and pruning (50 max)
- gate UI behind owner === "pullfrog" for internal dogfooding

Made-with: Cursor

* fix prisma enum import path for LearningsActor

Made-with: Cursor

* simplify learnings schema: remove LearningsActor enum, store model name directly

the actor/actorName split was unnecessary — learnings are only written by
agents so the revision table just needs a model column. removes all user
editing concepts from schema, API, and frontend.

Made-with: Cursor

* fix migration: add separate migration instead of rewriting existing one

restores original learnings_revisions migration and adds a new migration
that drops actor/actorName columns, backfills model from actorName, and
drops the LearningsActor enum.

Made-with: Cursor

* polish learnings feature: rename to Repo Intelligence, fix atomicity, fix review skip

- rename user-facing "learnings" to "Repo Intelligence" (UI, prompt section, wiki, sidebar)
- simplify description to "Automatically discovered by the agent across runs."
- wrap repo.update + revision create in $transaction for atomicity
- refactor recordLearningsRevision to pruneLearningsRevisions (prune-only)
- fix empty review skip: don't block APPROVE reviews with no body
- fix broken docs anchor: #free-options → #free-models
- update agent guidance to require flat bullet list format with pruning
- add accessibility: aria-expanded, sr-only loading, output element
- add chevron rotation, stale data clear on modal close, max-h scroll
- trim + length-limit model field, remove type cast, restore pre-existing comment
- update wiki prompt examples with actual bullet-formatted content
- update model test snapshot

Made-with: Cursor

* fix stale free model name in docs, rename utility file to match export

- docs/keys.mdx: MiMo V2 Flash → MiMo V2 Pro (matches model code change)
- rename recordLearningsRevision.ts → pruneLearningsRevisions.ts

Made-with: Cursor

* Add skill, .neon

* polish learnings UI and remove verbose log

- learnings code block: read-only appearance with muted text, copy button, rounded corners
- history modal: full-width rows with cursor-pointer, chevron moved to right, no preview text
- drop noisy update_learnings log line

Made-with: Cursor

* inject learningsStep into all modes, drop seed script, soften revision styling

Made-with: Cursor

* Drop seed

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-03-25 19:15:43 +00:00
Colin McDonnell c6a3ee0e9a show model name in footer, drop pullfrog.com link (#484)
* show model name in footer, drop pullfrog.com link

add model slug to buildPullfrogFooter so every Pullfrog comment
displays the active model (e.g. "Using `Big Pickle` (free)" or
"Using `Claude Opus`"). remove the pullfrog.com link from all footers.

Made-with: Cursor

* reject <br/> tags in comment bodies, add prompt guidance

add runtime validation in addFooter that throws if <br/> is followed
by a non-blank line (breaks GitHub heading rendering). the agent sees
the error and retries with clean markdown. also update Summarize mode
prompt to explicitly forbid <br/> tags.

Made-with: Cursor

* fix <br/> guidance: move to event instructions, clarify blank line rule

the formatting rule belongs in DEFAULT_PR_SUMMARY_INSTRUCTIONS (event
instructions), not the Summarize mode prompt. clarify that <br/> must
always be followed by a blank line before headings.

Made-with: Cursor

* generalize block-level HTML rule in summary instructions

add a prominent top-level rule about requiring blank lines between ALL
block-level HTML elements and markdown syntax, not just <br/>.

Made-with: Cursor

* move model to toolState instead of threading through params

model is set once at startup and read everywhere — it belongs on
toolState, not threaded as a separate param through 8 call sites.
postCleanup runs without toolState so it just omits the model label.

Made-with: Cursor

* update models.dev snapshot (openai latest changed)

Made-with: Cursor

* add comment to models snapshot test explaining its purpose

Made-with: Cursor
2026-03-17 19:59:11 +00:00
Colin McDonnell 4a8c432a48 add Summarize mode for updatable PR summary comments (#470)
* add Summarize mode for updatable PR summary comments

Introduces a Summarize mode that manages a single summary comment per PR,
updated in place on subsequent pushes. Mirrors the Plan/PlanEdit pattern:
API endpoint for existing-comment lookup at select_mode time, node ID
tracking on WorkflowRun, and SummaryUpdate guidance for edits.

Also fixes summary format instructions: Before/After uses inline <br/>
to avoid double line breaks, metadata line placed after key changes,
SHA-256 anchor instructions strengthened against fabrication.

Made-with: Cursor

* fix pre-existing lint error in checkout.ts

Made-with: Cursor

* fix dead restricted param in deepenForBeforeSha

GitAuthOptions dropped the restricted field in the ASKPASS refactor (#478)
but deepenForBeforeSha (#471) still passed it. Remove the field and the
now-unused shell param from DeepenForBeforeShaParams.

Made-with: Cursor
2026-03-12 05:32:17 +00:00
Colin McDonnell 6d25adfd1a Agent & model refactor (#478)
* agent & model refactor with ASKPASS git auth, UI restructure, clerk v7

Made-with: Cursor

* fix stale agent/effort refs, add tests for askpass + model resolution

- reviewCleanup.ts: payload.agent -> payload.model, remove effort
- selectMode.ts PlanEdit: remove delegation/subagent/effort references
- pullfrog.yml.ts: update env vars (drop GOOGLE_API_KEY/CURSOR_API_KEY,
  add GOOGLE_GENERATIVE_AI_API_KEY/XAI_API_KEY/MOONSHOT_API_KEY/OPENCODE_API_KEY)
- FlagsSettings/RepoInstructionsSection: remove stale effort/timeout copy
- new: gitAuthServer.test.ts (10 tests — lifecycle, token delivery, tamper detection, script gen)
- new: agent.test.ts (4 tests — default opentoad, AGENT_OVERRIDE, invalid override)
- new: models.test.ts (19 tests — parseModel, resolution, registry invariants)
- update models.dev snapshot

Made-with: Cursor

* fix changed-agents.sh to filter legacy agent files from CI matrix

legacy agent files (claude.ts, codex.ts, etc.) are @ts-nocheck and not
exported from index.ts. changed-agents.sh now reads index.ts imports to
build the active agent set and treats changes to inactive files as
non-agent changes (opentoad canary only).

Made-with: Cursor

* remove MCP file tools, old agent harnesses, and obsolete security tests

ASKPASS-based git auth makes the old MCP file tool security layer unnecessary:
- token never in subprocess env, so symlink/gitattributes/hook attacks can't exfiltrate it
- agents now use native file tools (OpenCode builtin read/edit)

deleted:
- action/mcp/file.ts (file_read, file_write, file_edit, file_delete, list_directory)
- action/mcp/index.ts (dead re-export)
- agent harnesses: claude.ts, codex.ts, cursor.ts, gemini.ts, opencode.ts
- opencode-runner.ts (inlined into opentoad.ts)
- security tests that validated MCP file tool restrictions
- commented-out three-step review flow (~300 lines)
- sanitizeSchema/wrapSchema dead code from mcp/shared.ts
- OPENCODE_MODEL_MINI/MAX env vars (effort-level model overrides removed)

updated test prompts to use generic file ops instead of MCP tool names.
restored pkg-json-scripts + requirements-txt-attack (test --ignore-scripts defense).

Made-with: Cursor

* bump actions/checkout v4 → v6 (node 24)

node 20 actions deprecated june 2, 2026.

Made-with: Cursor

* temporarily disable fail-fast on agnostic tests to debug checkout@v6

Made-with: Cursor

* re-enable fail-fast on agnostic tests

Made-with: Cursor

* fix test token mismatch: mint OIDC tokens scoped to target repo

CI tests override GITHUB_REPOSITORY to pullfrog/test-repo but inherit
the runner's GITHUB_TOKEN (scoped to pullfrog/app), causing 401s on
every run-context fetch. Clear GITHUB_TOKEN in the test subprocess so
ensureGitHubToken() mints a properly scoped token via OIDC.

Also centralizes the default GITHUB_REPOSITORY in runAgentStreaming
instead of repeating it in every test file, and fixes preview-cleanup
to remove workers from all queues (not just name-matching ones).

Made-with: Cursor

* fix ensureGitHubToken to try OIDC when app credentials are absent

ensureGitHubToken only attempted token minting when GITHUB_APP_ID and
GITHUB_PRIVATE_KEY were set. In CI, OIDC is available but app creds
aren't exposed — so the guard prevented minting entirely.

Made-with: Cursor

* dead code cleanup: remove remnants of deleted agents, file tools, effort system

remove unused @anthropic-ai/claude-agent-sdk and @openai/codex-sdk deps,
orphaned file-tool security tests, dead GEMINI_MODEL passthrough, stale
opencode-runner wiki refs, deleted test file references, and MCP file tool
docs. rename docs/effort → docs/models. fix vitest setup: move dotenv to
globalSetup (runs once before forks instead of per-file, 19s → 200ms).

Made-with: Cursor

* address review feedback: remove dead code, update stale references

- remove AGENT_OVERRIDE (only opentoad exists)
- remove shellToolName plumbing (always restricted shell)
- bump action version to 0.0.179
- remove CURSOR_API_KEY from all workflows/configs
- remove OPENCODE_MODEL_MINI/MAX from workflows/docs
- delete wiki/effort.md, rewrite docs/effort.mdx as "Models"
- rewrite wiki/modes.md: orchestrator/subagent → single agent
- simplify flag system: drop builtin flag extraction (debug, effort,
  timeout, agent), keep custom flag replacement only
- reserve all legacy flag names to prevent custom flag conflicts

Made-with: Cursor

* regenerate lockfile after removing claude-agent-sdk and codex-sdk

Made-with: Cursor

* fix import ordering, add lockfile check to pre-push hook

Made-with: Cursor

* remove dead debug payload field, stale packageExtensions

Made-with: Cursor

* merge proc-sandbox and token-exfil into a single test

proc-sandbox and token-exfil were duplicative — both tested that
SANDBOX_TEST_TOKEN couldn't be exfiltrated. consolidated into
token-exfil with shell:restricted (which actually exercises filterEnv)
and the /proc attack vector hints from proc-sandbox.

Made-with: Cursor

* fix wiki adversarial.md to match actual tokenExfil validator

Made-with: Cursor
2026-03-12 05:22:51 +00:00
David Blass 5bcfae990a restructure dashboard UI, add mode instructions, post-review follow-up dispatch (#453)
* add mode instructions and restructure dashboard sidebar

- add modeInstructions JSONB field to Repo model for per-mode user instructions
- thread modeInstructions through settings API, run-context API, RepoSettings, ToolContext, and selectMode runtime
- merge user-defined mode instructions with hardcoded orchestrator guidance, with IncrementalReview inheriting from Review
- reduce visible built-in modes from 7 to 4 (Build, Review, Plan, Fix) with editable Instructions textareas
- add TRIGGERS group header to sidebar above Mentions, Pull requests, Issues
- add wiki/modes.md documenting triggers and modes conceptual model

Made-with: Cursor

* fix leaping comment deletion and address review feedback

- wrap post-createReview operations in try/finally so deleteProgressComment
  runs even when updateReview or reportReviewNodeId throws
- add parseModeInstructions runtime guard to filter non-string values
  from the JSONB field before passing to buildOrchestratorGuidance
- add useEffect sync for localInstructions when props change
- guard onBlur to skip save when instructions haven't changed
- update wiki/modes.md to reflect V2 is implemented (no longer "proposed")

Made-with: Cursor

* harden review cleanup, fix type cast, stabilize mode instructions state

- wrap deleteProgressComment in try/catch inside finally to prevent masking original errors
- replace `as Record<string,string>` cast with runtime parseModeInstructions + useMemo
- fix wiki dual-prompt table to reflect mode.prompt fallback status

Made-with: Cursor

* fix wiki tense and heading ambiguity from PR review

Made-with: Cursor

* fix review "edited" badge by using pending review + submit flow

create review as PENDING first (no event/body), build the footer with
the now-known review ID, then submitReview with the full body. single
atomic publish — no updateReview edit needed.

Made-with: Cursor

* add post-agent follow-up re-review dispatch

After the agent exits, check if PR HEAD moved past the reviewed commit
and dispatch a follow-up re-review. This closes the gap where push
webhooks are suppressed during in-flight reviews.

Made-with: Cursor

* add silent flag to follow-up re-review dispatch

Made-with: Cursor

* restructure dashboard for consistency and clarity

- consolidate tools into single grouped card (was 4 separate cards)
- merge coding + autofix CI into one section
- remove redundant trigger section descriptions
- add bidirectional crosslinks between modes and triggers
- inline instruction links (review/plan/build) into descriptions
- add save status indicators to all sections
- restructure flags with grouped built-in/custom cards
- flatten sidebar (remove dividers and group headers)
- tighten all descriptions

Made-with: Cursor

* update PR screenshots for new dashboard layout

Made-with: Cursor

* extend review context inline instead of dispatching new workflow

when commits are pushed during a review, the agent now handles them
inline: create_pull_request_review detects HEAD movement, returns
instructions to pull and review the incremental diff, and the agent
submits a second review covering only the new changes. this avoids
the cost of spinning up a full new workflow run.

also fixes a bug where reviewedSha was set to the submission HEAD
(current) rather than the checkout HEAD (what was actually reviewed),
which caused commits pushed between checkout and submission to be
silently missed by postReviewCleanup.

the workflow dispatch is kept as a safety net for agent timeout/error.

Made-with: Cursor

* polish dashboard UI: fix debug markers, crosslinks, title consistency, descriptions

- remove all red debug borders/labels and CM component
- remove all inline style={{}} debug outlines from crosslinks
- fix ambiguous crosslinks: Build→"Coding ↓", Plan→"Enrich issues ↓"
- add missing "Edit build instructions ↑" backlink on Auto-address reviews
- normalize card title weight to text-sm font-semibold across all cards
- rename "Default" subcard to "Setup" with broader description
- fix Mentions description to imperative tone
- broaden Flags section description to cover built-in and custom
- remove useless fragments in ModesSection and ToolsSettings
- restructure Agent section: remove ConsoleSection wrappers, add sidebar indent support

Made-with: Cursor

* extract PR quick links as standalone card, consistent with issues

- PR quick links is now its own card under Reviews (was a sub-toggle inside Review PRs disabled state)
- Review PRs OFF sets prCreated="none" instead of auto-falling back to "links"
- Review PRs card hides sub-toggles when disabled (re-review/approve don't apply)
- Both PRs and Issues now have identical Quick links card structure

Made-with: Cursor

* update reviews screenshot with standalone quick links card

Made-with: Cursor

* polish dashboard UI: revert quick links to inline toggles, fix fonts and spacing

- revert standalone PR/issue Quick Links cards back to inline toggles inside
  Review PRs and Enrich Issues cards (fixes prCreated state coupling bug)
- restore original font-medium card titles across all trigger/settings cards
- fix sidebar: add CONSOLE heading, remove nested indentation, remove truncation
- right-justify Enrich Issues mode dropdown, group description with label
- move instructions links inline with behavior descriptions
- replace text save indicators with icon spinner/checkmark
- standardize section title spacing, move footer below danger zone

Made-with: Cursor

* fix formatting for biome lint

Made-with: Cursor

* address PR review feedback: cleanup guard, shared util, wiki update

- clear ctx.toolState.review after read to prevent double-execution of postReviewCleanup
- forward authorPermission in safety-net re-review dispatch
- extract parseModeInstructions to utils/schemas/modeInstructions.ts
- update wiki/modes.md: remove stale v1/v2 language, fix dashboard layout
- add typecheck to pre-push hook

Made-with: Cursor

* add action typecheck to pre-push, fix exactOptionalPropertyTypes errors

Made-with: Cursor

* fix duplicate actuallyReviewedSha from rebase

Made-with: Cursor

* remove PR screenshots

Made-with: Cursor

* add label/textarea association for mode instruction accessibility

Made-with: Cursor

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-03-11 04:24:09 +00:00
Anna Bocharova 9c99bcbbac feat: Improving the plan revisions (#465)
* feat(plans): Suggested plan for plan revisions.

* fix: add planCommentId to reduce GitHub API calls.

* Revert "fix: add planCommentId to reduce GitHub API calls."

This reverts commit ef9c24811fa291b12ac3601cc4cd3edb7c9a0fca.

* Improving plan revision: the implementation draft.

* fix schema composition order.

* fix: reusing existing retry helper (action) for reportPlanCommentToRun.

* mv: updatePlanCommentId.

* fix: higher severity for logging error.

* fix: add error handling when calling findExistingPlanCommentIdForIssue.

* feat: improving the revisit plan request detection by adding PLAN_REVISION_VERBS.

* Updating the plan with alternative non-determenistic solution.

* add more verbs to PLAN_REVISION_VERBS.

* fix: supply the previous plan in the event context as previousPlanBody, updating Plan mode instructions.

* fix: adjusting the way PLAN_REVISION_VERBS are used in sentences.

* fix: using GraphQL approach with NodeId to find commentId in findExistingPlanCommentIdForIssue.

* fix: use double word boundaries (both sides).

* fix condition in findExistingPlanCommentIdForIssue.

* fix: rm unused args from findExistingPlanCommentIdForIssue.

* bump the action version.

* fix(plan): rm everything related to approach A.

* fix(plan): No limit for progress comments.

* feat(plan): the new plan.

* Revert: changed to webhook (no longer involved).

* feat: mv plan comment lookup into a new API endpoint.

* Revert: changes to select_mode tool.

* FEAT: The new implementation.

* fix arktype issues.

* fix plan diagram.

* fix(selectMode): e2e type constraints for fetchExistingPlanComment.

* Revert "fix(selectMode): e2e type constraints for fetchExistingPlanComment."

This reverts commit 53f3b6650a9928e3080700faa9eead0052e94333.

* fix(selectMode): type constraints (copy) for fetchExistingPlanComment.

* feat: improving isHttpError helper and reusing it consistently instead of casting.

* address review: remove unconditional retry, add plan comment warning, dedupe type, remove dead guard, fix GraphQL types

* Fix: tightening the PlanEdit guidance.

* fix(select_mode): Providing the agent with existingPlanCommentId as well.

* fix(instructions): Adjusting the primary guidance to prefer Plan mode for issue-related ambiguous requests.

* fix(wiki): updating the delegation docs according to the current instructions.

* fix(instructions): rm implication to call for issue details.

* fix(select_mode): tweak for PlanEdit.

* fix(select_mode): more tweaks to PlanEdit.

* fix(select_mode): tweaks for the order of instructions and context.

* revert: to the state of 5c400efce1f1fec0a0855eeacad2bc3b721fd1bf.

* fix(select_mode): Correcting the guideline.

* rm the plan from the branch (impletemented).

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-03-10 20:34:54 +00:00
Mateusz Burzyński 5684cbef77 Implement support for output schemas (#411)
* tweak examples

* tweak prompt

* Implement support for output schemas

* fix: add example for structured output with zod schema

* tweak

* remove redundant cast

* fix input name

* strip $schema

* hack around vendor requirement

* clarify required result output

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-03-05 23:07:03 +00:00
David Blass 53970308ee Add incremental re-review on new PR commits (#388)
* add incremental re-review on new PR commits

When new commits are pushed to a PR that Pullfrog has previously reviewed,
automatically perform a focused re-review on only the new changes. Includes
a supersede mechanism to abort stale in-flight reviews on rapid pushes, a
new IncrementalReview mode with incremental diff + prior-feedback awareness,
and a PRReview tracking model so re-review fires for both auto-reviewed and
manually-triggered PRs. Reviews now always submit (APPROVE when clean).

Co-authored-by: Cursor <cursoragent@cursor.com>

* simplify re-review eligibility and add summary to incremental reviews

Remove the path1/path2 distinction for re-review eligibility — now simply
requires prReReview=enabled and a prior Pullfrog review on the PR. Show
the re-review toggle regardless of prCreated setting. Add a top-level
summary body to incremental reviews for consistency with full reviews.

Co-authored-by: Cursor <cursoragent@cursor.com>

* replace superseded polling with server-side in-flight dedup and add prApproveEnabled setting

Made-with: Cursor

* add armstrong cursor command

Made-with: Cursor

* update armstrong

* feat: Pullfrogger game v1 (#378)

* Frogger game basis code (CC0 1.0 Unversal license).

* Initial React port.

* fix props for Sprite.

* fixed context issue in FroggerGame.

* Fixed format.

* Fixed lint issue in FroggerGame.

* Restoring LeapingLoader, using FroggerGame as a new fallback in Suspense.

* feat: Display toast when URL ready.

* Add props constraints on Sprite.

* feat: frog sprite.

* fix: zoom and alignment.

* fix: extract const.

* fix: mv types.

* fix: mv game into index.tsx file.

* fix: replacing deprecated event prop which with key.

* feat: Log sprite.

* feat: turtle sprite.

* Adjusting game colors.

* feat: sprites for the cars.

* rm primitive sprites.

* fix: bulldozer sprite position.

* Adjusting colors.

* Shape constraints.

* rm original.

* minor: naming, cleanup.

* fix: renderers dict.

* fix: adjusting and renaming racer.

* fix renderer binding for scored frogs.

* feat: responsive layout with gap below and maintained aspect ratio.

* grammar fix.

* feat: road lane dividers.

* feat: using AbortController to cleanup events.

* fix: cleanup and shortening.

* feat: extracting drawGameBackground.

* feat: initObstacleRows and updateAndDrawObstacles helpers.

* feat: initFroggers helper.

* feat: drawFroggers helper.

* feat: checkForCollision helper.

* feat: makeKeydownHandler helper.

* feat: listenToKeyboardEvents helper.

* mv cleanup into drawGameBackground.

* fix: cleanup.

* feat: better adjustBrightness helper.

* Polling on the page.tsx side, restoring timeout and fallbacks, dynamic link msg.

* FEAT: wait for workflow to complete and notify additionally with a big link (incl.db migration).

* Fix: larger title, shorter link.

* fix(hook): Writing completedAt from hook.workflow_run.updated_at according to suggestion.

* fix(loader): rm unused props from WorkflowRunClientProps as suggested.

* fix(loader): mv id=dev case into the page.

* fix(DNRY): mv PollStartedResult and PollCompletedResult types.

* fix(DNRY): reusing drawEllipse() helper in Sprite.

* fix(style): reordering methods by priority in Sprite.

* fix(frogger): rm empty rows from canvas, square game.

* feat: game canvas rounded corners.

* fix(DNRY): extracting SpriteShape type for faster reference.

* fix: rm target from links, use same window.

* add incremental re-review on new PR commits

When new commits are pushed to a PR that Pullfrog has previously reviewed,
automatically perform a focused re-review on only the new changes. Includes
a supersede mechanism to abort stale in-flight reviews on rapid pushes, a
new IncrementalReview mode with incremental diff + prior-feedback awareness,
and a PRReview tracking model so re-review fires for both auto-reviewed and
manually-triggered PRs. Reviews now always submit (APPROVE when clean).

Co-authored-by: Cursor <cursoragent@cursor.com>

* replace superseded polling with server-side in-flight dedup and add prApproveEnabled setting

Made-with: Cursor

* consolidate workflow_run completed handling and track completedAt

Removes the duplicate exported handleWorkflowRunCompleted in favor of
the private one, merges status + orphan resolution logic into a single
path, and sets completedAt on both normal completion and orphan cancel.

Made-with: Cursor

* fix rebase conflict resolution: restore eligibility logic, incremental review summaries, and exhaustiveness check

- replace deleted hasPullfrogReviewedPR call with WorkflowRun.findFirst
  (the utility file was removed by the dedup improvements commit)
- restore IncrementalReview summary body in modes.ts and selectMode.ts
  (lost during ca0168b conflict resolution; origin had re-added them via f98f902)
- use switch + satisfies never for workflow_run event dispatch
- lowercase comments per project conventions

Made-with: Cursor

* fix workflow-run polling architecture and improve incremental review prompts

move polling loops from server actions to client to avoid serverless timeouts
(pollForCompleted ran up to 600s in a single invocation). each server action
is now a single DB check; client drives retries. also fix misleading prompt
text about incremental diff scope and remove dead code in handleWebhook.

Made-with: Cursor

* await reportReviewNodeId to eliminate race condition and webhook sleep

- refactor reportReviewNodeId from fire-and-forget to async/awaited,
  guaranteeing the dedup signal lands before the tool returns
- remove the 5-second grace period sleep in the synchronize webhook
  handler (no longer needed with the awaited PATCH)
- update IncrementalReview guidance to use get_review_comments for
  detailed prior line-level feedback instead of just review summaries
- remove dead fallbackUrl field from CheckStartedResult type

Made-with: Cursor

* fix rebase artifacts: broken triggeringIssue reference, review formatting, and prompt wording

Made-with: Cursor

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Anna Bocharova <robin_tail@me.com>
2026-02-28 18:30:49 +00:00
pullfrog[bot] 20b08b5321 Add "Rerun failed job ➔" link to error comment footer (#355)
* add "Rerun failed job" link to error comment footer

* Remove issueNumber guard from rerun link

The rerun action only needs run_id — the issue number in the trigger
URL path is just a route segment requirement. Use 0 as a fallback
so the link is always shown when a run ID is available.

* Overload `[number]` path segment as `runId` for the rerun action

For the rerun trigger, the `[number]` path param now carries the
workflow run ID instead of an issue number. The rerun link changes
from `/trigger/o/r/ISSUE?action=rerun&run_id=RID` to
`/trigger/o/r/RID?action=rerun`.

- Remove `run_id` query param from page.tsx and searchParams type
- Add error handling around `reRunWorkflow` for invalid run IDs
- Drop `issueNumber` from `BuildErrorCommentBodyParams` and all
  rerun link builders (errorReport, exitHandler, postCleanup)

* Reorder validation: action first, then rerun, then issueNumber

* address review: remove early toolState assignment, restructure rerun into dedicated block

* revert self-contained rerun block, share auth logic via issueOrRunId

* improve error handling

* normalize runid early

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Mateusz Burzyński <mateuszburzynski@gmail.com>
2026-02-27 12:32:06 +00:00
Colin McDonnell 52ec35790a fix review reply trigger: treat replies to Pullfrog threads as implicit triggers, only add eyes reaction when dispatching
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-24 19:28:08 +00:00
Mateusz Burzyński da72d0d6ee Fixed semantic conflict between #377 and #354 (#380)
* Move out checking out PRs from `etupGit` (#377 intent)

* Keep subagent-related changes from #377
2026-02-24 14:20:59 +00:00
Colin McDonnell b472aa1ba9 fix(opencode): add effort-aware model overrides and OpenRouter guidance (#354)
* chore: create empty commit for PR

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore(action): trigger preview repo creation workflow

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(opencode): merge repo opencode config and log provider key presence

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(opencode): add effort-aware model override precedence

Add OPENCODE_MODEL_MINI and OPENCODE_MODEL_MAX support with fallback to OPENCODE_MODEL and auto-selection, and keep provider resolution aligned via inline OpenCode config when overrides are used. Update workflow env wiring, test allowlists, and docs (including OpenRouter setup guidance and sidebar ordering) to document the new behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

* docs(effort): clarify OpenCode precedence and add section link

Add a concise OpenCode precedence callout in the summary area and link directly to the OpenCode section for full details and examples.

Co-authored-by: Cursor <cursoragent@cursor.com>

* Restructure dash (#372)

* Restructure dash

* WIP

* WIP

* refactor trigger UI: extract PR summary card, add mentions section, rename labels

Co-authored-by: Cursor <cursoragent@cursor.com>

* clean up console UI: remove info icons from section descriptions, rename mentions trigger

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix review feedback: layout, terminology, form scope

- extract console sidebar sections to module-level constant
- align three-column layout breakpoints to xl (match sidebar visibility)
- fix mixed shell/bash terminology in beta page
- scope FormProvider to trigger sections only, restore autoComplete="off"

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bump

---------

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: create empty commit for PR

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(opencode): merge repo opencode config and log provider key presence

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix(opencode): add effort-aware model override precedence

Add OPENCODE_MODEL_MINI and OPENCODE_MODEL_MAX support with fallback to OPENCODE_MODEL and auto-selection, and keep provider resolution aligned via inline OpenCode config when overrides are used. Update workflow env wiring, test allowlists, and docs (including OpenRouter setup guidance and sidebar ordering) to document the new behavior.

Co-authored-by: Cursor <cursoragent@cursor.com>

* chore: update agent rules and OpenCode config docs

Align AGENTS guidance with current preferences and apply review-driven wording updates in OpenCode-related files.

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-24 02:05:26 +00:00
Colin McDonnell e2d8dfeebf Clarify shell guidance and delegation checklists
Standardize orchestrator/subagent instructions on the MCP shell tool and format mode guidance as explicit checklists to make delegation flows easier to follow. Bump the action package version to 0.0.171 for this release.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-24 01:28:50 +00:00
Colin McDonnell 2017922780 Improve delegate (#377)
* Improve delegate

* fix stale log regexes in delegate tests and add test-coupling comments

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-23 23:41:27 +00:00
Colin McDonnell a7bd746f21 Restructure dash (#372)
* Restructure dash

* WIP

* WIP

* refactor trigger UI: extract PR summary card, add mentions section, rename labels

Co-authored-by: Cursor <cursoragent@cursor.com>

* clean up console UI: remove info icons from section descriptions, rename mentions trigger

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix review feedback: layout, terminology, form scope

- extract console sidebar sections to module-level constant
- align three-column layout breakpoints to xl (match sidebar visibility)
- fix mixed shell/bash terminology in beta page
- scope FormProvider to trigger sections only, restore autoComplete="off"

Co-authored-by: Cursor <cursoragent@cursor.com>

* Bump

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-23 23:34:29 +00:00
David Blass cfd38d82fc refactor delegation system, add PR summary comments, and improve code quality (#334)
* refactor delegation system and add PR summary comments

Delegation system:
- replace mode-based delegation with select_mode → delegate two-step flow
- orchestrator crafts self-contained subagent prompts (clean context — no system/repo/event instructions leak)
- add role-based tool filtering via FastMCP authenticate hook (?role=subagent hides orchestrator-only tools)
- add select_mode tool for orchestrator guidance per mode
- add ask_question tool for lightweight research subagents
- extract shared subagent lifecycle into subagent.ts (create, complete, stdout, instructions)
- route set_output to per-subagent state when activeSubagentId is set
- track per-subagent state (SubagentState Map) replacing boolean delegationActive flag
- capture and aggregate AgentUsage across all agents (claude, codex, gemini, opencode)
- write usage summary table to GitHub job summary
- block built-in subagent spawning (Task for Claude, Task(*) for Cursor)
- increase activity timeout from 60s to 300s (subagent thinking phases)
- fix gh CLI misguidance in system prompt — explicitly forbid usage

PR summary comments:
- add prSummaryComment trigger (DB schema + migrations + Zod + UI toggle)
- dispatch mini-effort summary job alongside PR review on pr.created
- add update_pull_request_body MCP tool
- add defaultEffort option to webhook dispatch

Hardening:
- rewrite delegate/selectMode tests with simulated state management
- add toolFiltering.test.ts for role extraction, canAccess, set_output routing
- remove non-null assertions for PULLFROG_TEMP_DIR (proper error throws)
- use fetchWithRetry for direct tarball downloads
- DRY fix for rate limit check in test runner

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: add type keyword to Effort import in handleWebhook.ts

Co-authored-by: Cursor <cursoragent@cursor.com>

* clean up delegation system, improve code quality across the codebase

- simplify delegate tool to instructions + effort params with subagent lifecycle in subagent.ts
- add select_mode and ask_question orchestrator-only tools with canAccess filtering
- replace delegate.test.ts/selectMode.test.ts with toolFiltering.test.ts (live MCP integration)
- add set_output routing for subagent context and AgentUsage tracking across all agents
- add PR summary comment trigger (schema, UI, webhook dispatch with silent flag)
- add update_pull_request_body MCP tool
- fix changed-agents.sh to always include claude canary for non-agent action changes
- fix cursor pagination bug in getSelectedInstallationReposPage
- remove destructuring patterns, inline type definitions, and unsafe type casts
- replace non-null assertions with explicit checks in install.ts
- convert multi-param functions to single param objects (postCleanup, runActionLocal, etc.)
- use isHttpError helper in API routes instead of catch-any patterns
- add adhoc test fixtures for delegation scenarios (context isolation, error handling, synthesis, etc.)

Co-authored-by: Cursor <cursoragent@cursor.com>

* no subagent mutation, one mcp per subagent

* address review feedback: parallel-safe usage tracking, subagent isolation, minor improvements

* fix subagent state isolation: replace Object.freeze with shallow copy

Object.freeze throws TypeErrors when subagent tools (checkout_pr,
report_progress) write scalar properties to toolState. A shallow copy
achieves the same isolation for scalar fields while allowing tools to
work normally. Shared references (subagents Map, usageEntries array)
remain shared for coordination.

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
2026-02-22 14:12:43 +00:00
Colin McDonnell 97937f46f7 console UI improvements and cleanup (#311)
* console UI improvements and cleanup

- add verify workflow button and API endpoint for manual installation check
- move env var check into PromptBox as blocking overlay (hoisted to RepoConsole)
- extract FlagsCheatSheet modal, replace verbose flag hints everywhere
- add info popovers for repo setup / post-checkout script descriptions
- remove unused prAutoFixCiFailures schema fields and migration
- default mentionAllowNonCollaborator to disabled for safety on public repos
- update docs for triggers and getting started

Co-authored-by: Cursor <cursoragent@cursor.com>

* add diagnostic logging for push_branch bug investigation

temporary [push-debug] logs to trace why getPushDestination falls back
to origin/<localBranch> instead of using the correct remote branch name
for same-repo PRs.

Co-authored-by: Cursor <cursoragent@cursor.com>

* add git config diagnostic to verify original bug cause

Co-authored-by: Cursor <cursoragent@cursor.com>

* temporarily disable StoredPushDest to test git config path

Co-authored-by: Cursor <cursoragent@cursor.com>

* remove diagnostic logging for push_branch investigation

verified that StoredPushDest fix works correctly on preview repo.
both the stored dest path and the git config fallback resolve to the
correct remote branch in the GitHub Actions environment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix formatting in AgentSettings and TriggersSettings

Co-authored-by: Cursor <cursoragent@cursor.com>

* pass derived env var state to PromptBox instead of raw secrets data

eliminates duplicated derivation logic between RepoConsole and PromptBox
by passing envVarMissing, envVarChecking, and agentKeyNames as props.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: prevent duplicate comment after PR review deletes progress comment

progressCommentId now uses three states: undefined (no comment yet),
number (active), null (deliberately deleted). After create_pull_request_review
deletes the progress comment, subsequent report_progress calls skip instead
of creating a new comment.

Co-authored-by: Cursor <cursoragent@cursor.com>

* effort descriptions, test ordering, husky, docs images, typo fix

- rewrote delegation effort level descriptions to per-level breakdown
- action-agents now waits for action-agnostic; action-agnostic waits for root
- added husky + lint-staged (biome check --write on staged files)
- updated triggers docs images and triggers.mdx content
- fixed "figured" → "figures" typo on landing page
- updated pnpm-lock.yaml

Co-authored-by: Cursor <cursoragent@cursor.com>

* Commit

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-16 04:41:04 +00:00
David Blass 9071c0ae6c refactor mode selection into delegate tool that spawns subagents (#265) 2026-02-12 19:34:47 +00:00
pullfrog[bot] a442f766aa feat: Resolve threads in AddressReviews mode (#266)
* Add review thread resolution to AddressReviews mode

- Add thread_id to comment metadata in buildThreadBlocks
- Implement ResolveReviewThreadTool with GraphQL mutation
- Register new tool in MCP server
- Update AddressReviews mode to resolve threads after addressing feedback

Closes #227

* Fix typo: use log.warning instead of log.warn

* refactor: DRY up catch block by extracting isResolved condition

* fix lint.

* fix: avoid using any.

* fix: combining log statements around the message.

* fix(test): Adjusting snapshot.

---------

Co-authored-by: pullfrog[bot] <226033991+pullfrog[bot]@users.noreply.github.com>
Co-authored-by: Robin Tail <robin_tail@me.com>
2026-02-12 15:25:21 +00:00
David Blass 19df8372cd add file_read/file_write tools, sandbox tests, CI improvements (#239)
* migrate to flags

* init

* iterate on file write lockdown tests

* improve ci

* fix lockfile

* fix typecheck

* fix lint

* improve pushRestricted

* ok

* fix more

* ok

* remove process.env spreading rule

Co-authored-by: Cursor <cursoragent@cursor.com>

* enhanced fs rw tools

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-02-10 06:35:47 +00:00
pullfrog[bot] 1d59fd3d21 feat: Lifecycle hooks (#219)
* flatten lifecycle hooks into RepoSettings string fields

replace the separate LifecycleHook model with setupScript and
postCheckoutScript string fields directly on RepoSettings. move the UI
into the Agent settings section alongside environment variables and
custom instructions. delete the standalone lifecycle-hooks API route,
component, and schema since the existing settings PATCH endpoint
handles the new fields automatically.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix: pass env to lifecycle hook spawn so scripts can use package managers

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-06 07:16:14 +00:00
Colin McDonnell 3a7145db1a Scope installation token permissions in restricted mode (#226)
* Scope installation token permissions in restricted mode

In restricted/disabled bash mode, the installation token is now scoped
to match the workflow's permissions block. This preserves fork push
capability while limiting what the agent can do with the token.

- Read workflow permissions from pullfrog.yml at runtime
- Pass permissions to API when acquiring installation token
- Clear OIDC env vars in restricted mode to prevent token minting
- Simplify setupGit by moving token resolution to main.ts

* Address review feedback: fail closed with default permissions

- Add restrictive default permissions (contents:read, pull_requests:read,
  issues:read) as fallback when workflow permissions can't be read
- Add support for job-level permissions via GITHUB_JOB env var
- Fix misleading comment about token resolution in restricted mode
- Add documentation about fork PR checkout behavior

* Simplify to separate git/MCP tokens without workflow permission scoping

- gitToken: minimal contents:write only (assumed exfiltratable)
- mcpToken: full installation token (not exfiltratable via MCP tools)
- Remove workflowPermissions.ts - security-conscious users can pass
  their own token via GH_TOKEN or inputs.token
- Add type-safe InstallationTokenPermissions to github.ts and API route

* Rename `write` permission to `push` and remove vestigial tool blocking

The `write` permission was previously used to block local file write tools
in agents. This was security theater since bash can write files anyway.

Now `push` only controls the git token scope:
- push: enabled → contents:write (can push commits)
- push: disabled → contents:read (read-only, can't push)

Changes:
- Rename `write` to `push` in action.yml, Prisma schema, and all TS types
- Remove vestigial write tool blocking from all agents (claude, cursor,
  gemini, opencode, codex)
- Add data-preserving Prisma migration using RENAME COLUMN
- Update UI: "Write files" → "Git push" with updated description

* add PID namespace isolation for bash sandbox

when running in CI, attempts to use unshare --pid to create a new PID
namespace for bash subprocesses. this prevents the /proc/$PPID/environ
attack where a malicious command could read secrets from the parent
process's environment.

the protection works by:
1. creating a new PID namespace (subprocess becomes PID 1)
2. mounting fresh /proc showing only sandbox PIDs
3. parent PIDs become invisible (PPID = 0, /proc/0 doesn't exist)

combined with filterEnv(), this provides complete protection against
/proc-based secret theft. falls back gracefully if namespaces aren't
available.

includes test script to verify the protection works.

* add PID namespace test to CI workflow

tests whether unshare --pid works on GHA runners out of the box,
and if not, whether enabling via sysctl helps. also runs the
pidNamespace.ts test to verify the full protection.

* fix pnpm setup and add procIsolation agent test

- fix pnpm/action-setup by specifying package_json_file path
- add procIsolation crossagent test that has agent attempt to
  read secrets via /proc/$PPID/environ
- add procIsolation to CI test matrix

* add pid-namespace test job to main workflow

this job tests unshare --pid capabilities on GHA runners and runs
the pidNamespace.ts adhoc test to verify /proc isolation works

* test bubblewrap's sysctl approach for enabling namespaces

- write to /etc/sysctl.d/99-userns.conf and run sysctl --system
- try aa-complain on unshare binary
- more detailed diagnostics

* fix pidNamespace test and add sudo-unshare fallback for GHA

- fix reference error in pidNamespace.ts (renamed function but didn't update calls)
- add sudo-unshare as fallback method for GHA runners where unprivileged
  namespaces are blocked but sudo is available
- update bash.ts to detect and use sudo unshare when unprivileged fails

* consolidate security docs and document PID namespace isolation

- update security.md with current implementation details
  - document sudo unshare fallback for GHA runners
  - add testing instructions for local Docker and CI
  - add "Further Exploration" section with Landlock and path validation ideas
- delete bash-sandbox.md and landlock.md (consolidated into security.md)

* move procIsolation test to adhoc folder

the procIsolation test requires PID namespace capabilities that aren't
available in the Docker test environment. moved to adhoc/ so it's excluded
from default test runs and can be run explicitly when needed (e.g. via
the pid-namespace CI job or locally with --privileged docker).

* fix Docker test environment for PID namespace isolation

- add CI and GITHUB_ACTIONS to testEnvAllowList so sandbox detection runs
- add --privileged to Docker run for PID namespace support (unshare)

this fixes the test environment to properly test the sandbox. in production,
the action runs directly on GHA runner where sudo unshare works.

* fix getJobToken() to work in test environment

add fallback to GH_TOKEN and GITHUB_TOKEN when INPUT_TOKEN is not set.
this allows tests to run without requiring workflow-level token input.

the token resolution order is:
1. INPUT_TOKEN (from workflow `with: token:`)
2. GH_TOKEN (external token override)
3. GITHUB_TOKEN (pre-acquired in tests or from GHA env)

* security: filter secrets from all subprocess environments

- extract filterEnv() to shared utils/secrets.ts
- make $() utility filter secrets by default (git, npm, etc. don't need them)
- disable git hooks via core.hooksPath to prevent hook-based exfiltration
- git auth uses token embedded in URL, not env vars

this prevents malicious git hooks, npm postinstall scripts, and other
code execution vectors from exfiltrating GITHUB_TOKEN and API keys.

* docs: clarify defense-in-depth security model

update security.md to explain why BOTH layers are required:
- filterEnv(): cleans child's own /proc/self/environ
- PID namespace: hides parent's /proc entries

PID namespace alone isn't sufficient - with --mount-proc, the child
becomes PID 1, so /proc/1/environ is the child's OWN environment.
without filterEnv(), secrets would still be accessible there.

* add procSandbox crossagent test for PID namespace security

- add crossagent/procSandbox.ts: security test that instructs agent to try
  various /proc attack vectors and validates sandbox blocks them
- update wiki/security.md: document PID namespace isolation details, add
  verification commands, explain why sudo inside sandbox doesn't break security
- update docker.ts: use node:24 with sudo for GHA-like test environment
- update instructions.ts: allow disabling security messaging for pentests
- clean up adhoc test files (procIsolation.ts, securityAudit.ts)

the procSandbox test sets SANDBOX_TEST_TOKEN (matches *_TOKEN filter), gives
the agent explicit hints about attack vectors (/proc, sudo, nsenter, etc.),
disables prompt-based mitigations, and validates the secret is never leaked.

* move procSandbox test to agnostic/ (runs with one agent)

* WIP

* docs: add agent testing guide (pnpm play, Docker, pentesting)

* docs: add CI details to agent testing guide

* docs: add interesting findings and gotchas from pentesting

* improve test fidelity: auto-set CI=true, verify sandbox active

- docker.ts: always set CI=true in container so sandbox activates
- docker.ts: skip sudo/user setup if already done (faster reruns)
- bash.ts: export getSandboxMethod() for diagnostics
- bash.ts: add debug log when sandbox disabled
- procSandbox.ts: add sandbox_was_active check to catch vacuous passes

the CI=true change is critical: without it, PID namespace isolation
is skipped and security tests pass without actually testing anything.

* docs: update agent-testing.md with CI=true auto-set note

* docs: clarify log format is agent-specific

* fix git auth, simplify MCP tools, add adversarial tests

- fix gitWithAuth to use Basic auth format (Bearer doesn't work with git's http.extraheader)
- fix token.ts: push:restricted now correctly gets contents:write
- fix github.ts: pass permissions when acquiring installation tokens locally
- remove commit_files and create_branch MCP tools (redundant, don't require credentials)
- remove containsSecrets() - trivially bypassable, not sound security
- add agnostic adversarial tests: pushDisabled, pushRestricted, tokenExfil
- update instructions.ts to clearly list available git MCP tools
- add wiki/git.md documenting credential isolation and push permission tiers
- update wiki/docker.md with custom image considerations
- update wiki/agent-testing.md with adversarial testing patterns

* fix type errors after rebase

- change ResolveTokensParams.push from ToolPermission to PushPermission
- use tags: ["agnostic"] instead of agnostic: true in test files

* fix cleanup permission error in sandbox tests

when sandbox isolation is enabled (CI=true), files created by the unshare
subprocess may have different ownership, causing rmSync to fail with EACCES.
this error in the finally block was overriding the test's success result.

fix: wrap cleanup in try-catch and fall back to sudo rm if rmSync fails.

* Add adhoc

* Handle git config/remote bypasses

* add git hooks protection and simplify ToolState

- disable git hooks in restricted mode via -c core.hooksPath=/dev/null
- add gitHooks adversarial test to verify hook protection works
- unify prNumber/issueNumber into single issueNumber field
- add pushUrl to ToolState for push validation
- add generateTestMarker() for simpler single-agent test markers
- export SENSITIVE_PATTERNS and isSensitiveEnvName from secrets.ts
- remove redundant pidNamespace.ts (duplicated by procSandbox.ts)
- update documentation

* harden $git() auth: subcommand whitelist, binary tamper detection

- rename gitWithAuth() to $git() with explicit subcommand first arg
- restrict to "fetch" | "push" at type level (filters don't run for these)
- resolve git binary path at startup via resolveGit(), sha256 fingerprint
- verify hash before each $git() call to detect binary replacement
- rename disableHooks to restricted for cleaner semantics
- document filter exfiltration attack and empirical verification in wiki

* remove redundant pid-namespace CI job

the PID namespace isolation testing is now handled by
action/test/agnostic/procSandbox.ts via pnpm runtest agnostic

* fix push_branch for new branches and improve token leak detection

- getPushDestination now falls back to origin/<branch> when @{push}
  is not configured (happens for new branches created locally)
- gitPerms validator now checks for actual token patterns instead
  of matching "x-access-token" string in test instructions

* use kebab-case for test names

* simplify shell env API: "restricted" | "inherit" | object

replace passFullEnv boolean with cleaner env option that accepts:
- "restricted" (default): filterEnv() to prevent secret leakage
- "inherit": full process.env
- object: custom env merged with restricted base

* share EnvMode and resolveEnv between shell.ts and bash.ts

move shared env resolution logic to secrets.ts

* add env option to bash tool (default: restricted)

* delete agent-testing.md (renamed to adversarial.md)

* Add checkout tests

* reframe githooks test prompt to avoid claude safety refusal

claude was refusing to execute the test because the prompt used words
like "malicious" and "security testing". reframed as a debugging task
with innocuous env var name (TESTING_DEBUG_TAG) per adversarial.md guidance.

Co-authored-by: Cursor <cursoragent@cursor.com>

* clean up verbose token acquisition logs

move logging responsibility to call sites which have better context
(git token vs MCP token). remove redundant intermediate OIDC logs
and unused "(permission-scoped)" suffix.

Co-authored-by: Cursor <cursoragent@cursor.com>

* isolate agnostic tests with matrix strategy, fix .pullfrog-env secret leak

- split action-agnostic into per-test matrix jobs for isolated logs and filesystems
- only write explicitly opted-in env vars to .pullfrog-env via fileAgentEnv
  (fixes token-exfil test where claude found SANDBOX_TEST_TOKEN on disk)
- mcpmerge test opts in via fileAgentEnv for cursor's repo-level MCP fallback

Co-authored-by: Cursor <cursoragent@cursor.com>

* remove env parameter from bash tool to prevent agents bypassing filterEnv

the bash tool exposed an `env` parameter accepting "restricted" | "inherit"
which allowed agents to pass env: "inherit" and see all secrets including
SANDBOX_TEST_TOKEN, bypassing the restricted environment filtering entirely.
env mode is now determined internally (always restricted).

Co-authored-by: Cursor <cursoragent@cursor.com>

* use pullfrog/test-repo for push tests to stop polluting main repo

push tests were creating branches and tags on pullfrog/app directly.
now all push tests (push-restricted, push-disabled, push-enabled,
git-permissions) target pullfrog/test-repo instead.

Co-authored-by: Cursor <cursoragent@cursor.com>

* use pullfrog/test-repo for all tests, not just push tests

no test should clone or operate on pullfrog/app directly.

Co-authored-by: Cursor <cursoragent@cursor.com>

* fix token scoping for test-repo and bash timeout defaults

- acquireTokenViaOIDC now includes GITHUB_REPOSITORY repo in token
  scope so push tests work against pullfrog/test-repo
- bash tool default timeout: 120s -> 30s, cap: 600s -> 120s
- activity timeout: 30s -> 60s
- prevents hung bash commands (e.g. find /) from killing the agent
  via activity timeout

Co-authored-by: Cursor <cursoragent@cursor.com>

---------

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-06 06:26:26 +00:00
Mateusz Burzyński bfe72ac2cf Fixed how payload-as-prompt is handled and progress comment updates (#212) 2026-02-01 22:13:39 +00:00
David Blass 18ba8e5fd0 improve runtest, optimize CI batching (#210) 2026-02-01 21:48:53 +00:00
Mateusz Burzyński c1f8247077 Add set_output tool (#205) 2026-01-29 22:49:00 +00:00
Mateusz Burzyński 071e885d63 Add upload tool and related APIs (#187)
* Add utils for r2 upload

* Add the tool and new routes

* fix auth issue

* sign headers

* add comment

* use our own API key to auth signed uploads

* Restructure things slightly

* tweak

* tweak

* add comments

* tweak

* revert a thing

* twaek

* drop mime type filtering

* new incarnation of mime type filtering

* jsut allow all octet-streams

* simplify further

* tweak

* update lockfile

---------

Co-authored-by: Colin McDonnell <colinmcd94@gmail.com>
2026-01-28 05:34:58 +00:00
Colin McDonnell 102417f442 Add post hooks for cleanup (#193)
* Add post hooks for cleanup

* Switch to signal-based cleanup

* Better exit handling
2026-01-28 01:59:15 +00:00
David Blass 54279e313b update security instructions, remove unused debug tool 2026-01-23 22:10:00 +00:00
David Blass 9a8db3e07c add restricted tests, refactor test infrastructure (#150) 2026-01-22 21:06:19 +00:00
Colin McDonnell 2f3c48edb6 Add get_commit_info 2026-01-21 03:22:29 +00:00