From b375a804b20e7673558b2325c1ea7595d16de90e Mon Sep 17 00:00:00 2001 From: Michael Ramos Date: Mon, 6 Apr 2026 12:15:27 -0700 Subject: [PATCH] feat(review): AI review agents, local worktree, and UI polish (#491) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * 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 --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/ 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 ``. 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/`) 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
. 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
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 — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted. --- AGENTS.md | 2 +- apps/hook/server/index.ts | 148 ++++- .../src/content/docs/guides/ai-code-review.md | 315 ++++++++++ apps/pi-extension/server/agent-jobs.ts | 157 ++++- .../server/external-annotations.ts | 8 + apps/pi-extension/server/serverReview.ts | 93 ++- apps/pi-extension/vendor.sh | 12 +- apps/review/package.json | 2 +- bun.lock | 16 +- import-octi/issue-closed.svg | 4 + import-octi/issue-opened.svg | 4 + import-octi/issue-reopened.svg | 4 + package.json | 2 +- packages/review-editor/App.tsx | 63 +- .../review-editor/components/CopyButton.tsx | 49 +- .../components/DiffHunkPreview.tsx | 116 ++++ .../review-editor/components/DiffViewer.tsx | 2 + .../review-editor/components/FileHeader.tsx | 4 +- .../review-editor/components/FileTree.tsx | 191 +++--- .../review-editor/components/FileTreeNode.tsx | 4 +- .../components/InlineAnnotation.tsx | 16 +- .../components/LiveLogViewer.tsx | 84 +++ .../review-editor/components/PRChecksTab.tsx | 19 +- .../components/PRCommentsTab.tsx | 557 +++++++++++++++--- .../review-editor/components/PRSummaryTab.tsx | 42 +- .../components/ReviewSidebar.tsx | 100 ++-- .../review-editor/components/ScrollFade.tsx | 54 ++ .../review-editor/dock/JobLogsContext.tsx | 23 + .../dock/ReviewDockTabRenderer.tsx | 2 +- .../review-editor/dock/ReviewStateContext.tsx | 1 + .../dock/panels/ReviewAgentJobDetailPanel.tsx | 501 +++++++++++----- .../dock/panels/ReviewPRCommentsPanel.tsx | 6 +- packages/review-editor/index.css | 44 +- packages/review-editor/package.json | 2 +- .../review-editor/utils/exportFeedback.ts | 4 + packages/server/agent-jobs.ts | 166 +++++- packages/server/claude-review.ts | 344 +++++++++++ packages/server/codex-review-schema.json | 41 ++ packages/server/codex-review.ts | 381 ++++++++++++ packages/server/external-annotations.ts | 9 + packages/server/git.ts | 3 +- packages/server/path-utils.ts | 18 + packages/server/review.ts | 145 ++++- packages/server/vcs.ts | 2 +- packages/shared/agent-jobs.ts | 11 + packages/shared/external-annotation.ts | 6 + packages/shared/package.json | 3 +- packages/shared/pr-github.ts | 86 ++- packages/shared/pr-gitlab.ts | 1 + packages/shared/pr-provider.ts | 22 + packages/shared/worktree.ts | 119 ++++ packages/ui/components/AgentsTab.tsx | 45 +- packages/ui/components/ConfirmDialog.tsx | 4 +- .../components/ReviewAgentsIcon.tsx | 0 packages/ui/components/ToolbarButtons.tsx | 13 +- packages/ui/hooks/useAgentJobs.ts | 11 +- packages/ui/types.ts | 11 + 57 files changed, 3536 insertions(+), 556 deletions(-) create mode 100644 apps/marketing/src/content/docs/guides/ai-code-review.md create mode 100644 import-octi/issue-closed.svg create mode 100644 import-octi/issue-opened.svg create mode 100644 import-octi/issue-reopened.svg create mode 100644 packages/review-editor/components/DiffHunkPreview.tsx create mode 100644 packages/review-editor/components/LiveLogViewer.tsx create mode 100644 packages/review-editor/components/ScrollFade.tsx create mode 100644 packages/review-editor/dock/JobLogsContext.tsx create mode 100644 packages/server/claude-review.ts create mode 100644 packages/server/codex-review-schema.json create mode 100644 packages/server/codex-review.ts create mode 100644 packages/server/path-utils.ts create mode 100644 packages/shared/worktree.ts rename packages/{review-editor => ui}/components/ReviewAgentsIcon.tsx (100%) diff --git a/AGENTS.md b/AGENTS.md index b028fdc4..3914db3c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -234,7 +234,7 @@ During normal plan review, an Archive sidebar tab provides the same browsing via | `/api/external-annotations` | POST | Add external annotations (single or batch `{ annotations: [...] }`) | | `/api/external-annotations` | PATCH | Update fields on a single annotation (`?id=`) | | `/api/external-annotations` | DELETE | Remove by `?id=`, `?source=`, or clear all | -| `/api/agents/capabilities` | GET | Check available agent providers (claude, codex, shell) | +| `/api/agents/capabilities` | GET | Check available agent providers (claude, codex) | | `/api/agents/jobs/stream` | GET | SSE stream for real-time agent job status updates | | `/api/agents/jobs` | GET | Snapshot of agent jobs (polling fallback, `?since=N` for version gating) | | `/api/agents/jobs` | POST | Launch an agent job (body: `{ provider, command, label }`) | diff --git a/apps/hook/server/index.ts b/apps/hook/server/index.ts index ad20c5fb..c3a4fe67 100644 --- a/apps/hook/server/index.ts +++ b/apps/hook/server/index.ts @@ -63,12 +63,14 @@ import { startAnnotateServer, handleAnnotateServerReady, } from "@plannotator/server/annotate"; -import { type DiffType, getVcsContext, runVcsDiff } from "@plannotator/server/vcs"; +import { type DiffType, getVcsContext, runVcsDiff, gitRuntime } from "@plannotator/server/vcs"; +import { fetchRef, createWorktree, removeWorktree, ensureObjectAvailable } from "@plannotator/shared/worktree"; import { parsePRUrl, checkPRAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr"; import { writeRemoteShareLink } from "@plannotator/server/share-url"; import { resolveMarkdownFile, hasMarkdownFiles } from "@plannotator/shared/resolve-file"; import { FILE_BROWSER_EXCLUDED } from "@plannotator/shared/reference-common"; -import { statSync } from "fs"; +import { statSync, rmSync, realpathSync } from "fs"; +import { parseRemoteUrl } from "@plannotator/shared/repo"; import { registerSession, unregisterSession, listSessions } from "@plannotator/server/sessions"; import { openBrowser } from "@plannotator/server/browser"; import { detectProjectName } from "@plannotator/server/project"; @@ -85,6 +87,7 @@ import { isTopLevelHelpInvocation, } from "./cli"; import path from "path"; +import { tmpdir } from "os"; // Embed the built HTML at compile time // @ts-ignore - Bun import attribute for text @@ -184,8 +187,17 @@ if (args[0] === "sessions") { // CODE REVIEW MODE // ============================================ + // Parse local flags (strip before URL detection) + // --local is now the default for PR/MR reviews; --no-local opts out. + // --local kept for backwards compat (no-op). + const localIdx = args.indexOf("--local"); + if (localIdx !== -1) args.splice(localIdx, 1); + const noLocalIdx = args.indexOf("--no-local"); + if (noLocalIdx !== -1) args.splice(noLocalIdx, 1); + const urlArg = args[1]; const isPRMode = urlArg?.startsWith("http://") || urlArg?.startsWith("https://"); + const useLocal = isPRMode && noLocalIdx === -1; let rawPatch: string; let gitRef: string; @@ -193,6 +205,8 @@ if (args[0] === "sessions") { let gitContext: Awaited> | undefined; let prMetadata: Awaited>["metadata"] | undefined; let initialDiffType: DiffType | undefined; + let agentCwd: string | undefined; + let worktreeCleanup: (() => void | Promise) | undefined; if (isPRMode) { // --- PR Review Mode --- @@ -231,6 +245,132 @@ if (args[0] === "sessions") { console.error(err instanceof Error ? err.message : "Failed to fetch PR"); process.exit(1); } + + // --local: create a local checkout with the PR head for full file access + if (useLocal && prMetadata) { + // Hoisted so catch block can clean up partially-created directories + let localPath: string | undefined; + try { + const repoDir = process.cwd(); + const identifier = prMetadata.platform === "github" + ? `${prMetadata.owner}-${prMetadata.repo}-${prMetadata.number}` + : `${prMetadata.projectPath.replace(/\//g, "-")}-${prMetadata.iid}`; + const suffix = Math.random().toString(36).slice(2, 8); + // Resolve tmpdir to its real path — on macOS, tmpdir() returns /var/folders/... + // but processes report /private/var/folders/... which breaks path stripping. + localPath = path.join(realpathSync(tmpdir()), `plannotator-pr-${identifier}-${suffix}`); + const fetchRefStr = prMetadata.platform === "github" + ? `refs/pull/${prMetadata.number}/head` + : `refs/merge-requests/${prMetadata.iid}/head`; + + // Validate inputs from platform API to prevent git flag/path injection + if (prMetadata.baseBranch.includes('..') || prMetadata.baseBranch.startsWith('-')) throw new Error(`Invalid base branch: ${prMetadata.baseBranch}`); + if (!/^[0-9a-f]{40,64}$/i.test(prMetadata.baseSha)) throw new Error(`Invalid base SHA: ${prMetadata.baseSha}`); + + // Detect same-repo vs cross-repo (must match both owner/repo AND host) + let isSameRepo = false; + try { + const remoteResult = await gitRuntime.runGit(["remote", "get-url", "origin"]); + if (remoteResult.exitCode === 0) { + const remoteUrl = remoteResult.stdout.trim(); + const currentRepo = parseRemoteUrl(remoteUrl); + const prRepo = prMetadata.platform === "github" + ? `${prMetadata.owner}/${prMetadata.repo}` + : prMetadata.projectPath; + const repoMatches = !!currentRepo && currentRepo.toLowerCase() === prRepo.toLowerCase(); + // Extract host from remote URL to avoid cross-instance false positives (GHE) + const sshHost = remoteUrl.match(/^[^@]+@([^:]+):/)?.[1]; + const httpsHost = (() => { try { return new URL(remoteUrl).hostname; } catch { return null; } })(); + const remoteHost = (sshHost || httpsHost || "").toLowerCase(); + const prHost = prMetadata.host.toLowerCase(); + isSameRepo = repoMatches && remoteHost === prHost; + } + } catch { /* not in a git repo — cross-repo path */ } + + if (isSameRepo) { + // ── Same-repo: fast worktree path ── + console.error("Fetching PR branch and creating local worktree..."); + // Fetch base branch so origin/ is current for agent diffs. + // Ensure baseSha is available (may fetch, which overwrites FETCH_HEAD). + // Both MUST happen before the PR head fetch since FETCH_HEAD is what + // createWorktree uses — the PR head fetch must be last. + await fetchRef(gitRuntime, prMetadata.baseBranch, { cwd: repoDir }); + await ensureObjectAvailable(gitRuntime, prMetadata.baseSha, { cwd: repoDir }); + // Fetch PR head LAST — sets FETCH_HEAD to the PR tip for createWorktree. + await fetchRef(gitRuntime, fetchRefStr, { cwd: repoDir }); + + await createWorktree(gitRuntime, { + ref: "FETCH_HEAD", + path: localPath, + detach: true, + cwd: repoDir, + }); + + worktreeCleanup = () => removeWorktree(gitRuntime, localPath, { force: true, cwd: repoDir }); + process.once("exit", () => { + try { Bun.spawnSync(["git", "worktree", "remove", "--force", localPath]); } catch {} + }); + } else { + // ── Cross-repo: shallow clone + fetch PR head ── + const prRepo = prMetadata.platform === "github" + ? `${prMetadata.owner}/${prMetadata.repo}` + : prMetadata.projectPath; + // Validate repo identifier to prevent flag injection via crafted URLs + if (/^-/.test(prRepo)) throw new Error(`Invalid repository identifier: ${prRepo}`); + const cli = prMetadata.platform === "github" ? "gh" : "glab"; + const host = prMetadata.host; + const hostnameArgs = (host === "github.com" || host === "gitlab.com") ? [] : ["--hostname", host]; + + // Step 1: Fast skeleton clone (no checkout, depth 1 — minimal data transfer) + console.error(`Cloning ${prRepo} (shallow)...`); + const cloneResult = Bun.spawnSync( + [cli, "repo", "clone", prRepo, localPath, ...hostnameArgs, "--", "--depth=1", "--no-checkout"], + { stderr: "pipe" }, + ); + if (cloneResult.exitCode !== 0) { + throw new Error(`${cli} repo clone failed: ${new TextDecoder().decode(cloneResult.stderr).trim()}`); + } + + // Step 2: Fetch only the PR head ref (targeted, much faster than full fetch) + console.error("Fetching PR branch..."); + const fetchResult = Bun.spawnSync( + ["git", "fetch", "--depth=50", "origin", fetchRefStr], + { cwd: localPath, stderr: "pipe" }, + ); + if (fetchResult.exitCode !== 0) throw new Error(`Failed to fetch PR head ref: ${new TextDecoder().decode(fetchResult.stderr).trim()}`); + + // Step 3: Checkout PR head (critical — if this fails, worktree is empty) + const checkoutResult = Bun.spawnSync(["git", "checkout", "FETCH_HEAD"], { cwd: localPath, stderr: "pipe" }); + if (checkoutResult.exitCode !== 0) { + throw new Error(`git checkout FETCH_HEAD failed: ${new TextDecoder().decode(checkoutResult.stderr).trim()}`); + } + + // Best-effort: create base refs so `git diff main...HEAD` and `git diff origin/main...HEAD` work + const baseFetch = Bun.spawnSync(["git", "fetch", "--depth=50", "origin", prMetadata.baseSha], { cwd: localPath, stderr: "pipe" }); + if (baseFetch.exitCode !== 0) console.error("Warning: failed to fetch baseSha, agent diffs may be inaccurate"); + Bun.spawnSync(["git", "branch", "--", prMetadata.baseBranch, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" }); + Bun.spawnSync(["git", "update-ref", `refs/remotes/origin/${prMetadata.baseBranch}`, prMetadata.baseSha], { cwd: localPath, stderr: "pipe" }); + + worktreeCleanup = () => { try { rmSync(localPath, { recursive: true, force: true }); } catch {} }; + process.once("exit", () => { + try { Bun.spawnSync(["rm", "-rf", localPath]); } catch {} + }); + } + + // --local only provides a sandbox path for agent processes. + // Do NOT set gitContext — that would contaminate the diff pipeline. + agentCwd = localPath; + + console.error(`Local checkout ready at ${localPath}`); + } catch (err) { + console.error(`Warning: --local failed, falling back to remote diff`); + console.error(err instanceof Error ? err.message : String(err)); + // Clean up partially-created directory (clone may have succeeded before fetch/checkout failed) + if (localPath) try { rmSync(localPath, { recursive: true, force: true }); } catch {} + agentCwd = undefined; + worktreeCleanup = undefined; + } + } } else { // --- Local Review Mode --- gitContext = await getVcsContext(); @@ -249,12 +389,14 @@ if (args[0] === "sessions") { gitRef, error: diffError, origin: detectedOrigin, - diffType: isPRMode ? undefined : (initialDiffType ?? "uncommitted"), + diffType: gitContext ? (initialDiffType ?? "uncommitted") : undefined, gitContext, prMetadata, + agentCwd, sharingEnabled, shareBaseUrl, htmlContent: reviewHtmlContent, + onCleanup: worktreeCleanup, onReady: async (url, isRemote, port) => { handleReviewServerReady(url, isRemote, port); diff --git a/apps/marketing/src/content/docs/guides/ai-code-review.md b/apps/marketing/src/content/docs/guides/ai-code-review.md new file mode 100644 index 00000000..5d79ad2f --- /dev/null +++ b/apps/marketing/src/content/docs/guides/ai-code-review.md @@ -0,0 +1,315 @@ +--- +title: "AI Code Review Agents" +description: "Automated code review using Codex and Claude Code agents with live findings, severity classification, and full prompt transparency." +sidebar: + order: 26 +section: "Guides" +--- + +Launch AI review agents from the Plannotator diff viewer. Agents analyze your changes in the background and produce structured findings inline. + +Two providers are supported: + +- **Codex CLI** uses priority-based findings (P0 through P3) +- **Claude Code** uses a multi-agent pipeline with severity-based findings (Important, Nit, Pre-existing) + +Both integrations are derived from official tooling. Claude's review model is based on Anthropic's [Claude Code Review](https://code.claude.com/docs/en/code-review) service and the open-source [code-review plugin](https://github.com/anthropics/claude-code/blob/main/plugins/code-review/README.md). Codex uses [OpenAI Codex CLI](https://github.com/openai/codex) structured output. + +## Flow + +1. Click **Run Agent** in the Agents tab (choose Codex or Claude) +2. The server builds the command with the appropriate prompt and schema +3. Agent runs in the background; live logs stream to the Logs tab +4. On completion, findings are parsed and appear as inline annotations + +For PR reviews, a temporary local checkout is created by default so the agent has file access beyond the diff. Pass `--no-local` to skip this. + +## Findings + +Each finding includes a file path, line range, description, and severity or priority. Claude findings also include a reasoning trace that explains how the issue was verified. + +Click any finding to navigate to the relevant file and line. Use the copy button on individual findings or "Copy All" to export as markdown. + +### Severity (Claude) + +| Level | Meaning | +|-------|---------| +| **Important** | Fix before merging. Build failures, logic errors, security issues. | +| **Nit** | Worth fixing, not blocking. Style, edge cases, code quality. | +| **Pre-existing** | Bug in surrounding code, not introduced by this PR. | + +### Priority (Codex) + +| Level | Meaning | +|-------|---------| +| **P0** | Blocking. Drop everything. | +| **P1** | Urgent. Next cycle. | +| **P2** | Normal. Fix eventually. | +| **P3** | Low. Nice to have. | + +## Local worktree + +PR and MR reviews automatically create a temporary checkout so agents can read files, follow imports, and understand the codebase. + +- **Same-repo**: git worktree (shared objects, fast) +- **Cross-repo**: shallow clone with targeted PR head fetch + +Cleaned up when the session ends. Use `--no-local` to review in remote-only mode. + +## Transparency + +Agents are read-only. They cannot modify code, access the network, or post comments. All AI communication goes directly to your provider (Anthropic or OpenAI). No code passes through Plannotator servers. Prompts and commands are visible in the review UI. + +Below are the exact prompts, commands, and schemas used. + +- [Claude Code: full prompt](#claude-code-full-prompt) +- [Claude Code: command](#claude-code-command) +- [Codex: full prompt](#codex-full-prompt) +- [Codex: command](#codex-command) +- [Codex: output schema](#codex-output-schema) + +--- + +### Claude Code: full prompt + +``` +# Claude Code Review System Prompt + +## Identity +You are a code review system. Your job is to find bugs that would break +production. You are not a linter, formatter, or style checker unless +project guidance files explicitly expand your scope. + +## Pipeline + +Step 1: Gather context + - Retrieve the PR diff (gh pr diff or git diff) + - Read CLAUDE.md and REVIEW.md at the repo root and in every directory + containing modified files + - Build a map of which rules apply to which file paths + - Identify any skip rules (paths, patterns, or file types to ignore) + +Step 2: Launch 4 parallel review agents + + Agent 1 — Bug + Regression (Opus-level reasoning) + Scan for logic errors, regressions, broken edge cases, build failures, + and code that will produce wrong results. Focus on the diff but read + surrounding code to understand call sites and data flow. Flag only + issues where the code is demonstrably wrong — not stylistic concerns, + not missing tests, not "could be cleaner." + + Agent 2 — Security + Deep Analysis (Opus-level reasoning) + Look for security vulnerabilities with concrete exploit paths, race + conditions, incorrect assumptions about trust boundaries, and subtle + issues in introduced code. Read surrounding code for context. Do not + flag theoretical risks without a plausible path to harm. + + Agent 3 — Code Quality + Reusability (Sonnet-level reasoning) + Look for code smells, unnecessary duplication, missed opportunities to + reuse existing utilities or patterns in the codebase, overly complex + implementations that could be simpler, and elegance issues. Read the + surrounding codebase to understand existing patterns before flagging. + Only flag issues a senior engineer would care about. + + Agent 4 — Guideline Compliance (Haiku-level reasoning) + Audit changes against rules from CLAUDE.md and REVIEW.md gathered in + Step 1. Only flag clear, unambiguous violations where you can cite the + exact rule broken. If a PR makes a CLAUDE.md statement outdated, flag + that the docs need updating. Respect all skip rules — never flag files + or patterns that guidance says to ignore. + + All agents: + - Do not duplicate each other's findings + - Do not flag issues in paths excluded by guidance files + - Provide file, line number, and a concise description for each candidate + +Step 3: Validate each candidate finding + For each candidate, launch a validation agent. The validator: + - Traces the actual code path to confirm the issue is real + - Checks whether the issue is handled elsewhere (try/catch, upstream + guard, fallback logic, type system guarantees) + - Confirms the finding is not a false positive with high confidence + - If validation fails, drop the finding silently + - If validation passes, write a clear reasoning chain explaining how + the issue was confirmed — this becomes the reasoning field + +Step 4: Classify each validated finding + Assign exactly one severity: + + important — A bug that should be fixed before merging. Build failures, + clear logic errors, security vulnerabilities with exploit paths, data + loss risks, race conditions with observable consequences. + + nit — A minor issue worth fixing but non-blocking. Style deviations + from project guidelines, code quality concerns, edge cases that are + unlikely but worth noting, convention violations that don't affect + correctness. + + pre_existing — A bug that exists in the surrounding codebase but was + NOT introduced by this PR. Only flag when directly relevant to the + changed code path. + +Step 5: Deduplicate and rank + - Merge findings that describe the same underlying issue from different + agents — keep the most specific description and the highest severity + - Sort by severity: important → nit → pre_existing + - Within each severity, sort by file path and line number + +Step 6: Return structured JSON output matching the schema. + If no issues are found, return an empty findings array with zeroed summary. + +## Hard constraints +- Never approve or block the PR +- Never comment on formatting or code style unless guidance files say to +- Never flag missing test coverage unless guidance files say to +- Never invent rules — only enforce what CLAUDE.md or REVIEW.md state +- Never flag issues in skipped paths or generated files unless guidance + explicitly includes them +- Prefer silence over false positives — when in doubt, drop the finding +- Do NOT post any comments to GitHub or GitLab +- Do NOT use gh pr comment or any commenting tool +- Your only output is the structured JSON findings +``` + +### Claude Code: command + +```bash +claude -p \ + --permission-mode dontAsk \ + --output-format stream-json \ + --verbose \ + --json-schema '{"type":"object","properties":{"findings":{"type":"array","items":{"type":"object","properties":{"severity":{"type":"string","enum":["important","nit","pre_existing"]},"file":{"type":"string"},"line":{"type":"integer"},"end_line":{"type":"integer"},"description":{"type":"string"},"reasoning":{"type":"string"}},"required":["severity","file","line","end_line","description","reasoning"],"additionalProperties":false}},"summary":{"type":"object","properties":{"important":{"type":"integer"},"nit":{"type":"integer"},"pre_existing":{"type":"integer"}},"required":["important","nit","pre_existing"],"additionalProperties":false}},"required":["findings","summary"],"additionalProperties":false}' \ + --no-session-persistence \ + --model sonnet \ + --tools Agent,Bash,Read,Glob,Grep \ + --allowedTools Agent,Read,Glob,Grep,Bash(gh pr view:*),Bash(gh pr diff:*),Bash(gh pr list:*),Bash(gh issue view:*),Bash(gh issue list:*),Bash(gh api repos/*/*/pulls/*),Bash(gh api repos/*/*/pulls/*/files*),Bash(gh api repos/*/*/pulls/*/comments*),Bash(gh api repos/*/*/issues/*/comments*),Bash(glab mr view:*),Bash(glab mr diff:*),Bash(glab mr list:*),Bash(glab api:*),Bash(git status:*),Bash(git diff:*),Bash(git log:*),Bash(git show:*),Bash(git blame:*),Bash(git branch:*),Bash(git grep:*),Bash(git ls-remote:*),Bash(git ls-tree:*),Bash(git merge-base:*),Bash(git remote:*),Bash(git rev-parse:*),Bash(git show-ref:*),Bash(wc:*) \ + --disallowedTools Edit,Write,NotebookEdit,WebFetch,WebSearch,Bash(python:*),Bash(python3:*),Bash(node:*),Bash(npx:*),Bash(bun:*),Bash(bunx:*),Bash(sh:*),Bash(bash:*),Bash(zsh:*),Bash(curl:*),Bash(wget:*) +``` + +Prompt is written to stdin. + +--- + +### Codex: full prompt + +``` +# Review guidelines: + +You are acting as a reviewer for a proposed code change made by another engineer. + +Below are some default guidelines for determining whether the original author +would appreciate the issue being flagged. + +These are not the final word in determining whether an issue is a bug. In many +cases, you will encounter other, more specific guidelines. These may be present +elsewhere in a developer message, a user message, a file, or even elsewhere in +this system message. Those guidelines should be considered to override these +general instructions. + +Here are the general guidelines for determining whether something is a bug and +should be flagged. + +1. It meaningfully impacts the accuracy, performance, security, or + maintainability of the code. +2. The bug is discrete and actionable (i.e. not a general issue with the + codebase or a combination of multiple issues). +3. Fixing the bug does not demand a level of rigor that is not present in the + rest of the codebase. +4. The bug was introduced in the commit (pre-existing bugs should not be + flagged). +5. The author of the original PR would likely fix the issue if they were made + aware of it. +6. The bug does not rely on unstated assumptions about the codebase or + author's intent. +7. It is not enough to speculate that a change may disrupt another part of the + codebase; to be considered a bug, one must identify the other parts of the + code that are provably affected. +8. The bug is clearly not just an intentional change by the original author. + +Comment guidelines: + +1. Clear about why the issue is a bug. +2. Appropriately communicates severity. Does not overclaim. +3. Brief. Body is at most 1 paragraph. +4. No code chunks longer than 3 lines. +5. Clearly communicates the scenarios or inputs necessary for the bug to arise. +6. Tone is matter-of-fact, not accusatory or overly positive. +7. Written so the original author can immediately grasp the idea. +8. Avoids flattery ("Great job ...", "Thanks for ..."). + +Output all findings that the original author would fix if they knew about it. If +there is no finding that a person would definitely love to see and fix, prefer +outputting no findings. + +Priority tags: [P0] Blocking. [P1] Urgent. [P2] Normal. [P3] Low. + +At the end, output an overall correctness verdict. +``` + +### Codex: command + +```bash +codex exec \ + --output-schema ~/.plannotator/codex-review-schema.json \ + -o /tmp/plannotator-codex-.json \ + --full-auto \ + --ephemeral \ + -C \ + "\n\n---\n\n" +``` + +### Codex: output schema + +```json +{ + "type": "object", + "properties": { + "findings": { + "type": "array", + "items": { + "type": "object", + "properties": { + "title": { "type": "string" }, + "body": { "type": "string" }, + "confidence_score": { "type": "number" }, + "priority": { "type": ["integer", "null"] }, + "code_location": { + "type": "object", + "properties": { + "absolute_file_path": { "type": "string" }, + "line_range": { + "type": "object", + "properties": { + "start": { "type": "integer" }, + "end": { "type": "integer" } + }, + "required": ["start", "end"] + } + }, + "required": ["absolute_file_path", "line_range"] + } + }, + "required": ["title", "body", "confidence_score", "priority", "code_location"] + } + }, + "overall_correctness": { "type": "string" }, + "overall_explanation": { "type": "string" }, + "overall_confidence_score": { "type": "number" } + }, + "required": ["findings", "overall_correctness", "overall_explanation", "overall_confidence_score"] +} +``` + +## Customization + +Add `CLAUDE.md` or `REVIEW.md` to your repo root or any subdirectory. The Claude agent reads them to understand project rules. + +```markdown +# Review Rules + +- Check for SQL injection in database queries +- Skip files in test-fixtures/ +- Enforce snake_case in Python +``` + +Both files are additive. REVIEW.md extends CLAUDE.md for review-specific guidance. diff --git a/apps/pi-extension/server/agent-jobs.ts b/apps/pi-extension/server/agent-jobs.ts index 4bd03440..2ca1b1b8 100644 --- a/apps/pi-extension/server/agent-jobs.ts +++ b/apps/pi-extension/server/agent-jobs.ts @@ -20,6 +20,7 @@ import { AGENT_HEARTBEAT_COMMENT, AGENT_HEARTBEAT_INTERVAL_MS, } from "../generated/agent-jobs.js"; +import { formatClaudeLogEvent } from "../generated/claude-review.js"; import { json, parseBody } from "./helpers.js"; // --------------------------------------------------------------------------- @@ -53,6 +54,18 @@ export interface AgentJobHandlerOptions { mode: "plan" | "review" | "annotate"; getServerUrl: () => string; getCwd: () => string; + /** Server-side command builder for known providers (codex, claude). */ + buildCommand?: (provider: string) => Promise<{ + command: string[]; + outputPath?: string; + captureStdout?: boolean; + stdinPrompt?: string; + cwd?: string; + prompt?: string; + label?: string; + } | null>; + /** Called when a job completes successfully — parse results and push annotations. */ + onJobComplete?: (job: AgentJobInfo, meta: { outputPath?: string; stdout?: string; cwd?: string }) => void | Promise; } export function createAgentJobHandler(options: AgentJobHandlerOptions) { @@ -60,6 +73,7 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { // --- State --- const jobs = new Map(); + const jobOutputPaths = new Map(); const subscribers = new Set(); let version = 0; @@ -67,7 +81,6 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { const capabilities: AgentCapability[] = [ { id: "claude", name: "Claude Code", available: whichCmd("claude") }, { id: "codex", name: "Codex CLI", available: whichCmd("codex") }, - { id: "shell", name: "Shell Command", available: true }, ]; const capabilitiesResponse: AgentCapabilities = { mode, @@ -93,6 +106,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { provider: string, command: string[], label: string, + outputPath?: string, + spawnOptions?: { captureStdout?: boolean; stdinPrompt?: string; cwd?: string; prompt?: string }, ): AgentJobInfo { const id = crypto.randomUUID(); const source = jobSource(id); @@ -105,14 +120,23 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { status: "starting", startedAt: Date.now(), command, + cwd: getCwd(), }; let proc: ChildProcess | null = null; try { + const spawnCwd = spawnOptions?.cwd ?? getCwd(); + const captureStdout = spawnOptions?.captureStdout ?? false; + const hasStdinPrompt = !!spawnOptions?.stdinPrompt; + proc = spawn(command[0], command.slice(1), { - cwd: getCwd(), - stdio: ["ignore", "ignore", "pipe"], + cwd: spawnCwd, + stdio: [ + hasStdinPrompt ? "pipe" : "ignore", + captureStdout ? "pipe" : "ignore", + "pipe", + ], env: { ...process.env, PLANNOTATOR_AGENT_SOURCE: source, @@ -120,20 +144,80 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { }, }); + // Write prompt to stdin and close (for providers that read prompt from stdin) + if (hasStdinPrompt && proc.stdin) { + proc.stdin.write(spawnOptions!.stdinPrompt!); + proc.stdin.end(); + } + info.status = "running"; + info.cwd = spawnCwd; + if (spawnOptions?.prompt) info.prompt = spawnOptions.prompt; jobs.set(id, { info, proc }); + if (outputPath) jobOutputPaths.set(id, outputPath); + if (spawnOptions?.cwd) jobOutputPaths.set(`${id}:cwd`, spawnOptions.cwd); broadcast({ type: "job:started", job: { ...info } }); - // Accumulate stderr continuously (must attach before exit fires) - let stderrBuf = ""; - if (proc.stderr) { - proc.stderr.on("data", (chunk: Buffer) => { - stderrBuf = (stderrBuf + chunk.toString()).slice(-500); + // --- Stdout capture (Claude JSONL streaming) --- + let stdoutBuf = ""; + if (captureStdout && proc.stdout) { + proc.stdout.on("data", (chunk: Buffer) => { + const text = chunk.toString(); + stdoutBuf += text; + + // Forward JSONL lines as log events + const lines = text.split('\n'); + for (const line of lines) { + if (!line.trim()) continue; + if (provider === "claude") { + const formatted = formatClaudeLogEvent(line); + if (formatted !== null) { + broadcast({ type: "job:log", jobId: id, delta: formatted + '\n' }); + } + continue; + } + try { + const event = JSON.parse(line); + if (event.type === 'result') continue; + } catch { /* not JSON — forward as raw log */ } + broadcast({ type: "job:log", jobId: id, delta: line + '\n' }); + } }); } - // Monitor process exit - proc.on("exit", (exitCode) => { + // --- Stderr: buffer tail for errors + live log streaming --- + let stderrBuf = ""; + let logPending = ""; + let logFlushTimer: ReturnType | null = null; + + if (proc.stderr) { + proc.stderr.on("data", (chunk: Buffer) => { + const text = chunk.toString(); + stderrBuf = (stderrBuf + text).slice(-500); + logPending += text; + + if (!logFlushTimer) { + logFlushTimer = setTimeout(() => { + if (logPending) { + broadcast({ type: "job:log", jobId: id, delta: logPending }); + logPending = ""; + } + logFlushTimer = null; + }, 200); + } + }); + } + + // Monitor process close (fires after stdio streams are fully drained, + // unlike 'exit' which fires before — critical for stdout capture) + proc.on("close", async (exitCode) => { + // Flush remaining stderr + if (logFlushTimer) { clearTimeout(logFlushTimer); logFlushTimer = null; } + if (logPending) { + broadcast({ type: "job:log", jobId: id, delta: logPending }); + logPending = ""; + } + const entry = jobs.get(id); if (!entry || isTerminalStatus(entry.info.status)) return; @@ -145,6 +229,23 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { entry.info.error = stderrBuf; } + // Ingest results before broadcasting completion + const jobOutputPath = jobOutputPaths.get(id); + const jobCwd = jobOutputPaths.get(`${id}:cwd`); + if (exitCode === 0 && options.onJobComplete) { + try { + await options.onJobComplete(entry.info, { + outputPath: jobOutputPath, + stdout: captureStdout ? stdoutBuf : undefined, + cwd: jobCwd, + }); + } catch { + // Result ingestion failure shouldn't prevent job completion broadcast + } + } + jobOutputPaths.delete(id); + jobOutputPaths.delete(`${id}:cwd`); + broadcast({ type: "job:completed", job: { ...entry.info } }); }); @@ -185,6 +286,8 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { entry.info.status = "killed"; entry.info.endedAt = Date.now(); + jobOutputPaths.delete(id); + jobOutputPaths.delete(`${id}:cwd`); broadcast({ type: "job:completed", job: { ...entry.info } }); return true; } @@ -276,10 +379,11 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { if (url.pathname === JOBS && req.method === "POST") { try { const body = await parseBody(req); - const provider = typeof body.provider === "string" ? body.provider : "shell"; - const rawCommand = Array.isArray(body.command) ? body.command : []; - const command = rawCommand.filter((c: unknown): c is string => typeof c === "string"); - const label = typeof body.label === "string" ? body.label : `${provider} agent`; + const provider = typeof body.provider === "string" ? body.provider : ""; + let rawCommand = Array.isArray(body.command) ? body.command : []; + let command = rawCommand.filter((c: unknown): c is string => typeof c === "string"); + let label = typeof body.label === "string" ? body.label : `${provider} agent`; + let outputPath: string | undefined; // Validate provider is a known, available capability const cap = capabilities.find((c) => c.id === provider); @@ -288,12 +392,35 @@ export function createAgentJobHandler(options: AgentJobHandlerOptions) { return true; } + // Try server-side command building for known providers + let captureStdout = false; + let stdinPrompt: string | undefined; + let spawnCwd: string | undefined; + let promptText: string | undefined; + if (options.buildCommand) { + const built = await options.buildCommand(provider); + if (built) { + command = built.command; + outputPath = built.outputPath; + captureStdout = built.captureStdout ?? false; + stdinPrompt = built.stdinPrompt; + spawnCwd = built.cwd; + promptText = built.prompt; + if (built.label) label = built.label; + } + } + if (command.length === 0) { json(res, { error: 'Missing "command" array' }, 400); return true; } - const job = spawnJob(provider, command, label); + const job = spawnJob(provider, command, label, outputPath, { + captureStdout, + stdinPrompt, + cwd: spawnCwd, + prompt: promptText, + }); json(res, { job }, 201); } catch { json(res, { error: "Invalid JSON" }, 400); diff --git a/apps/pi-extension/server/external-annotations.ts b/apps/pi-extension/server/external-annotations.ts index 6ba151b5..4bb48aa3 100644 --- a/apps/pi-extension/server/external-annotations.ts +++ b/apps/pi-extension/server/external-annotations.ts @@ -49,6 +49,14 @@ export function createExternalAnnotationHandler(mode: "plan" | "review") { }); return { + /** Push annotations directly into the store (bypasses HTTP, reuses same validation). */ + addAnnotations(body: unknown): { ids: string[] } | { error: string } { + const parsed = transform(body); + if ("error" in parsed) return { error: parsed.error }; + const created = store.add(parsed.annotations); + return { ids: created.map((a: { id: string }) => a.id) }; + }, + async handle( req: IncomingMessage, res: ServerResponse, diff --git a/apps/pi-extension/server/serverReview.ts b/apps/pi-extension/server/serverReview.ts index 468945e1..1b11c704 100644 --- a/apps/pi-extension/server/serverReview.ts +++ b/apps/pi-extension/server/serverReview.ts @@ -56,6 +56,20 @@ import { submitPRReview, } from "./pr.js"; import { getRepoInfo } from "./project.js"; +import { + CODEX_REVIEW_SYSTEM_PROMPT, + buildCodexReviewUserMessage, + buildCodexCommand, + generateOutputPath, + parseCodexOutput, + transformReviewFindings, +} from "../generated/codex-review.js"; +import { + CLAUDE_REVIEW_PROMPT, + buildClaudeCommand, + parseClaudeStreamOutput, + transformClaudeFindings, +} from "../generated/claude-review.js"; export interface ReviewServerResult { port: number; @@ -154,15 +168,84 @@ export async function startReviewServer(options: { // Agent jobs — background process manager (late-binds serverUrl via getter) let serverUrl = ""; + // Worktree-aware cwd resolver — shared by getCwd, buildCommand, and onJobComplete + function resolveAgentCwd(): string { + if (currentDiffType.startsWith("worktree:")) { + const parsed = parseWorktreeDiffType(currentDiffType); + if (parsed) return parsed.path; + } + return options.gitContext?.cwd ?? process.cwd(); + } const agentJobs = createAgentJobHandler({ mode: "review", getServerUrl: () => serverUrl, - getCwd: () => { - if (currentDiffType.startsWith("worktree:")) { - const parsed = parseWorktreeDiffType(currentDiffType); - if (parsed) return parsed.path; + getCwd: resolveAgentCwd, + + async buildCommand(provider) { + const cwd = resolveAgentCwd(); + const hasLocalAccess = !!options.gitContext; + const userMessage = buildCodexReviewUserMessage( + currentPatch, + currentDiffType, + { defaultBranch: options.gitContext?.defaultBranch, hasLocalAccess }, + options.prMetadata, + ); + + if (provider === "codex") { + const outputPath = generateOutputPath(); + const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage; + const command = await buildCodexCommand({ cwd, outputPath, prompt }); + return { command, outputPath, prompt, label: "Codex Review" }; + } + + if (provider === "claude") { + const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage; + const { command, stdinPrompt } = buildClaudeCommand(prompt); + return { command, stdinPrompt, prompt, cwd, label: "Claude Code Review", captureStdout: true }; + } + + return null; + }, + + async onJobComplete(job, meta) { + const cwd = resolveAgentCwd(); + + if (job.provider === "codex" && meta.outputPath) { + const output = await parseCodexOutput(meta.outputPath); + if (!output) return; + + job.summary = { + correctness: output.overall_correctness, + explanation: output.overall_explanation, + confidence: output.overall_confidence_score, + }; + + if (output.findings.length > 0) { + const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex"); + const result = externalAnnotations.addAnnotations({ annotations }); + if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error); + } + return; + } + + if (job.provider === "claude" && meta.stdout) { + const output = parseClaudeStreamOutput(meta.stdout); + if (!output) 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) { + const annotations = transformClaudeFindings(output.findings, job.source, cwd); + const result = externalAnnotations.addAnnotations({ annotations }); + if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error); + } + return; } - return options.gitContext?.cwd ?? process.cwd(); }, }); const sharingEnabled = diff --git a/apps/pi-extension/vendor.sh b/apps/pi-extension/vendor.sh index c383d592..579a6ce3 100755 --- a/apps/pi-extension/vendor.sh +++ b/apps/pi-extension/vendor.sh @@ -6,11 +6,21 @@ cd "$(dirname "$0")" mkdir -p generated generated/ai/providers -for f in feedback-templates review-core storage draft project pr-provider pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs; do +for f in feedback-templates review-core storage draft project pr-provider pr-github pr-gitlab checklist integrations-common repo reference-common favicon resolve-file config external-annotation agent-jobs worktree; do src="../../packages/shared/$f.ts" printf '// @generated — DO NOT EDIT. Source: packages/shared/%s.ts\n' "$f" | cat - "$src" > "generated/$f.ts" done +# Vendor review agent modules from packages/server/ — rewrite imports for generated/ layout +for f in codex-review claude-review path-utils; do + src="../../packages/server/$f.ts" + printf '// @generated — DO NOT EDIT. Source: packages/server/%s.ts\n' "$f" | cat - "$src" \ + | sed 's|from "./vcs"|from "./review-core.js"|' \ + | sed 's|from "./pr"|from "./pr-provider.js"|' \ + | sed 's|from "./path-utils"|from "./path-utils.js"|' \ + > "generated/$f.ts" +done + for f in index types provider session-manager endpoints context base-session; do src="../../packages/ai/$f.ts" printf '// @generated — DO NOT EDIT. Source: packages/ai/%s.ts\n' "$f" | cat - "$src" > "generated/ai/$f.ts" diff --git a/apps/review/package.json b/apps/review/package.json index 4238d042..91a1d1ec 100644 --- a/apps/review/package.json +++ b/apps/review/package.json @@ -12,7 +12,7 @@ "@plannotator/review-editor": "workspace:*", "@plannotator/server": "workspace:*", "@plannotator/ui": "workspace:*", - "@pierre/diffs": "^1.1.0-beta.19", + "@pierre/diffs": "^1.1.12", "dompurify": "^3.3.3", "react": "^19.2.3", "react-dom": "^19.2.3", diff --git a/bun.lock b/bun.lock index 4ea77e06..d0171a69 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ "@anthropic-ai/claude-agent-sdk": "^0.2.81", "@openai/codex-sdk": "^0.116.0", "@opencode-ai/sdk": "^1.3.0", - "@pierre/diffs": "^1.1.0-beta.19", + "@pierre/diffs": "^1.1.12", "diff": "^8.0.3", "dockview-react": "^5.2.0", "dompurify": "^3.3.3", @@ -62,7 +62,7 @@ }, "apps/opencode-plugin": { "name": "@plannotator/opencode", - "version": "0.16.6", + "version": "0.16.7", "dependencies": { "@opencode-ai/plugin": "^1.1.10", }, @@ -84,7 +84,7 @@ }, "apps/pi-extension": { "name": "@plannotator/pi-extension", - "version": "0.16.6", + "version": "0.16.7", "peerDependencies": { "@mariozechner/pi-coding-agent": ">=0.53.0", }, @@ -111,7 +111,7 @@ "name": "@plannotator/review", "version": "0.0.1", "dependencies": { - "@pierre/diffs": "^1.1.0-beta.19", + "@pierre/diffs": "^1.1.12", "@plannotator/review-editor": "workspace:*", "@plannotator/server": "workspace:*", "@plannotator/ui": "workspace:*", @@ -159,7 +159,7 @@ "name": "@plannotator/review-editor", "version": "0.0.1", "dependencies": { - "@pierre/diffs": "^1.1.0-beta.19", + "@pierre/diffs": "^1.1.12", "@plannotator/shared": "workspace:*", "@plannotator/ui": "workspace:*", "highlight.js": "^11.11.1", @@ -170,7 +170,7 @@ }, "packages/server": { "name": "@plannotator/server", - "version": "0.16.6", + "version": "0.16.7", "dependencies": { "@plannotator/ai": "workspace:*", "@plannotator/shared": "workspace:*", @@ -613,9 +613,9 @@ "@oven/bun-windows-x64-baseline": ["@oven/bun-windows-x64-baseline@1.3.5", "", { "os": "win32", "cpu": "x64" }, "sha512-rtVQB9/1XK8FWJgFtsOthbPifRMYypgJwxu+pK3NHx8WvFKmq7HcPDqNr8xLzGULjQEO7eAo2aOZfONOwYz+5g=="], - "@pierre/diffs": ["@pierre/diffs@1.1.0-beta.19", "", { "dependencies": { "@pierre/theme": "0.0.22", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-XxGPKkVW+1t2KJQfgjmSnS+93nI9+ACJl1XjhF3Lo4BdQJOxV3pHeyix31ySn/m/1llq6O/7bXucE0OYCK6Kog=="], + "@pierre/diffs": ["@pierre/diffs@1.1.12", "", { "dependencies": { "@pierre/theme": "0.0.28", "@shikijs/transformers": "^3.0.0", "diff": "8.0.3", "hast-util-to-html": "9.0.5", "lru_map": "0.4.1", "shiki": "^3.0.0" }, "peerDependencies": { "react": "^18.3.1 || ^19.0.0", "react-dom": "^18.3.1 || ^19.0.0" } }, "sha512-InssHHM7f0nkazIRkuaiNCy6GkBLfwJlqc7LtTkMD/KSqsuc6bnL2V9sIQoG5PZu9jwinQiXUb/gT7itFa6U9A=="], - "@pierre/theme": ["@pierre/theme@0.0.22", "", {}, "sha512-ePUIdQRNGjrveELTU7fY89Xa7YGHHEy5Po5jQy/18lm32eRn96+tnYJEtFooGdffrx55KBUtOXfvVy/7LDFFhA=="], + "@pierre/theme": ["@pierre/theme@0.0.28", "", {}, "sha512-1j/H/fECBuc9dEvntdWI+l435HZapw+RCJTlqCA6BboQ5TjlnE005j/ROWutXIs8aq5OAc82JI2Kwk4A1WWBgw=="], "@pkgjs/parseargs": ["@pkgjs/parseargs@0.11.0", "", {}, "sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg=="], diff --git a/import-octi/issue-closed.svg b/import-octi/issue-closed.svg new file mode 100644 index 00000000..eef723c0 --- /dev/null +++ b/import-octi/issue-closed.svg @@ -0,0 +1,4 @@ + + + + diff --git a/import-octi/issue-opened.svg b/import-octi/issue-opened.svg new file mode 100644 index 00000000..15b1e963 --- /dev/null +++ b/import-octi/issue-opened.svg @@ -0,0 +1,4 @@ + + + + diff --git a/import-octi/issue-reopened.svg b/import-octi/issue-reopened.svg new file mode 100644 index 00000000..00d8eb16 --- /dev/null +++ b/import-octi/issue-reopened.svg @@ -0,0 +1,4 @@ + + + + diff --git a/package.json b/package.json index 83b304ad..b7af75f1 100644 --- a/package.json +++ b/package.json @@ -36,7 +36,7 @@ "@anthropic-ai/claude-agent-sdk": "^0.2.81", "@openai/codex-sdk": "^0.116.0", "@opencode-ai/sdk": "^1.3.0", - "@pierre/diffs": "^1.1.0-beta.19", + "@pierre/diffs": "^1.1.12", "diff": "^8.0.3", "dockview-react": "^5.2.0", "dompurify": "^3.3.3", diff --git a/packages/review-editor/App.tsx b/packages/review-editor/App.tsx index 7ac60cc4..ce1d5abf 100644 --- a/packages/review-editor/App.tsx +++ b/packages/review-editor/App.tsx @@ -38,6 +38,7 @@ import { FileTree } from './components/FileTree'; import { DEMO_DIFF } from './demoData'; import { exportReviewFeedback } from './utils/exportFeedback'; import { ReviewStateProvider, type ReviewState } from './dock/ReviewStateContext'; +import { JobLogsProvider } from './dock/JobLogsContext'; import { reviewPanelComponents } from './dock/reviewPanelComponents'; import { ReviewDockTabRenderer } from './dock/ReviewDockTabRenderer'; import { usePRContext } from './hooks/usePRContext'; @@ -114,6 +115,7 @@ const ReviewApp: React.FC = () => { const [selectedAnnotationId, setSelectedAnnotationId] = useState(null); const [pendingSelection, setPendingSelection] = useState(null); const [showExportModal, setShowExportModal] = useState(false); + const [showWorktreeDialog, setShowWorktreeDialog] = useState(false); const [openSettingsMenu, setOpenSettingsMenu] = useState(false); const [showNoAnnotationsDialog, setShowNoAnnotationsDialog] = useState(false); const [isLoading, setIsLoading] = useState(true); @@ -151,6 +153,7 @@ const ReviewApp: React.FC = () => { const [isWSL, setIsWSL] = useState(false); const [diffType, setDiffType] = useState('uncommitted'); const [gitContext, setGitContext] = useState(null); + const [agentCwd, setAgentCwd] = useState(null); const [isLoadingDiff, setIsLoadingDiff] = useState(false); const [diffError, setDiffError] = useState(null); const [isSendingFeedback, setIsSendingFeedback] = useState(false); @@ -617,6 +620,7 @@ const ReviewApp: React.FC = () => { origin?: Origin; diffType?: string; gitContext?: GitContext; + agentCwd?: string; sharingEnabled?: boolean; repoInfo?: { display: string; branch?: string }; prMetadata?: PRMetadata; @@ -644,6 +648,7 @@ const ReviewApp: React.FC = () => { if (data.origin) setOrigin(data.origin); if (data.diffType) setDiffType(data.diffType); if (data.gitContext) setGitContext(data.gitContext); + if (data.agentCwd) setAgentCwd(data.agentCwd); if (data.sharingEnabled !== undefined) setSharingEnabled(data.sharingEnabled); if (data.repoInfo) setRepoInfo(data.repoInfo); if (data.prMetadata) setPrMetadata(data.prMetadata); @@ -970,6 +975,7 @@ const ReviewApp: React.FC = () => { isPRContextLoading, prContextError, fetchPRContext, + platformUser, openDiffFile, }), [ files, activeFileIndex, diffStyle, diffOverflow, diffIndicators, @@ -984,9 +990,12 @@ const ReviewApp: React.FC = () => { aiAvailable, aiChat.messages, aiChat.isCreatingSession, aiChat.isStreaming, handleAskAI, handleViewAIResponse, handleClickAIMarker, aiHistoryForSelection, agentJobs.jobs, prMetadata, prContext, - isPRContextLoading, prContextError, fetchPRContext, openDiffFile, + isPRContextLoading, prContextError, fetchPRContext, platformUser, openDiffFile, ]); + // Separate context for high-frequency job logs — prevents re-rendering all panels on every SSE event + const jobLogsValue = useMemo(() => ({ jobLogs: agentJobs.jobLogs }), [agentJobs.jobLogs]); + // Copy raw diff to clipboard const handleCopyDiff = useCallback(async () => { if (!diffData) return; @@ -1300,12 +1309,21 @@ const ReviewApp: React.FC = () => { return ( +
{/* Header */} -
+
{prMetadata ? (
+ {prMetadata && (gitContext || agentCwd) && ( + + )} { {mrNumberLabel} {prMetadata.title} +
+ + + +
) : repoInfo ? (
@@ -1469,7 +1498,9 @@ const ReviewApp: React.FC = () => { isLoading={isSendingFeedback || isPlatformActioning} muted={!platformMode && totalAnnotationCount === 0 && !isSendingFeedback && !isApproving && !isPlatformActioning} label={platformMode ? 'Post Comments' : 'Send Feedback'} + shortLabel={platformMode ? 'Post' : 'Send'} loadingLabel={platformMode ? 'Posting...' : 'Sending...'} + shortLoadingLabel={platformMode ? 'Posting...' : 'Sending...'} title={!platformMode && totalAnnotationCount === 0 ? "Add annotations to send feedback" : "Send feedback"} /> @@ -1766,6 +1797,33 @@ const ReviewApp: React.FC = () => { />
+ {/* Worktree info dialog */} + {(gitContext?.cwd || agentCwd) && prMetadata && ( + setShowWorktreeDialog(false)} + title="Local Worktree" + wide + message={ +
+

This PR is checked out locally so review agents have full file access.

+
+ Path + +
+

Automatically removed when this review session ends.

+
+ } + variant="info" + /> + )} + {/* No annotations dialog */} {
)}
+
); diff --git a/packages/review-editor/components/CopyButton.tsx b/packages/review-editor/components/CopyButton.tsx index 823afa6c..5053fac1 100644 --- a/packages/review-editor/components/CopyButton.tsx +++ b/packages/review-editor/components/CopyButton.tsx @@ -4,10 +4,27 @@ import { useState } from 'react'; interface CopyButtonProps { text: string; className?: string; + /** "overlay" (default): absolute-positioned, hover-reveal (parent needs group relative). + * "inline": normal flow, always visible, compact. */ + variant?: 'overlay' | 'inline'; + /** Optional label shown next to the icon (inline variant only). */ + label?: string; } -/** Hover-reveal copy button with "Copied" flash. Parent needs className="group relative". */ -export const CopyButton: React.FC = ({ text, className = '' }) => { +const CopyIcon = () => ( + +); + +const CheckIcon = () => ( + +); + +/** Copy-to-clipboard button with "Copied" flash. */ +export const CopyButton: React.FC = ({ text, className = '', variant = 'overlay', label }) => { const [copied, setCopied] = useState(false); const handleCopy = async (e: React.MouseEvent) => { @@ -21,6 +38,24 @@ export const CopyButton: React.FC = ({ text, className = '' }) } }; + if (variant === 'inline') { + return ( + + ); + } + return ( ); }; diff --git a/packages/review-editor/components/DiffHunkPreview.tsx b/packages/review-editor/components/DiffHunkPreview.tsx new file mode 100644 index 00000000..5212bd90 --- /dev/null +++ b/packages/review-editor/components/DiffHunkPreview.tsx @@ -0,0 +1,116 @@ +import React, { useMemo, useState, useEffect } from 'react'; +import { FileDiff } from '@pierre/diffs/react'; +import { getSingularPatch } from '@pierre/diffs'; +import { useTheme } from '@plannotator/ui/components/ThemeProvider'; +import { useReviewState } from '../dock/ReviewStateContext'; + +interface DiffHunkPreviewProps { + /** Raw diff hunk string (unified diff format). */ + hunk: string; + /** Max height in pixels before "Show more" toggle. Default 128. */ + maxHeight?: number; + className?: string; +} + +/** + * Renders a small inline diff hunk using @pierre/diffs. + * Compact, read-only, no file header. Shares theme + font settings + * with the main DiffViewer via the same unsafeCSS injection pattern. + */ +export const DiffHunkPreview: React.FC = ({ + hunk, + maxHeight = 128, + className, +}) => { + const { resolvedMode } = useTheme(); + const state = useReviewState(); + const [expanded, setExpanded] = useState(false); + + const fileDiff = useMemo(() => { + if (!hunk) return undefined; + try { + const needsHeaders = !hunk.startsWith('diff --git') && !hunk.startsWith('--- '); + const patch = needsHeaders + ? `diff --git a/file b/file\n--- a/file\n+++ b/file\n${hunk}` + : hunk; + return getSingularPatch(patch); + } catch { + return undefined; + } + }, [hunk]); + + // Theme injection — same pattern as DiffViewer (reads computed CSS vars, injects via unsafeCSS) + const [pierreTheme, setPierreTheme] = useState<{ type: 'dark' | 'light'; css: string }>({ + type: resolvedMode, + css: '', + }); + + useEffect(() => { + const rafId = requestAnimationFrame(() => { + const styles = getComputedStyle(document.documentElement); + const bg = styles.getPropertyValue('--background').trim(); + const fg = styles.getPropertyValue('--foreground').trim(); + if (!bg || !fg) return; + + const fontFamily = state.fontFamily; + const fontSize = state.fontSize; + const fontCSS = fontFamily || fontSize ? ` + pre, code, [data-line-content], [data-column-number] { + ${fontFamily ? `font-family: '${fontFamily}', monospace !important;` : ''} + ${fontSize ? `font-size: ${fontSize} !important; line-height: 1.5 !important;` : ''} + }` : ''; + + setPierreTheme({ + type: resolvedMode, + css: ` + :host, [data-diff], [data-file], [data-diffs-header], [data-error-wrapper], [data-virtualizer-buffer] { + --diffs-bg: ${bg} !important; + --diffs-fg: ${fg} !important; + --diffs-dark-bg: ${bg}; + --diffs-light-bg: ${bg}; + --diffs-dark: ${fg}; + --diffs-light: ${fg}; + } + pre, code { background-color: ${bg} !important; } + [data-column-number] { background-color: ${bg} !important; } + [data-file-info] { display: none !important; } + [data-diffs-header] { display: none !important; } + ${fontCSS} + `, + }); + }); + return () => cancelAnimationFrame(rafId); + }, [resolvedMode, state.fontFamily, state.fontSize]); + + if (!fileDiff) return null; + + return ( +
+
+ +
+ {!expanded && ( + + )} +
+ ); +}; diff --git a/packages/review-editor/components/DiffViewer.tsx b/packages/review-editor/components/DiffViewer.tsx index 9f3e3c9e..b1b4d2f7 100644 --- a/packages/review-editor/components/DiffViewer.tsx +++ b/packages/review-editor/components/DiffViewer.tsx @@ -355,6 +355,8 @@ export const DiffViewer: React.FC = ({ suggestedCode: ann.suggestedCode, originalCode: ann.originalCode, author: ann.author, + severity: ann.severity, + reasoning: ann.reasoning, } as DiffAnnotationMetadata, })); }, [annotations]); diff --git a/packages/review-editor/components/FileHeader.tsx b/packages/review-editor/components/FileHeader.tsx index a40d359f..30759cf0 100644 --- a/packages/review-editor/components/FileHeader.tsx +++ b/packages/review-editor/components/FileHeader.tsx @@ -79,8 +79,8 @@ export const FileHeader: React.FC = ({ return (
diff --git a/packages/review-editor/components/FileTree.tsx b/packages/review-editor/components/FileTree.tsx index 54969dc7..d657476f 100644 --- a/packages/review-editor/components/FileTree.tsx +++ b/packages/review-editor/components/FileTree.tsx @@ -166,11 +166,11 @@ export const FileTree: React.FC = ({ }, []); return ( -