Commit Graph

55 Commits

Author SHA1 Message Date
Michael Ramos afac44b940 feat(review): migrate all-files code review to Pierre CodeView (#885)
Replaces the all-files renderer with Pierre's virtualized CodeView (one scroller, identical look, scales to huge diffs); deletes the legacy AllFilesDiffView/LazyFileDiff and their flag; single-file panels stay on FileDiff. @pierre/diffs pinned exact 1.2.8 (1.2.9's tree is broken on npm — see #880).

Also ships: diff staleness detection ('Diff out of date · Refresh' toolbar notice backed by shared per-VCS fingerprints + GET /api/diff/fresh on both Bun and Pi servers), a stale-content guard so files edited mid-review degrade to raw-patch view instead of breaking virtualization, the Ask AI wrong-file fix (pre-existing), and toolbar/header UI polish (global settings cog, aligned sem badges, no all-files split dragger).

Hardened through five review waves; tested with 1384 passing tests incl. real-git fingerprint and patch-consistency suites. Known minor gaps documented in the PR.
2026-06-10 21:07:58 -07:00
Michael Ramos c3ba55e889 feat(review): add semantic diff overview (#871)
* feat(review): add semantic diff overview

* fix(review): address semantic diff review findings

* fix(review): harden semantic diff fallback

* fix(review): avoid repo-local sem execution

* fix(review): normalize semantic diff cwd

* test(review): cover semantic diff local cwd

* fix(gitlab): fetch raw MR diffs

* fix(review): harden sem path resolution

* docs(review): add semantic diff handoff

* feat(review): semantic diff cards, header sem badges, jump-to-line

- Restyle the semantic panel as real bordered cards (shadcn surface) instead
  of ASCII box-drawing; centered column, grid-aligned entity rows.
- Hide orphan (module-level) changes from the rows, matching sem's default;
  the count still surfaces in the summary line.
- Add a 'sem · N' hover popover to each diff file header showing that file's
  semantic changes, reusing the same row component as the panel.
- Clicking an entity (panel or popover) scrolls the diff to the lines via
  pierre's [data-selected-line]; centers only when off-screen so manual
  drag-selection isn't disturbed.
- Extract shared rows/helpers into semanticDiffShared; share one cached
  /api/semantic-diff fetch across header badges.

* feat(review): land on All files by default

Semantic diff stays available via the file-tree nav entry and header badges,
but it's no longer the initial landing view.

* chore(review): drop dead change-symbol entries, log badge fetch failures

- Remove unreachable 'moved'/'renamed' entries from the changeSymbols table
  (getChangeSymbol early-returns for those before the lookup).
- Log a console.error once per patch when the file-header badge's semantic
  diff fetch fails or returns a non-ok status, so a systemic failure leaves a
  trace instead of every badge silently showing nothing.

* feat(review): flatten semantic diff panel into grouped list

- Dissolve the per-file bordered cards into flat sections: the file path is now
  a quiet underlined header (single hairline) with entity rows flush beneath,
  hierarchy from whitespace + hover tint instead of boxes.
- Split the path into muted directory + emphasized filename for faster scanning.
- Nudge the add/remove glyphs (⊕/⊖) ~15% larger, line-height pinned so rows
  don't grow; modified/rename/reorder glyphs unchanged.
2026-06-08 22:23:54 -07:00
Oscar Silva f08764063d feat(review): support multi-repo workspace reviews (#543)
* feat(review): support multi-repo workspace reviews (#527)

* fix(workspace): address critical issues from deep review

- Fix race condition in label generation by pre-computing labels sequentially
- Fix rewritePatchLine to support quoted paths and rename/copy headers
- Add separator between aggregated patches to avoid invalid diffs
- Normalize input paths in resolveWorkspaceFilePath
- Add timeout to PR discovery (15s) to prevent server hangs
- Fix PATCH /api/workspace/repo to rollback state on failure via applyRepoMutation
- Validate body.source runtime (must be 'local' or 'pr')
- Snapshot active repo in agent jobs at launch to prevent race in onJobComplete
- Prevent double-prefixing of agent findings when paths are already prefixed
- Fix frontend findWorkspaceRepoForPath to use longest-prefix matching
- Fix shared types: diffType uses DiffType, platformUser is string | null

* fix: remove duplicate gitRuntime export in vcs.ts

* fix: resolve remaining merge conflict in local review mode, remove stale detectManagedVcs import

* Add local multi-repo workspace review support

* Fix workspace review edge cases

* Remove session query from browser launch

* Add switchable workspace review modes

* fix(review): cover opencode workspace bridge

* fix(review): clean workspace review plumbing

* fix(review): clarify workspace agent finding paths

* fix(review): preserve diff paths with spaces

---------

Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-06-05 14:29:38 -07:00
Michael Ramos 2a5528693f Add Ask AI to plan and annotate reviews (#763)
* Add Ask AI to plan and annotate reviews

- mount shared AI runtime on plan, annotate, review, and Pi servers

- add shared document chat UI and comment-popover Ask AI entry point

- default providers from detected agent origin and document first-run announcement

- reuse shared code-review AI hook and document setup/docs

* Address Ask AI review followups

Stabilize AI chat session resets and callbacks, preserve per-origin provider defaults, share AI chat formatting utilities, and avoid blocking startup on model discovery.

* Fix AI permission details and Pi CLI lookup

Show formatted tool input in document AI permission cards and make Pi AI provider CLI detection work on Windows.

* Fix Pi model discovery in AI capabilities

Keep AI runtime startup non-blocking while making the capabilities endpoint await pending Pi/OpenCode model discovery before returning provider metadata.
2026-05-21 01:32:17 -07:00
Michael Ramos 95750ab657 feat: search-based code navigation with peek view (#711)
* feat: search-based code navigation with peek view (#694)

Add IDE-like code navigation to the review UI. Cmd/Ctrl+click a token
in a diff to find its definitions and references across the repo via
ripgrep, displayed in a VS Code-style peek panel below the diff.

Backend: bounded rg search with language-aware definition patterns
(TS/JS, Python, Go, Rust), ranked results (same file > changed files >
same directory), confidence labels, and graceful degradation when rg
is not installed. Both Bun and Pi servers implement the endpoints.

Frontend: Dockview peek panel with syntax-highlighted full-file preview
on the left and grouped reference list on the right. Clicking a
reference scrolls the preview; double-clicking an in-diff result
navigates to the file with a gold line flash.

Closes #694

* fix: resolve Pi server TypeScript errors for code-nav

Add missing spawn import, type the close callback parameter,
and use double-cast for parseBody → CodeNavRequest.

* fix: clear loading state on cached preview hits

Without this, clicking a cached file while a fetch is in-flight
leaves isLoading stuck true — the spinner hides the preview.

* feat: show pointer cursor on Cmd/Ctrl+hover for navigable tokens

Adds pn-token-nav class with thicker underline and pointer cursor
when hovering a token while holding the modifier key, signaling
the token is Cmd+clickable for code navigation.

* refactor: remove go-to-diff navigation from peek panel

Strip the in-diff badge, double-click-to-jump, highlightDiffLine
wiring, and onCodeNavGoToDiff from the peek panel. The peek view
is the primary interaction — jump-to-diff adds complexity without
clear value at this stage.

* chore: remove dead code from code-nav cleanup

Delete unused highlightDiffLine.ts, remove codeNavChangedFiles
and codeNavActiveSide from context and App.tsx, drop stale
extractChangedFiles import.

* chore: add code-nav endpoints to AGENTS.md, remove dead activeSide state

* fix: don't classify bare indented calls as definitions

Change the TS/JS method pattern from zero-or-more (*) to
one-or-more (+) declaration keywords, so plain calls like
startServer(config) are no longer misclassified as definitions.

* feat: show toast when code-nav is unavailable in platform-only PR mode

Instead of opening the peek panel and showing misleading "No results",
Cmd+click in non-local PR mode shows a brief toast explaining that
code navigation requires a local checkout.

* fix: strip hljs hardcoded background from code-nav preview

The highlight.js github-dark theme sets a fixed dark background
on all .hljs elements. Apply transparent override for the entire
peek preview so code inherits the active theme's background.
2026-05-13 12:24:37 -07:00
Graeme Folk 69ef11bdfb feat(review): add jj review workflows (#675)
* feat(review): add jj support for local diffs

* feat(review): add jj review workflows

* fix(review): tighten jj diff defaults

* test(review): add jj manual sandbox

* fix(review): share jj agent diff prompts

* fix(review): quote jj agent revsets

* feat(review): share jj vcs handling with pi

* fix(review): tighten jj bookmark and pi pr handling

* fix(review): tighten jj defaults and detection

* fix(review): harden jj diff and vcs detection

---------

Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-05-07 19:57:33 -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 bb404f8d14 feat: stacked PR review — PR switching, scope toggling, multi-PR posting (#620)
* feat(shared): add isSameProject, PR stack types, and PR list provider

Extends PRRef/PRMetadata with defaultBranch, PRStackInfo, PRStackTree,
PRStackNode, PRDiffScope, and PRListItem types. Adds isSameProject()
for owner/repo validation on PR switching. Adds fetchPRStack() and
fetchPRList() dispatch functions (GitHub-only for now, GitLab stubs).

Includes 9 new tests for isSameProject covering GitHub, GitLab, and
cross-platform scenarios.

For provenance purposes, this commit was AI assisted.

* feat(shared): add GitHub PR stack tree walking and PR list fetching

Implements fetchGhPRStack() which walks up/down the PR stack via
GraphQL, resolving numbers and titles for each node in the chain.
Collapses queryPRsByHead/queryPRsByBase into a single queryPRsByRef
helper. Adds fetchGhPRList() using gh pr list. Fixes GHE support
by removing hostnameArgs from fetchGhPRList (--repo already handles
GHE). Filters jq "null" string from defaultBranch detection.

For provenance purposes, this commit was AI assisted.

* feat(shared): fetch defaultBranch for GitLab MRs

Queries the project's default_branch via glab API so getPRStackInfo
can detect stacked MRs on GitLab. Best-effort — caught errors fall
back to undefined.

For provenance purposes, this commit was AI assisted.

* feat(shared): add PR stack detection and full-stack diff module

New pr-stack module with:
- getPRStackInfo(): detects stacked PRs from baseBranch vs defaultBranch
- getPRDiffScopeOptions(): generates layer/full-stack scope options
- runPRFullStackDiff(): computes diff from default branch to HEAD
- resolvePRFullStackBaseRef(): resolves origin/main or local main
- checkoutPRHead(): fetches and checks out a PR head in a worktree
- buildMinimalStackTree(): builds UI tree from stack info

Includes 13 tests covering ref resolution, branch fallbacks, and
GitLab ref formats.

For provenance purposes, this commit was AI assisted.

* feat(shared): add worktree pool for per-PR agent isolation

Creates a session-scoped pool of git worktrees — each PR visited
during a stacked review gets its own isolated checkout. Agents run
in their PR's worktree undisturbed by PR switches. Handles
deduplication of concurrent ensure() calls for the same PR.

Includes 11 tests covering caching, cross-repo restrictions, GitLab
ref formats, and cleanup.

For provenance purposes, this commit was AI assisted.

* feat(shared): add diffScope/prUrl to agent jobs, branch diff type

Adds prUrl and diffScope optional fields to AgentJobInfo so agent
findings carry the PR and scope context they were launched under.
Exports new pr-stack and worktree-pool modules from package.json.
Adds 'branch' to DefaultDiffType union for branch diff as default.

For provenance purposes, this commit was AI assisted.

* feat(ui): add PR annotation fields, Popover, and SearchableSelect

Extends CodeAnnotation with prUrl, prNumber, prTitle, prRepo, and
diffScope fields for stacked PR attribution. Adds shared Popover
wrapper around radix-ui. Adds SearchableSelect for filterable
dropdown lists (used by PR selector).

For provenance purposes, this commit was AI assisted.

* feat(ui): add branch diff as default option, new Git settings tab

Adds 'Branch' as a fourth default diff type option in both the
first-run dialog and settings panel. Moves the default diff type
setting from the Display tab to a new Git tab in review mode.
Updates config store validators to accept 'branch'.

For provenance purposes, this commit was AI assisted.

* feat(server): add prUrl/diffScope plumbing to agent jobs and prompts

Threads prUrl and diffScope through the agent job lifecycle so
findings carry the PR and scope they were generated under. Adds
full-stack prompt branch to codex-review and tour-review — when
in full-stack mode, the diff is inlined in the prompt instead of
telling the agent to run git diff. Re-exports isSameProject and
new PR provider functions from server/pr.ts.

For provenance purposes, this commit was AI assisted.

* feat(server): add stacked PR support to Bun review server

Adds PR switching, layer/full-stack scope toggling, PR list caching,
worktree pool integration, and multi-PR platform posting to the Bun
review server. Key additions:

- /api/pr-diff-scope: switch between layer and full-stack diffs
- /api/pr-list: cached PR list for the current repo
- /api/pr-switch: in-place navigation between PRs in a stack
- /api/pr-action: targetPrUrl support for multi-PR posting
- /api/file-content: full-stack branch for hunk expansion
- prSwitchCache/prStackTreeCache for session-scoped caching
- diffScope tagging on agent job completion
- Scope guard: returns 400 on full-stack diff failure instead of
  overwriting the working diff with empty content

For provenance purposes, this commit was AI assisted.

* feat(ai): pass cwd to Claude agent SDK for worktree support

Forwards the working directory to the Claude agent provider so
agents run in the correct worktree when reviewing stacked PRs.

For provenance purposes, this commit was AI assisted.

* feat(pi): add stacked PR support to Pi server (Bun parity)

Mirrors all stacked PR features from the Bun server:
- PR switching, scope toggling, PR list, multi-PR posting
- prSwitchCache/prStackTreeCache with initial PR seeding
- diffScope/prUrl plumbing in agent jobs
- Worktree pool creation and lifecycle
- Full-stack file-content resolution matching Bun's guard structure
- targetPrUrl support on /api/pr-action

Hoists worktreePool declaration to outer scope in plannotator-browser
to fix TS18004 scoping error. Updates vendor.sh for new shared modules.

For provenance purposes, this commit was AI assisted.

* feat(hook): create worktree pool for PR review sessions

Creates a worktree pool when opening a PR review with --local,
seeding it with the initial PR's checkout. Integrates pool cleanup
into server shutdown. Passes the pool to startReviewServer for
agent isolation during PR switching.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): add hooks for PR stack, context, and annotations

- useAnnotationFactory: stamps prUrl/prNumber/prTitle/prRepo/diffScope
  onto annotations, only when viewing a stacked PR
- usePRStack: handles scope selection and PR switching with loading state
- usePRContext: adds URL-change detection to prevent stale-fetch race
  when switching PRs (discards in-flight responses for previous PR)

For provenance purposes, this commit was AI assisted.

* feat(review-editor): add stacked PR UI components

- PRSelector: searchable dropdown for switching between PRs in a repo
- PRSwitchOverlay: loading animation during PR switch
- StackedPRLabel: stack tree popover with scope selector and PR navigation
- ReviewSubmissionDialog: multi-PR submission dialog with per-target
  status, orphaned findings section with copy-as-markdown, and
  partial failure retry

For provenance purposes, this commit was AI assisted.

* feat(review-editor): multi-PR export with heading hierarchy

Updates exportReviewFeedback for multi-PR sessions:
- Groups annotations by prUrl, then by file within each PR
- Uses proper heading hierarchy (## for files, ### for annotations
  in multi-PR mode)
- Detects single-PR mismatch (annotations from a different PR than
  the current view) and uses annotation-level PR context
- Adds diffScope labels per PR group when present

Includes 5 new tests: multi-PR headings, single-PR mismatch,
diffScope labels, and non-stacked annotation handling.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): integrate stacked PR into sidebar, diff panel, and agents

- ReviewSidebar: groups annotations by PR in multi-PR sessions,
  shows PR headers with annotation counts
- ReviewDiffPanel: filters annotations by prUrl and diffScope so
  only matching annotations appear in the diff gutter
- ReviewStateContext: adds prDiffScope to shared review state
- ReviewAgentJobDetailPanel: shows diffScope in job detail
- PRSummaryTab: shows stack info in PR summary
- index.css: PR switch shimmer and overlay animations

For provenance purposes, this commit was AI assisted.

* feat(review-editor): wire stacked PR into main review app

Integrates all stacked PR features into the review editor:
- PR stack state management (prStackInfo, prStackTree, prDiffScope)
- applyPRResponse: shared handler for PR switch and scope toggle,
  preserves active file index on scope changes
- Multi-PR platform posting via Promise.allSettled with parallel
  requests, partial failure retry, and per-target status tracking
- ReviewSubmissionDialog replaces inline dialog JSX
- useAnnotationFactory stamps PR context onto annotations
- keepalive on /api/feedback to survive tab closure
- Proper try/catch/finally on handlePlatformAction

For provenance purposes, this commit was AI assisted.

* docs: add stacked PR review documentation

Updates AGENTS.md, code-review command docs, and AI code review
guide with stacked PR review capabilities.

For provenance purposes, this commit was AI assisted.

* fix(server): stamp prNumber/prTitle/prRepo on agent findings

Agent annotations only had prUrl and diffScope, missing prNumber,
prTitle, and prRepo. When agent findings were the only annotations
for a PR target in the submission dialog, the target rendered as
#0 with no title. Now resolves full PR context from prSwitchCache
at job completion and stamps all five fields. Both Bun and Pi.

For provenance purposes, this commit was AI assisted.

* feat(ui): rename diff options — "Committed" replaces "Branch" / "Current PR Diff"

Consolidates two confusing committed-diff options into one:
- Settings/first-run: "Committed" — "Everything you've committed on this branch"
- Mid-session switcher: "Committed changes" (replaces both "vs main" and "Current PR Diff")

Uses merge-base under the hood (matches GitHub PR behavior). Removes
the two-dot branch diff from the UI — it stays in the runtime DiffType
union for backwards compat. Old "branch" values in config/cookies are
silently upgraded to merge-base.

Git settings tab now uses radio cards with descriptions instead of
a cramped segmented control. First-run dialog descriptions rewritten
in plain language — no git commands.

For provenance purposes, this commit was AI assisted.

* fix(review-editor): rename client-side "PR Diff" labels to "Committed changes"

DiffTypePicker.tsx had a hardcoded "PR Diff" override for merge-base
when the base picker is present. exportFeedback.ts also used "PR Diff"
in export labels. Both now say "Committed changes" to match the
server-side label and settings UI.

For provenance purposes, this commit was AI assisted.

* fix(server): discover stack UI for root PRs targeting the default branch

Root PRs (baseBranch === defaultBranch) were excluded from stack
detection because getPRStackInfo returned null. Now the server
always fetches the stack tree in PR mode. If the tree reveals
descendant PRs, prStackInfo is retroactively set with source
"tree-discovered", enabling the stack UI, scope selector, and
PR navigation from the root of a stack.

Both Bun and Pi servers updated. Adds "tree-discovered" to the
PRStackInfo source union.

For provenance purposes, this commit was AI assisted.

* fix(review-editor): derive diff scope from annotations, not UI state

The export function now reads diffScope from annotations instead of
the prReviewScope parameter. Fixes two issues:

1. Agent job "Copy All" showed the wrong scope when the user switched
   between layer/full-stack after launching the agent
2. Mixed-scope annotations produced a confusing "layer, full-stack"
   comma-joined label instead of grouping by scope

Extracts renderScopedGroups helper for scope-aware grouping — used
by both single-PR and multi-PR export paths. When annotations share
one scope, it appears in the header. When mixed, annotations are
grouped under ## Layer / ## Full-stack headings.

Includes 4 new tests: uniform scope derivation, mixed scope grouping,
single scope header, and prReviewScope override prevention.

For provenance purposes, this commit was AI assisted.

* fix(server): add tree-discovered stack fallback to pr-switch handler

The initial-load path upgrades prStackInfo for root PRs when the
stack tree reveals descendants, but the pr-switch handler was missing
this logic. The server now sends correct prStackInfo after switching
to a root-of-stack PR. Both Bun and Pi.

Also removes stale prReviewScope dependency from agent job panel's
copyAllText useMemo.

For provenance purposes, this commit was AI assisted.

* fix: extract resolveStackInfo helper, fix stack UI on non-stacked PRs

Extracts the tree-discovered stack fallback into resolveStackInfo()
in pr-stack.ts — eliminates 4 copies of the same logic across Bun
startup, Bun pr-switch, Pi startup, and Pi pr-switch.

Fixes StackedPRLabel showing on every PR: the check now counts
non-default-branch nodes (> 1) instead of all nodes (> 1). Without
this, every PR showed a "Stack (1 PR)" popover because the tree
always has at least [defaultBranch, currentPR].

For provenance purposes, this commit was AI assisted.

* fix(review-editor): don't re-open already-succeeded PR tabs on retry

On partial failure retry, openUrls was pre-seeded with URLs from
previously succeeded targets, causing those PR pages to re-open
in the browser alongside newly succeeded ones. Now starts empty —
only URLs from the current attempt are opened.

For provenance purposes, this commit was AI assisted.

* refactor(review-editor): extract PR session state into usePRSession hook

Consolidates 5 independent useState calls (prMetadata, prStackInfo,
prStackTree, prDiffScope, prDiffScopeOptions) into a single
usePRSession hook with atomic updatePRSession callback.

Replaces two identical 5-line setter blocks (initial load and
applyPRResponse) with single updatePRSession calls. All ~60 consumer
sites unchanged — same variable names via destructuring.

For provenance purposes, this commit was AI assisted.
2026-04-27 22:07:55 -07:00
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 68972aa6a6 feat(review): custom base branch for code review (#599) (#602)
Adds a searchable base-branch picker to the code review UI so reviewers
can compare against any branch, not just the auto-detected default.

Key changes:
- Base-branch picker (Radix Popover + search, local/remote groups)
- Diff-type picker (Radix DropdownMenu + info tooltips)
- Worktree picker (Radix Popover + search)
- getDefaultBranch prefers upstream ref (origin/main) for fresher diffs
- listBranches populates GitContext.availableBranches
- resolveBaseBranch trusts caller verbatim (no silent rewrites)
- --end-of-options hardens git argv against flag-injection via base refs
- Branch diff / PR Diff always available (removed hide-on-default guard)
- merge-base agent prompt runs git itself instead of inlining the patch
- Agent jobs snapshot diff context at launch for honest "Copy All"
- Feedback export includes diff mode + base header for agent context
- Round-trip base through /api/diff so refresh preserves the selection
- selectedBase / committedBase split prevents file-content race
- Optimistic picker reverts on switch failure
- DiffViewer remounts on mode switch to invalidate stale file content
- Worktree switch preserves active diff mode
- Pi parity: initialBase, currentBase, agent diffContext, vendor.sh
- Tooltip wide mode, TooltipProvider mounted, keyboard/touch fixes
- GPT-5.5 added to Codex model picker
- CLAUDE.md API table updated

Closes #599

For provenance purposes, this PR was AI assisted.
2026-04-23 16:49:25 -07:00
Michael Ramos 53d2246b16 feat: Code Tour — guided PR walkthrough as a third agent provider (#569)
* feat(server): add Code Tour agent as third review provider

Adds a "tour" provider alongside "claude" and "codex" that generates a
guided walkthrough of a changeset from a product-minded colleague's
perspective. Reuses the entire agent-jobs infrastructure (process
lifecycle, SSE broadcasting, live logs, kill support, capability
detection) so the only new server plumbing is the prompt/schema module,
the GET endpoint for the result, and checklist persistence.

- tour-review.ts: prompt, JSON schema, Claude (stream-json) and Codex
  (file output) command builders, and parsers for both. Prompt frames
  the agent as a colleague giving a casual tour, orders stops by reading
  flow (not impact), chunks by logical change (not per-file), and writes
  QA questions a human can answer by reading code or using the product.
- review.ts: tour buildCommand with per-engine model defaults (fixes a
  bug where Codex was defaulting to "sonnet", a Claude model), an
  onJobComplete handler that parses and stores the tour, plus GET
  /api/tour/:jobId and PUT /api/tour/:jobId/checklist endpoints.
- agent-jobs.ts: tour capability detection and config threading from the
  POST body through to the provider's buildCommand.
- shared/agent-jobs.ts: engine/model fields on AgentJobInfo so the UI
  can render tour jobs with their chosen provider + model.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): Code Tour dialog with animated walkthrough

Adds the tour overlay surface: a full-screen dialog with three animated
pages (Overview, Walkthrough, Checklist) that renders the CodeTourOutput
from the server-side agent. Opens automatically when a tour job completes
and can be dismissed with Escape or backdrop click.

- components/tour/TourDialog.tsx: three-page animated dialog. Intro page
  uses a composition cascade (greeting, Intent/Before/After cards with
  one-shot color-dot pulse, key takeaways table) with a pinned Start
  Tour button and a bottom fade so content scrolls cleanly under it.
  Page slides between Overview/Walkthrough/Checklist are ease-out
  springs with direction auto-derived from tab index.
- components/tour/TourStopCard.tsx: per-stop accordion using motion's
  AnimatePresence for height + opacity springs with staggered children
  for detail text and anchor blocks. Anchors lazy-mount DiffHunkPreview
  on first open to keep mount costs low. Callout labels (Important,
  Warning, Note) are deterministic typography, no emoji.
- components/tour/QAChecklist.tsx: always-open list of verification
  questions with per-item spring entrance and persistent checkbox state
  that PUTs to the server.
- hooks/useTourData.ts: fetch + checklist persistence with a dev-mode
  short-circuit when jobId === DEMO_TOUR_ID so UI iteration doesn't
  require a live agent run.
- demoTour.ts: realistic demo data (multi-stop, multiple takeaways,
  real diff hunks) for dev iteration.
- App.tsx: tour dialog state, auto-open on job completion, and a
  dev-only "Demo tour" floating button + Cmd/Ctrl+Shift+T shortcut
  guarded by import.meta.env.DEV.
- index.css: all tour animations (dialog enter/exit, page slides, stop
  reveal cascade, intro exit) with reduced-motion fallbacks. Dark-mode
  contrast tuning across structural surfaces (borders, surface tints,
  callout backgrounds) so the design works in both themes.
- package.json: adds motion@12.38.0 for spring-driven accordion physics
  and the intro composition cascade.

For provenance purposes, this commit was AI assisted.

* feat(review-editor): wire Code Tour into agent jobs UI + polish DiffHunkPreview

Connects the tour provider to the existing agent jobs sidebar and detail
panel so the user can launch a tour the same way they launch Claude or
Codex reviews. Also tightens DiffHunkPreview (used inside tour anchors)
to render correctly on first mount and handle every diff hunk shape the
agent might produce.

- ui/components/AgentsTab.tsx: tour engine (Claude/Codex) + model select
  when launching a tour job. Resets model to blank when falling back to
  Codex-only so Codex uses its own default instead of inheriting
  "sonnet" (a Claude model).
- ui/hooks/useAgentJobs.ts: forward engine/model config from the UI
  through to the POST /api/agents/jobs body so the server's tour
  provider can pick the right command shape.
- dock/panels/ReviewAgentJobDetailPanel.tsx: tour-aware detail panel.
  Replaces the "Findings" tab with a "Status" card for tour jobs and
  surfaces an "Open Tour" button that opens the dialog overlay when
  the tab is already in the dock.
- components/DiffHunkPreview.tsx: synchronous pierre theme init via a
  useState lazy initializer so the first render (inside a tooltip) is
  already themed; robust hunk parser that handles bare @@ hunks, file-
  level --- hunks, and full git diffs; "Diff not available" fallback
  for broken hunks.
- components/ReviewSidebar.tsx, dock/ReviewStateContext.tsx: small
  wiring changes to expose openTourPanel from the review state context.

Also removes two dead components (TourHeader, DiffAnchorChip) that were
superseded by the inline title bar in TourDialog and the inline
AnchorBlock in TourStopCard.

For provenance purposes, this commit was AI assisted.

* refactor(server): extract Code Tour lifecycle into shared createTourSession factory + Pi parity

The route-parity test suite requires the Pi server (apps/pi-extension/)
to expose the same routes as the Bun server (packages/server/). After
Code Tour shipped in the prior 3 commits, Pi was missing /api/tour/:jobId
(GET) and /api/tour/:jobId/checklist (PUT).

A naive mirror would duplicate ~100 lines of provider-branch logic
(buildCommand, onJobComplete, in-memory maps) into Pi's serverReview.ts,
perpetuating the existing claude/codex duplication problem. Instead,
extract the pure runtime-agnostic tour lifecycle into a
createTourSession() factory that both servers consume. Route handlers
stay per-server (different HTTP primitives) but are ~5 lines each.

Net effect: Pi port is ~25 lines instead of ~100. Future providers that
adopt the same pattern cost ~15 lines per server.

- tour-review.ts: new createTourSession() at the bottom of the module.
  Encapsulates tourResults + tourChecklists maps, buildCommand (with
  the Claude-vs-Codex model-default fix baked in), onJobComplete
  (parse/store/summarize), plus getTour/saveChecklist lookup helpers
  for route handlers.
- review.ts (Bun): tour branch in buildCommand, tour branch in
  onJobComplete, and both route handlers collapse to one-line calls
  into the factory. Drops ~70 lines.
- vendor.sh: add tour-review to the review-agent loop so Pi regenerates
  generated/tour-review.ts on every build:pi.
- serverReview.ts (Pi): import createTourSession from
  ../generated/tour-review.js; add tour branch to buildCommand (one
  line), tour branch to onJobComplete (three lines), and GET/PUT route
  handlers using Pi's json() helper. ~25 lines added.
- agent-jobs.ts (Pi): extend buildCommand interface to accept config
  and return engine/model; thread config from POST body; extend
  spawnJob to persist engine/model on AgentJobInfo; add tour to
  capability list.

Claude and Codex branches are intentionally left in the old pattern;
they can migrate to the factory approach when next touched to keep
this change's blast radius contained.

Tests: 518/518 passing (previous 3 route-parity failures resolved,
plus 2 extra assertions passing since tour is now in both servers'
route tables).

For provenance purposes, this commit was AI assisted.

* refactor(tour): self-review cleanup — Pi route match parity + remove setOpen shim

Two small cleanups surfaced by a self-review pass:

- Pi's GET /api/tour/:jobId route used `endsWith("/checklist")` to block
  the checklist sub-route, while Bun uses `includes("/", ...)`. The two
  are not equivalent: a URL like /api/tour/abc/extra would be accepted
  by Pi (jobId becomes "abc/extra") but correctly rejected by Bun.
  Align Pi to Bun's pattern.
- TourStopCard had a leftover `setOpen` shim from when open state was
  local to the card. State is now lifted to TourDialog, so the shim
  just aliases onToggle and ignores its argument. Replace with a
  direct `onClick={onToggle}` on the trigger button.

520/0 tests still pass.

For provenance purposes, this commit was AI assisted.

* feat(review): per-provider model + effort controls across all review agents

Exposes model, effort/reasoning, and fast-mode (Codex) as per-job knobs
for Claude, Codex, and Code Tour via the Agents tab. Threads the config
from the UI through the POST body into each provider's buildCommand,
which emits the corresponding CLI flags (--model/--effort for Claude;
-m / -c model_reasoning_effort / -c service_tier for Codex). Bun and Pi
servers stay in parity.

UI: option catalogs (CLAUDE_MODELS, CLAUDE_EFFORT, CODEX_MODELS,
CODEX_REASONING, TOUR_CLAUDE_MODELS) are defined once and mapped into
every dropdown so there's a single source of truth for the choices.
Tour's Claude/Codex settings are kept separate from the standalone
provider's state so toggling the tour engine no longer overwrites the
provider's last choice.

Job badge now surfaces the model/reasoning/fast selection for both Tour
and the standalone Codex provider.

For provenance purposes, this commit was AI assisted.

* docs: add Prompts reference page

Documents the three-layer structure every review call travels through
(CLI system prompt, our user message of review-prompt + user-prompt,
output schema flag), names each constant + its file, and calls out
that the Claude/Codex review prompts are the upstream ones from those
projects (only Code Tour's prompt is original to Plannotator).

Linked from the Code Review command page.

For provenance purposes, this commit was AI assisted.

* feat(review): persist per-agent, per-model settings in a single cookie

Drops the hidden "Default" options from the agent dropdowns, locks in explicit
sensible defaults (Opus 4.7/High for Claude review, gpt-5.3-codex/High for Codex,
Sonnet/Medium for Tour Claude, gpt-5.3-codex/Medium for Tour Codex), and
remembers the last-used effort/reasoning/fast-mode per (agent job × model) so
switching models reveals the choices you made last time.

Backed by a single `plannotator.agents` cookie holding the whole settings tree —
one read on mount, one mirror write per change, all mutations funnel through a
single React state owner to avoid stale-read or lost-write races across rapid
successive updates.

For provenance purposes, this commit was AI assisted.

* fix(tour): unblock reduced-motion nav + flush pending checklist save on close

Two P2 issues surfaced in review:

- Under prefers-reduced-motion, tour page animations are suppressed, so
  onAnimationEnd never fires and exitingPage stuck on 'intro' kept the
  walkthrough/checklist gated out. navigate() now swaps pages directly when
  reduced motion is on, mirroring the pattern already used in the wrapper.

- Checklist toggles are debounced 500ms before the PUT, but unmount only
  cleared the timer — checking an item and closing within the window dropped
  the save. Cleanup now flushes the pending payload with keepalive: true.

For provenance purposes, this commit was AI assisted.

* feat(review): surface Claude model + effort in job badge, trim redundant labels

Claude effort was never persisted on AgentJobInfo, so the job badge had nothing
to render beyond "Claude". Plumbs `effort` through the shared type, both
server build-command pipelines (Bun + Pi), and spawnJob, then teaches the
ProviderBadge to display Claude and Tour Claude model + effort with the same
shape Codex already had. Labels resolve via the dropdown catalogs so the
badge shows "Opus 4.7" / "High" instead of raw ids.

Server labels for both Claude and Codex reviews collapse to plain "Code Review"
(matching tour's "Code Tour"), since the badge now carries the provider +
model + settings — the title only needs to name the action.

For provenance purposes, this commit was AI assisted.

* polish(review): prefix agent dropdown options with the action name

The Run launcher listed "Claude Code", "Codex CLI", and "Code Tour" side by
side — the CLI's detection name was doing double duty as the action label.
Prefixes the review entries with "Code Review · " so scanning three options
surfaces two reviews + one tour instead of three raw provider names.

For provenance purposes, this commit was AI assisted.

* fix(review): drop invalid codex reasoning option + fail tour on empty output

Two P2 issues from PR review:

- Tour jobs exited 0 but returned null output would still be marked "done",
  and the auto-open watcher would greet the user with a 404 "Tour not found"
  dialog. onJobComplete now flips the job to failed with an error message
  when nothing was stored, so the card reflects the real state.

- The codex reasoning dropdown offered "None", but codex-rs only accepts
  minimal/low/medium/high/xhigh. Picking None sent `-c model_reasoning_effort=none`
  and launched a broken job. Removed the option; added a one-shot cookie
  migration so users who already saved "none" don't keep shipping it.

For provenance purposes, this commit was AI assisted.

* fix(tour): format Claude-engine logs + allow reading linked issues

Two P2/P3 issues from PR review:

- The stdout formatter keyed only on provider === "claude", so Code Tour
  jobs running on the Claude engine streamed raw JSONL to the log panel
  while Claude review jobs got formatted text. Widened the check to also
  catch spawnOptions.engine === "claude" and mirrored the fix into Pi.

- The tour Claude allowlist permitted PR/MR commands but not issue reads,
  yet the prompt explicitly asks the agent to open `Fixes #123` / `Closes
  owner/repo#456` targets for deeper context. Claude was being denied
  those commands mid-tour. Added gh issue view + gh api issues + glab
  issue view to the allowlist.

For provenance purposes, this commit was AI assisted.

* cleanup(review): e2e punchlist — Pi parity + dedup + tests

- Pi now logs Claude parse failures with the same diagnostic as Bun
- Tour route match uses a regex instead of an includes-offset trick
- Drop `any` cast in Pi's Codex blocking-findings predicate
- Extract `patchClaude` twin of `patchCodex` in useAgentSettings
- Factor `resolveAgentCwd` helper in Bun review to match Pi
- AgentsTab launch payload becomes a per-provider dispatch table
- Wrap TourDialog in MotionConfig reducedMotion="user" so motion.*
  children honor prefers-reduced-motion alongside the CSS keyframes
- Tests for parseTourStreamOutput/parseTourFileOutput and the Codex
  perModel sanitizer

For provenance purposes, this commit was AI assisted.

* test(tour-review): use real TourStop shape in fixtures

The parsers don't validate stop fields so the original made-up shape
passed fine, but future readers would be misled. Use the real
CodeTourOutput / TourStop / TourDiffAnchor shapes from tour-review.ts.

For provenance purposes, this commit was AI assisted.

* cleanup(tour): hoist shared types + subfolder server module + dedup

- Hoist tour output types to packages/shared/tour.ts so server and UI
  share one source of truth (prevents silent drift when schema changes).
- Move tour-review into packages/server/tour/ subfolder alongside the
  existing packages/review-editor/components/tour/ convention.
- Extend tour.buildCommand to accept tour context directly (patch,
  diffType, options, prMetadata), so Bun and Pi no longer duplicate the
  buildTourUserMessage call site. Export TOUR_EMPTY_OUTPUT_ERROR from
  the tour module to prevent string drift between servers.
- Early-return the tour branch in buildCommand so the review userMessage
  is built once on the shared non-tour path instead of unconditionally
  (dead work on tour launches) or twice (codex+claude dup).
- Regex capture group for tour checklist jobId in both servers —
  replaces a second url.pathname.split("/")[3] fragile fallback.
- Drop existsSync guard in parseTourFileOutput (TOCTOU + duplicate
  syscall); the outer try/catch already handles ENOENT.
- Dedupe two matchMedia reads in TourDialog behind a prefersReducedMotion
  helper; memoize intro-page card array so unrelated state churn doesn't
  recompute it.
- Comment hygiene on tour files — drop WHAT/change-referencing comments
  added by this PR; keep non-obvious WHY.

For provenance purposes, this commit was AI assisted.

* fix(tour): hoist introCards useMemo above early returns + subfolder hook

The memoized intro-card array was placed after the loading/error early
returns in TourDialogContent, so the first successful render called one
more hook than the initial loading render — React threw "Rendered more
hooks than during the previous render" (error #310) the moment a tour
finished loading. Move the useMemo above the early returns and use
optional chaining on `tour` so it's safe to run during loading.

Also move useTourData.ts into a hooks/tour/ subfolder to start a
standard for feature-scoped hooks (was flat among siblings).

For provenance purposes, this commit was AI assisted.
2026-04-20 20:57:57 -07:00
David han (Bart) c2dadc9717 Bind local Plannotator servers to loopback by default (#533)
* Harden review agent job launch endpoints

* Stabilize agent job auth tests

* Drop review agent job token gating

* Align useAgentJobs with upstream formatting

* Allow remote sessions to bind all interfaces
2026-04-13 07:00:05 -07:00
Vladyslav Hrabovyi 3b1b3317ae feat(review,annotate): add Close button to exit sessions without feedback (#523)
Adds a Close button to review and annotation sessions so users can exit
cleanly without sending feedback or killing the agent. Works across all
agent origins and includes a warning dialog when annotations would be lost.

Fixes #522

Co-authored-by: gwynnnplaine <vladyslav.hrabovyii@gmail.com>
2026-04-09 19:22:01 -07:00
Michael Ramos 93b09c7dc2 chore: bump version to 0.17.6
For provenance purposes, this commit was AI assisted.
2026-04-09 08:05:34 -07:00
Michael Ramos dd04e6b1cd feat: add Conventional Comments support to code review (#501)
* feat: add Conventional Comments support to code review

Add structured label system based on the Conventional Comments spec
(conventionalcomments.org) to the code review annotation toolbar.

- Label picker with 9 default labels (suggestion, nit, question, issue,
  praise, thought, note, todo, chore) shown above the comment textarea
- Per-label blocking/non-blocking toggle for labels where severity is
  ambiguous (issue, suggestion, todo, chore)
- Labels exported as `**label** (decoration): text` in markdown feedback,
  naturally readable on GitHub and machine-parseable
- Label badges shown on inline annotations and sidebar cards
- Settings tab (Comments) with: master on/off toggle, editable label
  list with add/remove/rename, per-label blocking decorator toggle,
  educational intro with spec link and example output
- Feature is off by default, persisted via config store
- Custom labels supported via settings (up to 12)

For provenance purposes, this commit was AI assisted.

* fix(review): address conventional comments review feedback

Fix label clearing bug where editing an annotation to remove its
conventional label silently preserved the old value. Fix parseCCLabels
accepting 'non-blocking' as a truthy blocking value. Fix duplicate
custom label identities when adding multiple labels. Prepend
conventional prefix to platform PR/MR inline comments.

For provenance purposes, this commit was AI assisted.

* fix(server): persist conventionalComments setting to config.json

All six server config handlers (bun plan/review/annotate + pi
plan/review/annotate) now accept and save the conventionalComments
boolean, so the setting survives server restarts.

For provenance purposes, this commit was AI assisted.

* fix: add conventionalComments to server config round-trip

getServerConfig() was not returning the conventionalComments value
from config.json, so the setting silently reset to false on cookie
clear or new browser sessions. Also adds the field to the
PlannotatorConfig interface so saveConfig() is properly typed.

For provenance purposes, this commit was AI assisted.

* fix: label display, export, and draft persistence for conventional comments

- Remove slug derivation from label editing — store display text
  verbatim so badges and exports show what the user typed
- Emit conventional prefix in export even when annotation has no
  prose text (suggestion-only annotations were losing their label)
- Include conventionalLabel in draft save condition so label
  selection persists across file switches

For provenance purposes, this commit was AI assisted.

* fix: spec-compliant export format and empty label support

- Wrap label + decorations + colon in markdown bold per the
  Conventional Comments spec examples (was bolding only the label)
- Allow users to clear all labels — empty array no longer falls
  back to defaults in either the picker or the settings parser
- Enable blocking decorator on the question label by default; the
  spec permits blocking questions and they sometimes are critical

For provenance purposes, this commit was AI assisted.

* fix: server-sync conventionalLabels and small cleanups

- Sync conventionalLabels to ~/.plannotator/config.json so custom
  label configurations survive cookie clears and remote/SSH
  sessions, matching the persistence story for conventionalComments.
  Stored as a parsed array on disk; serialized as JSON string in
  the local config store to match the cookie format.
- Remove no-op intermediate variable in handleSubmitAnnotation;
  pass conventionalLabel/decorations directly with proper coalescing
  per call path (edit preserves null, add coalesces to undefined).
- Use index-prefixed key in the picker label list to avoid React
  warnings if duplicate labels ever exist.

For provenance purposes, this commit was AI assisted.
2026-04-06 22:27:47 -07:00
Michael Ramos 0e1ea9e363 fix(review): use merge-base SHA for PR file contents
gh pr diff computes diffs against the merge-base (common ancestor), but
file contents were fetched at baseSha (base branch tip). When the base
branch has moved since the branch point, line counts don't match the
diff hunks, causing iterateOverDiff trailing context mismatch crashes.

Fetch the merge-base SHA via GitHub's compare API and use it for old
file contents. Added try/catch around processFile as a safety net.
Fixed in both Bun and Pi servers.

For provenance purposes, this commit was AI assisted.
2026-04-06 13:05:30 -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
foxytanuki 26364543b2 fix(remote): support explicit local override (#481) 2026-04-04 13:17:16 -07:00
rtsummit e642e25124 feat: add Perforce (P4) pending changelist diff support (#472)
* feat: add Perforce pending changelist diff support for code review

Introduce P4 support alongside existing Git backend via a VCS dispatch
layer (vcs.ts). Detects Git vs Perforce workspace automatically and
routes diff/file-content operations to the appropriate backend.

- Add p4-default and p4-changelist:<N> DiffType variants
- Add P4 runtime (p4.ts): workspace detection with TTL cache, changelist
  context, unified diff conversion, binary file exclusion, batch p4 where
- Add VCS dispatch layer (vcs.ts): auto-detect Git/P4, unified API
- Update review server and CLI entry point to use VCS dispatch
- Filter empty changelists from dropdown, disable staging for P4

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

* refactor: introduce VcsProvider interface for extensible VCS support

Replace hardcoded Git/P4 dispatch with a provider-based architecture.
Each VCS implements VcsProvider interface and registers in a providers
array — adding a new VCS only requires implementing the interface.

- Define VcsProvider with detect, ownsDiffType, getContext, runDiff,
  getFileContents, and optional stageFile/unstageFile/resolveCwd
- Create gitProvider and p4Provider as concrete implementations
- Replace isP4DiffType/gitAddFile/gitResetFile in review.ts with
  provider-based canStageFiles/stageFile/unstageFile/resolveVcsCwd
- Remove VCS-specific branching from review server endpoints

Note: GitContext interface is not renamed to VcsContext in this commit.
The rename touches too many files across the codebase (Pi extension,
OpenCode plugin, shared types, tests) and should be handled as a
separate pull request to keep the diff reviewable.

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

---------

Co-authored-by: rtsummit <rtsummit@abutton.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 10:49:24 -07:00
Michael Ramos d8a67beb1c feat: agentic review — background job runner with SSE streaming (#443)
* feat(server): add agent job manager with process lifecycle and SSE streaming

Introduces the backend for agentic review — a server-agnostic job runner
that spawns agent processes, monitors their lifecycle via proc.exited, and
broadcasts status updates over a dedicated SSE stream.

New files:
- packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine
- packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes

Wired into the review server with late-bound serverUrl, killAll on stop
and process exit for defense-in-depth cleanup. Capability detection via
Bun.which() for Claude Code, Codex CLI, and shell.

For provenance purposes, this commit was AI assisted.

* feat(ui): add Review Agents tab with job management and live status

Adds the client-side UI for agentic review:
- useAgentJobs hook: SSE primary with polling fallback, capabilities fetch
- AgentsTab: shared component with provider dropdown, job cards, kill controls
- ReviewAgentsIcon: magnifying glass with cog icon
- ReviewPanel: new "Review Agents" tab conditional on detected capabilities
- App.tsx: initializes hook and passes props to ReviewPanel

Jobs show live elapsed time, status badges, annotation counts per source,
and expandable error details. Stub command (sleep 10-30s) for initial testing.

For provenance purposes, this commit was AI assisted.

* fix(server): narrow proc.stderr type to satisfy TS

Bun types proc.stderr as ReadableStream | number. Add typeof guard
to narrow before passing to Response constructor.

For provenance purposes, this commit was AI assisted.

* fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch

- Change stdout from "pipe" to "ignore" — agents post findings via the
  annotations API, not stdout. Unconsumed pipe buffer caused deadlock.
- Drain stderr continuously instead of reading after exit — prevents
  pipe-full stall on chatty agents.
- Make agent getCwd worktree-aware using the same currentDiffType check
  the AI endpoints use, so agents spawn in the correct checkout.
- Exclude 'agents' tab from PR context fetch guard in ReviewPanel.

For provenance purposes, this commit was AI assisted.

* feat(pi): mirror agent-job endpoints in Pi review server

Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun
agent-jobs handler using child_process.spawn, res.write() SSE, and
execFileSync for capability detection.

Wire into serverReview.ts: route delegation, killAll in stop(),
process.on("exit") guard, worktree-aware getCwd, and serverUrl
late-binding. Add agent-jobs to vendor.sh for shared type vendoring.

For provenance purposes, this commit was AI assisted.

* fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs

- Use process.once instead of process.on to prevent exit listener accumulation
- Validate provider against known capabilities before spawning (rejects unknown providers)
- Use platform-aware which/where for CLI detection on Windows
- Broadcast jobs:cleared event from kill-all endpoint (was dead client code)
- Document all /api/agents/* endpoints in CLAUDE.md Review Server table

For provenance purposes, this commit was AI assisted.

* fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup

- Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback
  activates correctly on subsequent tab switches
- Remove jobs:cleared broadcast from kill-all — killAll() already fires
  individual job:completed events, so the UI shows status transitions
  instead of going blank
- Store exit handler ref so stop() can removeListener, preventing
  accumulation in long-lived hosts (OpenCode, Pi)

For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
Michael Ramos b0980ef928 fix(opencode): remove verbose logs that flood the TUI (#440)
Remove writeRemoteShareLink stderr output from the OpenCode plugin —
the base64 share URL was flooding the TUI on remote sessions. Also
strip leftover console.log debug statements from the PR viewed files
feature in the review server.

Closes #435

For provenance purposes, this commit was AI assisted.
2026-03-30 10:51:27 -07:00
foxytanuki 16756e082b fix(server): keep external annotation SSE streams alive (#439) 2026-03-30 08:49:34 -07:00
Michael Ramos 4627f75426 feat: external annotations API with real-time SSE (#400)
Adds a general-purpose External Annotations API that allows external programs (linters, AI tools, security scanners) to push annotations into a live Plannotator session via HTTP, with real-time delivery over SSE.

## What's included

- **Shared core** (`packages/shared/external-annotation.ts`): types, in-memory store, input validation, SSE serialization
- **Server handlers**: Bun + Pi implementations with full CRUD (GET/POST/PATCH/DELETE) + SSE streaming
- **Client hook** (`useExternalAnnotations`): EventSource with polling fallback, optimistic updates
- **Editor integration**: two-array state model (local + external), content-aware dedup, ID-based routing
- **Persistence**: source field preserved through share URLs and crash-recovery drafts
- **Docs**: new Integrations category with API overview page, updated API reference

## API surface

All three servers (plan, review, annotate) expose:
- `GET /api/external-annotations/stream` - SSE stream
- `GET /api/external-annotations` - JSON snapshot (polling fallback)
- `POST /api/external-annotations` - Add annotations (single or batch)
- `PATCH /api/external-annotations?id=` - Update fields
- `DELETE /api/external-annotations` - Remove by id, source, or clear all

For provenance purposes, this commit was AI assisted.
2026-03-29 17:18:31 -07:00
Michael Ramos 9b016da4ae feat(review): diff display options with ConfigStore integration (#428)
* feat(config): add DiffOptions to PlannotatorConfig with deep-merge support

Extends the server-side config system to support diff display options
namespaced under `diffOptions` in ~/.plannotator/config.json. The
saveConfig deep-merge ensures partial writes (e.g. changing only
overflow) don't clobber sibling keys.

For provenance purposes, this commit was AI assisted.

* feat(server): accept diffOptions in POST /api/config handlers

All six server handlers (plan, review, annotate x Bun + Pi) now
whitelist diffOptions alongside displayName, forwarding it to
saveConfig for deep-merged disk persistence.

For provenance purposes, this commit was AI assisted.

* feat(config): register diff display settings with deep-merge write batching

Adds 6 diff option settings to the ConfigStore registry (diffStyle,
diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers,
diffShowBackground), all synced to disk under the diffOptions namespace.

Fixes write batching for nested server keys — replaces Object.assign
with deepMerge so rapid changes to multiple diff options within the
300ms debounce window don't clobber each other. Includes legacy cookie
migration for the old review-diff-style key.

For provenance purposes, this commit was AI assisted.

* feat(review): wire diff display options through to @pierre/diffs

Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6
diff options via useConfigValue and forwards them to FileDiff: overflow,
diffIndicators, lineDiffType, disableLineNumbers, disableBackground.

Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified
toggle. Disables the custom resizable split dragger in wrap mode since
Pierre manages its own grid layout. Fixes the unsafeCSS grid override
to only target scroll mode, preventing per-character wrapping in split
view.

For provenance purposes, this commit was AI assisted.

* feat(review): add Display tab to review-mode Settings dialog

Adds a Display tab when Settings is in review mode, exposing all 6 diff
options: Diff Style, Line Overflow, Change Indicators, Inline Diff
Granularity, Show Line Numbers, and Show Diff Background. Changes take
effect immediately and persist via ConfigStore (cookie + disk).

Extracts reusable SegmentedControl and ToggleSwitch helpers for the
review display controls.

For provenance purposes, this commit was AI assisted.

* chore: update bun.lock

For provenance purposes, this commit was AI assisted.

* fix(review): reapply search highlights after display option changes

Add new diff display props to the search highlight and scroll-to-match
effect dependency arrays so highlights are restored after Pierre re-renders.

For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
Stacey Haffner 2d90d381c9 fix: Detect calling agent via env vars and centralize agent config (#418)
* fix: detect calling agent via env vars for correct badge display

Add prioritized agent detection chain: CODEX_THREAD_ID (codex) >
COPILOT_CLI (copilot-cli) > default (claude-code). All subcommands
use the shared detectedOrigin constant. Display name updated from
'Copilot CLI' to 'GitHub Copilot'. TypeScript origin union type
updated to include 'copilot-cli'.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* refactor: centralize agent config into @plannotator/shared/agents

- Create packages/shared/agents.ts as single source of truth for Origin type,
  agent display names (AGENT_CONFIG), getAgentName(), and getAgentBadge()
- Replace all inline origin type unions across 8 files with Origin import
- Type detectedOrigin and ServerOptions.origin as Origin for compile-time safety
- Add @plannotator/shared dependency to @plannotator/editor package.json
- Adding a new agent is now a one-file change to AGENT_CONFIG

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>

* fix: restore gitContext in startReviewServer call

Accidentally removed alongside the origin refactor. Without it, local
code reviews lose branch detection, diff-type switching, and CWD resolution.

For provenance purposes, this commit was AI assisted.

---------

Co-authored-by: Yecats <Yecats@users.noreply.github.com>
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-03-28 16:37:56 -07:00
Michael Ramos 401793e35f feat: custom display name + config file foundation (#399)
Adds user-editable display names and persistent config via ~/.plannotator/config.json.

- ConfigStore singleton with precedence: server config file > cookie > default
- Editable identity input in Settings with "Use git name" and regenerate buttons
- POST /api/config endpoint for write-back across all 6 servers
- getServerConfig() reads config fresh per request (no stale cache)
- Eager constructor hydration so the store is safe to read before init()
- vendor.sh as single source of truth for Pi extension vendoring
- Vendor parity test to prevent missing generated modules

Closes #396
2026-03-26 11:54:22 -07:00
Rock Neurotiko a8260eb389 Sync github Viewed files (#393) 2026-03-25 13:33:33 -07:00
Alexandre Silvestri 81f29dfe6e unix update command for wsl users on UpdateBanner (#395) 2026-03-25 11:06:29 -07:00
Michael Ramos f96758da0a feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers

Phase 1-3 of Pi endpoint parity:

Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff

Annotate server: image, upload, draft, favicon, linked documents, file browser

Review server: extract shared handlers, add favicon

Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.

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

* feat(pi): add PR review endpoints and Node.js PR runtime adapter

Phase 4 of Pi endpoint parity:

- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared

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

* feat(pi): wire AI backbone with Node.js Pi SDK provider

Phase 5 of Pi endpoint parity:

- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
  using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
  codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
  for SSE streaming
- Dispose AI sessions and registry on server stop

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

* fix(pi): address parity audit findings across all three servers

Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode

Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails

Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations

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

* feat(pi): complete parity — integrations, planSave, save-notes

Ports all remaining missing functionality:

- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
  (Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
  planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js

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

* refactor(pi): wire domain module imports and fix type errors

- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)

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

* refactor(pi): move generated shared files to generated/ directory

Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.

Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.

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

* refactor(pi): replace hand-maintained utils.ts with generated checklist

utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.

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

* chore(pi): gitignore generated/ and built HTML files

These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.

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

* refactor(pi): split server.ts into domain-organized modules

- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
  update imports for generated/checklist.js

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

* fix(pi): parity audit fixes + shared code extraction

Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).

Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support

Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources

For provenance purposes, this commit was AI assisted.

* fix: parity audit B3-C10 — review + annotate server fixes

Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)

Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files

For provenance purposes, this commit was AI assisted.

* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction

D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
  - Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
  - Made function sync (no longer async)
  - Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
  - Gains Windows path normalization, isWithinProjectRoot security check
  - Deleted packages/server/resolve-file.ts re-export, consumers import from shared
  - Cleaned up stale await calls in hook entry, reference handler, and tests
  - All 19 resolve-file tests pass

For provenance purposes, this commit was AI assisted.

* fix: parity audit D6-D10 — integrations, PR naming, shared modules

D6: Fixed broken detectProjectNameSync — was using require() for
    non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
    Bun server, hook, and OpenCode plugin to match Pi naming.
    Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.

For provenance purposes, this commit was AI assisted.

* update openpackage.yml

* fix: bump Pi git-add test timeout to 15s for parallel suite stability

For provenance purposes, this commit was AI assisted.

* test: add route parity test — Bun ↔ Pi server route drift detection

For provenance purposes, this commit was AI assisted.

* fix(ci): update Pi generate step to use generated/ directory with full file list

The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.

For provenance purposes, this commit was AI assisted.

* fix(ci): update release workflow Pi generate step to match new layout

Same stale generate step as test.yml — old flat layout, missing files.

For provenance purposes, this commit was AI assisted.

* fix(pi): update files array for modular server layout

The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.

For provenance purposes, this commit was AI assisted.

* feat: add TypeScript type-checking to CI pipeline

- Fix broken barrel export: buildFileTree/VaultNode re-exported from
  @plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows

For provenance purposes, this commit was AI assisted.

* fix(ci): use bun-types instead of @types/node for typecheck

CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.

For provenance purposes, this commit was AI assisted.

* fix(ci): add @types/node for Node-runtime type checks

Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.

For provenance purposes, this commit was AI assisted.

* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat

crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.

Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.

For provenance purposes, this commit was AI assisted.

* fix(ci): add bun-types as explicit devDependency

CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.

For provenance purposes, this commit was AI assisted.

* fix(ci): remove Pi extension from typecheck

Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.

For provenance purposes, this commit was AI assisted.

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
Michael Ramos d4ff4a8df7 feat(ai): OpenCode provider via HTTP + SSE (#379)
* feat(ai): add OpenCode provider via HTTP + SSE

Bundle @opencode-ai/sdk to spawn `opencode serve` and communicate via
HTTP REST + SSE. Richest provider: fork, resume, streaming, tools, and
runtime permission approvals all work natively.

- OpenCodeProvider: lazy server spawn, shared HTTP client, dynamic model
  discovery via GET /provider
- OpenCodeSession: SSE event drain loop, system prompt via API field,
  permission reply (once/reject), abort via HTTP
- mapOpenCodeEvent: SSE → AIMessage mapping (text deltas, tool lifecycle,
  permissions, session status, errors)
- 11 new event mapping tests (78 total, 157 expect calls)

For provenance purposes, this commit was AI assisted.

* docs(ai): add OpenCode to AI features guide and code review docs

For provenance purposes, this commit was AI assisted.

* fix(ai): prevent double server spawn in OpenCode ensureServer()

Use a promise-mutex pattern so concurrent callers (e.g. fetchModels +
createSession) share a single server spawn instead of racing to create two.
Also remove empty finally block from SSE drain loop.

For provenance purposes, this commit was AI assisted.

* fix(ai): await SSE subscribe in OpenCode provider

The SDK's event.subscribe() is async — must be awaited before
destructuring the stream.

For provenance purposes, this commit was AI assisted.

* fix(ui): scrollable model dropdown with search filter

Cap dropdown height at min(320px, 50vh) so it doesn't overflow the
viewport when providers expose many models (e.g. OpenCode with 20+).
Add a search/filter input when there are more than 8 models.

For provenance purposes, this commit was AI assisted.

* fix(ai): close SSE stream, rename to opencode-sdk, move dep to root

- Close SSE stream in finally block to prevent connection leak on
  abort/early return
- Rename provider from opencode to opencode-sdk for consistency with
  claude-agent-sdk, codex-sdk, pi-sdk
- Move @opencode-ai/sdk dependency to root package.json alongside the
  other SDK dependencies

For provenance purposes, this commit was AI assisted.

* feat(ui): add first-run AI setup dialog for provider selection

Show a one-time modal on first review when AI providers are available.
Users pick a default provider and model from a 2-column grid, with a
brief feature intro and auth disclaimer. Persists via cookie, can be
changed later in Settings.

For provenance purposes, this commit was AI assisted.

* fix(ai): clear startPromise on failure so OpenCode provider can retry

If doStart() fails (port conflict, timeout, binary crash), the cached
rejected promise prevented all future ensureServer() calls from
retrying. Now cleared on failure and on dispose().

Also updates stale "future" comment in types.ts.

For provenance purposes, this commit was AI assisted.
2026-03-23 17:37:56 -07:00
Michael Ramos 877b0c78ac feat(ai): Pi provider via RPC subprocess (#377)
* refactor(ai): extract BaseSession and buildEffectivePrompt

Pull shared session lifecycle (~80 lines duplicated across Claude and
Codex providers) into BaseSession: query guard, abort, ID resolution,
generation counter. Extract first-query prompt prepending into
buildEffectivePrompt() in context.ts.

Both providers now extend BaseSession. Behavior-preserving — all 54
existing tests pass unchanged.

For provenance purposes, this commit was AI assisted.

* feat(ai): add Pi provider via RPC subprocess

Spawns `pi --mode rpc` and communicates via JSONL over stdio. No Pi SDK
bundled — user must have the pi CLI installed. Provider auto-discovers
available models at startup via get_available_models.

Includes: PiProcess (JSONL client), PiSDKProvider, PiSDKSession extending
BaseSession, mapPiEvent for streaming, Pi icon in provider UI, and 12
new tests (9 event mapping + 3 buildEffectivePrompt).

For provenance purposes, this commit was AI assisted.

* fix(ai): harden Pi provider error paths

- Surface startup errors when Pi process dies (bad config, missing API keys)
  instead of hanging the chat indefinitely
- Map tool-call errors as non-terminal tool_result instead of AIErrorMessage,
  so Pi can continue reasoning after a failed tool call
- Fix subprocess leak in fetchModels() by moving proc.kill() to finally block

For provenance purposes, this commit was AI assisted.

* fix(ai): detect Pi prompt rejections and process crashes

- Use sendAndWait for prompt command so RPC-level rejections (expired
  credentials, invalid session) surface as errors instead of hanging
- Emit process_exited instead of synthetic agent_end when Pi subprocess
  dies, so crashes show as errors instead of silent empty successes

For provenance purposes, this commit was AI assisted.

* docs(ai): add Pi to AI features guide, code review docs, and installation

For provenance purposes, this commit was AI assisted.

* style(ai): apply biome formatting to new files

For provenance purposes, this commit was AI assisted.
2026-03-23 15:50:30 -07:00
Michael Ramos 4b097197a0 feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat

Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.

- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
  per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers

For provenance purposes, this commit was AI assisted.

* fix(ai): address code review findings from PR #363

- Concurrent query race: reject with session_busy error instead of
  racing; add query generation counter so stale finally blocks don't
  clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
  and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
  returns { id, provider } so capabilities endpoint sends the correct
  key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
  of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
  CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
  baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
  (type "user"), not a "tool_result" type

For provenance purposes, this commit was AI assisted.

* feat(ai): inline AI chat on code review diffs

Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.

- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover

For provenance purposes, this commit was AI assisted.

* fix(ai): toolbar popover ergonomics and visual consistency

- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
  in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover

For provenance purposes, this commit was AI assisted.

* fix(ai): visual consistency, shared primitives, markdown rendering

Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind

Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash

Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button

Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes

For provenance purposes, this commit was AI assisted.

* feat(ai): permission inheritance + inline approval UI

The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.

For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.

Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions

Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation

For provenance purposes, this commit was AI assisted.

* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking

Streaming fixes:
- State updates now create new object references via prev.map()
  instead of mutating objects inside the array — fixes React not
  re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
  streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
  all turns on tools)

Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
  files and never got to write its answer)

Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
  through to handleViewAIResponse, triggering the file group flash
  highlight in the sidebar (same behavior as clicking inline markers)

Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser

For provenance purposes, this commit was AI assisted.

* refactor(ai): simplification pass — types, perf, cleanup

From the three-agent code review analysis:

Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
  with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]

Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
  (prevents querySelectorAll on every streaming token)

Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts

Net: -2 lines. No behavior changes.

For provenance purposes, this commit was AI assisted.

* chore: biome lint fixes — import types, button a11y, unused import

- Use `import type` where only types are consumed (endpoints, CountBadge,
  CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs

For provenance purposes, this commit was AI assisted.

* feat(ai): Codex SDK provider + multi-provider backend

- Add CodexSDKProvider implementing AIProvider interface
  - Maps Codex ThreadEvents to AIMessage types
  - Delta tracking for streaming text from cumulative item.updated events
  - Supports resume, abort, sandbox modes
  - Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)

For provenance purposes, this commit was AI assisted.

* feat(ai): provider settings UI + inline config bar

- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation

For provenance purposes, this commit was AI assisted.

* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep

- Add missing selectedReasoningEffort + onReasoningEffortChange props to
  populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
  working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
  a broken provider

For provenance purposes, this commit was AI assisted.

* fix(ai): polish config bar, input, and sidebar header

- Replace native <select> dropdowns with custom popover menus that show
  provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions

For provenance purposes, this commit was AI assisted.

* fix(ai): honest fork capability + permissionMode doc accuracy

- Endpoint now checks capabilities.fork before calling forkSession(),
  falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
  (was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"

For provenance purposes, this commit was AI assisted.

* fix(review): move search result count inside input field

Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.

For provenance purposes, this commit was AI assisted.

* fix(ai): use claude_code preset, pass selected code to queries

- Claude provider now uses { preset: "claude_code", append } instead of
  a raw system prompt, so inline chat inherits Claude Code's full
  built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
  emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
  sends it with the query, fixing hallucinations on large PRs where the
  file's diff was truncated out of the system prompt

For provenance purposes, this commit was AI assisted.

* fix(ai): bundle both SDKs, remove peer dependencies

Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.

Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.

For provenance purposes, this commit was AI assisted.

* refactor: canonical platform.ts, file renames, file-level comments

- Created packages/ui/utils/platform.ts as the single source for
  isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId

For provenance purposes, this commit was AI assisted.

* docs(ai): add AI features guide + link from settings

New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.

AISettingsTab now links to the docs in both empty and populated states.

For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
Michael Ramos 40002e69dc feat: GitLab merge request review support (#364)
* feat: GitLab merge request review support

Add full GitLab MR review parity with existing GitHub PR review:

- Auto-detect platform from URL (github.com vs any GitLab host)
- Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation
- Widen PRRef/PRMetadata to discriminated unions for type safety
- Dispatch functions route to correct platform implementation
- Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons)
- Self-hosted GitLab support via --hostname flag
- Normalize glab diff output to standard git format
- Handle glab CLI differences (no --jq, Content-Type header for --input)
- Defensive JSON parsing for GitLab context API responses

Tested against gitlab.com with inline comments, multi-line ranges,
approval, and PR context tabs (summary, comments, checks).

For provenance purposes, this commit was AI assisted.

* fix: correct GitLab enum mappings and add shared file path encoding

- Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL)
- Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN
- Fix false approval state on repos without required approvers
- Add shared encodeApiFilePath helper used by both GitHub and GitLab

For provenance purposes, this commit was AI assisted.

* fix: align panel headers and refine file tree selection style

- Use shared --panel-header-h CSS variable for consistent header heights
  across file tree search, file header, and annotations panel
- Update GitLab icon to use official tanuki SVG paths with currentColor
- Replace solid primary fill on active file tree items with 30% tinted
  background for better readability and semantic color preservation

For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
Rock Neurotiko c352465254 feat: Approve and review PR to github (#352)
* Approve and review PR to github

* fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling

- Add start_line/start_side to review payload for multi-line annotations
- Detect current GitHub user and disable Approve on own PRs with tooltip
- Fix loading state: approve button no longer shows "Approving..." during feedback
- Fix empty submit: block Post Comments when no annotations and no comment
- Fix Cmd+Enter in GitHub comment dialog
- Fix completion screen text for GitHub mode ("submitted to GitHub")
- Fix agent label fallback to "Your agent" instead of "OpenCode"
- Improve gh-not-installed error message with install URL
- Fix stale useCallback dependency array on handleGitHubAction

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

* feat(review): destination dropdown, icon components, and UI polish

Replace Agent/GitHub toggle with a compact destination dropdown.
Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve")
with behavior routed by destination. Double-tap Option to toggle.

- Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor)
- Add repo/PR icons to editor header
- Add keyboard hint in destination dropdown
- Add double-Option shortcut to settings
- Hide duplicate filename from Pierre diff header
- Refine FileHeader typography (text-xs font-semibold, no mono)

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

* fix: include VS Code editor annotations in GitHub PR reviews

Editor annotations were silently dropped when submitting to GitHub.
Now converts them to inline PR comments with selected text as context.

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

* fix: rename visibility, own-PR keyboard guard, and editor annotation filtering

- Keep data-prev-name visible in Pierre header for rename diffs
- Block Cmd+Enter approve path for own PRs (was only blocked via mouse)
- Filter editor annotations to diff files only to prevent GitHub API rejection

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

---------

Co-authored-by: Michael Ramos <mdramos8@gmail.com>
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-20 16:48:26 -07:00
Michael Ramos 1821943d06 feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs

When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.

Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.

Closes #348

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

* fix(review): reset fetch guard on error and detect inline HTML in PR bodies

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-19 23:14:21 -07:00
Michael Ramos 216815c12e feat: PR review support via GitHub URL (#324)
* feat(review): add runtime-agnostic PR provider

Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface
(same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR
operations: URL parsing, auth check, diff/metadata fetching, and file
content retrieval via `gh` CLI.

`packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime,
matching the git.ts pattern.

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

* feat(review): add PR mode to review server

When `prMetadata` is provided to `startReviewServer`, the server enters
PR mode: `/api/diff` includes PR metadata and omits gitContext,
`/api/diff/switch` and `/api/git-add` return 400 (not applicable),
and `/api/file-content` fetches from GitHub API using base/head SHAs
instead of local git.

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

* feat(review): PR review flow for Claude Code and OpenCode

Detects URL argument in `/plannotator-review` command. When a GitHub PR
URL is provided, fetches diff and metadata via `gh` CLI and starts the
review server in PR mode. Local review mode is unchanged when no URL
is passed.

Updates slash command definitions to pass $ARGUMENTS through.

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

* feat(review): PR metadata display in review UI

Shows "PR Review" badge, PR title with link, and owner/repo in the
header when reviewing a pull request. Diff switcher and staging
controls auto-hide since gitContext is omitted in PR mode.

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

* feat(review): contextualized PR feedback for agent

In PR mode, the feedback markdown now includes PR metadata (repo,
number, title, branches, URL) so the agent has full context about
the remote PR being reviewed. Removes the aggressive "address all
of them" instruction in PR mode since the content is self-explanatory.

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

* refactor(review): extract exportReviewFeedback + add tests

Moves the pure feedback construction function from App.tsx to
utils/exportFeedback.ts so it can be unit tested. Drops the unused
`files` parameter. 11 tests covering local/PR headers, annotation
grouping, sorting, file-scope ordering, and suggested code rendering.

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

* test(review): strengthen PR/local boundary tests

Replaces shallow header checks with comprehensive boundary assertions:
local mode must never contain PR-specific content (repo, URL, branches),
PR mode must include all context fields and exclude the generic header.
Covers null/undefined prMetadata edge cases.

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

* test(review): remove redundant empty-annotations test

Covered by the "no annotations: returns generic empty regardless of
prMetadata" test which checks all three cases (no arg, null, PR mode).

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

* fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps

- Wrap fetchPR() in try/catch in both hook and OpenCode entry points
  so network/auth errors show a clean message instead of a stack trace
- Replace atob() with Buffer.from() for UTF-8 correct base64 decoding
  of PR file content from GitHub API
- Fix stale useCallback deps in handleCopyFeedback (files → prMetadata)

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

* fix(install): add $ARGUMENTS to review command for PR URL support

Install scripts were writing the review slash command without
$ARGUMENTS, so PR URLs passed to /plannotator-review were silently
dropped. Also switches PS1 heredoc to single-quoted to prevent
$ARGUMENTS from being expanded as a PowerShell variable.

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

* docs: add PR review support to docs and READMEs

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

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
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
dgrissen2 01d807787b feat: add favicon (Purple P + gold highlight) (#312)
* feat: add favicon (option 2 — purple P with gold highlight)

Adds the "Purple P + Highlight" favicon across all three Plannotator
servers (plan, review, annotate). The icon is a rounded purple square
with a bold white "P" and a semi-transparent gold stripe through the
middle — typographic, on-brand, and legible at 16px.

Implementation:
- shared-handlers.ts: handleFavicon() serves the inline SVG with a
  1-day cache header, shared by all servers
- index.ts, review.ts, annotate.ts: /favicon.svg route added before
  the SPA catch-all
- apps/hook/index.html, apps/review/index.html: <link rel="icon">
  added pointing to /favicon.svg

SVG favicons are the modern standard and render crisply at all sizes
without a separate .ico file.

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

* feat: add favicon to marketing site

Use the same purple P + gold highlight SVG favicon on plannotator.ai.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: Michael Ramos <mdramos8@gmail.com>
2026-03-16 07:45:00 -07:00
Michael Ramos 54e951e2f7 fix: don't ask agent to address feedback on LGTM approval (#293)
* fix: don't ask agent to address feedback on LGTM approval (#284)

When the reviewer approves with no annotations, send a neutral
"Code review completed — no changes requested." message instead of
the contradictory "LGTM" + "Please address this feedback."

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

* fix: use explicit approved flag instead of annotations.length heuristic

The previous fix inferred LGTM from an empty annotations array, but
VS Code editor annotations are carried in feedbackMarkdown without
populating the annotations array — causing real review comments to be
misclassified as approvals. Thread an explicit `approved` boolean from
the UI through the review server to all three integrations.

Closes #284

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

* fix: append assertive instruction to review feedback output

When the reviewer submits actual feedback, append "The reviewer has
identified issues above. You must address all of them." so the agent
treats annotations with urgency rather than soft-acknowledging them.

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

* chore: annotate unused LGTM feedback string

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-14 17:58:57 -07:00
Michael Ramos b6bec6943b feat: add Pi origin support to code review UI (#263)
* feat: add Pi origin support to code review UI and update banner

Pi users were seeing "OpenCode" badge and getting the wrong update
command. Adds 'pi' to origin types in review/annotate servers, shows
violet "Pi" badge in code review header, and copies the correct
`pi install` command in the update banner.

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

* feat: update Pi extension from install scripts when pi is available

The install scripts now check if `pi` is on PATH and run
`pi install npm:@plannotator/pi-extension` to update the extension.
Silent for users without Pi installed.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-09 23:41:29 -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 cb4de46636 feat: VS Code editor annotations + theme integration (#239)
* feat: add shared EditorAnnotation type

Single source of truth for the editor annotation interface,
imported by both @plannotator/server and @plannotator/ui.

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

* feat: editor annotation server endpoints

In-memory store with POST/GET/DELETE endpoints for editor annotations.
The array lives in the handler closure and dies with the server session.

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

* feat: editor annotation UI — polling hook, card, panel, and export

- useEditorAnnotations hook with auto-disable polling (500ms interval)
- EditorAnnotationCard with file path, code preview, and comment
- AnnotationPanel conditionally renders editor annotation section
- exportEditorAnnotations formats annotations for Claude feedback
- App.tsx wires hook, includes in output memo and send feedback gate

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

* feat: VS Code extension editor annotation command

Cmd+Shift+. or right-click to capture selected text as an annotation.
POSTs through the cookie proxy to the plannotator server. Adds amber
left-border decorations on annotated lines, cleared on panel close.

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

* feat: inline comment threads, lightbulb menu, and stronger decorations

Replace showInputBox with VS Code CommentController for inline annotation
threads anchored to selected code. Add CodeActionProvider for lightbulb
discoverability. Stronger decoration styling with gutter icon.

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

* feat: VS Code theme integration for webview

Bridge VS Code CSS variables to Plannotator's CSS variable system via
postMessage between wrapper page and proxied iframe. Automatically adopts
the active VS Code color theme (dark/light/custom) without touching any
UI components or CSS files.

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

* fix: gate editor annotation polling behind VS Code detection

Only poll /api/editor-annotations when running inside a VS Code webview
(window.__PLANNOTATOR_VSCODE). Browser and shared URL users now have
zero network cost from the editor annotations feature. Also fixes poll
interval from 500ms to 2000ms.

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

* fix: faster polling, prevent unnecessary re-renders, unify HTTP helper

- Poll interval 2s → 500ms for snappier annotation pickup
- Shallow equality check on annotation IDs prevents React re-renders
  when poll data is unchanged
- Merge postToProxy/deleteFromProxy into single requestProxy function

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

* feat: editor annotations support in code review

Wire existing editor annotation infrastructure into the review flow
so VS Code users can annotate files outside the diff during code review.

- Add editor annotation endpoints to review server (same 3-line pattern)
- Call useEditorAnnotations hook in review App.tsx
- Display editor annotations in ReviewPanel with "Editor" divider
- Include editor annotations in feedback export and gating logic

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-07 12:25:02 -08:00
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
Michael Ramos aa71ede0f3 Auto-save annotation drafts to survive server crashes (#217)
* feat: auto-save annotation drafts to survive server crashes

Adds server-side draft persistence so annotations are not lost when the
server process dies. Drafts are saved to ~/.plannotator/drafts/ keyed by
a SHA-256 content hash, debounced at 500ms. On reload, a dialog prompts
the user to restore or dismiss. Drafts are auto-deleted on approve/deny/feedback.

Closes #212

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

* fix: remove duplicate imports and update CLAUDE.md for draft feature

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

* fix: wrap handleRestoreDraft in useCallback and update shared-handlers comment

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-04 10:12:58 -08:00
Michael Ramos d9c2d46113 refactor: extract shared route handlers and modularize plan server (#214)
* refactor: extract shared route handlers and modularize plan server

Pull duplicated /api/image, /api/upload, /api/agents handlers and
handleServerReady into shared-handlers.ts. Move /api/doc and Obsidian
reference endpoints into reference-handlers.ts. Eliminates ~120 lines
of verbatim duplication across index.ts, review.ts, and annotate.ts.

Closes #210

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

* fix: deduplicate OpencodeClient type and fix stale module comment

Export OpencodeClient interface from shared-handlers.ts and import it
in index.ts and review.ts instead of redefining inline. Also corrects
the module doc comment about /api/agents usage scope.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-03 23:17:16 -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
Dor Tzur b2fc5ab849 fix(server): prevent arbitrary file read via /api/image endpoint (#164)
The /api/image endpoint serves files from the local filesystem based on
a user-provided path parameter with no validation. This allows any
process on localhost to read arbitrary files (e.g., /etc/passwd,
~/.ssh/id_rsa) by requesting /api/image?path=<any-path>.

This commit adds:
- Path validation requiring image file extensions (png, jpg, gif, etc.)
- Path resolution via path.resolve() to normalize traversal sequences
- Upload extension validation against the same image allowlist
- Shared image.ts module used by all three servers (plan, review, annotate)
[agent]
2026-02-18 09:50:32 -08:00
Michael Ramos e46815d8ea feat: named image references and annotate command (#147)
* feat: named image references and annotate command (#67, #109)

Add human-readable names to image attachments throughout the annotation
pipeline, and add a new `plannotator annotate <file.md>` command for
annotating arbitrary markdown files.

Image names: ImageAttachment type replaces plain string paths, upload
endpoints return originalName, editable name inputs under thumbnails,
[name] path format in exported feedback, backward-compatible sharing.

Annotate command: new server module reusing plan editor HTML with
mode:"annotate", CLI subcommand, slash commands for Claude Code and
OpenCode, annotate mode UI (hides Approve, shows Send Annotations).

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

* refactor: move image name input to ImageAnnotator screen

The name input now appears on the full-screen annotator modal that opens
immediately when uploading/pasting an image, pre-populated from the
filename. Removes the disruptive inline name editing from thumbnails.

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

* fix: stale closure in paste handler, update CLAUDE.md for new features

Fix race condition where globalAttachments was captured as empty array
in the paste event listener (missing dependency). Also update CLAUDE.md
to document ImageAttachment type, annotate server/flow, updated sharing
format with image support, and new slash commands.

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

---------

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00