15 Commits

Author SHA1 Message Date
Raúl bc5470b90d fix(review): bound server memory for large tracked-file diffs (#1167)
* fix(review): bound server memory for large tracked-file diffs

PR #1118 renders large untracked files as binary additions, but staging
one moves it into the tracked `git diff` path, which had no size guard and
buffered the full multi-megabyte patch (~240 MB RSS on a 51 MB text
artifact). Any large tracked text file modified in the working tree hits
the same unguarded path.

Add a per-invocation `git -c core.bigFileThreshold=<MAX_REVIEW_FILE_CONTENT_BYTES>`
prefix to every content-producing git diff, so git renders oversized blobs
as "Binary files ... differ" instead of a text patch. Their bytes never
enter git's diff machinery or the server's buffered stdout, mirroring the
untracked-file guard. The flag is a no-op at or below the threshold, so
smaller files are byte-for-byte unaffected, and the blob hash git emits in
the binary diff still changes with content, so staleness detection holds.

The guard is applied in the shared cores, so the Bun and Pi runtimes
inherit it identically: `review-core.ts` covers the ordinary git provider
(working-tree, staged, commit, and the freshness fingerprint) and
`gitbutler-core.ts` covers the GitButler object diff. The jj provider runs
`jj diff`, which has no `core.bigFileThreshold` equivalent, so it is out of
scope here and stays unbounded as before.

* fix(review): preflight oversized tracked diffs

* fix(review): batch tracked diff preflight

* fix(review): restore browser-safe diff core

* fix(review): preserve gitlinks and textconv

* fix(review): require filesystem runtime seam

Fail compilation when a runtime omits file metadata or symlink support instead of silently disabling bounded reads and expansion.
2026-08-03 13:25:35 -07:00
Michael Ramos 8e9a359a8f fix(review): make remote discovery noninteractive (#1062) 2026-07-16 14:15:11 -07:00
Michael Ramos 9b7c39d2a4 fix(review): move hide-whitespace to server-side git diff -w (#635 follow-up) (#638)
The client-side approach from PR #635 normalized file contents before
diffing, which destroyed all indentation. Move whitespace handling to
the server by threading a `-w` flag through the git diff pipeline.

- Add `GitDiffOptions` to review-core.ts, inject `-w` in all 7 diff
  type paths + untracked file diffs
- Thread options through git.ts → vcs.ts → review.ts / Pi server
- Read `hideWhitespace` from ~/.plannotator/config.json on startup so
  the initial diff already respects the persisted preference
- Accept `hideWhitespace` in `/api/diff/switch`, echo in responses
- Client toggles trigger a lightweight server refetch that preserves
  the active file (no panel reset)
- Handle edge case where current file disappears when `-w` removes
  whitespace-only diffs
- Remove broken client-side parseDiffFromFile/normalize hack
- Update API docs in AGENTS.md

Closes the indentation bug reported by @zeroZshadow on PR #631.

For provenance purposes, this commit was AI assisted.
2026-04-30 17:23:55 -07:00
Michael Ramos 657cccaee0 fix(review): support non-ASCII and whitespace file paths in code review (#637)
Pass `-c core.quotePath=false` to all git invocations so paths with
non-ASCII characters (Korean, Chinese, accented, etc.) and whitespace
are output as raw UTF-8 instead of octal escapes. Fixes the 0/0 files
issue when repos contain such paths.

Closes #628

For provenance purposes, this commit was AI assisted.
2026-04-30 13:01:27 -07:00
Michael Ramos b0c5db924f fix(review): detect remote default branch asynchronously at startup (#609)
getDefaultBranch relied on `symbolic-ref refs/remotes/origin/HEAD`
which is commonly unset in worktrees, manual remote setups, and
long-lived repos. When absent, the code fell through to local
`main`/`master`, silently losing the upstream-preference behavior.

Adds `detectRemoteDefaultBranch()` — queries the remote via
`git ls-remote --symref origin HEAD` to find the actual default
branch name (works for any name: develop, trunk, etc.).

The call is fire-and-forget at server startup: non-blocking, runs
concurrently while the browser loads. By the time the user opens
Branch diff or PR Diff (usually 1-2 seconds later), the result has
arrived and `currentBase` has been silently upgraded to the upstream
ref. If offline or slow, the 5-second timeout fires and the local
fallback sticks. If the user has already switched bases manually,
their choice is never overwritten.

`ReviewGitRuntime.runGit` gains an optional `timeoutMs` param. Bun
kills the process via setTimeout + proc.kill(). Pi uses spawnSync's
native `timeout` option. Both treat timeout as a non-zero exit.

For provenance purposes, this commit was AI assisted.
2026-04-23 18:13:03 -07:00
Michael Ramos b375a804b2 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
Jared Wyce 9e760fb973 fix: opencode review cwd context flow (#323)
* fix opencode review cwd context flow

* fix: sync pi-extension review-core with shared cwd changes

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-17 17:29:09 -07:00
Michael Ramos ea689d9745 Unify review core across Bun and Pi (#310)
* Unify review core across Bun and Pi

* Surface review diff failures

* fix: review core fixes from code review

- Handle unborn HEAD in runGitDiff("uncommitted") via rev-parse check
  instead of assertGitSuccess, so fresh repos fall through to untracked diffs
- Bind Pi server to 0.0.0.0 for remote sessions (regression from e47eda0)
- Update CLAUDE.md: packages/shared/ description, PLANNOTATOR_SHARE env var,
  /api/diff response shape

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: update favicon background to dark navy

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-16 07:55:15 -07:00
Michael Ramos d29dd08c13 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
Michael Ramos 933f44737e 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
Michael Ramos 472e17be3d 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
Michael Ramos 411e1b932d feat: support git worktrees in code review (#241)
feat: support git worktrees in code review (#196)

Adds full worktree support to the code review flow:

- Detects worktrees via `git worktree list --porcelain` and surfaces them in the diff dropdown
- Selecting a worktree enters "worktree mode" with scoped diff options (uncommitted, last commit, vs main)
- "Back to main repo" restores the original dropdown
- Handles initial commits gracefully (no HEAD~1 crash)

Closes #196
2026-03-07 10:06:55 -08:00
zerone0x b7bc82c607 fix: include untracked new files in uncommitted/unstaged diffs (#227) 2026-03-05 03:19:01 -08:00
김영준E 09384361e4 fix: Fix review showing empty files + propagate diff errors to UI (#200)
* 🐛 fix: force standard a/b diff prefix to handle mnemonic prefix config

When diff.mnemonicPrefix is enabled in git config, `git diff` uses
context-dependent prefixes (c/ for commit, w/ for worktree, i/ for
index) instead of the standard a/b. Both the internal parseDiffToFiles
and @pierre/diffs library expect a/b prefixes, causing silent parse
failures that result in an empty file list.

Add --src-prefix=a/ --dst-prefix=b/ to all git diff invocations to
ensure consistent output regardless of user git configuration.

*  feat: propagate git diff errors to review UI

Previously, git diff errors were silently caught and returned as empty
patches. The UI showed "No changes" with no indication of failure.

- Add error field to DiffResult and propagate through ReviewServerOptions
- Include error in /api/diff and /api/diff/switch responses
- Show distinct error state in review UI (red icon + error message)
- Clear/set error state on diff type switch

* Fix mnemonic prefix handling in pi-extension runGitDiff

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Michael Ramos <mdramos8@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 22:26:07 -08:00
Michael Ramos 8019f73a44 Feat/code review system (#57)
## Summary
Complete code review system for reviewing git diffs with annotations.

### Features
- Interactive diff viewer with split/unified views
- Line-level annotation system
- Diff type selector (uncommitted, last commit, vs main branch)
- Dynamic default branch detection
- Empty state handling
- Simplified UX with streamlined feedback flow

Closes #51
Closes #56
2026-01-12 19:36:09 -08:00