Files
backnotprop__plannotator/packages/server/review.ts
T

1319 lines
54 KiB
TypeScript
Raw Normal View History

/**
* Code Review Server
*
* Provides a server implementation for code review with git diff rendering.
* Follows the same patterns as the plan server.
*
* Environment variables:
* PLANNOTATOR_REMOTE - Set to "1"/"true" for remote, "0"/"false" for local
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
*/
import { isRemoteSession, getServerHostname, getServerPort } from "./remote";
fix: Detect calling agent via env vars and centralize agent config (#418) * fix: detect calling agent via env vars for correct badge display Add prioritized agent detection chain: CODEX_THREAD_ID (codex) > COPILOT_CLI (copilot-cli) > default (claude-code). All subcommands use the shared detectedOrigin constant. Display name updated from 'Copilot CLI' to 'GitHub Copilot'. TypeScript origin union type updated to include 'copilot-cli'. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor: centralize agent config into @plannotator/shared/agents - Create packages/shared/agents.ts as single source of truth for Origin type, agent display names (AGENT_CONFIG), getAgentName(), and getAgentBadge() - Replace all inline origin type unions across 8 files with Origin import - Type detectedOrigin and ServerOptions.origin as Origin for compile-time safety - Add @plannotator/shared dependency to @plannotator/editor package.json - Adding a new agent is now a one-file change to AGENT_CONFIG Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: restore gitContext in startReviewServer call Accidentally removed alongside the origin refactor. Without it, local code reviews lose branch detection, diff-type switching, and CWD resolution. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Yecats <Yecats@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-03-28 16:37:56 -07:00
import type { Origin } from "@plannotator/shared/agents";
import { type DiffType, type GitContext, runVcsDiff, getVcsFileContentsForDiff, canStageFiles, stageFile, unstageFile, resolveVcsCwd, validateFilePath, getVcsContext, detectRemoteDefaultCompareTarget, gitRuntime } from "./vcs";
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
import { basename } from "node:path";
import { parseWorktreeDiffType, resolveBaseBranch } from "@plannotator/shared/review-core";
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
import {
createDefaultSemanticDiffRuntime,
getSemanticDiffAvailability,
getSemanticDiffScratchCwd,
runSemanticDiff,
semanticDiffCacheKey,
semanticDiffFileExtsFromSearchParams,
SemanticDiffResponseCache,
} from "@plannotator/shared/semantic-diff";
import type { SemanticDiffAvailability, SemanticDiffResponse } from "@plannotator/shared/semantic-diff-types";
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
import {
getPRDiffScopeOptions,
getPRStackInfo,
resolveStackInfo,
resolvePRFullStackBaseRef,
runPRFullStackDiff,
checkoutPRHead,
type PRDiffScope,
} from "@plannotator/shared/pr-stack";
2026-04-23 16:49:25 -07:00
import type { AgentJobInfo } from "@plannotator/shared/agent-jobs";
import { getRepoInfo } from "./repo";
import { handleImage, handleUpload, handleAgents, handleServerReady, handleDraftSave, handleDraftLoad, handleDraftDelete, handleFavicon, type OpencodeClient } from "./shared-handlers";
import { contentHash, deleteDraft } from "./draft";
feat: VS Code editor annotations + theme integration (#239) * feat: add shared EditorAnnotation type Single source of truth for the editor annotation interface, imported by both @plannotator/server and @plannotator/ui. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation server endpoints In-memory store with POST/GET/DELETE endpoints for editor annotations. The array lives in the handler closure and dies with the server session. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation UI — polling hook, card, panel, and export - useEditorAnnotations hook with auto-disable polling (500ms interval) - EditorAnnotationCard with file path, code preview, and comment - AnnotationPanel conditionally renders editor annotation section - exportEditorAnnotations formats annotations for Claude feedback - App.tsx wires hook, includes in output memo and send feedback gate Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code extension editor annotation command Cmd+Shift+. or right-click to capture selected text as an annotation. POSTs through the cookie proxy to the plannotator server. Adds amber left-border decorations on annotated lines, cleared on panel close. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: inline comment threads, lightbulb menu, and stronger decorations Replace showInputBox with VS Code CommentController for inline annotation threads anchored to selected code. Add CodeActionProvider for lightbulb discoverability. Stronger decoration styling with gutter icon. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code theme integration for webview Bridge VS Code CSS variables to Plannotator's CSS variable system via postMessage between wrapper page and proxied iframe. Automatically adopts the active VS Code color theme (dark/light/custom) without touching any UI components or CSS files. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: gate editor annotation polling behind VS Code detection Only poll /api/editor-annotations when running inside a VS Code webview (window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have zero network cost from the editor annotations feature. Also fixes poll interval from 500ms to 2000ms. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: faster polling, prevent unnecessary re-renders, unify HTTP helper - Poll interval 2s → 500ms for snappier annotation pickup - Shallow equality check on annotation IDs prevents React re-renders when poll data is unchanged - Merge postToProxy/deleteFromProxy into single requestProxy function Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotations support in code review Wire existing editor annotation infrastructure into the review flow so VS Code users can annotate files outside the diff during code review. - Add editor annotation endpoints to review server (same 3-line pattern) - Call useEditorAnnotations hook in review App.tsx - Display editor annotations in ReviewPanel with "Editor" divider - Include editor annotations in feedback export and gating logic Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
import { createEditorAnnotationHandler } from "./editor-annotations";
import { createExternalAnnotationHandler } from "./external-annotations";
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
import { createAgentJobHandler } from "./agent-jobs";
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
import {
CODEX_REVIEW_SYSTEM_PROMPT,
buildCodexCommand,
generateOutputPath,
parseCodexOutput,
transformReviewFindings,
} from "./codex-review";
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
import { buildAgentReviewUserMessage, buildAgentReviewUserMessageForTarget, type WorkspaceReviewPromptContext } from "./agent-review-message";
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
import {
CLAUDE_REVIEW_PROMPT,
buildClaudeCommand,
parseClaudeStreamOutput,
transformClaudeFindings,
} from "./claude-review";
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
import { createTourSession, TOUR_EMPTY_OUTPUT_ERROR } from "./tour/tour-review";
import { loadConfig, saveConfig, detectGitUser, getServerConfig } from "./config";
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
import { type PRMetadata, type PRReviewFileComment, type PRStackTree, type PRListItem, fetchPR, fetchPRFileContent, fetchPRContext, submitPRReview, fetchPRViewedFiles, markPRFilesViewed, fetchPRStack, fetchPRList, getPRUser, parsePRUrl, prRefFromMetadata, isSameProject, getDisplayRepo, getMRLabel, getMRNumberLabel } from "./pr";
import { AI_QUERY_ENDPOINT, createAIRuntime } from "./ai-runtime";
import type { AIEndpoints } from "@plannotator/ai";
import { isWSL } from "./browser";
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
import type { LocalWorkspaceReview, WorkspaceDiffType } from "./review-workspace";
feat: search-based code navigation with peek view (#711) * feat: search-based code navigation with peek view (#694) Add IDE-like code navigation to the review UI. Cmd/Ctrl+click a token in a diff to find its definitions and references across the repo via ripgrep, displayed in a VS Code-style peek panel below the diff. Backend: bounded rg search with language-aware definition patterns (TS/JS, Python, Go, Rust), ranked results (same file > changed files > same directory), confidence labels, and graceful degradation when rg is not installed. Both Bun and Pi servers implement the endpoints. Frontend: Dockview peek panel with syntax-highlighted full-file preview on the left and grouped reference list on the right. Clicking a reference scrolls the preview; double-clicking an in-diff result navigates to the file with a gold line flash. Closes #694 * fix: resolve Pi server TypeScript errors for code-nav Add missing spawn import, type the close callback parameter, and use double-cast for parseBody → CodeNavRequest. * fix: clear loading state on cached preview hits Without this, clicking a cached file while a fetch is in-flight leaves isLoading stuck true — the spinner hides the preview. * feat: show pointer cursor on Cmd/Ctrl+hover for navigable tokens Adds pn-token-nav class with thicker underline and pointer cursor when hovering a token while holding the modifier key, signaling the token is Cmd+clickable for code navigation. * refactor: remove go-to-diff navigation from peek panel Strip the in-diff badge, double-click-to-jump, highlightDiffLine wiring, and onCodeNavGoToDiff from the peek panel. The peek view is the primary interaction — jump-to-diff adds complexity without clear value at this stage. * chore: remove dead code from code-nav cleanup Delete unused highlightDiffLine.ts, remove codeNavChangedFiles and codeNavActiveSide from context and App.tsx, drop stale extractChangedFiles import. * chore: add code-nav endpoints to AGENTS.md, remove dead activeSide state * fix: don't classify bare indented calls as definitions Change the TS/JS method pattern from zero-or-more (*) to one-or-more (+) declaration keywords, so plain calls like startServer(config) are no longer misclassified as definitions. * feat: show toast when code-nav is unavailable in platform-only PR mode Instead of opening the peek panel and showing misleading "No results", Cmd+click in non-local PR mode shows a brief toast explaining that code navigation requires a local checkout. * fix: strip hljs hardcoded background from code-nav preview The highlight.js github-dark theme sets a fixed dark background on all .hljs elements. Apply transparent override for the entire peek preview so code inherits the active theme's background.
2026-05-13 12:24:37 -07:00
import { handleCodeNavResolve, extractChangedFiles } from "./code-nav";
// Re-export utilities
export { isRemoteSession, getServerPort } from "./remote";
export { openBrowser } from "./browser";
feat: add Perforce (P4) pending changelist diff support (#472) * feat: add Perforce pending changelist diff support for code review Introduce P4 support alongside existing Git backend via a VCS dispatch layer (vcs.ts). Detects Git vs Perforce workspace automatically and routes diff/file-content operations to the appropriate backend. - Add p4-default and p4-changelist:<N> DiffType variants - Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist context, unified diff conversion, binary file exclusion, batch p4 where - Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API - Update review server and CLI entry point to use VCS dispatch - Filter empty changelists from dropdown, disable staging for P4 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: introduce VcsProvider interface for extensible VCS support Replace hardcoded Git/P4 dispatch with a provider-based architecture. Each VCS implements VcsProvider interface and registers in a providers array — adding a new VCS only requires implementing the interface. - Define VcsProvider with detect, ownsDiffType, getContext, runDiff, getFileContents, and optional stageFile/unstageFile/resolveCwd - Create gitProvider and p4Provider as concrete implementations - Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd - Remove VCS-specific branching from review server endpoints Note: GitContext interface is not renamed to VcsContext in this commit. The rename touches too many files across the codebase (Pi extension, OpenCode plugin, shared types, tests) and should be handled as a separate pull request to keep the diff reviewable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: rtsummit <rtsummit@abutton.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
export { type DiffType, type DiffOption, type GitContext, type WorktreeInfo } from "./vcs";
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
export { type PRMetadata } from "./pr";
export { handleServerReady as handleReviewServerReady } from "./shared-handlers";
// --- Types ---
export interface ReviewServerOptions {
/** Raw git diff patch string */
rawPatch: string;
/** Git ref used for the diff (e.g., "HEAD", "main..HEAD", "--staged") */
gitRef: string;
/** Error message if git diff failed */
error?: string;
/** HTML content to serve for the UI */
htmlContent: string;
/** Origin identifier for UI customization */
fix: Detect calling agent via env vars and centralize agent config (#418) * fix: detect calling agent via env vars for correct badge display Add prioritized agent detection chain: CODEX_THREAD_ID (codex) > COPILOT_CLI (copilot-cli) > default (claude-code). All subcommands use the shared detectedOrigin constant. Display name updated from 'Copilot CLI' to 'GitHub Copilot'. TypeScript origin union type updated to include 'copilot-cli'. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * refactor: centralize agent config into @plannotator/shared/agents - Create packages/shared/agents.ts as single source of truth for Origin type, agent display names (AGENT_CONFIG), getAgentName(), and getAgentBadge() - Replace all inline origin type unions across 8 files with Origin import - Type detectedOrigin and ServerOptions.origin as Origin for compile-time safety - Add @plannotator/shared dependency to @plannotator/editor package.json - Adding a new agent is now a one-file change to AGENT_CONFIG Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> * fix: restore gitContext in startReviewServer call Accidentally removed alongside the origin refactor. Without it, local code reviews lose branch detection, diff-type switching, and CWD resolution. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Yecats <Yecats@users.noreply.github.com> Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-03-28 16:37:56 -07:00
origin?: Origin;
/** Current diff type being displayed */
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
diffType?: DiffType | WorkspaceDiffType;
/** Git context with branch info and available diff options */
gitContext?: GitContext;
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
/** Local parent directory containing multiple child VCS repositories. */
workspace?: LocalWorkspaceReview;
2026-04-23 16:49:25 -07:00
/**
* Initial base branch the caller used to compute `rawPatch`. When a caller
* overrides the detected default (e.g. Pi's `openCodeReview` accepting a
* custom `defaultBranch`), this must be forwarded so the server's internal
* `currentBase` state, the `/api/diff` response, and downstream agent
* prompts stay consistent with the patch that's already on screen.
*/
initialBase?: string;
/** Whether URL sharing is enabled (default: true) */
sharingEnabled?: boolean;
/** Custom base URL for share links (default: https://share.plannotator.ai) */
shareBaseUrl?: string;
/** Called when server starts with the URL, remote status, and port */
onReady?: (url: string, isRemote: boolean, port: number) => void;
/** OpenCode client for querying available agents (OpenCode only) */
opencodeClient?: OpencodeClient;
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
/** PR metadata when reviewing a pull request (PR mode) */
prMetadata?: PRMetadata;
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
/** Working directory for agent processes (e.g., --local worktree). Independent of diff pipeline. */
agentCwd?: string;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
/** Per-PR worktree pool. When set, pr-switch creates worktrees instead of checking out. */
worktreePool?: import("@plannotator/shared/worktree-pool").WorktreePool;
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
/** Cleanup callback invoked when server stops (e.g., remove temp worktree) */
onCleanup?: () => void | Promise<void>;
}
export interface ReviewServerResult {
/** The port the server is running on */
port: number;
/** The full URL to access the server */
url: string;
/** Whether running in remote mode */
isRemote: boolean;
/** Wait for user review decision */
waitForDecision: () => Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}>;
/** Stop the server */
stop: () => void;
}
// --- Server Implementation ---
const MAX_RETRIES = 5;
const RETRY_DELAY_MS = 500;
/**
* Start the Code Review server
*
* Handles:
* - Remote detection and port configuration
* - API routes (/api/diff, /api/feedback)
* - Port conflict retries
*/
export async function startReviewServer(
options: ReviewServerOptions
): Promise<ReviewServerResult> {
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
const { htmlContent, origin, gitContext, sharingEnabled = true, shareBaseUrl, onReady } = options;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let prMetadata = options.prMetadata;
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
const isPRMode = !!prMetadata;
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const workspace = options.workspace;
const isWorkspaceMode = !!workspace;
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const hasLocalAccess = !!gitContext;
const sessionVcsType = gitContext?.vcsType;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let draftKey = contentHash(options.rawPatch);
feat: VS Code editor annotations + theme integration (#239) * feat: add shared EditorAnnotation type Single source of truth for the editor annotation interface, imported by both @plannotator/server and @plannotator/ui. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation server endpoints In-memory store with POST/GET/DELETE endpoints for editor annotations. The array lives in the handler closure and dies with the server session. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation UI — polling hook, card, panel, and export - useEditorAnnotations hook with auto-disable polling (500ms interval) - EditorAnnotationCard with file path, code preview, and comment - AnnotationPanel conditionally renders editor annotation section - exportEditorAnnotations formats annotations for Claude feedback - App.tsx wires hook, includes in output memo and send feedback gate Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code extension editor annotation command Cmd+Shift+. or right-click to capture selected text as an annotation. POSTs through the cookie proxy to the plannotator server. Adds amber left-border decorations on annotated lines, cleared on panel close. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: inline comment threads, lightbulb menu, and stronger decorations Replace showInputBox with VS Code CommentController for inline annotation threads anchored to selected code. Add CodeActionProvider for lightbulb discoverability. Stronger decoration styling with gutter icon. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code theme integration for webview Bridge VS Code CSS variables to Plannotator's CSS variable system via postMessage between wrapper page and proxied iframe. Automatically adopts the active VS Code color theme (dark/light/custom) without touching any UI components or CSS files. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: gate editor annotation polling behind VS Code detection Only poll /api/editor-annotations when running inside a VS Code webview (window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have zero network cost from the editor annotations feature. Also fixes poll interval from 500ms to 2000ms. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: faster polling, prevent unnecessary re-renders, unify HTTP helper - Poll interval 2s → 500ms for snappier annotation pickup - Shallow equality check on annotation IDs prevents React re-renders when poll data is unchanged - Merge postToProxy/deleteFromProxy into single requestProxy function Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotations support in code review Wire existing editor annotation infrastructure into the review flow so VS Code users can annotate files outside the diff during code review. - Add editor annotation endpoints to review server (same 3-line pattern) - Call useEditorAnnotations hook in review App.tsx - Display editor annotations in ReviewPanel with "Editor" divider - Include editor annotations in feedback export and gating logic Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
const editorAnnotations = createEditorAnnotationHandler();
const externalAnnotations = createExternalAnnotationHandler("review");
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
const tour = createTourSession();
// Mutable state for diff switching
let currentPatch = options.rawPatch;
let currentGitRef = options.gitRef;
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
let currentDiffType: DiffType | WorkspaceDiffType = options.diffType || workspace?.diffType || "uncommitted";
let currentError = options.error;
let currentHideWhitespace = loadConfig().diffOptions?.hideWhitespace ?? false;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let originalPRPatch = options.rawPatch;
let originalPRGitRef = options.gitRef;
let originalPRError = options.error;
let currentPRDiffScope: PRDiffScope = "layer";
let prListCache: PRListItem[] | null = null;
let prListCacheTime = 0;
const prSwitchCache = new Map<string, { metadata: PRMetadata; rawPatch: string }>();
if (isPRMode && prMetadata) prSwitchCache.set(prMetadata.url, { metadata: prMetadata, rawPatch: options.rawPatch });
const prStackTreeCache = new Map<string, PRStackTree | null>();
2026-04-23 16:49:25 -07:00
// Tracks the base branch the user picked from the UI. Agent review prompts
// read this (not gitContext.defaultBranch) so they analyze the same diff
// the reviewer is currently looking at. Honors an explicit initialBase from
// the caller — e.g. programmatic Pi callers can request a non-detected base.
const detectedCompareTarget = (): string => gitContext?.defaultBranch || gitContext?.compareTarget?.fallback || "main";
let currentBase = options.initialBase || detectedCompareTarget();
let baseEverSwitched = false;
const resolveReviewBase = (requestedBase?: string): string => {
return resolveBaseBranch(requestedBase, detectedCompareTarget());
};
// Fire-and-forget: query the remote for its actual default branch. If it
// arrives before the user interacts, quietly upgrade currentBase from the
// local fallback (e.g. "main") to the upstream ref (e.g. "origin/main").
// Non-blocking — the server is already listening by the time this resolves.
if (gitContext && !options.initialBase && !isPRMode) {
detectRemoteDefaultCompareTarget(gitContext.cwd, sessionVcsType).then((remote) => {
if (remote && !baseEverSwitched) currentBase = remote;
});
}
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
const resolveAgentCwd = (): string => {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
if (workspace) return workspace.root;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
if (options.worktreePool && prMetadata) {
const poolPath = options.worktreePool.resolve(prMetadata.url);
if (poolPath) return poolPath;
}
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
return options.agentCwd ?? resolveVcsCwd(currentDiffType as DiffType, gitContext?.cwd) ?? process.cwd();
};
const getWorkspacePromptContext = (): WorkspaceReviewPromptContext | undefined => {
if (!workspace) return undefined;
return workspace.getPromptContext();
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
};
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
const semanticDiffScratchCwd = getSemanticDiffScratchCwd();
const resolveSemanticDiffCwd = (): string => {
if (workspace) return workspace.root;
if (options.worktreePool && prMetadata) {
const poolPath = options.worktreePool.resolve(prMetadata.url);
if (poolPath) return poolPath;
}
if (options.agentCwd) return options.agentCwd;
if (gitContext) {
const vcsCwd = resolveVcsCwd(currentDiffType as DiffType, gitContext.cwd);
if (vcsCwd) return vcsCwd;
if (gitContext.cwd) return gitContext.cwd;
}
return semanticDiffScratchCwd;
};
const semanticDiffCache = new SemanticDiffResponseCache();
const semanticDiffAvailabilityCache = new Map<string, Promise<SemanticDiffAvailability>>();
const createSemanticDiffRuntime = (cwd: string) => ({
...createDefaultSemanticDiffRuntime(),
cwd,
});
const getSemanticDiffAvailabilityForCwd = (cwd: string): Promise<SemanticDiffAvailability> => {
const cached = semanticDiffAvailabilityCache.get(cwd);
if (cached) return cached;
const next: Promise<SemanticDiffAvailability> = getSemanticDiffAvailability(createSemanticDiffRuntime(cwd)).catch((error) => ({
available: false,
reason: "sem-probe-failed",
message: error instanceof Error ? error.message : String(error),
}));
semanticDiffAvailabilityCache.set(cwd, next);
return next;
};
const getSemanticDiffAdvert = async () => {
const availability = await getSemanticDiffAvailabilityForCwd(resolveSemanticDiffCwd());
return {
available: availability.available,
...(availability.semVersion && { semVersion: availability.semVersion }),
...(availability.semSource && { semSource: availability.semSource }),
};
};
const getSemanticDiff = async (url: URL): Promise<SemanticDiffResponse> => {
const cwd = resolveSemanticDiffCwd();
const fileExts = semanticDiffFileExtsFromSearchParams(url.searchParams);
const cacheKey = semanticDiffCacheKey({ rawPatch: currentPatch, cwd, fileExts });
const cached = semanticDiffCache.get(cacheKey, currentPatch);
if (cached) return cached;
const result = await runSemanticDiff(
{ rawPatch: currentPatch, cwd, fileExts },
createSemanticDiffRuntime(cwd),
);
if (result.status === "ok") {
semanticDiffCache.set(cacheKey, currentPatch, result);
}
return result;
};
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
const agentJobs = createAgentJobHandler({
mode: "review",
getServerUrl: () => serverUrl,
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
getCwd: resolveAgentCwd,
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
async buildCommand(provider, config) {
const cwd = resolveAgentCwd();
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const workspacePrompt = getWorkspacePromptContext();
const hasAgentLocalAccess = !!workspacePrompt || !!options.worktreePool || !!options.agentCwd || !!gitContext;
const userMessageOptions = {
defaultBranch: currentBase,
hasLocalAccess: hasAgentLocalAccess,
prDiffScope: currentPRDiffScope,
...(workspacePrompt && { workspace: workspacePrompt }),
};
2026-04-23 16:49:25 -07:00
// Snapshot the diff context at launch — stored on the job so
// downstream "Copy All" produces the same markdown as /api/feedback
// would right now, even if the reviewer switches modes/bases later.
// Skipped in PR mode (prMetadata carries equivalent context).
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const worktreeParts = String(currentDiffType).startsWith("worktree:")
? parseWorktreeDiffType(currentDiffType as DiffType)
2026-04-23 16:49:25 -07:00
: null;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
const launchPrUrl = prMetadata?.url;
const launchDiffScope = isPRMode ? currentPRDiffScope : undefined;
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const diffContext: AgentJobInfo["diffContext"] | undefined = workspacePrompt
? { mode: String(currentDiffType), worktreePath: null }
: prMetadata
2026-04-23 16:49:25 -07:00
? undefined
: {
mode: (worktreeParts?.subType ?? currentDiffType) as string,
base: currentBase,
worktreePath: worktreeParts?.path ?? null,
};
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
if (provider === "tour") {
2026-04-23 16:49:25 -07:00
const built = await tour.buildCommand({
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
cwd,
patch: currentPatch,
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
diffType: currentDiffType as DiffType,
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
options: userMessageOptions,
prMetadata,
config,
});
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
return built ? { ...built, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext } : built;
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
}
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const userMessage = workspacePrompt
? buildAgentReviewUserMessageForTarget({
kind: "workspace",
patch: currentPatch,
workspace: workspacePrompt,
})
: buildAgentReviewUserMessage(currentPatch, currentDiffType as DiffType, userMessageOptions, prMetadata);
const jobLabel = workspacePrompt ? "Workspace Review" : "Code Review";
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
if (provider === "codex") {
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
const model = typeof config?.model === "string" && config.model ? config.model : undefined;
const reasoningEffort = typeof config?.reasoningEffort === "string" && config.reasoningEffort ? config.reasoningEffort : undefined;
const fastMode = config?.fastMode === true;
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const outputPath = generateOutputPath();
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
const command = await buildCodexCommand({ cwd, outputPath, prompt, model, reasoningEffort, fastMode });
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
return { command, outputPath, prompt, cwd, label: jobLabel, model, reasoningEffort, fastMode: fastMode || undefined, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext };
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
}
if (provider === "claude") {
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
const model = typeof config?.model === "string" && config.model ? config.model : undefined;
const effort = typeof config?.effort === "string" && config.effort ? config.effort : undefined;
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
const { command, stdinPrompt } = buildClaudeCommand(prompt, model, effort);
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
return { command, stdinPrompt, prompt, cwd, label: jobLabel, captureStdout: true, model, effort, prUrl: launchPrUrl, diffScope: launchDiffScope, diffContext };
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
}
return null;
},
async onJobComplete(job, meta) {
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
const cwd = meta.cwd ?? resolveAgentCwd();
const jobPrUrl = job.prUrl;
const jobDiffScope = job.diffScope;
const jobPrMeta = jobPrUrl ? prSwitchCache.get(jobPrUrl)?.metadata : undefined;
const jobPrContext = jobPrMeta ? {
prUrl: jobPrUrl,
prNumber: jobPrMeta.platform === "github" ? jobPrMeta.number : jobPrMeta.iid,
prTitle: jobPrMeta.title,
prRepo: getDisplayRepo(jobPrMeta),
} : jobPrUrl ? { prUrl: jobPrUrl } : {};
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
// --- Codex path ---
if (job.provider === "codex" && meta.outputPath) {
const output = await parseCodexOutput(meta.outputPath);
if (!output) return;
// Override verdict if there are blocking findings (P0/P1) — Codex's
// freeform correctness string can say "mostly correct" with real bugs.
const hasBlockingFindings = output.findings.some(f => f.priority !== null && f.priority <= 1);
job.summary = {
correctness: hasBlockingFindings ? "Issues Found" : output.overall_correctness,
explanation: output.overall_explanation,
confidence: output.overall_confidence_score,
};
if (output.findings.length > 0) {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const annotations = transformReviewFindings(
output.findings,
job.source,
cwd,
"Codex",
workspace ? (filePath) => workspace.normalizeAnnotationPath(filePath) : undefined,
)
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
.map(a => ({ ...a, ...jobPrContext, ...(jobDiffScope && { diffScope: jobDiffScope }) }));
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error);
}
return;
}
// --- Claude path ---
if (job.provider === "claude" && meta.stdout) {
const output = parseClaudeStreamOutput(meta.stdout);
if (!output) {
console.error(`[claude-review] Failed to parse output (${meta.stdout.length} bytes, last 200: ${meta.stdout.slice(-200)})`);
return;
}
const total = output.summary.important + output.summary.nit + output.summary.pre_existing;
job.summary = {
correctness: output.summary.important === 0 ? "Correct" : "Issues Found",
explanation: `${output.summary.important} important, ${output.summary.nit} nit, ${output.summary.pre_existing} pre-existing`,
confidence: total === 0 ? 1.0 : Math.max(0, 1.0 - (output.summary.important * 0.2)),
};
if (output.findings.length > 0) {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const annotations = transformClaudeFindings(
output.findings,
job.source,
cwd,
workspace ? (filePath) => workspace.normalizeAnnotationPath(filePath) : undefined,
)
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
.map(a => ({ ...a, ...jobPrContext, ...(jobDiffScope && { diffScope: jobDiffScope }) }));
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error);
}
return;
}
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
// --- Tour path ---
if (job.provider === "tour") {
const { summary } = await tour.onJobComplete({ job, meta });
if (summary) {
job.summary = summary;
} else {
// The process exited 0 but the model returned empty or malformed output
// and nothing was stored. Flip status so the client doesn't auto-open
// a successful-looking card that 404s on /api/tour/:id.
job.status = "failed";
job.error = TOUR_EMPTY_OUTPUT_ERROR;
}
return;
}
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
},
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
});
// AI provider setup (graceful — capabilities report unavailable if no provider is registered)
const aiRuntime = await createAIRuntime({ getCwd: resolveAgentCwd });
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
const isRemote = isRemoteSession();
const configuredPort = getServerPort();
const wslFlag = await isWSL();
const gitUser = detectGitUser();
// Detect repo info (cached for this session)
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
// In PR mode, derive from metadata instead of local git
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let repoInfo = isPRMode && prMetadata
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
? { display: getDisplayRepo(prMetadata), branch: `${getMRLabel(prMetadata)} ${getMRNumberLabel(prMetadata)}` }
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
: workspace
? { display: basename(workspace.root), branch: "Workspace" }
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
: await getRepoInfo();
if (gitContext?.repository?.displayFallback) {
repoInfo = {
...repoInfo,
display: repoInfo?.display || gitContext.repository.displayFallback,
};
}
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
// Fetch current platform user (for own-PR/MR detection)
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let prRef = isPRMode && prMetadata ? prRefFromMetadata(prMetadata) : null;
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382) * feat(pi): add missing endpoints to plan, review, and annotate servers Phase 1-3 of Pi endpoint parity: Plan server: image, upload, draft, editor-annotations, agents, favicon, linked documents, Obsidian vaults/files/doc, file browser, VS Code diff Annotate server: image, upload, draft, favicon, linked documents, file browser Review server: extract shared handlers, add favicon Shared utilities extracted from review server inline code into reusable functions (handleImageRequest, handleUploadRequest, handleDraftRequest, handleFavicon). Reference handlers (doc, Obsidian, file browser) implemented using Node.js fs APIs replacing Bun.Glob/Bun.file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): add PR review endpoints and Node.js PR runtime adapter Phase 4 of Pi endpoint parity: - Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern) - GET /api/pr-context — fetch PR summary, comments, checks - POST /api/pr-action — submit review to GitHub/GitLab - PR mode guards on /api/diff/switch and /api/git-add - /api/diff response includes prMetadata and platformUser in PR mode - /api/file-content fetches from platform API in PR mode - Build script copies pr-provider, pr-github, pr-gitlab from shared Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): wire AI backbone with Node.js Pi SDK provider Phase 5 of Pi endpoint parity: - Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class using child_process.spawn instead of Bun.spawn, same RPC protocol - Register 4 AI providers in Pi review server (claude-agent-sdk, codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation - Route /api/ai/* endpoints through createAIEndpoints handlers - Pipe Web Response → node:http response with ReadableStream support for SSE streaming - Dispose AI sessions and registry on server stop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): address parity audit findings across all three servers Plan server: - /api/plan: add repoInfo and projectRoot to response - /api/approve: pass agentSwitch and permissionMode in decision - Update decision promise type to include agentSwitch, permissionMode Review server: - /api/diff/switch: pass gitContext.cwd to runGitDiff - /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore - /api/git-add: add fallback to gitContext.cwd when worktree parse fails Annotate server: - /api/plan: add repoInfo and projectRoot to response - /api/feedback: capture annotations array (was silently dropped) - Update decision promise type to include annotations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): complete parity — integrations, planSave, save-notes Ports all remaining missing functionality: - Node.js versions of saveToObsidian, saveToBear, saveToOctarine (Bun.write → writeFileSync, Bun.$ → spawn) - Node.js detectProjectNameSync (Bun.$ → execSync) - extractTags, generateFrontmatter, generateFilename, extractTitle - POST /api/save-notes — decoupled note saving - POST /api/approve — full implementation: note integrations, planSave snapshots, saveAnnotations, saveFinalSnapshot - POST /api/deny — planSave snapshots on denial - Import saveAnnotations, saveFinalSnapshot from storage.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): wire domain module imports and fix type errors - Add all missing imports from ./server/* domain modules to server.ts - Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.) - Move toWebRequest to helpers.ts, remove duplicate from handlers.ts - Add git() helper to project.ts (was in server.ts, needed by getRepoInfo) - Fix os default import → named imports in handlers.ts and network.ts - Fix readdirSync Dirent type in reference.ts - Fix Headers.entries() → forEach for Node compat in AI endpoint piping - Fix ReadableStream type cast in AI SSE streaming - Fix matchAll iterator compat in integrations.ts (use while + exec) - Cast pi-sdk provider config to any (PiSDKConfig not in base union) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): move generated shared files to generated/ directory Moves all build-time copied shared files (feedback-templates, review-core, storage, draft, project, pr-provider, pr-github, pr-gitlab) from the pi-extension root into generated/ subdirectory. Updates build script to output there. Updates all imports in server.ts, index.ts, and server/ domain modules to use ./generated/ paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): replace hand-maintained utils.ts with generated checklist utils.ts was a manual copy of parseChecklist, extractDoneSteps, and markCompletedSteps from packages/shared/checklist.ts. Add checklist to the build-time copy list and import from generated/checklist.js. Delete the redundant utils.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(pi): gitignore generated/ and built HTML files These are build artifacts created by `bun run build:pi`. Untrack them and add .gitignore to prevent re-adding. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): split server.ts into domain-organized modules - server.ts is now a barrel re-exporting from server/ modules - server/serverPlan.ts — plan review server - server/serverReview.ts — code review server - server/serverAnnotate.ts — annotate server - server/helpers.ts — add requestUrl() to eliminate non-null assertions - server/project.ts — linter fix (sanitizeTag import path) - packages/ai/package.json — add pi-sdk-node export entry - index.ts — fix waitForDone non-null assertion with guard check, update imports for generated/checklist.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): parity audit fixes + shared code extraction Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete). Fixes found during audit: - PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode - Missing permissionMode option and /api/plan response field - editorAnnotations created unnecessarily in archive mode - repoInfo called per-request instead of cached at init - Approve handler missing effectivePermissionMode fallback - Deny handler missing savedPath in decision resolution - Archive /api/plan response had extra pasteApiUrl - Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files - Review server had stray pasteApiUrl option/response field - AI getCwd missing worktree support Shared code extraction: - packages/shared/favicon.ts — single source for favicon SVG - packages/shared/integrations-common.ts — note app pure functions - packages/shared/reference-common.ts — file tree building - packages/shared/repo.ts — git remote parsing - Updated all consumers to import from shared sources For provenance purposes, this commit was AI assisted. * fix: parity audit B3-C10 — review + annotate server fixes Review server (B3-B17): - diff/switch missing try/catch error handling - git-add parseBody outside try/catch - feedback missing try/catch error handling - Unknown /api/ai/* paths now return 404 (both Bun and Pi) Annotate server (C1-C10): - Bun annotate server missing pasteApiUrl (short URL sharing broken) - Added pasteApiUrl to Bun options, response, and both hook callers - Pi repoInfo called per-request instead of cached at init - Pi feedback missing try/catch error handling - Missing GET method guards on doc and reference/files For provenance purposes, this commit was AI assisted. * fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400 D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync) - Made function sync (no longer async) - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution - Gains Windows path normalization, isWithinProjectRoot security check - Deleted packages/server/resolve-file.ts re-export, consumers import from shared - Cleaned up stale await calls in hook entry, reference handler, and tests - All 19 resolve-file tests pass For provenance purposes, this commit was AI assisted. * fix: parity audit D6-D10 — integrations, PR naming, shared modules D6: Fixed broken detectProjectNameSync — was using require() for non-existent exports. Now uses basename + sanitizeTag directly. D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across Bun server, hook, and OpenCode plugin to match Pi naming. Also fixed stale resolve-file import in OpenCode plugin. D8-D10: Verified clean — ide, project detection, network. For provenance purposes, this commit was AI assisted. * update openpackage.yml * fix: bump Pi git-add test timeout to 15s for parallel suite stability For provenance purposes, this commit was AI assisted. * test: add route parity test — Bun ↔ Pi server route drift detection For provenance purposes, this commit was AI assisted. * fix(ci): update Pi generate step to use generated/ directory with full file list The Pi extension was refactored to use generated/ subdirectory but the CI generate step still used the old flat layout with a subset of files. For provenance purposes, this commit was AI assisted. * fix(ci): update release workflow Pi generate step to match new layout Same stale generate step as test.yml — old flat layout, missing files. For provenance purposes, this commit was AI assisted. * fix(pi): update files array for modular server layout The files array still referenced the old flat layout (server.ts monolith, root-level generated files, deleted utils.ts). npm publish would have produced a broken package missing server/ and generated/ directories. For provenance purposes, this commit was AI assisted. * feat: add TypeScript type-checking to CI pipeline - Fix broken barrel export: buildFileTree/VaultNode re-exported from @plannotator/shared instead of reference-handlers (P1 bug) - Fix server.port type narrowing in all 3 servers - Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk) - Extract mapPiEvent to pi-events.ts to break Bun→Node type chain - Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension - Add `typecheck` script to root package.json - Add type-check step to test.yml and release.yml CI workflows For provenance purposes, this commit was AI assisted. * fix(ci): use bun-types instead of @types/node for typecheck CI environment has bun-types (includes Node types) but not @types/node as a standalone package. For provenance purposes, this commit was AI assisted. * fix(ci): add @types/node for Node-runtime type checks Pi extension and packages/shared run on Node, not Bun — they should type-check against @types/node, not bun-types. Added @types/node as a dev dependency so CI resolves it. For provenance purposes, this commit was AI assisted. * fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer) vs ArrayBuffer. Explicit cast resolves the overload mismatch. Astro pulls in TS 5.9 transitively, so CI resolves a different TypeScript version than local dev. This fix works on both 5.8 and 5.9. For provenance purposes, this commit was AI assisted. * fix(ci): add bun-types as explicit devDependency CI's bun install doesn't hoist bun-types to root node_modules when it's only a transitive dep of @types/bun. Adding it as a direct devDependency guarantees tsc can resolve it. For provenance purposes, this commit was AI assisted. * fix(ci): remove Pi extension from typecheck Pi extension depends on @mariozechner/pi-* peer dependencies that aren't installed in CI. Type-checking it requires Pi's runtime environment. The three packages we check (shared, ai, server) are sufficient to catch barrel export bugs and type errors. Pi extension coverage comes from route parity tests and bun test. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
const platformUser = prRef ? await getPRUser(prRef) : null;
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
let prStackInfo = prMetadata ? getPRStackInfo(prMetadata) : null;
let prDiffScopeOptions = prMetadata
? getPRDiffScopeOptions(prMetadata, !!(options.worktreePool || options.agentCwd))
: [];
// Fetch full stack tree (best-effort — always try in PR mode so root PRs
// that target the default branch can still discover descendant PRs)
let prStackTree: PRStackTree | null = null;
if (prRef && prMetadata) {
try {
prStackTree = await fetchPRStack(prRef, prMetadata);
} catch {
// Non-fatal: client falls back to buildMinimalStackTree()
}
prStackTreeCache.set(prMetadata.url, prStackTree);
const resolved = resolveStackInfo(prMetadata, prStackTree, prStackInfo);
if (resolved && !prStackInfo) {
prStackInfo = resolved;
prDiffScopeOptions = getPRDiffScopeOptions(prMetadata, !!(options.worktreePool || options.agentCwd));
}
}
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
2026-03-25 21:33:33 +01:00
// Fetch GitHub viewed file state (non-blocking — errors are silently ignored)
let initialViewedFiles: string[] = [];
if (isPRMode && prRef) {
try {
const viewedMap = await fetchPRViewedFiles(prRef);
initialViewedFiles = Object.entries(viewedMap)
.filter(([, isViewed]) => isViewed)
.map(([path]) => path);
} catch {
2026-03-25 21:33:33 +01:00
// Non-fatal: viewed state is best-effort
}
}
// Decision promise
let resolveDecision: (result: {
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}) => void;
const decisionPromise = new Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
exit?: boolean;
}>((resolve) => {
resolveDecision = resolve;
});
// Start server with retry logic
let server: ReturnType<typeof Bun.serve> | null = null;
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
try {
server = Bun.serve({
hostname: getServerHostname(),
port: configuredPort,
async fetch(req, server) {
const url = new URL(req.url);
feat: Code Tour — guided PR walkthrough as a third agent provider (#569) * feat(server): add Code Tour agent as third review provider Adds a "tour" provider alongside "claude" and "codex" that generates a guided walkthrough of a changeset from a product-minded colleague's perspective. Reuses the entire agent-jobs infrastructure (process lifecycle, SSE broadcasting, live logs, kill support, capability detection) so the only new server plumbing is the prompt/schema module, the GET endpoint for the result, and checklist persistence. - tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex (file output) command builders, and parsers for both. Prompt frames the agent as a colleague giving a casual tour, orders stops by reading flow (not impact), chunks by logical change (not per-file), and writes QA questions a human can answer by reading code or using the product. - review.ts: tour buildCommand with per-engine model defaults (fixes a bug where Codex was defaulting to "sonnet", a Claude model), an onJobComplete handler that parses and stores the tour, plus GET /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints. - agent-jobs.ts: tour capability detection and config threading from the POST body through to the provider's buildCommand. - shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI can render tour jobs with their chosen provider + model. For provenance purposes, this commit was AI assisted. * feat(review-editor): Code Tour dialog with animated walkthrough Adds the tour overlay surface: a full-screen dialog with three animated pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput from the server-side agent. Opens automatically when a tour job completes and can be dismissed with Escape or backdrop click. - components/tour/TourDialog.tsx: three-page animated dialog. Intro page uses a composition cascade (greeting, Intent/Before/After cards with one-shot color-dot pulse, key takeaways table) with a pinned Start Tour button and a bottom fade so content scrolls cleanly under it. Page slides between Overview/Walkthrough/Checklist are ease-out springs with direction auto-derived from tab index. - components/tour/TourStopCard.tsx: per-stop accordion using motion's AnimatePresence for height + opacity springs with staggered children for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview on first open to keep mount costs low. Callout labels (Important, Warning, Note) are deterministic typography, no emoji. - components/tour/QAChecklist.tsx: always-open list of verification questions with per-item spring entrance and persistent checkbox state that PUTs to the server. - hooks/useTourData.ts: fetch + checklist persistence with a dev-mode short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't require a live agent run. - demoTour.ts: realistic demo data (multi-stop, multiple takeaways, real diff hunks) for dev iteration. - App.tsx: tour dialog state, auto-open on job completion, and a dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut guarded by import.meta.env.DEV. - index.css: all tour animations (dialog enter/exit, page slides, stop reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode contrast tuning across structural surfaces (borders, surface tints, callout backgrounds) so the design works in both themes. - package.json: adds motion@12.38.0 for spring-driven accordion physics and the intro composition cascade. For provenance purposes, this commit was AI assisted. * feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview Connects the tour provider to the existing agent jobs sidebar and detail panel so the user can launch a tour the same way they launch Claude or Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors) to render correctly on first mount and handle every diff hunk shape the agent might produce. - ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select when launching a tour job. Resets model to blank when falling back to Codex-only so Codex uses its own default instead of inheriting "sonnet" (a Claude model). - ui/hooks/useAgentJobs.ts: forward engine/model config from the UI through to the POST /api/agents/jobs body so the server's tour provider can pick the right command shape. - dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel. Replaces the "Findings" tab with a "Status" card for tour jobs and surfaces an "Open Tour" button that opens the dialog overlay when the tab is already in the dock. - components/DiffHunkPreview.tsx: synchronous pierre theme init via a useState lazy initializer so the first render (inside a tooltip) is already themed; robust hunk parser that handles bare @@ hunks, file- level --- hunks, and full git diffs; "Diff not available" fallback for broken hunks. - components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small wiring changes to expose openTourPanel from the review state context. Also removes two dead components (TourHeader, DiffAnchorChip) that were superseded by the inline title bar in TourDialog and the inline AnchorBlock in TourStopCard. For provenance purposes, this commit was AI assisted. * refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity The route-parity test suite requires the Pi server (apps/pi-extension/) to expose the same routes as the Bun server (packages/server/). After Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId (GET) and /api/tour/:jobId/checklist (PUT). A naive mirror would duplicate ~100 lines of provider-branch logic (buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts, perpetuating the existing claude/codex duplication problem. Instead, extract the pure runtime-agnostic tour lifecycle into a createTourSession() factory that both servers consume. Route handlers stay per-server (different HTTP primitives) but are ~5 lines each. Net effect: Pi port is ~25 lines instead of ~100. Future providers that adopt the same pattern cost ~15 lines per server. - tour-review.ts: new createTourSession() at the bottom of the module. Encapsulates tourResults + tourChecklists maps, buildCommand (with the Claude-vs-Codex model-default fix baked in), onJobComplete (parse/store/summarize), plus getTour/saveChecklist lookup helpers for route handlers. - review.ts (Bun): tour branch in buildCommand, tour branch in onJobComplete, and both route handlers collapse to one-line calls into the factory. Drops ~70 lines. - vendor.sh: add tour-review to the review-agent loop so Pi regenerates generated/tour-review.ts on every build:pi. - serverReview.ts (Pi): import createTourSession from ../generated/tour-review.js; add tour branch to buildCommand (one line), tour branch to onJobComplete (three lines), and GET/PUT route handlers using Pi's json() helper. ~25 lines added. - agent-jobs.ts (Pi): extend buildCommand interface to accept config and return engine/model; thread config from POST body; extend spawnJob to persist engine/model on AgentJobInfo; add tour to capability list. Claude and Codex branches are intentionally left in the old pattern; they can migrate to the factory approach when next touched to keep this change's blast radius contained. Tests: 518/518 passing (previous 3 route-parity failures resolved, plus 2 extra assertions passing since tour is now in both servers' route tables). For provenance purposes, this commit was AI assisted. * refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim Two small cleanups surfaced by a self-review pass: - Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block the checklist sub-route, while Bun uses `includes("/", ...)`. The two are not equivalent: a URL like /api/tour/abc/extra would be accepted by Pi (jobId becomes "abc/extra") but correctly rejected by Bun. Align Pi to Bun's pattern. - TourStopCard had a leftover `setOpen` shim from when open state was local to the card. State is now lifted to TourDialog, so the shim just aliases onToggle and ignores its argument. Replace with a direct `onClick={onToggle}` on the trigger button. 520/0 tests still pass. For provenance purposes, this commit was AI assisted. * feat(review): per-provider model + effort controls across all review agents Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs for Claude, Codex, and Code Tour via the Agents tab. Threads the config from the UI through the POST body into each provider's buildCommand, which emits the corresponding CLI flags (--model/--effort for Claude; -m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi servers stay in parity. UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS, CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into every dropdown so there's a single source of truth for the choices. Tour's Claude/Codex settings are kept separate from the standalone provider's state so toggling the tour engine no longer overwrites the provider's last choice. Job badge now surfaces the model/reasoning/fast selection for both Tour and the standalone Codex provider. For provenance purposes, this commit was AI assisted. * docs: add Prompts reference page Documents the three-layer structure every review call travels through (CLI system prompt, our user message of review-prompt + user-prompt, output schema flag), names each constant + its file, and calls out that the Claude/Codex review prompts are the upstream ones from those projects (only Code Tour's prompt is original to Plannotator). Linked from the Code Review command page. For provenance purposes, this commit was AI assisted. * feat(review): persist per-agent, per-model settings in a single cookie Drops the hidden "Default" options from the agent dropdowns, locks in explicit sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex, Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and remembers the last-used effort/reasoning/fast-mode per (agent job × model) so switching models reveals the choices you made last time. Backed by a single `plannotator.agents` cookie holding the whole settings tree — one read on mount, one mirror write per change, all mutations funnel through a single React state owner to avoid stale-read or lost-write races across rapid successive updates. For provenance purposes, this commit was AI assisted. * fix(tour): unblock reduced-motion nav + flush pending checklist save on close Two P2 issues surfaced in review: - Under prefers-reduced-motion, tour page animations are suppressed, so onAnimationEnd never fires and exitingPage stuck on 'intro' kept the walkthrough/checklist gated out. navigate() now swaps pages directly when reduced motion is on, mirroring the pattern already used in the wrapper. - Checklist toggles are debounced 500ms before the PUT, but unmount only cleared the timer — checking an item and closing within the window dropped the save. Cleanup now flushes the pending payload with keepalive: true. For provenance purposes, this commit was AI assisted. * feat(review): surface Claude model + effort in job badge, trim redundant labels Claude effort was never persisted on AgentJobInfo, so the job badge had nothing to render beyond "Claude". Plumbs `effort` through the shared type, both server build-command pipelines (Bun + Pi), and spawnJob, then teaches the ProviderBadge to display Claude and Tour Claude model + effort with the same shape Codex already had. Labels resolve via the dropdown catalogs so the badge shows "Opus 4.7" / "High" instead of raw ids. Server labels for both Claude and Codex reviews collapse to plain "Code Review" (matching tour's "Code Tour"), since the badge now carries the provider + model + settings — the title only needs to name the action. For provenance purposes, this commit was AI assisted. * polish(review): prefix agent dropdown options with the action name The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by side — the CLI's detection name was doing double duty as the action label. Prefixes the review entries with "Code Review · " so scanning three options surfaces two reviews + one tour instead of three raw provider names. For provenance purposes, this commit was AI assisted. * fix(review): drop invalid codex reasoning option + fail tour on empty output Two P2 issues from PR review: - Tour jobs exited 0 but returned null output would still be marked "done", and the auto-open watcher would greet the user with a 404 "Tour not found" dialog. onJobComplete now flips the job to failed with an error message when nothing was stored, so the card reflects the real state. - The codex reasoning dropdown offered "None", but codex-rs only accepts minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none` and launched a broken job. Removed the option; added a one-shot cookie migration so users who already saved "none" don't keep shipping it. For provenance purposes, this commit was AI assisted. * fix(tour): format Claude-engine logs + allow reading linked issues Two P2/P3 issues from PR review: - The stdout formatter keyed only on provider === "claude", so Code Tour jobs running on the Claude engine streamed raw JSONL to the log panel while Claude review jobs got formatted text. Widened the check to also catch spawnOptions.engine === "claude" and mirrored the fix into Pi. - The tour Claude allowlist permitted PR/MR commands but not issue reads, yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes owner/repo#456` targets for deeper context. Claude was being denied those commands mid-tour. Added gh issue view + gh api issues + glab issue view to the allowlist. For provenance purposes, this commit was AI assisted. * cleanup(review): e2e punchlist — Pi parity + dedup + tests - Pi now logs Claude parse failures with the same diagnostic as Bun - Tour route match uses a regex instead of an includes-offset trick - Drop `any` cast in Pi's Codex blocking-findings predicate - Extract `patchClaude` twin of `patchCodex` in useAgentSettings - Factor `resolveAgentCwd` helper in Bun review to match Pi - AgentsTab launch payload becomes a per-provider dispatch table - Wrap TourDialog in MotionConfig reducedMotion="user" so motion.* children honor prefers-reduced-motion alongside the CSS keyframes - Tests for parseTourStreamOutput/parseTourFileOutput and the Codex perModel sanitizer For provenance purposes, this commit was AI assisted. * test(tour-review): use real TourStop shape in fixtures The parsers don't validate stop fields so the original made-up shape passed fine, but future readers would be misled. Use the real CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts. For provenance purposes, this commit was AI assisted. * cleanup(tour): hoist shared types + subfolder server module + dedup - Hoist tour output types to packages/shared/tour.ts so server and UI share one source of truth (prevents silent drift when schema changes). - Move tour-review into packages/server/tour/ subfolder alongside the existing packages/review-editor/components/tour/ convention. - Extend tour.buildCommand to accept tour context directly (patch, diffType, options, prMetadata), so Bun and Pi no longer duplicate the buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from the tour module to prevent string drift between servers. - Early-return the tour branch in buildCommand so the review userMessage is built once on the shared non-tour path instead of unconditionally (dead work on tour launches) or twice (codex+claude dup). - Regex capture group for tour checklist jobId in both servers — replaces a second url.pathname.split("/")[3] fragile fallback. - Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate syscall); the outer try/catch already handles ENOENT. - Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion helper; memoize intro-page card array so unrelated state churn doesn't recompute it. - Comment hygiene on tour files — drop WHAT/change-referencing comments added by this PR; keep non-obvious WHY. For provenance purposes, this commit was AI assisted. * fix(tour): hoist introCards useMemo above early returns + subfolder hook The memoized intro-card array was placed after the loading/error early returns in TourDialogContent, so the first successful render called one more hook than the initial loading render — React threw "Rendered more hooks than during the previous render" (error #310) the moment a tour finished loading. Move the useMemo above the early returns and use optional chaining on `tour` so it's safe to run during loading. Also move useTourData.ts into a hooks/tour/ subfolder to start a standard for feature-scoped hooks (was flat among siblings). For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
// API: Get tour result
if (url.pathname.match(/^\/api\/tour\/[^/]+$/) && req.method === "GET") {
const jobId = url.pathname.slice("/api/tour/".length);
const result = tour.getTour(jobId);
if (!result) return Response.json({ error: "Tour not found" }, { status: 404 });
return Response.json(result);
}
// API: Save tour checklist state
const checklistMatch = url.pathname.match(/^\/api\/tour\/([^/]+)\/checklist$/);
if (checklistMatch && req.method === "PUT") {
const jobId = checklistMatch[1];
try {
const body = await req.json() as { checked: boolean[] };
if (Array.isArray(body.checked)) tour.saveChecklist(jobId, body.checked);
return Response.json({ ok: true });
} catch {
return Response.json({ error: "Invalid JSON" }, { status: 400 });
}
}
// API: Get diff content
if (url.pathname === "/api/diff" && req.method === "GET") {
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
origin,
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
mode: isWorkspaceMode ? "workspace" : undefined,
diffType: hasLocalAccess || isWorkspaceMode ? currentDiffType : undefined,
2026-04-23 16:49:25 -07:00
// Echo the active base so a page refresh or reconnect rehydrates
// the picker to what the server is actually using — not the
// detected default.
base: hasLocalAccess ? currentBase : undefined,
hideWhitespace: currentHideWhitespace,
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
...(workspace && { diffOptions: workspace.diffOptions }),
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
gitContext: hasLocalAccess ? gitContext : undefined,
sharingEnabled,
shareBaseUrl,
repoInfo,
isWSL: wslFlag,
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
...(options.agentCwd && { agentCwd: options.agentCwd }),
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
...(workspace && { agentCwd: workspace.root }),
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
...(isPRMode && {
prMetadata,
platformUser,
prStackInfo,
prStackTree,
prDiffScope: currentPRDiffScope,
prDiffScopeOptions,
}),
2026-03-25 21:33:33 +01:00
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
...(currentError && { error: currentError }),
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
serverConfig: getServerConfig(gitUser),
});
}
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
// API: Get semantic diff content
if (url.pathname === "/api/semantic-diff" && req.method === "GET") {
return Response.json(await getSemanticDiff(url));
}
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
// API: Switch diff type (requires local file access)
if (url.pathname === "/api/diff/switch" && req.method === "POST") {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
if (!hasLocalAccess && !workspace) {
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
return Response.json(
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
{ error: "Not available without local file access" },
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
{ status: 400 },
);
}
try {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const body = (await req.json()) as { diffType: DiffType | WorkspaceDiffType; base?: string; hideWhitespace?: boolean };
let newDiffType = body.diffType;
if (!newDiffType) {
return Response.json(
{ error: "Missing diffType" },
{ status: 400 }
);
}
if (typeof body.hideWhitespace === "boolean") {
currentHideWhitespace = body.hideWhitespace;
}
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
if (workspace) {
const snapshot = await workspace.rebuild({
diffType: newDiffType,
hideWhitespace: currentHideWhitespace,
});
currentPatch = snapshot.rawPatch;
currentGitRef = snapshot.gitRef;
currentDiffType = workspace.diffType;
currentError = snapshot.error;
draftKey = contentHash(currentPatch);
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
diffType: currentDiffType,
diffOptions: workspace.diffOptions,
hideWhitespace: currentHideWhitespace,
...(currentError && { error: currentError }),
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
});
}
2026-04-23 16:49:25 -07:00
// Guard against non-string payloads — resolveBaseBranch calls
// string methods and would throw a TypeError otherwise. Mirrors
// Pi's guard so both runtimes validate identically.
const requestedBase = typeof body.base === "string" ? body.base : undefined;
const base = resolveReviewBase(requestedBase);
const defaultCwd = gitContext?.cwd;
// Run the new diff
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const result = await runVcsDiff(newDiffType as DiffType, base, defaultCwd, {
hideWhitespace: currentHideWhitespace,
});
// Update state
currentPatch = result.patch;
currentGitRef = result.label;
currentDiffType = newDiffType;
2026-04-23 16:49:25 -07:00
currentBase = base;
baseEverSwitched = true;
currentError = result.error;
2026-04-23 16:49:25 -07:00
// Recompute gitContext for the effective cwd so the client's
// sidebar (current branch, default branch, diff-mode options)
// reflects the worktree we're now reviewing — not the main
// repo's startup state. Best-effort: on failure the client
// keeps its existing context.
let updatedContext: GitContext | undefined;
if (gitContext) {
try {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const effectiveCwd = resolveVcsCwd(newDiffType as DiffType, gitContext.cwd);
updatedContext = await getVcsContext(effectiveCwd, sessionVcsType);
2026-04-23 16:49:25 -07:00
} catch {
/* best-effort */
}
}
feat: split worktree/diff-type into separate controls (#248) * feat: split worktree/diff-type into separate controls The single dropdown that mixed diff type selection (uncommitted, last-commit, branch) with worktree switching was confusing — entering a worktree silently replaced all dropdown options with no persistent indicator of which worktree was active. Split into two controls: - Context dropdown: switches between main repo and worktrees (only shown when worktrees exist, highlighted when a worktree is active) - View dropdown: always shows the same diff type options regardless of context Server changes: - GitContext now exposes worktrees as a separate field - Removed getWorktreeDiffOptions() and back-to-main sentinel handling - Simplified /api/diff/switch (no more diffOptions replacement) Client changes: - New activeWorktreePath state + handleWorktreeSwitch callback - handleDiffSwitch composes worktree prefix from context automatically - Derived activeDiffBase strips worktree prefix for dropdown display Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: derive activeWorktreePath from diffType instead of separate state Eliminates redundant state — activeWorktreePath and activeDiffBase are now both derived in a single useMemo from the composite diffType string. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move DiffOption, WorktreeInfo, GitContext to @plannotator/shared Eliminates duplicate interface definitions across server and client. Types now live in packages/shared/types.ts and are imported by both packages/server/git.ts and packages/review-editor/. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 16:15:14 -07:00
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
diffType: currentDiffType,
2026-04-23 16:49:25 -07:00
// Echo the base the server actually used. resolveBaseBranch
// trusts the caller verbatim; this echo lets the client
// confirm the request landed (and pick it up when the client
// didn't supply one and we fell back to detected default).
base: currentBase,
hideWhitespace: currentHideWhitespace,
2026-04-23 16:49:25 -07:00
...(updatedContext && { gitContext: updatedContext }),
...(currentError && { error: currentError }),
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
feat: split worktree/diff-type into separate controls (#248) * feat: split worktree/diff-type into separate controls The single dropdown that mixed diff type selection (uncommitted, last-commit, branch) with worktree switching was confusing — entering a worktree silently replaced all dropdown options with no persistent indicator of which worktree was active. Split into two controls: - Context dropdown: switches between main repo and worktrees (only shown when worktrees exist, highlighted when a worktree is active) - View dropdown: always shows the same diff type options regardless of context Server changes: - GitContext now exposes worktrees as a separate field - Removed getWorktreeDiffOptions() and back-to-main sentinel handling - Simplified /api/diff/switch (no more diffOptions replacement) Client changes: - New activeWorktreePath state + handleWorktreeSwitch callback - handleDiffSwitch composes worktree prefix from context automatically - Derived activeDiffBase strips worktree prefix for dropdown display Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: derive activeWorktreePath from diffType instead of separate state Eliminates redundant state — activeWorktreePath and activeDiffBase are now both derived in a single useMemo from the composite diffType string. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move DiffOption, WorktreeInfo, GitContext to @plannotator/shared Eliminates duplicate interface definitions across server and client. Types now live in packages/shared/types.ts and are imported by both packages/server/git.ts and packages/review-editor/. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 16:15:14 -07:00
});
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to switch diff";
return Response.json({ error: message }, { status: 500 });
}
}
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
// API: Switch PR diff scope between the platform layer diff and a local full-stack diff.
if (url.pathname === "/api/pr-diff-scope" && req.method === "POST") {
if (!isPRMode || !prMetadata) {
return Response.json({ error: "Not in PR mode" }, { status: 400 });
}
try {
const body = (await req.json()) as { scope?: PRDiffScope };
if (body.scope !== "layer" && body.scope !== "full-stack") {
return Response.json({ error: "Invalid PR diff scope" }, { status: 400 });
}
if (body.scope === "layer") {
currentPatch = originalPRPatch;
currentGitRef = originalPRGitRef;
currentError = originalPRError;
currentPRDiffScope = "layer";
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
prDiffScope: currentPRDiffScope,
...(currentError && { error: currentError }),
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
});
}
const fullStackOption = prDiffScopeOptions.find((option) => option.id === "full-stack");
if (!fullStackOption?.enabled || !(options.worktreePool || options.agentCwd)) {
return Response.json(
{ error: "Full stack diff requires a stacked PR and a local checkout" },
{ status: 400 },
);
}
const fullStackCwd = (options.worktreePool && prMetadata ? options.worktreePool.resolve(prMetadata.url) : undefined) ?? options.agentCwd;
const result = await runPRFullStackDiff(gitRuntime, prMetadata, fullStackCwd);
if (result.error) {
return Response.json({ error: result.error }, { status: 400 });
}
currentPatch = result.patch;
currentGitRef = result.label;
currentError = undefined;
currentPRDiffScope = "full-stack";
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
prDiffScope: currentPRDiffScope,
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
});
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to switch PR diff scope";
return Response.json({ error: message }, { status: 500 });
}
}
// API: List PRs for the current repo (cached for 30s)
if (url.pathname === "/api/pr-list" && req.method === "GET") {
if (!isPRMode || !prRef) {
return Response.json({ error: "Not in PR mode" }, { status: 400 });
}
try {
const now = Date.now();
if (prListCache && now - prListCacheTime < 30_000) {
return Response.json({ prs: prListCache });
}
const prs = await fetchPRList(prRef);
prListCache = prs;
prListCacheTime = now;
return Response.json({ prs });
} catch (err) {
return Response.json({ error: "Failed to fetch PR list" }, { status: 500 });
}
}
// API: Switch to a different PR in the stack (in-place navigation)
if (url.pathname === "/api/pr-switch" && req.method === "POST") {
if (!isPRMode || !prRef) {
return Response.json({ error: "Not in PR mode" }, { status: 400 });
}
try {
const body = (await req.json()) as { url?: string };
if (!body.url) {
return Response.json({ error: "Missing PR URL" }, { status: 400 });
}
const newRef = parsePRUrl(body.url);
if (!newRef) {
return Response.json({ error: "Invalid PR URL" }, { status: 400 });
}
if (!isSameProject(newRef, prRef!)) {
return Response.json({ error: "Cannot switch to a PR in a different repository" }, { status: 400 });
}
const cached = prSwitchCache.get(body.url);
const pr = cached ?? await fetchPR(newRef);
if (!cached) prSwitchCache.set(body.url, pr);
// Update mutable server state
prMetadata = pr.metadata;
prRef = prRefFromMetadata(pr.metadata);
currentPatch = pr.rawPatch;
currentGitRef = `${getMRLabel(pr.metadata)} ${getMRNumberLabel(pr.metadata)}`;
currentError = undefined;
originalPRPatch = pr.rawPatch;
originalPRGitRef = currentGitRef;
originalPRError = undefined;
currentPRDiffScope = "layer";
draftKey = contentHash(pr.rawPatch);
prListCache = null;
// Recompute stack info
prStackInfo = getPRStackInfo(pr.metadata);
// Fetch stack tree (cached per PR for the session)
if (prStackTreeCache.has(body.url)) {
prStackTree = prStackTreeCache.get(body.url) ?? null;
} else {
try {
prStackTree = await fetchPRStack(prRef, pr.metadata);
} catch {
prStackTree = null;
}
prStackTreeCache.set(body.url, prStackTree);
}
// Ensure worktree for the new PR (pool creates a fresh one, no shared-state mutation)
let hasLocalForNewPR = false;
if (options.worktreePool) {
try {
await options.worktreePool.ensure(gitRuntime, pr.metadata);
hasLocalForNewPR = true;
} catch {
// Pool creation failed — full-stack will be disabled
}
} else if (options.agentCwd) {
hasLocalForNewPR = await checkoutPRHead(gitRuntime, pr.metadata, options.agentCwd);
}
prStackInfo = resolveStackInfo(pr.metadata, prStackTree, prStackInfo);
prDiffScopeOptions = prStackInfo
? getPRDiffScopeOptions(pr.metadata, hasLocalForNewPR)
: [];
// Fetch viewed files for the new PR
let switchedViewedFiles: string[] = [];
try {
const viewedMap = await fetchPRViewedFiles(prRef);
switchedViewedFiles = Object.entries(viewedMap)
.filter(([, isViewed]) => isViewed)
.map(([path]) => path);
} catch {
// Non-fatal
}
initialViewedFiles = switchedViewedFiles;
repoInfo = {
display: getDisplayRepo(pr.metadata),
branch: `${getMRLabel(pr.metadata)} ${getMRNumberLabel(pr.metadata)}`,
};
return Response.json({
rawPatch: currentPatch,
gitRef: currentGitRef,
prMetadata: pr.metadata,
prStackInfo,
prStackTree,
prDiffScope: currentPRDiffScope,
prDiffScopeOptions,
repoInfo,
...(switchedViewedFiles.length > 0 && { viewedFiles: switchedViewedFiles }),
...(currentError ? { error: currentError } : {}),
feat(review): add semantic diff overview (#871) * feat(review): add semantic diff overview * fix(review): address semantic diff review findings * fix(review): harden semantic diff fallback * fix(review): avoid repo-local sem execution * fix(review): normalize semantic diff cwd * test(review): cover semantic diff local cwd * fix(gitlab): fetch raw MR diffs * fix(review): harden sem path resolution * docs(review): add semantic diff handoff * feat(review): semantic diff cards, header sem badges, jump-to-line - Restyle the semantic panel as real bordered cards (shadcn surface) instead of ASCII box-drawing; centered column, grid-aligned entity rows. - Hide orphan (module-level) changes from the rows, matching sem's default; the count still surfaces in the summary line. - Add a 'sem · N' hover popover to each diff file header showing that file's semantic changes, reusing the same row component as the panel. - Clicking an entity (panel or popover) scrolls the diff to the lines via pierre's [data-selected-line]; centers only when off-screen so manual drag-selection isn't disturbed. - Extract shared rows/helpers into semanticDiffShared; share one cached /api/semantic-diff fetch across header badges. * feat(review): land on All files by default Semantic diff stays available via the file-tree nav entry and header badges, but it's no longer the initial landing view. * chore(review): drop dead change-symbol entries, log badge fetch failures - Remove unreachable 'moved'/'renamed' entries from the changeSymbols table (getChangeSymbol early-returns for those before the lookup). - Log a console.error once per patch when the file-header badge's semantic diff fetch fails or returns a non-ok status, so a systemic failure leaves a trace instead of every badge silently showing nothing. * feat(review): flatten semantic diff panel into grouped list - Dissolve the per-file bordered cards into flat sections: the file path is now a quiet underlined header (single hairline) with entity rows flush beneath, hierarchy from whitespace + hover tint instead of boxes. - Split the path into muted directory + emphasized filename for faster scanning. - Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
semanticDiff: await getSemanticDiffAdvert(),
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
});
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to switch PR";
return Response.json({ error: message }, { status: 500 });
}
}
// API: Fetch PR context (comments, checks, merge status) — PR mode only
if (url.pathname === "/api/pr-context" && req.method === "GET") {
if (!isPRMode) {
return Response.json(
{ error: "Not in PR mode" },
{ status: 400 },
);
}
try {
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
const context = await fetchPRContext(prRef!);
return Response.json(context);
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to fetch PR context";
return Response.json({ error: message }, { status: 500 });
}
}
feat: expandable diff context in code review (#247) * feat: expandable diff context in code review (closes #243) Switch from PatchDiff to FileDiff component from @pierre/diffs to enable GitHub-style "show more lines" buttons between hunks. The library handles all expansion UI when provided full file contents via oldLines/newLines. - Add /api/file-content endpoint to serve old/new file content per diff type - Add getFileContentsForDiff() helper with ref mapping for all diff types - Parse patch client-side via getSingularPatch(), augment with file contents - Update @pierre/diffs from 1.0.4 to 1.0.11 (scroll sync fix, no breaking changes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: upgrade @pierre/diffs to beta, re-parse patch with full file contents The previous approach spread file content arrays onto a partial-mode FileDiffMetadata, causing hunk index mismatches and Shiki decoration errors. Now uses processFile() to re-parse the patch with oldFile/newFile so hunk indices are computed against the full file (isPartial: false), which is required for expansion to work correctly. Also fixes a flash error on file switch by tagging fileContents with the filePath they were fetched for, preventing stale contents from being paired with the wrong patch during the render before useEffect fires. - Upgrade @pierre/diffs from ^1.0.x to ^1.1.0-beta.19 in all workspaces - Add test fixtures for disjoint hunks, deleted/renamed/new files Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: abort stale file-content fetches, validate path params - Add AbortController to file-content fetch effect to cancel in-flight requests when switching files - Reject path traversal (.. or absolute paths) on /api/file-content - Document /api/file-content endpoint in CLAUDE.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:00:43 -07:00
// API: Get file content for expandable diff context
if (url.pathname === "/api/file-content" && req.method === "GET") {
const filePath = url.searchParams.get("path");
if (!filePath) {
return Response.json({ error: "Missing path" }, { status: 400 });
}
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
try { validateFilePath(filePath); } catch {
feat: expandable diff context in code review (#247) * feat: expandable diff context in code review (closes #243) Switch from PatchDiff to FileDiff component from @pierre/diffs to enable GitHub-style "show more lines" buttons between hunks. The library handles all expansion UI when provided full file contents via oldLines/newLines. - Add /api/file-content endpoint to serve old/new file content per diff type - Add getFileContentsForDiff() helper with ref mapping for all diff types - Parse patch client-side via getSingularPatch(), augment with file contents - Update @pierre/diffs from 1.0.4 to 1.0.11 (scroll sync fix, no breaking changes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: upgrade @pierre/diffs to beta, re-parse patch with full file contents The previous approach spread file content arrays onto a partial-mode FileDiffMetadata, causing hunk index mismatches and Shiki decoration errors. Now uses processFile() to re-parse the patch with oldFile/newFile so hunk indices are computed against the full file (isPartial: false), which is required for expansion to work correctly. Also fixes a flash error on file switch by tagging fileContents with the filePath they were fetched for, preventing stale contents from being paired with the wrong patch during the render before useEffect fires. - Upgrade @pierre/diffs from ^1.0.x to ^1.1.0-beta.19 in all workspaces - Add test fixtures for disjoint hunks, deleted/renamed/new files Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: abort stale file-content fetches, validate path params - Add AbortController to file-content fetch effect to cancel in-flight requests when switching files - Reject path traversal (.. or absolute paths) on /api/file-content - Document /api/file-content endpoint in CLAUDE.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:00:43 -07:00
return Response.json({ error: "Invalid path" }, { status: 400 });
}
const oldPath = url.searchParams.get("oldPath") || undefined;
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
if (oldPath) {
try { validateFilePath(oldPath); } catch {
return Response.json({ error: "Invalid path" }, { status: 400 });
}
feat: expandable diff context in code review (#247) * feat: expandable diff context in code review (closes #243) Switch from PatchDiff to FileDiff component from @pierre/diffs to enable GitHub-style "show more lines" buttons between hunks. The library handles all expansion UI when provided full file contents via oldLines/newLines. - Add /api/file-content endpoint to serve old/new file content per diff type - Add getFileContentsForDiff() helper with ref mapping for all diff types - Parse patch client-side via getSingularPatch(), augment with file contents - Update @pierre/diffs from 1.0.4 to 1.0.11 (scroll sync fix, no breaking changes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: upgrade @pierre/diffs to beta, re-parse patch with full file contents The previous approach spread file content arrays onto a partial-mode FileDiffMetadata, causing hunk index mismatches and Shiki decoration errors. Now uses processFile() to re-parse the patch with oldFile/newFile so hunk indices are computed against the full file (isPartial: false), which is required for expansion to work correctly. Also fixes a flash error on file switch by tagging fileContents with the filePath they were fetched for, preventing stale contents from being paired with the wrong patch during the render before useEffect fires. - Upgrade @pierre/diffs from ^1.0.x to ^1.1.0-beta.19 in all workspaces - Add test fixtures for disjoint hunks, deleted/renamed/new files Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: abort stale file-content fetches, validate path params - Add AbortController to file-content fetch effect to cancel in-flight requests when switching files - Reject path traversal (.. or absolute paths) on /api/file-content - Document /api/file-content endpoint in CLAUDE.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:00:43 -07:00
}
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
if (workspace) {
try {
const result = await workspace.getFileContents(filePath, oldPath);
return Response.json(result);
} catch (error) {
return Response.json(
{ error: error instanceof Error ? error.message : "No file access available" },
{ status: 400 },
);
}
}
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
// Full-stack PR mode uses local git for file expansion because
// the patch is no longer the platform's layer diff.
const fileContentCwd = (options.worktreePool && prMetadata) ? options.worktreePool.resolve(prMetadata.url) : options.agentCwd;
if (
isPRMode &&
currentPRDiffScope === "full-stack" &&
fileContentCwd &&
prMetadata?.defaultBranch
) {
const baseRef = await resolvePRFullStackBaseRef(
gitRuntime,
prMetadata!.defaultBranch,
fileContentCwd,
);
if (!baseRef) {
return Response.json(
{ oldContent: null, newContent: null },
);
}
const result = await getVcsFileContentsForDiff(
"merge-base",
baseRef,
filePath,
oldPath,
fileContentCwd,
);
return Response.json(result);
}
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
// Local review: read file contents from local git
if (hasLocalAccess) {
const requestedBase = url.searchParams.get("base") ?? undefined;
const base = resolveReviewBase(requestedBase);
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
const defaultCwd = gitContext?.cwd;
const result = await getVcsFileContentsForDiff(
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
currentDiffType as DiffType,
2026-04-23 16:49:25 -07:00
base,
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
filePath,
oldPath,
defaultCwd,
);
return Response.json(result);
}
// PR mode: fetch from platform API using merge-base/head SHAs.
// The diff is computed against the merge-base (common ancestor), not the
// base branch tip. File contents must match the diff for hunk expansion.
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
if (isPRMode && prMetadata) {
const oldSha = prMetadata.mergeBaseSha ?? prMetadata.baseSha;
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
const [oldContent, newContent] = await Promise.all([
fetchPRFileContent(prRef!, oldSha, oldPath || filePath),
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
fetchPRFileContent(prRef!, prMetadata.headSha, filePath),
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
]);
return Response.json({ oldContent, newContent });
}
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
return Response.json({ error: "No file access available" }, { status: 400 });
feat: expandable diff context in code review (#247) * feat: expandable diff context in code review (closes #243) Switch from PatchDiff to FileDiff component from @pierre/diffs to enable GitHub-style "show more lines" buttons between hunks. The library handles all expansion UI when provided full file contents via oldLines/newLines. - Add /api/file-content endpoint to serve old/new file content per diff type - Add getFileContentsForDiff() helper with ref mapping for all diff types - Parse patch client-side via getSingularPatch(), augment with file contents - Update @pierre/diffs from 1.0.4 to 1.0.11 (scroll sync fix, no breaking changes) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: upgrade @pierre/diffs to beta, re-parse patch with full file contents The previous approach spread file content arrays onto a partial-mode FileDiffMetadata, causing hunk index mismatches and Shiki decoration errors. Now uses processFile() to re-parse the patch with oldFile/newFile so hunk indices are computed against the full file (isPartial: false), which is required for expansion to work correctly. Also fixes a flash error on file switch by tagging fileContents with the filePath they were fetched for, preventing stale contents from being paired with the wrong patch during the render before useEffect fires. - Upgrade @pierre/diffs from ^1.0.x to ^1.1.0-beta.19 in all workspaces - Add test fixtures for disjoint hunks, deleted/renamed/new files Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: abort stale file-content fetches, validate path params - Add AbortController to file-content fetch effect to cancel in-flight requests when switching files - Reject path traversal (.. or absolute paths) on /api/file-content - Document /api/file-content endpoint in CLAUDE.md Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-08 14:00:43 -07:00
}
feat: search-based code navigation with peek view (#711) * feat: search-based code navigation with peek view (#694) Add IDE-like code navigation to the review UI. Cmd/Ctrl+click a token in a diff to find its definitions and references across the repo via ripgrep, displayed in a VS Code-style peek panel below the diff. Backend: bounded rg search with language-aware definition patterns (TS/JS, Python, Go, Rust), ranked results (same file > changed files > same directory), confidence labels, and graceful degradation when rg is not installed. Both Bun and Pi servers implement the endpoints. Frontend: Dockview peek panel with syntax-highlighted full-file preview on the left and grouped reference list on the right. Clicking a reference scrolls the preview; double-clicking an in-diff result navigates to the file with a gold line flash. Closes #694 * fix: resolve Pi server TypeScript errors for code-nav Add missing spawn import, type the close callback parameter, and use double-cast for parseBody → CodeNavRequest. * fix: clear loading state on cached preview hits Without this, clicking a cached file while a fetch is in-flight leaves isLoading stuck true — the spinner hides the preview. * feat: show pointer cursor on Cmd/Ctrl+hover for navigable tokens Adds pn-token-nav class with thicker underline and pointer cursor when hovering a token while holding the modifier key, signaling the token is Cmd+clickable for code navigation. * refactor: remove go-to-diff navigation from peek panel Strip the in-diff badge, double-click-to-jump, highlightDiffLine wiring, and onCodeNavGoToDiff from the peek panel. The peek view is the primary interaction — jump-to-diff adds complexity without clear value at this stage. * chore: remove dead code from code-nav cleanup Delete unused highlightDiffLine.ts, remove codeNavChangedFiles and codeNavActiveSide from context and App.tsx, drop stale extractChangedFiles import. * chore: add code-nav endpoints to AGENTS.md, remove dead activeSide state * fix: don't classify bare indented calls as definitions Change the TS/JS method pattern from zero-or-more (*) to one-or-more (+) declaration keywords, so plain calls like startServer(config) are no longer misclassified as definitions. * feat: show toast when code-nav is unavailable in platform-only PR mode Instead of opening the peek panel and showing misleading "No results", Cmd+click in non-local PR mode shows a brief toast explaining that code navigation requires a local checkout. * fix: strip hljs hardcoded background from code-nav preview The highlight.js github-dark theme sets a fixed dark background on all .hljs elements. Apply transparent override for the entire peek preview so code inherits the active theme's background.
2026-05-13 12:24:37 -07:00
// API: Code navigation (search-based symbol resolution)
if (url.pathname === "/api/code-nav/resolve" && req.method === "POST") {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const hasCodeNavAccess = !!workspace || !!gitContext || !!options.agentCwd || !!options.worktreePool;
feat: search-based code navigation with peek view (#711) * feat: search-based code navigation with peek view (#694) Add IDE-like code navigation to the review UI. Cmd/Ctrl+click a token in a diff to find its definitions and references across the repo via ripgrep, displayed in a VS Code-style peek panel below the diff. Backend: bounded rg search with language-aware definition patterns (TS/JS, Python, Go, Rust), ranked results (same file > changed files > same directory), confidence labels, and graceful degradation when rg is not installed. Both Bun and Pi servers implement the endpoints. Frontend: Dockview peek panel with syntax-highlighted full-file preview on the left and grouped reference list on the right. Clicking a reference scrolls the preview; double-clicking an in-diff result navigates to the file with a gold line flash. Closes #694 * fix: resolve Pi server TypeScript errors for code-nav Add missing spawn import, type the close callback parameter, and use double-cast for parseBody → CodeNavRequest. * fix: clear loading state on cached preview hits Without this, clicking a cached file while a fetch is in-flight leaves isLoading stuck true — the spinner hides the preview. * feat: show pointer cursor on Cmd/Ctrl+hover for navigable tokens Adds pn-token-nav class with thicker underline and pointer cursor when hovering a token while holding the modifier key, signaling the token is Cmd+clickable for code navigation. * refactor: remove go-to-diff navigation from peek panel Strip the in-diff badge, double-click-to-jump, highlightDiffLine wiring, and onCodeNavGoToDiff from the peek panel. The peek view is the primary interaction — jump-to-diff adds complexity without clear value at this stage. * chore: remove dead code from code-nav cleanup Delete unused highlightDiffLine.ts, remove codeNavChangedFiles and codeNavActiveSide from context and App.tsx, drop stale extractChangedFiles import. * chore: add code-nav endpoints to AGENTS.md, remove dead activeSide state * fix: don't classify bare indented calls as definitions Change the TS/JS method pattern from zero-or-more (*) to one-or-more (+) declaration keywords, so plain calls like startServer(config) are no longer misclassified as definitions. * feat: show toast when code-nav is unavailable in platform-only PR mode Instead of opening the peek panel and showing misleading "No results", Cmd+click in non-local PR mode shows a brief toast explaining that code navigation requires a local checkout. * fix: strip hljs hardcoded background from code-nav preview The highlight.js github-dark theme sets a fixed dark background on all .hljs elements. Apply transparent override for the entire peek preview so code inherits the active theme's background.
2026-05-13 12:24:37 -07:00
if (!hasCodeNavAccess) {
return Response.json(
{ error: "Code navigation requires local access" },
{ status: 400 },
);
}
const navCwd = resolveAgentCwd();
const changedFiles = extractChangedFiles(currentPatch);
return handleCodeNavResolve(req, navCwd, changedFiles);
}
// API: Code navigation file preview (read file from working tree)
if (url.pathname === "/api/code-nav/file" && req.method === "GET") {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const hasCodeNavAccess = !!workspace || !!gitContext || !!options.agentCwd || !!options.worktreePool;
feat: search-based code navigation with peek view (#711) * feat: search-based code navigation with peek view (#694) Add IDE-like code navigation to the review UI. Cmd/Ctrl+click a token in a diff to find its definitions and references across the repo via ripgrep, displayed in a VS Code-style peek panel below the diff. Backend: bounded rg search with language-aware definition patterns (TS/JS, Python, Go, Rust), ranked results (same file > changed files > same directory), confidence labels, and graceful degradation when rg is not installed. Both Bun and Pi servers implement the endpoints. Frontend: Dockview peek panel with syntax-highlighted full-file preview on the left and grouped reference list on the right. Clicking a reference scrolls the preview; double-clicking an in-diff result navigates to the file with a gold line flash. Closes #694 * fix: resolve Pi server TypeScript errors for code-nav Add missing spawn import, type the close callback parameter, and use double-cast for parseBody → CodeNavRequest. * fix: clear loading state on cached preview hits Without this, clicking a cached file while a fetch is in-flight leaves isLoading stuck true — the spinner hides the preview. * feat: show pointer cursor on Cmd/Ctrl+hover for navigable tokens Adds pn-token-nav class with thicker underline and pointer cursor when hovering a token while holding the modifier key, signaling the token is Cmd+clickable for code navigation. * refactor: remove go-to-diff navigation from peek panel Strip the in-diff badge, double-click-to-jump, highlightDiffLine wiring, and onCodeNavGoToDiff from the peek panel. The peek view is the primary interaction — jump-to-diff adds complexity without clear value at this stage. * chore: remove dead code from code-nav cleanup Delete unused highlightDiffLine.ts, remove codeNavChangedFiles and codeNavActiveSide from context and App.tsx, drop stale extractChangedFiles import. * chore: add code-nav endpoints to AGENTS.md, remove dead activeSide state * fix: don't classify bare indented calls as definitions Change the TS/JS method pattern from zero-or-more (*) to one-or-more (+) declaration keywords, so plain calls like startServer(config) are no longer misclassified as definitions. * feat: show toast when code-nav is unavailable in platform-only PR mode Instead of opening the peek panel and showing misleading "No results", Cmd+click in non-local PR mode shows a brief toast explaining that code navigation requires a local checkout. * fix: strip hljs hardcoded background from code-nav preview The highlight.js github-dark theme sets a fixed dark background on all .hljs elements. Apply transparent override for the entire peek preview so code inherits the active theme's background.
2026-05-13 12:24:37 -07:00
if (!hasCodeNavAccess) {
return Response.json({ error: "Code navigation requires local access" }, { status: 400 });
}
const filePath = url.searchParams.get("path");
if (!filePath) {
return Response.json({ error: "Missing path" }, { status: 400 });
}
try { validateFilePath(filePath); } catch {
return Response.json({ error: "Invalid path" }, { status: 400 });
}
try {
const navCwd = resolveAgentCwd();
const content = await Bun.file(`${navCwd}/${filePath}`).text();
return Response.json({ content });
} catch {
return Response.json({ error: "File not found" }, { status: 404 });
}
}
feat: add Perforce (P4) pending changelist diff support (#472) * feat: add Perforce pending changelist diff support for code review Introduce P4 support alongside existing Git backend via a VCS dispatch layer (vcs.ts). Detects Git vs Perforce workspace automatically and routes diff/file-content operations to the appropriate backend. - Add p4-default and p4-changelist:<N> DiffType variants - Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist context, unified diff conversion, binary file exclusion, batch p4 where - Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API - Update review server and CLI entry point to use VCS dispatch - Filter empty changelists from dropdown, disable staging for P4 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: introduce VcsProvider interface for extensible VCS support Replace hardcoded Git/P4 dispatch with a provider-based architecture. Each VCS implements VcsProvider interface and registers in a providers array — adding a new VCS only requires implementing the interface. - Define VcsProvider with detect, ownsDiffType, getContext, runDiff, getFileContents, and optional stageFile/unstageFile/resolveCwd - Create gitProvider and p4Provider as concrete implementations - Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd - Remove VCS-specific branching from review server endpoints Note: GitContext interface is not renamed to VcsContext in this commit. The rename touches too many files across the codebase (Pi extension, OpenCode plugin, shared types, tests) and should be handled as a separate pull request to keep the diff reviewable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: rtsummit <rtsummit@abutton.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
// API: Stage / unstage a file (disabled when VCS doesn't support it)
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
if (url.pathname === "/api/git-add" && req.method === "POST") {
try {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
const body = (await req.json()) as { filePath?: unknown; undo?: boolean };
if (typeof body.filePath !== "string" || !body.filePath) {
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
return Response.json({ error: "Missing filePath" }, { status: 400 });
}
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
try { validateFilePath(body.filePath); } catch {
return Response.json({ error: "Invalid path" }, { status: 400 });
}
if (workspace) {
try {
await workspace.stageFile(body.filePath, body.undo);
return Response.json({ ok: true });
} catch (error) {
return Response.json(
{ error: error instanceof Error ? error.message : "Failed to stage file" },
{ status: 400 },
);
}
}
const stageCwd = resolveVcsCwd(currentDiffType as DiffType, gitContext?.cwd);
if (isPRMode || !(await canStageFiles(currentDiffType as DiffType, stageCwd))) {
return Response.json(
{ error: "Staging not available" },
{ status: 400 },
);
}
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
if (body.undo) {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
await unstageFile(currentDiffType as DiffType, body.filePath, stageCwd);
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
} else {
feat(review): support multi-repo workspace reviews (#543) * feat(review): support multi-repo workspace reviews (#527) * fix(workspace): address critical issues from deep review - Fix race condition in label generation by pre-computing labels sequentially - Fix rewritePatchLine to support quoted paths and rename/copy headers - Add separator between aggregated patches to avoid invalid diffs - Normalize input paths in resolveWorkspaceFilePath - Add timeout to PR discovery (15s) to prevent server hangs - Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation - Validate body.source runtime (must be 'local' or 'pr') - Snapshot active repo in agent jobs at launch to prevent race in onJobComplete - Prevent double-prefixing of agent findings when paths are already prefixed - Fix frontend findWorkspaceRepoForPath to use longest-prefix matching - Fix shared types: diffType uses DiffType, platformUser is string | null * fix: remove duplicate gitRuntime export in vcs.ts * fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import * Add local multi-repo workspace review support * Fix workspace review edge cases * Remove session query from browser launch * Add switchable workspace review modes * fix(review): cover opencode workspace bridge * fix(review): clean workspace review plumbing * fix(review): clarify workspace agent finding paths * fix(review): preserve diff paths with spaces --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 18:29:38 -03:00
await stageFile(currentDiffType as DiffType, body.filePath, stageCwd);
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
}
return Response.json({ ok: true });
} catch (err) {
feat: add Perforce (P4) pending changelist diff support (#472) * feat: add Perforce pending changelist diff support for code review Introduce P4 support alongside existing Git backend via a VCS dispatch layer (vcs.ts). Detects Git vs Perforce workspace automatically and routes diff/file-content operations to the appropriate backend. - Add p4-default and p4-changelist:<N> DiffType variants - Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist context, unified diff conversion, binary file exclusion, batch p4 where - Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API - Update review server and CLI entry point to use VCS dispatch - Filter empty changelists from dropdown, disable staging for P4 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: introduce VcsProvider interface for extensible VCS support Replace hardcoded Git/P4 dispatch with a provider-based architecture. Each VCS implements VcsProvider interface and registers in a providers array — adding a new VCS only requires implementing the interface. - Define VcsProvider with detect, ownsDiffType, getContext, runDiff, getFileContents, and optional stageFile/unstageFile/resolveCwd - Create gitProvider and p4Provider as concrete implementations - Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd - Remove VCS-specific branching from review server endpoints Note: GitContext interface is not renamed to VcsContext in this commit. The rename touches too many files across the codebase (Pi extension, OpenCode plugin, shared types, tests) and should be handled as a separate pull request to keep the diff reviewable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: rtsummit <rtsummit@abutton.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 02:49:24 +09:00
const message = err instanceof Error ? err.message : "Failed to stage file";
feat: git add files from code review UI (#257) * feat: add per-file git add from code review UI (#254) Adds the ability to `git add` individual files directly from the code review interface. Users can stage approved files then switch to the new "Unstaged changes" diff view to see only remaining work. - POST /api/git-add endpoint with worktree support - gitAddFile/gitResetFile utilities in packages/server/git.ts - "Staged changes" and "Unstaged changes" added to diff type dropdown - useGitAdd hook encapsulating all staging state and API logic - "Git Add" / "Added" toggle button in FileHeader (next to Viewed) - Visual indicator (left border) for staged files in sidebar FileTree Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * style: use green background tint for staged files instead of left border Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: support staged/unstaged diffs in worktrees and display stage errors Adds "staged" and "unstaged" to worktree sub-type allowlists (server parser, client parser, and runGitDiff switch), displays stageError in FileHeader, and documents /api/git-add in CLAUDE.md. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: clean up git add feature — fix stale closure, timeout leak, dedup validation - useGitAdd: use ref for stagedFiles to stabilize stageFile callback, clear error timeout on reset, drop unnecessary useMemo - App.tsx: wrap onFileViewed in useCallback - FileTree: merge duplicate staged count conditionals - review.ts: reuse exported validateFilePath for /api/file-content Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 07:31:17 -07:00
return Response.json({ error: message }, { status: 500 });
}
}
// API: Update user config (write-back to ~/.plannotator/config.json)
if (url.pathname === "/api/config" && req.method === "POST") {
try {
feat: add Conventional Comments support to code review (#501) * feat: add Conventional Comments support to code review Add structured label system based on the Conventional Comments spec (conventionalcomments.org) to the code review annotation toolbar. - Label picker with 9 default labels (suggestion, nit, question, issue, praise, thought, note, todo, chore) shown above the comment textarea - Per-label blocking/non-blocking toggle for labels where severity is ambiguous (issue, suggestion, todo, chore) - Labels exported as `**label** (decoration): text` in markdown feedback, naturally readable on GitHub and machine-parseable - Label badges shown on inline annotations and sidebar cards - Settings tab (Comments) with: master on/off toggle, editable label list with add/remove/rename, per-label blocking decorator toggle, educational intro with spec link and example output - Feature is off by default, persisted via config store - Custom labels supported via settings (up to 12) For provenance purposes, this commit was AI assisted. * fix(review): address conventional comments review feedback Fix label clearing bug where editing an annotation to remove its conventional label silently preserved the old value. Fix parseCCLabels accepting 'non-blocking' as a truthy blocking value. Fix duplicate custom label identities when adding multiple labels. Prepend conventional prefix to platform PR/MR inline comments. For provenance purposes, this commit was AI assisted. * fix(server): persist conventionalComments setting to config.json All six server config handlers (bun plan/review/annotate + pi plan/review/annotate) now accept and save the conventionalComments boolean, so the setting survives server restarts. For provenance purposes, this commit was AI assisted. * fix: add conventionalComments to server config round-trip getServerConfig() was not returning the conventionalComments value from config.json, so the setting silently reset to false on cookie clear or new browser sessions. Also adds the field to the PlannotatorConfig interface so saveConfig() is properly typed. For provenance purposes, this commit was AI assisted. * fix: label display, export, and draft persistence for conventional comments - Remove slug derivation from label editing — store display text verbatim so badges and exports show what the user typed - Emit conventional prefix in export even when annotation has no prose text (suggestion-only annotations were losing their label) - Include conventionalLabel in draft save condition so label selection persists across file switches For provenance purposes, this commit was AI assisted. * fix: spec-compliant export format and empty label support - Wrap label + decorations + colon in markdown bold per the Conventional Comments spec examples (was bolding only the label) - Allow users to clear all labels — empty array no longer falls back to defaults in either the picker or the settings parser - Enable blocking decorator on the question label by default; the spec permits blocking questions and they sometimes are critical For provenance purposes, this commit was AI assisted. * fix: server-sync conventionalLabels and small cleanups - Sync conventionalLabels to ~/.plannotator/config.json so custom label configurations survive cookie clears and remote/SSH sessions, matching the persistence story for conventionalComments. Stored as a parsed array on disk; serialized as JSON string in the local config store to match the cookie format. - Remove no-op intermediate variable in handleSubmitAnnotation; pass conventionalLabel/decorations directly with proper coalescing per call path (edit preserves null, add coalesces to undefined). - Use index-prefixed key in the picker label list to avoid React warnings if duplicate labels ever exist. For provenance purposes, this commit was AI assisted.
2026-04-06 22:27:47 -07:00
const body = (await req.json()) as { displayName?: string; diffOptions?: Record<string, unknown>; conventionalComments?: boolean; conventionalLabels?: unknown[] | null };
feat(review): diff display options with ConfigStore integration (#428) * feat(config): add DiffOptions to PlannotatorConfig with deep-merge support Extends the server-side config system to support diff display options namespaced under `diffOptions` in ~/.plannotator/config.json. The saveConfig deep-merge ensures partial writes (e.g. changing only overflow) don't clobber sibling keys. For provenance purposes, this commit was AI assisted. * feat(server): accept diffOptions in POST /api/config handlers All six server handlers (plan, review, annotate x Bun + Pi) now whitelist diffOptions alongside displayName, forwarding it to saveConfig for deep-merged disk persistence. For provenance purposes, this commit was AI assisted. * feat(config): register diff display settings with deep-merge write batching Adds 6 diff option settings to the ConfigStore registry (diffStyle, diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers, diffShowBackground), all synced to disk under the diffOptions namespace. Fixes write batching for nested server keys — replaces Object.assign with deepMerge so rapid changes to multiple diff options within the 300ms debounce window don't clobber each other. Includes legacy cookie migration for the old review-diff-style key. For provenance purposes, this commit was AI assisted. * feat(review): wire diff display options through to @pierre/diffs Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6 diff options via useConfigValue and forwards them to FileDiff: overflow, diffIndicators, lineDiffType, disableLineNumbers, disableBackground. Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified toggle. Disables the custom resizable split dragger in wrap mode since Pierre manages its own grid layout. Fixes the unsafeCSS grid override to only target scroll mode, preventing per-character wrapping in split view. For provenance purposes, this commit was AI assisted. * feat(review): add Display tab to review-mode Settings dialog Adds a Display tab when Settings is in review mode, exposing all 6 diff options: Diff Style, Line Overflow, Change Indicators, Inline Diff Granularity, Show Line Numbers, and Show Diff Background. Changes take effect immediately and persist via ConfigStore (cookie + disk). Extracts reusable SegmentedControl and ToggleSwitch helpers for the review display controls. For provenance purposes, this commit was AI assisted. * chore: update bun.lock For provenance purposes, this commit was AI assisted. * fix(review): reapply search highlights after display option changes Add new diff display props to the search highlight and scroll-to-match effect dependency arrays so highlights are restored after Pierre re-renders. For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
const toSave: Record<string, unknown> = {};
if (body.displayName !== undefined) toSave.displayName = body.displayName;
if (body.diffOptions !== undefined) toSave.diffOptions = body.diffOptions;
feat: add Conventional Comments support to code review (#501) * feat: add Conventional Comments support to code review Add structured label system based on the Conventional Comments spec (conventionalcomments.org) to the code review annotation toolbar. - Label picker with 9 default labels (suggestion, nit, question, issue, praise, thought, note, todo, chore) shown above the comment textarea - Per-label blocking/non-blocking toggle for labels where severity is ambiguous (issue, suggestion, todo, chore) - Labels exported as `**label** (decoration): text` in markdown feedback, naturally readable on GitHub and machine-parseable - Label badges shown on inline annotations and sidebar cards - Settings tab (Comments) with: master on/off toggle, editable label list with add/remove/rename, per-label blocking decorator toggle, educational intro with spec link and example output - Feature is off by default, persisted via config store - Custom labels supported via settings (up to 12) For provenance purposes, this commit was AI assisted. * fix(review): address conventional comments review feedback Fix label clearing bug where editing an annotation to remove its conventional label silently preserved the old value. Fix parseCCLabels accepting 'non-blocking' as a truthy blocking value. Fix duplicate custom label identities when adding multiple labels. Prepend conventional prefix to platform PR/MR inline comments. For provenance purposes, this commit was AI assisted. * fix(server): persist conventionalComments setting to config.json All six server config handlers (bun plan/review/annotate + pi plan/review/annotate) now accept and save the conventionalComments boolean, so the setting survives server restarts. For provenance purposes, this commit was AI assisted. * fix: add conventionalComments to server config round-trip getServerConfig() was not returning the conventionalComments value from config.json, so the setting silently reset to false on cookie clear or new browser sessions. Also adds the field to the PlannotatorConfig interface so saveConfig() is properly typed. For provenance purposes, this commit was AI assisted. * fix: label display, export, and draft persistence for conventional comments - Remove slug derivation from label editing — store display text verbatim so badges and exports show what the user typed - Emit conventional prefix in export even when annotation has no prose text (suggestion-only annotations were losing their label) - Include conventionalLabel in draft save condition so label selection persists across file switches For provenance purposes, this commit was AI assisted. * fix: spec-compliant export format and empty label support - Wrap label + decorations + colon in markdown bold per the Conventional Comments spec examples (was bolding only the label) - Allow users to clear all labels — empty array no longer falls back to defaults in either the picker or the settings parser - Enable blocking decorator on the question label by default; the spec permits blocking questions and they sometimes are critical For provenance purposes, this commit was AI assisted. * fix: server-sync conventionalLabels and small cleanups - Sync conventionalLabels to ~/.plannotator/config.json so custom label configurations survive cookie clears and remote/SSH sessions, matching the persistence story for conventionalComments. Stored as a parsed array on disk; serialized as JSON string in the local config store to match the cookie format. - Remove no-op intermediate variable in handleSubmitAnnotation; pass conventionalLabel/decorations directly with proper coalescing per call path (edit preserves null, add coalesces to undefined). - Use index-prefixed key in the picker label list to avoid React warnings if duplicate labels ever exist. For provenance purposes, this commit was AI assisted.
2026-04-06 22:27:47 -07:00
if (body.conventionalComments !== undefined) toSave.conventionalComments = body.conventionalComments;
if (body.conventionalLabels !== undefined) toSave.conventionalLabels = body.conventionalLabels;
feat(review): diff display options with ConfigStore integration (#428) * feat(config): add DiffOptions to PlannotatorConfig with deep-merge support Extends the server-side config system to support diff display options namespaced under `diffOptions` in ~/.plannotator/config.json. The saveConfig deep-merge ensures partial writes (e.g. changing only overflow) don't clobber sibling keys. For provenance purposes, this commit was AI assisted. * feat(server): accept diffOptions in POST /api/config handlers All six server handlers (plan, review, annotate x Bun + Pi) now whitelist diffOptions alongside displayName, forwarding it to saveConfig for deep-merged disk persistence. For provenance purposes, this commit was AI assisted. * feat(config): register diff display settings with deep-merge write batching Adds 6 diff option settings to the ConfigStore registry (diffStyle, diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers, diffShowBackground), all synced to disk under the diffOptions namespace. Fixes write batching for nested server keys — replaces Object.assign with deepMerge so rapid changes to multiple diff options within the 300ms debounce window don't clobber each other. Includes legacy cookie migration for the old review-diff-style key. For provenance purposes, this commit was AI assisted. * feat(review): wire diff display options through to @pierre/diffs Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6 diff options via useConfigValue and forwards them to FileDiff: overflow, diffIndicators, lineDiffType, disableLineNumbers, disableBackground. Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified toggle. Disables the custom resizable split dragger in wrap mode since Pierre manages its own grid layout. Fixes the unsafeCSS grid override to only target scroll mode, preventing per-character wrapping in split view. For provenance purposes, this commit was AI assisted. * feat(review): add Display tab to review-mode Settings dialog Adds a Display tab when Settings is in review mode, exposing all 6 diff options: Diff Style, Line Overflow, Change Indicators, Inline Diff Granularity, Show Line Numbers, and Show Diff Background. Changes take effect immediately and persist via ConfigStore (cookie + disk). Extracts reusable SegmentedControl and ToggleSwitch helpers for the review display controls. For provenance purposes, this commit was AI assisted. * chore: update bun.lock For provenance purposes, this commit was AI assisted. * fix(review): reapply search highlights after display option changes Add new diff display props to the search highlight and scroll-to-match effect dependency arrays so highlights are restored after Pierre re-renders. For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
if (Object.keys(toSave).length > 0) saveConfig(toSave as Parameters<typeof saveConfig>[0]);
return Response.json({ ok: true });
} catch {
return Response.json({ error: "Invalid request" }, { status: 400 });
}
}
// API: Serve images (local paths or temp uploads)
if (url.pathname === "/api/image") {
return handleImage(req);
}
// API: Upload image -> save to temp -> return path
if (url.pathname === "/api/upload" && req.method === "POST") {
return handleUpload(req);
}
// API: Get available agents (OpenCode only)
if (url.pathname === "/api/agents") {
return handleAgents(options.opencodeClient);
}
// API: Annotation draft persistence
if (url.pathname === "/api/draft") {
if (req.method === "POST") return handleDraftSave(req, draftKey);
if (req.method === "DELETE") return handleDraftDelete(draftKey);
return handleDraftLoad(draftKey);
}
feat: VS Code editor annotations + theme integration (#239) * feat: add shared EditorAnnotation type Single source of truth for the editor annotation interface, imported by both @plannotator/server and @plannotator/ui. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation server endpoints In-memory store with POST/GET/DELETE endpoints for editor annotations. The array lives in the handler closure and dies with the server session. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotation UI — polling hook, card, panel, and export - useEditorAnnotations hook with auto-disable polling (500ms interval) - EditorAnnotationCard with file path, code preview, and comment - AnnotationPanel conditionally renders editor annotation section - exportEditorAnnotations formats annotations for Claude feedback - App.tsx wires hook, includes in output memo and send feedback gate Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code extension editor annotation command Cmd+Shift+. or right-click to capture selected text as an annotation. POSTs through the cookie proxy to the plannotator server. Adds amber left-border decorations on annotated lines, cleared on panel close. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: inline comment threads, lightbulb menu, and stronger decorations Replace showInputBox with VS Code CommentController for inline annotation threads anchored to selected code. Add CodeActionProvider for lightbulb discoverability. Stronger decoration styling with gutter icon. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: VS Code theme integration for webview Bridge VS Code CSS variables to Plannotator's CSS variable system via postMessage between wrapper page and proxied iframe. Automatically adopts the active VS Code color theme (dark/light/custom) without touching any UI components or CSS files. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: gate editor annotation polling behind VS Code detection Only poll /api/editor-annotations when running inside a VS Code webview (window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have zero network cost from the editor annotations feature. Also fixes poll interval from 500ms to 2000ms. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: faster polling, prevent unnecessary re-renders, unify HTTP helper - Poll interval 2s → 500ms for snappier annotation pickup - Shallow equality check on annotation IDs prevents React re-renders when poll data is unchanged - Merge postToProxy/deleteFromProxy into single requestProxy function Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * feat: editor annotations support in code review Wire existing editor annotation infrastructure into the review flow so VS Code users can annotate files outside the diff during code review. - Add editor annotation endpoints to review server (same 3-line pattern) - Call useEditorAnnotations hook in review App.tsx - Display editor annotations in ReviewPanel with "Editor" divider - Include editor annotations in feedback export and gating logic Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
// API: Editor annotations (VS Code extension)
const editorResponse = await editorAnnotations.handle(req, url);
if (editorResponse) return editorResponse;
// API: External annotations (SSE-based, for any external tool)
const externalResponse = await externalAnnotations.handle(req, url, {
disableIdleTimeout: () => server.timeout(req, 0),
});
if (externalResponse) return externalResponse;
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
// API: Agent jobs (background review agents)
const agentResponse = await agentJobs.handle(req, url, {
disableIdleTimeout: () => server.timeout(req, 0),
});
if (agentResponse) return agentResponse;
// API: Exit review session without feedback
if (url.pathname === "/api/exit" && req.method === "POST") {
deleteDraft(draftKey);
resolveDecision({ approved: false, feedback: "", annotations: [], exit: true });
return Response.json({ ok: true });
}
// API: Submit review feedback
if (url.pathname === "/api/feedback" && req.method === "POST") {
try {
const body = (await req.json()) as {
approved?: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
};
deleteDraft(draftKey);
resolveDecision({
approved: body.approved ?? false,
feedback: body.feedback || "",
annotations: body.annotations || [],
agentSwitch: body.agentSwitch,
});
return Response.json({ ok: true });
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to process feedback";
return Response.json({ error: message }, { status: 500 });
}
}
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
// API: Submit PR review directly to GitHub (PR mode only)
if (url.pathname === "/api/pr-action" && req.method === "POST") {
if (!isPRMode || !prMetadata) {
return Response.json({ error: "Not in PR mode" }, { status: 400 });
}
try {
const body = (await req.json()) as {
action: "approve" | "comment";
body: string;
fileComments: PRReviewFileComment[];
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
targetPrUrl?: string;
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
};
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
// Resolve target PR — either explicit target or current.
// When targetPrUrl is provided, the client has already filtered
// annotations by diffScope, so we skip the server-side scope guard.
let targetRef = prRef!;
let targetHeadSha = prMetadata.headSha;
let targetUrl = prMetadata.url;
if (body.targetPrUrl) {
const cached = prSwitchCache.get(body.targetPrUrl);
if (!cached) {
return Response.json({ error: "Target PR not found in session" }, { status: 400 });
}
targetRef = prRefFromMetadata(cached.metadata);
targetHeadSha = cached.metadata.headSha;
targetUrl = cached.metadata.url;
} else if (currentPRDiffScope !== "layer") {
return Response.json(
{ error: "Switch to Layer diff before posting a platform review" },
{ status: 400 },
);
}
console.error(`[pr-action] ${body.action} with ${body.fileComments.length} file comment(s), target=${targetUrl}, headSha=${targetHeadSha}`);
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
await submitPRReview(
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
targetRef,
targetHeadSha,
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
body.action,
body.body,
body.fileComments,
);
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
console.error(`[pr-action] Success`);
feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620) * feat(shared): add isSameProject, PR stack types, and PR list provider Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree, PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject() for owner/repo validation on PR switching. Adds fetchPRStack() and fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs). Includes 9 new tests for isSameProject covering GitHub, GitLab, and cross-platform scenarios. For provenance purposes, this commit was AI assisted. * feat(shared): add GitHub PR stack tree walking and PR list fetching Implements fetchGhPRStack() which walks up/down the PR stack via GraphQL, resolving numbers and titles for each node in the chain. Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support by removing hostnameArgs from fetchGhPRList (--repo already handles GHE). Filters jq "null" string from defaultBranch detection. For provenance purposes, this commit was AI assisted. * feat(shared): fetch defaultBranch for GitLab MRs Queries the project's default_branch via glab API so getPRStackInfo can detect stacked MRs on GitLab. Best-effort — caught errors fall back to undefined. For provenance purposes, this commit was AI assisted. * feat(shared): add PR stack detection and full-stack diff module New pr-stack module with: - getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch - getPRDiffScopeOptions(): generates layer/full-stack scope options - runPRFullStackDiff(): computes diff from default branch to HEAD - resolvePRFullStackBaseRef(): resolves origin/main or local main - checkoutPRHead(): fetches and checks out a PR head in a worktree - buildMinimalStackTree(): builds UI tree from stack info Includes 13 tests covering ref resolution, branch fallbacks, and GitLab ref formats. For provenance purposes, this commit was AI assisted. * feat(shared): add worktree pool for per-PR agent isolation Creates a session-scoped pool of git worktrees — each PR visited during a stacked review gets its own isolated checkout. Agents run in their PR's worktree undisturbed by PR switches. Handles deduplication of concurrent ensure() calls for the same PR. Includes 11 tests covering caching, cross-repo restrictions, GitLab ref formats, and cleanup. For provenance purposes, this commit was AI assisted. * feat(shared): add diffScope/prUrl to agent jobs, branch diff type Adds prUrl and diffScope optional fields to AgentJobInfo so agent findings carry the PR and scope context they were launched under. Exports new pr-stack and worktree-pool modules from package.json. Adds 'branch' to DefaultDiffType union for branch diff as default. For provenance purposes, this commit was AI assisted. * feat(ui): add PR annotation fields, Popover, and SearchableSelect Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and diffScope fields for stacked PR attribution. Adds shared Popover wrapper around radix-ui. Adds SearchableSelect for filterable dropdown lists (used by PR selector). For provenance purposes, this commit was AI assisted. * feat(ui): add branch diff as default option, new Git settings tab Adds 'Branch' as a fourth default diff type option in both the first-run dialog and settings panel. Moves the default diff type setting from the Display tab to a new Git tab in review mode. Updates config store validators to accept 'branch'. For provenance purposes, this commit was AI assisted. * feat(server): add prUrl/diffScope plumbing to agent jobs and prompts Threads prUrl and diffScope through the agent job lifecycle so findings carry the PR and scope they were generated under. Adds full-stack prompt branch to codex-review and tour-review — when in full-stack mode, the diff is inlined in the prompt instead of telling the agent to run git diff. Re-exports isSameProject and new PR provider functions from server/pr.ts. For provenance purposes, this commit was AI assisted. * feat(server): add stacked PR support to Bun review server Adds PR switching, layer/full-stack scope toggling, PR list caching, worktree pool integration, and multi-PR platform posting to the Bun review server. Key additions: - /api/pr-diff-scope: switch between layer and full-stack diffs - /api/pr-list: cached PR list for the current repo - /api/pr-switch: in-place navigation between PRs in a stack - /api/pr-action: targetPrUrl support for multi-PR posting - /api/file-content: full-stack branch for hunk expansion - prSwitchCache/prStackTreeCache for session-scoped caching - diffScope tagging on agent job completion - Scope guard: returns 400 on full-stack diff failure instead of overwriting the working diff with empty content For provenance purposes, this commit was AI assisted. * feat(ai): pass cwd to Claude agent SDK for worktree support Forwards the working directory to the Claude agent provider so agents run in the correct worktree when reviewing stacked PRs. For provenance purposes, this commit was AI assisted. * feat(pi): add stacked PR support to Pi server (Bun parity) Mirrors all stacked PR features from the Bun server: - PR switching, scope toggling, PR list, multi-PR posting - prSwitchCache/prStackTreeCache with initial PR seeding - diffScope/prUrl plumbing in agent jobs - Worktree pool creation and lifecycle - Full-stack file-content resolution matching Bun's guard structure - targetPrUrl support on /api/pr-action Hoists worktreePool declaration to outer scope in plannotator-browser to fix TS18004 scoping error. Updates vendor.sh for new shared modules. For provenance purposes, this commit was AI assisted. * feat(hook): create worktree pool for PR review sessions Creates a worktree pool when opening a PR review with --local, seeding it with the initial PR's checkout. Integrates pool cleanup into server shutdown. Passes the pool to startReviewServer for agent isolation during PR switching. For provenance purposes, this commit was AI assisted. * feat(review-editor): add hooks for PR stack, context, and annotations - useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope onto annotations, only when viewing a stacked PR - usePRStack: handles scope selection and PR switching with loading state - usePRContext: adds URL-change detection to prevent stale-fetch race when switching PRs (discards in-flight responses for previous PR) For provenance purposes, this commit was AI assisted. * feat(review-editor): add stacked PR UI components - PRSelector: searchable dropdown for switching between PRs in a repo - PRSwitchOverlay: loading animation during PR switch - StackedPRLabel: stack tree popover with scope selector and PR navigation - ReviewSubmissionDialog: multi-PR submission dialog with per-target status, orphaned findings section with copy-as-markdown, and partial failure retry For provenance purposes, this commit was AI assisted. * feat(review-editor): multi-PR export with heading hierarchy Updates exportReviewFeedback for multi-PR sessions: - Groups annotations by prUrl, then by file within each PR - Uses proper heading hierarchy (## for files, ### for annotations in multi-PR mode) - Detects single-PR mismatch (annotations from a different PR than the current view) and uses annotation-level PR context - Adds diffScope labels per PR group when present Includes 5 new tests: multi-PR headings, single-PR mismatch, diffScope labels, and non-stacked annotation handling. For provenance purposes, this commit was AI assisted. * feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents - ReviewSidebar: groups annotations by PR in multi-PR sessions, shows PR headers with annotation counts - ReviewDiffPanel: filters annotations by prUrl and diffScope so only matching annotations appear in the diff gutter - ReviewStateContext: adds prDiffScope to shared review state - ReviewAgentJobDetailPanel: shows diffScope in job detail - PRSummaryTab: shows stack info in PR summary - index.css: PR switch shimmer and overlay animations For provenance purposes, this commit was AI assisted. * feat(review-editor): wire stacked PR into main review app Integrates all stacked PR features into the review editor: - PR stack state management (prStackInfo, prStackTree, prDiffScope) - applyPRResponse: shared handler for PR switch and scope toggle, preserves active file index on scope changes - Multi-PR platform posting via Promise.allSettled with parallel requests, partial failure retry, and per-target status tracking - ReviewSubmissionDialog replaces inline dialog JSX - useAnnotationFactory stamps PR context onto annotations - keepalive on /api/feedback to survive tab closure - Proper try/catch/finally on handlePlatformAction For provenance purposes, this commit was AI assisted. * docs: add stacked PR review documentation Updates AGENTS.md, code-review command docs, and AI code review guide with stacked PR review capabilities. For provenance purposes, this commit was AI assisted. * fix(server): stamp prNumber/prTitle/prRepo on agent findings Agent annotations only had prUrl and diffScope, missing prNumber, prTitle, and prRepo. When agent findings were the only annotations for a PR target in the submission dialog, the target rendered as #0 with no title. Now resolves full PR context from prSwitchCache at job completion and stamps all five fields. Both Bun and Pi. For provenance purposes, this commit was AI assisted. * feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff" Consolidates two confusing committed-diff options into one: - Settings/first-run: "Committed" — "Everything you've committed on this branch" - Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff") Uses merge-base under the hood (matches GitHub PR behavior). Removes the two-dot branch diff from the UI — it stays in the runtime DiffType union for backwards compat. Old "branch" values in config/cookies are silently upgraded to merge-base. Git settings tab now uses radio cards with descriptions instead of a cramped segmented control. First-run dialog descriptions rewritten in plain language — no git commands. For provenance purposes, this commit was AI assisted. * fix(review-editor): rename client-side "PR Diff" labels to "Committed changes" DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base when the base picker is present. exportFeedback.ts also used "PR Diff" in export labels. Both now say "Committed changes" to match the server-side label and settings UI. For provenance purposes, this commit was AI assisted. * fix(server): discover stack UI for root PRs targeting the default branch Root PRs (baseBranch === defaultBranch) were excluded from stack detection because getPRStackInfo returned null. Now the server always fetches the stack tree in PR mode. If the tree reveals descendant PRs, prStackInfo is retroactively set with source "tree-discovered", enabling the stack UI, scope selector, and PR navigation from the root of a stack. Both Bun and Pi servers updated. Adds "tree-discovered" to the PRStackInfo source union. For provenance purposes, this commit was AI assisted. * fix(review-editor): derive diff scope from annotations, not UI state The export function now reads diffScope from annotations instead of the prReviewScope parameter. Fixes two issues: 1. Agent job "Copy All" showed the wrong scope when the user switched between layer/full-stack after launching the agent 2. Mixed-scope annotations produced a confusing "layer, full-stack" comma-joined label instead of grouping by scope Extracts renderScopedGroups helper for scope-aware grouping — used by both single-PR and multi-PR export paths. When annotations share one scope, it appears in the header. When mixed, annotations are grouped under ## Layer / ## Full-stack headings. Includes 4 new tests: uniform scope derivation, mixed scope grouping, single scope header, and prReviewScope override prevention. For provenance purposes, this commit was AI assisted. * fix(server): add tree-discovered stack fallback to pr-switch handler The initial-load path upgrades prStackInfo for root PRs when the stack tree reveals descendants, but the pr-switch handler was missing this logic. The server now sends correct prStackInfo after switching to a root-of-stack PR. Both Bun and Pi. Also removes stale prReviewScope dependency from agent job panel's copyAllText useMemo. For provenance purposes, this commit was AI assisted. * fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs Extracts the tree-discovered stack fallback into resolveStackInfo() in pr-stack.ts — eliminates 4 copies of the same logic across Bun startup, Bun pr-switch, Pi startup, and Pi pr-switch. Fixes StackedPRLabel showing on every PR: the check now counts non-default-branch nodes (> 1) instead of all nodes (> 1). Without this, every PR showed a "Stack (1 PR)" popover because the tree always has at least [defaultBranch, currentPR]. For provenance purposes, this commit was AI assisted. * fix(review-editor): don't re-open already-succeeded PR tabs on retry On partial failure retry, openUrls was pre-seeded with URLs from previously succeeded targets, causing those PR pages to re-open in the browser alongside newly succeeded ones. Now starts empty — only URLs from the current attempt are opened. For provenance purposes, this commit was AI assisted. * refactor(review-editor): extract PR session state into usePRSession hook Consolidates 5 independent useState calls (prMetadata, prStackInfo, prStackTree, prDiffScope, prDiffScopeOptions) into a single usePRSession hook with atomic updatePRSession callback. Replaces two identical 5-line setter blocks (initial load and applyPRResponse) with single updatePRSession calls. All ~60 consumer sites unchanged — same variable names via destructuring. For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
return Response.json({ ok: true, prUrl: targetUrl });
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to submit PR review";
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
console.error(`[pr-action] Failed: ${message}`);
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
return Response.json({ error: message }, { status: 500 });
}
}
2026-03-25 21:33:33 +01:00
// API: Mark/unmark PR files as viewed on GitHub (PR mode, GitHub only)
if (url.pathname === "/api/pr-viewed" && req.method === "POST") {
if (!isPRMode || !prMetadata) {
return Response.json({ error: "Not in PR mode" }, { status: 400 });
}
if (prMetadata.platform !== "github") {
return Response.json({ error: "Viewed sync only supported for GitHub" }, { status: 400 });
}
const prNodeId = prMetadata.prNodeId;
if (!prNodeId) {
return Response.json({ error: "PR node ID not available" }, { status: 400 });
}
try {
const body = (await req.json()) as {
filePaths: string[];
viewed: boolean;
};
await markPRFilesViewed(prRef!, prNodeId, body.filePaths, body.viewed);
return Response.json({ ok: true });
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to update viewed state";
console.error("[plannotator] /api/pr-viewed error:", message);
return Response.json({ error: message }, { status: 500 });
}
}
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
// AI endpoints
if (url.pathname.startsWith("/api/ai/")) {
const handler = aiRuntime.endpoints[url.pathname as keyof AIEndpoints];
if (handler) {
if (url.pathname === AI_QUERY_ENDPOINT) {
server.timeout(req, 0);
}
return handler(req);
}
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382) * feat(pi): add missing endpoints to plan, review, and annotate servers Phase 1-3 of Pi endpoint parity: Plan server: image, upload, draft, editor-annotations, agents, favicon, linked documents, Obsidian vaults/files/doc, file browser, VS Code diff Annotate server: image, upload, draft, favicon, linked documents, file browser Review server: extract shared handlers, add favicon Shared utilities extracted from review server inline code into reusable functions (handleImageRequest, handleUploadRequest, handleDraftRequest, handleFavicon). Reference handlers (doc, Obsidian, file browser) implemented using Node.js fs APIs replacing Bun.Glob/Bun.file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): add PR review endpoints and Node.js PR runtime adapter Phase 4 of Pi endpoint parity: - Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern) - GET /api/pr-context — fetch PR summary, comments, checks - POST /api/pr-action — submit review to GitHub/GitLab - PR mode guards on /api/diff/switch and /api/git-add - /api/diff response includes prMetadata and platformUser in PR mode - /api/file-content fetches from platform API in PR mode - Build script copies pr-provider, pr-github, pr-gitlab from shared Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): wire AI backbone with Node.js Pi SDK provider Phase 5 of Pi endpoint parity: - Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class using child_process.spawn instead of Bun.spawn, same RPC protocol - Register 4 AI providers in Pi review server (claude-agent-sdk, codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation - Route /api/ai/* endpoints through createAIEndpoints handlers - Pipe Web Response → node:http response with ReadableStream support for SSE streaming - Dispose AI sessions and registry on server stop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): address parity audit findings across all three servers Plan server: - /api/plan: add repoInfo and projectRoot to response - /api/approve: pass agentSwitch and permissionMode in decision - Update decision promise type to include agentSwitch, permissionMode Review server: - /api/diff/switch: pass gitContext.cwd to runGitDiff - /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore - /api/git-add: add fallback to gitContext.cwd when worktree parse fails Annotate server: - /api/plan: add repoInfo and projectRoot to response - /api/feedback: capture annotations array (was silently dropped) - Update decision promise type to include annotations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): complete parity — integrations, planSave, save-notes Ports all remaining missing functionality: - Node.js versions of saveToObsidian, saveToBear, saveToOctarine (Bun.write → writeFileSync, Bun.$ → spawn) - Node.js detectProjectNameSync (Bun.$ → execSync) - extractTags, generateFrontmatter, generateFilename, extractTitle - POST /api/save-notes — decoupled note saving - POST /api/approve — full implementation: note integrations, planSave snapshots, saveAnnotations, saveFinalSnapshot - POST /api/deny — planSave snapshots on denial - Import saveAnnotations, saveFinalSnapshot from storage.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): wire domain module imports and fix type errors - Add all missing imports from ./server/* domain modules to server.ts - Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.) - Move toWebRequest to helpers.ts, remove duplicate from handlers.ts - Add git() helper to project.ts (was in server.ts, needed by getRepoInfo) - Fix os default import → named imports in handlers.ts and network.ts - Fix readdirSync Dirent type in reference.ts - Fix Headers.entries() → forEach for Node compat in AI endpoint piping - Fix ReadableStream type cast in AI SSE streaming - Fix matchAll iterator compat in integrations.ts (use while + exec) - Cast pi-sdk provider config to any (PiSDKConfig not in base union) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): move generated shared files to generated/ directory Moves all build-time copied shared files (feedback-templates, review-core, storage, draft, project, pr-provider, pr-github, pr-gitlab) from the pi-extension root into generated/ subdirectory. Updates build script to output there. Updates all imports in server.ts, index.ts, and server/ domain modules to use ./generated/ paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): replace hand-maintained utils.ts with generated checklist utils.ts was a manual copy of parseChecklist, extractDoneSteps, and markCompletedSteps from packages/shared/checklist.ts. Add checklist to the build-time copy list and import from generated/checklist.js. Delete the redundant utils.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(pi): gitignore generated/ and built HTML files These are build artifacts created by `bun run build:pi`. Untrack them and add .gitignore to prevent re-adding. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): split server.ts into domain-organized modules - server.ts is now a barrel re-exporting from server/ modules - server/serverPlan.ts — plan review server - server/serverReview.ts — code review server - server/serverAnnotate.ts — annotate server - server/helpers.ts — add requestUrl() to eliminate non-null assertions - server/project.ts — linter fix (sanitizeTag import path) - packages/ai/package.json — add pi-sdk-node export entry - index.ts — fix waitForDone non-null assertion with guard check, update imports for generated/checklist.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): parity audit fixes + shared code extraction Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete). Fixes found during audit: - PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode - Missing permissionMode option and /api/plan response field - editorAnnotations created unnecessarily in archive mode - repoInfo called per-request instead of cached at init - Approve handler missing effectivePermissionMode fallback - Deny handler missing savedPath in decision resolution - Archive /api/plan response had extra pasteApiUrl - Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files - Review server had stray pasteApiUrl option/response field - AI getCwd missing worktree support Shared code extraction: - packages/shared/favicon.ts — single source for favicon SVG - packages/shared/integrations-common.ts — note app pure functions - packages/shared/reference-common.ts — file tree building - packages/shared/repo.ts — git remote parsing - Updated all consumers to import from shared sources For provenance purposes, this commit was AI assisted. * fix: parity audit B3-C10 — review + annotate server fixes Review server (B3-B17): - diff/switch missing try/catch error handling - git-add parseBody outside try/catch - feedback missing try/catch error handling - Unknown /api/ai/* paths now return 404 (both Bun and Pi) Annotate server (C1-C10): - Bun annotate server missing pasteApiUrl (short URL sharing broken) - Added pasteApiUrl to Bun options, response, and both hook callers - Pi repoInfo called per-request instead of cached at init - Pi feedback missing try/catch error handling - Missing GET method guards on doc and reference/files For provenance purposes, this commit was AI assisted. * fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400 D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync) - Made function sync (no longer async) - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution - Gains Windows path normalization, isWithinProjectRoot security check - Deleted packages/server/resolve-file.ts re-export, consumers import from shared - Cleaned up stale await calls in hook entry, reference handler, and tests - All 19 resolve-file tests pass For provenance purposes, this commit was AI assisted. * fix: parity audit D6-D10 — integrations, PR naming, shared modules D6: Fixed broken detectProjectNameSync — was using require() for non-existent exports. Now uses basename + sanitizeTag directly. D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across Bun server, hook, and OpenCode plugin to match Pi naming. Also fixed stale resolve-file import in OpenCode plugin. D8-D10: Verified clean — ide, project detection, network. For provenance purposes, this commit was AI assisted. * update openpackage.yml * fix: bump Pi git-add test timeout to 15s for parallel suite stability For provenance purposes, this commit was AI assisted. * test: add route parity test — Bun ↔ Pi server route drift detection For provenance purposes, this commit was AI assisted. * fix(ci): update Pi generate step to use generated/ directory with full file list The Pi extension was refactored to use generated/ subdirectory but the CI generate step still used the old flat layout with a subset of files. For provenance purposes, this commit was AI assisted. * fix(ci): update release workflow Pi generate step to match new layout Same stale generate step as test.yml — old flat layout, missing files. For provenance purposes, this commit was AI assisted. * fix(pi): update files array for modular server layout The files array still referenced the old flat layout (server.ts monolith, root-level generated files, deleted utils.ts). npm publish would have produced a broken package missing server/ and generated/ directories. For provenance purposes, this commit was AI assisted. * feat: add TypeScript type-checking to CI pipeline - Fix broken barrel export: buildFileTree/VaultNode re-exported from @plannotator/shared instead of reference-handlers (P1 bug) - Fix server.port type narrowing in all 3 servers - Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk) - Extract mapPiEvent to pi-events.ts to break Bun→Node type chain - Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension - Add `typecheck` script to root package.json - Add type-check step to test.yml and release.yml CI workflows For provenance purposes, this commit was AI assisted. * fix(ci): use bun-types instead of @types/node for typecheck CI environment has bun-types (includes Node types) but not @types/node as a standalone package. For provenance purposes, this commit was AI assisted. * fix(ci): add @types/node for Node-runtime type checks Pi extension and packages/shared run on Node, not Bun — they should type-check against @types/node, not bun-types. Added @types/node as a dev dependency so CI resolves it. For provenance purposes, this commit was AI assisted. * fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer) vs ArrayBuffer. Explicit cast resolves the overload mismatch. Astro pulls in TS 5.9 transitively, so CI resolves a different TypeScript version than local dev. This fix works on both 5.8 and 5.9. For provenance purposes, this commit was AI assisted. * fix(ci): add bun-types as explicit devDependency CI's bun install doesn't hoist bun-types to root node_modules when it's only a transitive dep of @types/bun. Adding it as a direct devDependency guarantees tsc can resolve it. For provenance purposes, this commit was AI assisted. * fix(ci): remove Pi extension from typecheck Pi extension depends on @mariozechner/pi-* peer dependencies that aren't installed in CI. Type-checking it requires Pi's runtime environment. The three packages we check (shared, ai, server) are sufficient to catch barrel export bugs and type errors. Pi extension coverage comes from route parity tests and bun test. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
return Response.json({ error: "Not found" }, { status: 404 });
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
}
// Favicon
if (url.pathname === "/favicon.svg") return handleFavicon();
// Serve embedded HTML for all other routes (SPA)
return new Response(htmlContent, {
headers: { "Content-Type": "text/html" },
});
},
error(err) {
console.error("[plannotator] Server error:", err);
return new Response(
`Internal Server Error: ${err instanceof Error ? err.message : String(err)}`,
{ status: 500, headers: { "Content-Type": "text/plain" } },
);
},
});
break; // Success, exit retry loop
} catch (err: unknown) {
const isAddressInUse =
err instanceof Error && err.message.includes("EADDRINUSE");
if (isAddressInUse && attempt < MAX_RETRIES) {
await Bun.sleep(RETRY_DELAY_MS);
continue;
}
if (isAddressInUse) {
const hint = isRemote ? " (set PLANNOTATOR_PORT to use different port)" : "";
throw new Error(`Port ${configuredPort} in use after ${MAX_RETRIES} retries${hint}`);
}
throw err;
}
}
if (!server) {
throw new Error("Failed to start server");
}
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382) * feat(pi): add missing endpoints to plan, review, and annotate servers Phase 1-3 of Pi endpoint parity: Plan server: image, upload, draft, editor-annotations, agents, favicon, linked documents, Obsidian vaults/files/doc, file browser, VS Code diff Annotate server: image, upload, draft, favicon, linked documents, file browser Review server: extract shared handlers, add favicon Shared utilities extracted from review server inline code into reusable functions (handleImageRequest, handleUploadRequest, handleDraftRequest, handleFavicon). Reference handlers (doc, Obsidian, file browser) implemented using Node.js fs APIs replacing Bun.Glob/Bun.file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): add PR review endpoints and Node.js PR runtime adapter Phase 4 of Pi endpoint parity: - Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern) - GET /api/pr-context — fetch PR summary, comments, checks - POST /api/pr-action — submit review to GitHub/GitLab - PR mode guards on /api/diff/switch and /api/git-add - /api/diff response includes prMetadata and platformUser in PR mode - /api/file-content fetches from platform API in PR mode - Build script copies pr-provider, pr-github, pr-gitlab from shared Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): wire AI backbone with Node.js Pi SDK provider Phase 5 of Pi endpoint parity: - Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class using child_process.spawn instead of Bun.spawn, same RPC protocol - Register 4 AI providers in Pi review server (claude-agent-sdk, codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation - Route /api/ai/* endpoints through createAIEndpoints handlers - Pipe Web Response → node:http response with ReadableStream support for SSE streaming - Dispose AI sessions and registry on server stop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): address parity audit findings across all three servers Plan server: - /api/plan: add repoInfo and projectRoot to response - /api/approve: pass agentSwitch and permissionMode in decision - Update decision promise type to include agentSwitch, permissionMode Review server: - /api/diff/switch: pass gitContext.cwd to runGitDiff - /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore - /api/git-add: add fallback to gitContext.cwd when worktree parse fails Annotate server: - /api/plan: add repoInfo and projectRoot to response - /api/feedback: capture annotations array (was silently dropped) - Update decision promise type to include annotations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): complete parity — integrations, planSave, save-notes Ports all remaining missing functionality: - Node.js versions of saveToObsidian, saveToBear, saveToOctarine (Bun.write → writeFileSync, Bun.$ → spawn) - Node.js detectProjectNameSync (Bun.$ → execSync) - extractTags, generateFrontmatter, generateFilename, extractTitle - POST /api/save-notes — decoupled note saving - POST /api/approve — full implementation: note integrations, planSave snapshots, saveAnnotations, saveFinalSnapshot - POST /api/deny — planSave snapshots on denial - Import saveAnnotations, saveFinalSnapshot from storage.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): wire domain module imports and fix type errors - Add all missing imports from ./server/* domain modules to server.ts - Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.) - Move toWebRequest to helpers.ts, remove duplicate from handlers.ts - Add git() helper to project.ts (was in server.ts, needed by getRepoInfo) - Fix os default import → named imports in handlers.ts and network.ts - Fix readdirSync Dirent type in reference.ts - Fix Headers.entries() → forEach for Node compat in AI endpoint piping - Fix ReadableStream type cast in AI SSE streaming - Fix matchAll iterator compat in integrations.ts (use while + exec) - Cast pi-sdk provider config to any (PiSDKConfig not in base union) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): move generated shared files to generated/ directory Moves all build-time copied shared files (feedback-templates, review-core, storage, draft, project, pr-provider, pr-github, pr-gitlab) from the pi-extension root into generated/ subdirectory. Updates build script to output there. Updates all imports in server.ts, index.ts, and server/ domain modules to use ./generated/ paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): replace hand-maintained utils.ts with generated checklist utils.ts was a manual copy of parseChecklist, extractDoneSteps, and markCompletedSteps from packages/shared/checklist.ts. Add checklist to the build-time copy list and import from generated/checklist.js. Delete the redundant utils.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(pi): gitignore generated/ and built HTML files These are build artifacts created by `bun run build:pi`. Untrack them and add .gitignore to prevent re-adding. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): split server.ts into domain-organized modules - server.ts is now a barrel re-exporting from server/ modules - server/serverPlan.ts — plan review server - server/serverReview.ts — code review server - server/serverAnnotate.ts — annotate server - server/helpers.ts — add requestUrl() to eliminate non-null assertions - server/project.ts — linter fix (sanitizeTag import path) - packages/ai/package.json — add pi-sdk-node export entry - index.ts — fix waitForDone non-null assertion with guard check, update imports for generated/checklist.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): parity audit fixes + shared code extraction Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete). Fixes found during audit: - PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode - Missing permissionMode option and /api/plan response field - editorAnnotations created unnecessarily in archive mode - repoInfo called per-request instead of cached at init - Approve handler missing effectivePermissionMode fallback - Deny handler missing savedPath in decision resolution - Archive /api/plan response had extra pasteApiUrl - Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files - Review server had stray pasteApiUrl option/response field - AI getCwd missing worktree support Shared code extraction: - packages/shared/favicon.ts — single source for favicon SVG - packages/shared/integrations-common.ts — note app pure functions - packages/shared/reference-common.ts — file tree building - packages/shared/repo.ts — git remote parsing - Updated all consumers to import from shared sources For provenance purposes, this commit was AI assisted. * fix: parity audit B3-C10 — review + annotate server fixes Review server (B3-B17): - diff/switch missing try/catch error handling - git-add parseBody outside try/catch - feedback missing try/catch error handling - Unknown /api/ai/* paths now return 404 (both Bun and Pi) Annotate server (C1-C10): - Bun annotate server missing pasteApiUrl (short URL sharing broken) - Added pasteApiUrl to Bun options, response, and both hook callers - Pi repoInfo called per-request instead of cached at init - Pi feedback missing try/catch error handling - Missing GET method guards on doc and reference/files For provenance purposes, this commit was AI assisted. * fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400 D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync) - Made function sync (no longer async) - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution - Gains Windows path normalization, isWithinProjectRoot security check - Deleted packages/server/resolve-file.ts re-export, consumers import from shared - Cleaned up stale await calls in hook entry, reference handler, and tests - All 19 resolve-file tests pass For provenance purposes, this commit was AI assisted. * fix: parity audit D6-D10 — integrations, PR naming, shared modules D6: Fixed broken detectProjectNameSync — was using require() for non-existent exports. Now uses basename + sanitizeTag directly. D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across Bun server, hook, and OpenCode plugin to match Pi naming. Also fixed stale resolve-file import in OpenCode plugin. D8-D10: Verified clean — ide, project detection, network. For provenance purposes, this commit was AI assisted. * update openpackage.yml * fix: bump Pi git-add test timeout to 15s for parallel suite stability For provenance purposes, this commit was AI assisted. * test: add route parity test — Bun ↔ Pi server route drift detection For provenance purposes, this commit was AI assisted. * fix(ci): update Pi generate step to use generated/ directory with full file list The Pi extension was refactored to use generated/ subdirectory but the CI generate step still used the old flat layout with a subset of files. For provenance purposes, this commit was AI assisted. * fix(ci): update release workflow Pi generate step to match new layout Same stale generate step as test.yml — old flat layout, missing files. For provenance purposes, this commit was AI assisted. * fix(pi): update files array for modular server layout The files array still referenced the old flat layout (server.ts monolith, root-level generated files, deleted utils.ts). npm publish would have produced a broken package missing server/ and generated/ directories. For provenance purposes, this commit was AI assisted. * feat: add TypeScript type-checking to CI pipeline - Fix broken barrel export: buildFileTree/VaultNode re-exported from @plannotator/shared instead of reference-handlers (P1 bug) - Fix server.port type narrowing in all 3 servers - Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk) - Extract mapPiEvent to pi-events.ts to break Bun→Node type chain - Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension - Add `typecheck` script to root package.json - Add type-check step to test.yml and release.yml CI workflows For provenance purposes, this commit was AI assisted. * fix(ci): use bun-types instead of @types/node for typecheck CI environment has bun-types (includes Node types) but not @types/node as a standalone package. For provenance purposes, this commit was AI assisted. * fix(ci): add @types/node for Node-runtime type checks Pi extension and packages/shared run on Node, not Bun — they should type-check against @types/node, not bun-types. Added @types/node as a dev dependency so CI resolves it. For provenance purposes, this commit was AI assisted. * fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer) vs ArrayBuffer. Explicit cast resolves the overload mismatch. Astro pulls in TS 5.9 transitively, so CI resolves a different TypeScript version than local dev. This fix works on both 5.8 and 5.9. For provenance purposes, this commit was AI assisted. * fix(ci): add bun-types as explicit devDependency CI's bun install doesn't hoist bun-types to root node_modules when it's only a transitive dep of @types/bun. Adding it as a direct devDependency guarantees tsc can resolve it. For provenance purposes, this commit was AI assisted. * fix(ci): remove Pi extension from typecheck Pi extension depends on @mariozechner/pi-* peer dependencies that aren't installed in CI. Type-checking it requires Pi's runtime environment. The three packages we check (shared, ai, server) are sufficient to catch barrel export bugs and type errors. Pi extension coverage comes from route parity tests and bun test. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
const port = server.port!;
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
serverUrl = `http://localhost:${port}`;
const exitHandler = () => agentJobs.killAll();
process.once("exit", exitHandler);
// Notify caller that server is ready
if (onReady) {
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382) * feat(pi): add missing endpoints to plan, review, and annotate servers Phase 1-3 of Pi endpoint parity: Plan server: image, upload, draft, editor-annotations, agents, favicon, linked documents, Obsidian vaults/files/doc, file browser, VS Code diff Annotate server: image, upload, draft, favicon, linked documents, file browser Review server: extract shared handlers, add favicon Shared utilities extracted from review server inline code into reusable functions (handleImageRequest, handleUploadRequest, handleDraftRequest, handleFavicon). Reference handlers (doc, Obsidian, file browser) implemented using Node.js fs APIs replacing Bun.Glob/Bun.file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): add PR review endpoints and Node.js PR runtime adapter Phase 4 of Pi endpoint parity: - Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern) - GET /api/pr-context — fetch PR summary, comments, checks - POST /api/pr-action — submit review to GitHub/GitLab - PR mode guards on /api/diff/switch and /api/git-add - /api/diff response includes prMetadata and platformUser in PR mode - /api/file-content fetches from platform API in PR mode - Build script copies pr-provider, pr-github, pr-gitlab from shared Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): wire AI backbone with Node.js Pi SDK provider Phase 5 of Pi endpoint parity: - Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class using child_process.spawn instead of Bun.spawn, same RPC protocol - Register 4 AI providers in Pi review server (claude-agent-sdk, codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation - Route /api/ai/* endpoints through createAIEndpoints handlers - Pipe Web Response → node:http response with ReadableStream support for SSE streaming - Dispose AI sessions and registry on server stop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): address parity audit findings across all three servers Plan server: - /api/plan: add repoInfo and projectRoot to response - /api/approve: pass agentSwitch and permissionMode in decision - Update decision promise type to include agentSwitch, permissionMode Review server: - /api/diff/switch: pass gitContext.cwd to runGitDiff - /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore - /api/git-add: add fallback to gitContext.cwd when worktree parse fails Annotate server: - /api/plan: add repoInfo and projectRoot to response - /api/feedback: capture annotations array (was silently dropped) - Update decision promise type to include annotations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): complete parity — integrations, planSave, save-notes Ports all remaining missing functionality: - Node.js versions of saveToObsidian, saveToBear, saveToOctarine (Bun.write → writeFileSync, Bun.$ → spawn) - Node.js detectProjectNameSync (Bun.$ → execSync) - extractTags, generateFrontmatter, generateFilename, extractTitle - POST /api/save-notes — decoupled note saving - POST /api/approve — full implementation: note integrations, planSave snapshots, saveAnnotations, saveFinalSnapshot - POST /api/deny — planSave snapshots on denial - Import saveAnnotations, saveFinalSnapshot from storage.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): wire domain module imports and fix type errors - Add all missing imports from ./server/* domain modules to server.ts - Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.) - Move toWebRequest to helpers.ts, remove duplicate from handlers.ts - Add git() helper to project.ts (was in server.ts, needed by getRepoInfo) - Fix os default import → named imports in handlers.ts and network.ts - Fix readdirSync Dirent type in reference.ts - Fix Headers.entries() → forEach for Node compat in AI endpoint piping - Fix ReadableStream type cast in AI SSE streaming - Fix matchAll iterator compat in integrations.ts (use while + exec) - Cast pi-sdk provider config to any (PiSDKConfig not in base union) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): move generated shared files to generated/ directory Moves all build-time copied shared files (feedback-templates, review-core, storage, draft, project, pr-provider, pr-github, pr-gitlab) from the pi-extension root into generated/ subdirectory. Updates build script to output there. Updates all imports in server.ts, index.ts, and server/ domain modules to use ./generated/ paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): replace hand-maintained utils.ts with generated checklist utils.ts was a manual copy of parseChecklist, extractDoneSteps, and markCompletedSteps from packages/shared/checklist.ts. Add checklist to the build-time copy list and import from generated/checklist.js. Delete the redundant utils.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(pi): gitignore generated/ and built HTML files These are build artifacts created by `bun run build:pi`. Untrack them and add .gitignore to prevent re-adding. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): split server.ts into domain-organized modules - server.ts is now a barrel re-exporting from server/ modules - server/serverPlan.ts — plan review server - server/serverReview.ts — code review server - server/serverAnnotate.ts — annotate server - server/helpers.ts — add requestUrl() to eliminate non-null assertions - server/project.ts — linter fix (sanitizeTag import path) - packages/ai/package.json — add pi-sdk-node export entry - index.ts — fix waitForDone non-null assertion with guard check, update imports for generated/checklist.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): parity audit fixes + shared code extraction Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete). Fixes found during audit: - PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode - Missing permissionMode option and /api/plan response field - editorAnnotations created unnecessarily in archive mode - repoInfo called per-request instead of cached at init - Approve handler missing effectivePermissionMode fallback - Deny handler missing savedPath in decision resolution - Archive /api/plan response had extra pasteApiUrl - Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files - Review server had stray pasteApiUrl option/response field - AI getCwd missing worktree support Shared code extraction: - packages/shared/favicon.ts — single source for favicon SVG - packages/shared/integrations-common.ts — note app pure functions - packages/shared/reference-common.ts — file tree building - packages/shared/repo.ts — git remote parsing - Updated all consumers to import from shared sources For provenance purposes, this commit was AI assisted. * fix: parity audit B3-C10 — review + annotate server fixes Review server (B3-B17): - diff/switch missing try/catch error handling - git-add parseBody outside try/catch - feedback missing try/catch error handling - Unknown /api/ai/* paths now return 404 (both Bun and Pi) Annotate server (C1-C10): - Bun annotate server missing pasteApiUrl (short URL sharing broken) - Added pasteApiUrl to Bun options, response, and both hook callers - Pi repoInfo called per-request instead of cached at init - Pi feedback missing try/catch error handling - Missing GET method guards on doc and reference/files For provenance purposes, this commit was AI assisted. * fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400 D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync) - Made function sync (no longer async) - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution - Gains Windows path normalization, isWithinProjectRoot security check - Deleted packages/server/resolve-file.ts re-export, consumers import from shared - Cleaned up stale await calls in hook entry, reference handler, and tests - All 19 resolve-file tests pass For provenance purposes, this commit was AI assisted. * fix: parity audit D6-D10 — integrations, PR naming, shared modules D6: Fixed broken detectProjectNameSync — was using require() for non-existent exports. Now uses basename + sanitizeTag directly. D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across Bun server, hook, and OpenCode plugin to match Pi naming. Also fixed stale resolve-file import in OpenCode plugin. D8-D10: Verified clean — ide, project detection, network. For provenance purposes, this commit was AI assisted. * update openpackage.yml * fix: bump Pi git-add test timeout to 15s for parallel suite stability For provenance purposes, this commit was AI assisted. * test: add route parity test — Bun ↔ Pi server route drift detection For provenance purposes, this commit was AI assisted. * fix(ci): update Pi generate step to use generated/ directory with full file list The Pi extension was refactored to use generated/ subdirectory but the CI generate step still used the old flat layout with a subset of files. For provenance purposes, this commit was AI assisted. * fix(ci): update release workflow Pi generate step to match new layout Same stale generate step as test.yml — old flat layout, missing files. For provenance purposes, this commit was AI assisted. * fix(pi): update files array for modular server layout The files array still referenced the old flat layout (server.ts monolith, root-level generated files, deleted utils.ts). npm publish would have produced a broken package missing server/ and generated/ directories. For provenance purposes, this commit was AI assisted. * feat: add TypeScript type-checking to CI pipeline - Fix broken barrel export: buildFileTree/VaultNode re-exported from @plannotator/shared instead of reference-handlers (P1 bug) - Fix server.port type narrowing in all 3 servers - Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk) - Extract mapPiEvent to pi-events.ts to break Bun→Node type chain - Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension - Add `typecheck` script to root package.json - Add type-check step to test.yml and release.yml CI workflows For provenance purposes, this commit was AI assisted. * fix(ci): use bun-types instead of @types/node for typecheck CI environment has bun-types (includes Node types) but not @types/node as a standalone package. For provenance purposes, this commit was AI assisted. * fix(ci): add @types/node for Node-runtime type checks Pi extension and packages/shared run on Node, not Bun — they should type-check against @types/node, not bun-types. Added @types/node as a dev dependency so CI resolves it. For provenance purposes, this commit was AI assisted. * fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer) vs ArrayBuffer. Explicit cast resolves the overload mismatch. Astro pulls in TS 5.9 transitively, so CI resolves a different TypeScript version than local dev. This fix works on both 5.8 and 5.9. For provenance purposes, this commit was AI assisted. * fix(ci): add bun-types as explicit devDependency CI's bun install doesn't hoist bun-types to root node_modules when it's only a transitive dep of @types/bun. Adding it as a direct devDependency guarantees tsc can resolve it. For provenance purposes, this commit was AI assisted. * fix(ci): remove Pi extension from typecheck Pi extension depends on @mariozechner/pi-* peer dependencies that aren't installed in CI. Type-checking it requires Pi's runtime environment. The three packages we check (shared, ai, server) are sufficient to catch barrel export bugs and type errors. Pi extension coverage comes from route parity tests and bun test. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
onReady(serverUrl, isRemote, port);
}
return {
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382) * feat(pi): add missing endpoints to plan, review, and annotate servers Phase 1-3 of Pi endpoint parity: Plan server: image, upload, draft, editor-annotations, agents, favicon, linked documents, Obsidian vaults/files/doc, file browser, VS Code diff Annotate server: image, upload, draft, favicon, linked documents, file browser Review server: extract shared handlers, add favicon Shared utilities extracted from review server inline code into reusable functions (handleImageRequest, handleUploadRequest, handleDraftRequest, handleFavicon). Reference handlers (doc, Obsidian, file browser) implemented using Node.js fs APIs replacing Bun.Glob/Bun.file. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): add PR review endpoints and Node.js PR runtime adapter Phase 4 of Pi endpoint parity: - Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern) - GET /api/pr-context — fetch PR summary, comments, checks - POST /api/pr-action — submit review to GitHub/GitLab - PR mode guards on /api/diff/switch and /api/git-add - /api/diff response includes prMetadata and platformUser in PR mode - /api/file-content fetches from platform API in PR mode - Build script copies pr-provider, pr-github, pr-gitlab from shared Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): wire AI backbone with Node.js Pi SDK provider Phase 5 of Pi endpoint parity: - Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class using child_process.spawn instead of Bun.spawn, same RPC protocol - Register 4 AI providers in Pi review server (claude-agent-sdk, codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation - Route /api/ai/* endpoints through createAIEndpoints handlers - Pipe Web Response → node:http response with ReadableStream support for SSE streaming - Dispose AI sessions and registry on server stop Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): address parity audit findings across all three servers Plan server: - /api/plan: add repoInfo and projectRoot to response - /api/approve: pass agentSwitch and permissionMode in decision - Update decision promise type to include agentSwitch, permissionMode Review server: - /api/diff/switch: pass gitContext.cwd to runGitDiff - /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore - /api/git-add: add fallback to gitContext.cwd when worktree parse fails Annotate server: - /api/plan: add repoInfo and projectRoot to response - /api/feedback: capture annotations array (was silently dropped) - Update decision promise type to include annotations Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(pi): complete parity — integrations, planSave, save-notes Ports all remaining missing functionality: - Node.js versions of saveToObsidian, saveToBear, saveToOctarine (Bun.write → writeFileSync, Bun.$ → spawn) - Node.js detectProjectNameSync (Bun.$ → execSync) - extractTags, generateFrontmatter, generateFilename, extractTitle - POST /api/save-notes — decoupled note saving - POST /api/approve — full implementation: note integrations, planSave snapshots, saveAnnotations, saveFinalSnapshot - POST /api/deny — planSave snapshots on denial - Import saveAnnotations, saveFinalSnapshot from storage.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): wire domain module imports and fix type errors - Add all missing imports from ./server/* domain modules to server.ts - Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.) - Move toWebRequest to helpers.ts, remove duplicate from handlers.ts - Add git() helper to project.ts (was in server.ts, needed by getRepoInfo) - Fix os default import → named imports in handlers.ts and network.ts - Fix readdirSync Dirent type in reference.ts - Fix Headers.entries() → forEach for Node compat in AI endpoint piping - Fix ReadableStream type cast in AI SSE streaming - Fix matchAll iterator compat in integrations.ts (use while + exec) - Cast pi-sdk provider config to any (PiSDKConfig not in base union) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): move generated shared files to generated/ directory Moves all build-time copied shared files (feedback-templates, review-core, storage, draft, project, pr-provider, pr-github, pr-gitlab) from the pi-extension root into generated/ subdirectory. Updates build script to output there. Updates all imports in server.ts, index.ts, and server/ domain modules to use ./generated/ paths. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): replace hand-maintained utils.ts with generated checklist utils.ts was a manual copy of parseChecklist, extractDoneSteps, and markCompletedSteps from packages/shared/checklist.ts. Add checklist to the build-time copy list and import from generated/checklist.js. Delete the redundant utils.ts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore(pi): gitignore generated/ and built HTML files These are build artifacts created by `bun run build:pi`. Untrack them and add .gitignore to prevent re-adding. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(pi): split server.ts into domain-organized modules - server.ts is now a barrel re-exporting from server/ modules - server/serverPlan.ts — plan review server - server/serverReview.ts — code review server - server/serverAnnotate.ts — annotate server - server/helpers.ts — add requestUrl() to eliminate non-null assertions - server/project.ts — linter fix (sanitizeTag import path) - packages/ai/package.json — add pi-sdk-node export entry - index.ts — fix waitForDone non-null assertion with guard check, update imports for generated/checklist.js Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(pi): parity audit fixes + shared code extraction Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete). Fixes found during audit: - PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode - Missing permissionMode option and /api/plan response field - editorAnnotations created unnecessarily in archive mode - repoInfo called per-request instead of cached at init - Approve handler missing effectivePermissionMode fallback - Deny handler missing savedPath in decision resolution - Archive /api/plan response had extra pasteApiUrl - Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files - Review server had stray pasteApiUrl option/response field - AI getCwd missing worktree support Shared code extraction: - packages/shared/favicon.ts — single source for favicon SVG - packages/shared/integrations-common.ts — note app pure functions - packages/shared/reference-common.ts — file tree building - packages/shared/repo.ts — git remote parsing - Updated all consumers to import from shared sources For provenance purposes, this commit was AI assisted. * fix: parity audit B3-C10 — review + annotate server fixes Review server (B3-B17): - diff/switch missing try/catch error handling - git-add parseBody outside try/catch - feedback missing try/catch error handling - Unknown /api/ai/* paths now return 404 (both Bun and Pi) Annotate server (C1-C10): - Bun annotate server missing pasteApiUrl (short URL sharing broken) - Added pasteApiUrl to Bun options, response, and both hook callers - Pi repoInfo called per-request instead of cached at init - Pi feedback missing try/catch error handling - Missing GET method guards on doc and reference/files For provenance purposes, this commit was AI assisted. * fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400 D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync) - Made function sync (no longer async) - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution - Gains Windows path normalization, isWithinProjectRoot security check - Deleted packages/server/resolve-file.ts re-export, consumers import from shared - Cleaned up stale await calls in hook entry, reference handler, and tests - All 19 resolve-file tests pass For provenance purposes, this commit was AI assisted. * fix: parity audit D6-D10 — integrations, PR naming, shared modules D6: Fixed broken detectProjectNameSync — was using require() for non-existent exports. Now uses basename + sanitizeTag directly. D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across Bun server, hook, and OpenCode plugin to match Pi naming. Also fixed stale resolve-file import in OpenCode plugin. D8-D10: Verified clean — ide, project detection, network. For provenance purposes, this commit was AI assisted. * update openpackage.yml * fix: bump Pi git-add test timeout to 15s for parallel suite stability For provenance purposes, this commit was AI assisted. * test: add route parity test — Bun ↔ Pi server route drift detection For provenance purposes, this commit was AI assisted. * fix(ci): update Pi generate step to use generated/ directory with full file list The Pi extension was refactored to use generated/ subdirectory but the CI generate step still used the old flat layout with a subset of files. For provenance purposes, this commit was AI assisted. * fix(ci): update release workflow Pi generate step to match new layout Same stale generate step as test.yml — old flat layout, missing files. For provenance purposes, this commit was AI assisted. * fix(pi): update files array for modular server layout The files array still referenced the old flat layout (server.ts monolith, root-level generated files, deleted utils.ts). npm publish would have produced a broken package missing server/ and generated/ directories. For provenance purposes, this commit was AI assisted. * feat: add TypeScript type-checking to CI pipeline - Fix broken barrel export: buildFileTree/VaultNode re-exported from @plannotator/shared instead of reference-handlers (P1 bug) - Fix server.port type narrowing in all 3 servers - Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk) - Extract mapPiEvent to pi-events.ts to break Bun→Node type chain - Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension - Add `typecheck` script to root package.json - Add type-check step to test.yml and release.yml CI workflows For provenance purposes, this commit was AI assisted. * fix(ci): use bun-types instead of @types/node for typecheck CI environment has bun-types (includes Node types) but not @types/node as a standalone package. For provenance purposes, this commit was AI assisted. * fix(ci): add @types/node for Node-runtime type checks Pi extension and packages/shared run on Node, not Bun — they should type-check against @types/node, not bun-types. Added @types/node as a dev dependency so CI resolves it. For provenance purposes, this commit was AI assisted. * fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer) vs ArrayBuffer. Explicit cast resolves the overload mismatch. Astro pulls in TS 5.9 transitively, so CI resolves a different TypeScript version than local dev. This fix works on both 5.8 and 5.9. For provenance purposes, this commit was AI assisted. * fix(ci): add bun-types as explicit devDependency CI's bun install doesn't hoist bun-types to root node_modules when it's only a transitive dep of @types/bun. Adding it as a direct devDependency guarantees tsc can resolve it. For provenance purposes, this commit was AI assisted. * fix(ci): remove Pi extension from typecheck Pi extension depends on @mariozechner/pi-* peer dependencies that aren't installed in CI. Type-checking it requires Pi's runtime environment. The three packages we check (shared, ai, server) are sufficient to catch barrel export bugs and type errors. Pi extension coverage comes from route parity tests and bun test. For provenance purposes, this commit was AI assisted. --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
port,
url: serverUrl,
isRemote,
waitForDecision: () => decisionPromise,
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
stop: () => {
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
process.removeListener("exit", exitHandler);
agentJobs.killAll();
aiRuntime.dispose();
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
server.stop();
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
// Invoke cleanup callback (e.g., remove temp worktree)
if (options.onCleanup) {
try {
const result = options.onCleanup();
if (result instanceof Promise) result.catch(() => {});
} catch { /* best effort */ }
}
feat(ai): AI backbone + inline chat for code review (#363) * feat(ai): add provider-agnostic AI backbone for inline chat Introduces @plannotator/ai — a pluggable provider layer that powers AI features (inline chat, plan Q&A, code review assistance) across all Plannotator surfaces. - ProviderRegistry: class-based, multi-instance provider management - SessionManager: in-memory session tracking with eviction, ID aliasing - Context builders: system prompts and fork preambles for all three modes - SSE streaming endpoints: session create/fork, query, abort, list - Claude Agent SDK provider: fork from parent sessions, read-only tools, per-query abort, cached SDK import, concurrent query guard - 34 passing tests covering all layers For provenance purposes, this commit was AI assisted. * fix(ai): address code review findings from PR #363 - Concurrent query race: reject with session_busy error instead of racing; add query generation counter so stale finally blocks don't clobber newer query state - Text dropped before tool_use: mapSDKMessage now returns AIMessage[] and flushes accumulated text before each tool_use block - defaultProvider returns instance ID: ProviderRegistry.getDefault() returns { id, provider } so capabilities endpoint sends the correct key for multi-instance setups - Fork preamble re-sent on error: use _firstQuerySent boolean instead of _resolvedId to guard preamble injection - Dead abortController params: remove unused abortController from CreateSessionOptions and AIProvider.resumeSession - Unused context in memory: remove context from SessionConfig and baseConfig — already consumed to build systemPrompt/forkPreamble - Fix tool_result mapping: SDK wraps tool results in SDKUserMessage (type "user"), not a "tool_result" type For provenance purposes, this commit was AI assisted. * feat(ai): inline AI chat on code review diffs Add "Ask AI" to the code review toolbar — select lines, ask questions about agent-written code, get streaming responses. Conversation persists across file switches with inline markers on the diff showing where questions were asked. - useAIChat hook: SSE streaming, lazy session creation, multi-turn - AskAIInput: question input with per-selection AI history - InlineAIMarker: compact sparkle markers on diff lines via @pierre - AITab: sidebar conversation grouped by file with collapsible sections - SparklesIcon: shared 3-star sparkle from automations branch - ReviewPanel: AI tab with message count badge, file group flash highlight - Server: mount AI endpoints in review server with graceful fallback - Support three question scopes: line, file, and general - Toolbar ergonomics: typed text submits as AI question, no double popover For provenance purposes, this commit was AI assisted. * fix(ai): toolbar popover ergonomics and visual consistency - X button closes entire toolbar in both modes (no ghost popover) - Comment/Ask AI toggle is inline in the action row, same position in both modes (left side, mirrored layout) - AI history appears below the input, not above - File group flash highlight uses --muted to match file tree hover For provenance purposes, this commit was AI assisted. * fix(ai): visual consistency, shared primitives, markdown rendering Visual consistency: - AI tab file group headers match FileTree pattern (sizing, hover, badges) - Q&A bubbles match annotation card padding and border-radius - Empty state uses circle-bg icon (same as annotations) - General input matches search input styling - Removed redundant CSS classes, moved to Tailwind Shared primitives: - Extract formatTimestamp to shared utility (was duplicated) - CountBadge component for consistent badge styling - CopyButton component with hover-reveal + "Copied" flash Affordances: - Copy button on AI responses (hover-reveal) - Send button on general input with keyboard shortcut hint - Timestamps on Q&A pairs - Keyboard shortcut title on Ask button Markdown rendering: - Add marked dependency for full block-level markdown in AI responses - renderMarkdown utility using marked + DOMPurify - Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes For provenance purposes, this commit was AI assisted. * feat(ai): permission inheritance + inline approval UI The inline AI agent now inherits the user's existing Claude Code permission rules via settingSources: ['user', 'project']. Tools already approved in ~/.claude/settings.json auto-approve silently. For tools not covered by existing rules, the SDK emits control_request messages. These are mapped to a new AIPermissionRequestMessage type and surfaced as inline approval cards in the AI tab — showing the tool name, command/input, and Allow/Deny buttons. Backend: - Map control_request to AIPermissionRequestMessage in provider - Store Query object on session for sending control_response back - respondToPermission() method on AISession sends allow/deny - POST /api/ai/permission endpoint for frontend → backend decisions - Add settingSources to ClaudeSDKQueryOptions Frontend: - PermissionCard component with Allow/Deny buttons + resolved state - useAIChat tracks permissionRequests array - respondToPermission() POSTs decision to server - AITab renders pending permission cards inline in conversation For provenance purposes, this commit was AI assisted. * fix(ai): streaming reactivity, maxTurns, popover→sidebar linking Streaming fixes: - State updates now create new object references via prev.map() instead of mutating objects inside the array — fixes React not re-rendering the sidebar during streaming - Complete assistant text messages only used as fallback when no streaming deltas received (prevents duplicate text) - Result text used as fallback when response is empty (agent spent all turns on tools) Config: - maxTurns raised to 99 (was 3 — agent ran out of turns reading files and never got to write its answer) Popover → sidebar linking: - Clicking AI history items in comment popover now passes questionId through to handleViewAIResponse, triggering the file group flash highlight in the sidebar (same behavior as clicking inline markers) Debug logging (temporary): - Server-side: [AI STREAM] logs every message the provider yields - Client-side: [AI SSE] logs every message received in the browser For provenance purposes, this commit was AI assisted. * refactor(ai): simplification pass — types, perf, cleanup From the three-agent code review analysis: Quality: - Rename AIMessage → AIChatEntry in review-editor to avoid collision with the wire-protocol AIMessage from packages/ai - Type permissionMode as union (not string) in SessionConfig + QueryOptions - Type _activeQuery with narrow interface instead of any - Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it) - Remove redundant sessionIdRef double-write in useAIChat - Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask] Performance: - Wrap QAPair in React.memo to prevent re-renders on sibling updates - Memoize renderMarkdown output via useMemo (avoid re-parsing on every token) - Fix auto-scroll useEffect: depend on messages.length not messages ref (prevents querySelectorAll on every streaming token) Cleanup: - Remove debug console.log from SSE endpoint and browser parser - Extract isMac/submitHint to shared utils/platform.ts - Extract generateId to shared utils/generateId.ts Net: -2 lines. No behavior changes. For provenance purposes, this commit was AI assisted. * chore: biome lint fixes — import types, button a11y, unused import - Use `import type` where only types are consumed (endpoints, CountBadge, CopyButton, renderMarkdown) - Remove unused AIContext import from session-manager - Template literal instead of string concat in context.ts truncate() - Add type="button" + aria-hidden on CopyButton SVGs For provenance purposes, this commit was AI assisted. * feat(ai): Codex SDK provider + multi-provider backend - Add CodexSDKProvider implementing AIProvider interface - Maps Codex ThreadEvents to AIMessage types - Delta tracking for streaming text from cumulative item.updated events - Supports resume, abort, sandbox modes - Factory self-registration pattern matching Claude provider - Enhance capabilities endpoint with provider models + metadata - Register both providers in review server (graceful degradation) - Add CodexSDKConfig type, models list (GPT-5.4 family) - Add reasoningEffort to CreateSessionOptions (Codex only) - Extract DiffFile interface to shared types.ts - Update CLAUDE.md with build order documentation - 54 tests passing (20+ new for Codex event mapping) For provenance purposes, this commit was AI assisted. * feat(ai): provider settings UI + inline config bar - Settings → AI tab: provider cards with per-provider model dropdowns - Inline config bar in AI chat sidebar (provider, model, reasoning effort) - Provider icons: Claude SVG + Codex PNG from marketing assets - Cookie-based persistence for provider + per-provider model preferences - useAIChat accepts providerId, model, reasoningEffort from props - Session reset on provider/model switch (next question starts fresh) - Reasoning effort selector (Codex only: Low/Medium/High/Max) - Update code review docs with AI provider documentation For provenance purposes, this commit was AI assisted. * fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep - Add missing selectedReasoningEffort + onReasoningEffortChange props to populated-state AIConfigBar (was only on empty-state, causing crash) - Disable GeneralInput while streaming to prevent concurrent queries - Thread cwd through CreateSessionOptions so AI sessions use the correct working directory (worktree-aware via getCwd resolver) - Add @openai/codex-sdk as a real dependency (was only an optional peer) - Eagerly verify codex-sdk importability at startup to avoid advertising a broken provider For provenance purposes, this commit was AI assisted. * fix(ai): polish config bar, input, and sidebar header - Replace native <select> dropdowns with custom popover menus that show provider icons, model names, and checkmarks on active selection - Remove disabled gear placeholder button - Auto-grow textarea upward on multi-line input (capped at 6 lines) - Push tab icons to far right in sidebar header (w-full on flex container) - Add centered divider between file-scoped and general questions For provenance purposes, this commit was AI assisted. * fix(ai): honest fork capability + permissionMode doc accuracy - Endpoint now checks capabilities.fork before calling forkSession(), falling back to createSession() for providers that can't truly fork - Codex forkSession() now throws as the interface contract requires (was silently faking a fork with no history — misleading UX) - Fixed permissionMode JSDoc: said "plan" but code defaults to "default" For provenance purposes, this commit was AI assisted. * fix(review): move search result count inside input field Count now appears inline to the left of the X button instead of squeezing the input from outside. Dynamic right padding accommodates the count + clear button when a query is active. For provenance purposes, this commit was AI assisted. * fix(ai): use claude_code preset, pass selected code to queries - Claude provider now uses { preset: "claude_code", append } instead of a raw system prompt, so inline chat inherits Claude Code's full built-in capabilities - Stripped custom role/guidelines preamble from context builders — just emit the review context (diff, plan, document) - handleAskAI now extracts selected code via extractLinesFromPatch and sends it with the query, fixing hallucinations on large PRs where the file's diff was truncated out of the system prompt For provenance purposes, this commit was AI assisted. * fix(ai): bundle both SDKs, remove peer dependencies Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now direct imports (no string indirection) so bun build --compile bundles them into the binary. Users don't need to install SDKs separately. Removed peer dependency declarations from packages/ai/package.json — meaningless for a compiled binary. For provenance purposes, this commit was AI assisted. * refactor: canonical platform.ts, file renames, file-level comments - Created packages/ui/utils/platform.ts as the single source for isMac, modKey, altKey, submitHint, isWindows - Consolidated inline navigator.platform checks from 6 files - Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor) - Renamed formatTimestamp → formatRelativeTime (clearer purpose) - Added file-level comments to InlineAIMarker, PermissionCard, generateId For provenance purposes, this commit was AI assisted. * docs(ai): add AI features guide + link from settings New docs page at guides/ai-features covering providers, models, configuration, session behavior, permissions, and available settings. AISettingsTab now links to the docs in both empty and populated states. For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
},
};
}