Files
backnotprop__plannotator/AGENTS.md
T

470 lines
24 KiB
Markdown
Raw Normal View History

# Plannotator
A plan review UI for Claude Code that intercepts `ExitPlanMode` via hooks, letting users approve or request changes with annotated feedback. Also provides code review for git diffs and annotation of arbitrary markdown files.
## Project Structure
```
plannotator/
├── apps/
│ ├── hook/ # Claude Code plugin
│ │ ├── .claude-plugin/plugin.json
│ │ ├── commands/ # Slash commands (plannotator-review.md, plannotator-annotate.md)
│ │ ├── hooks/hooks.json # PermissionRequest hook config
│ │ ├── server/index.ts # Entry point (plan + review + annotate + archive subcommands)
│ │ └── dist/ # Built single-file apps (index.html, review.html)
│ ├── opencode-plugin/ # OpenCode plugin
│ │ ├── commands/ # Slash commands (plannotator-review.md, plannotator-annotate.md)
│ │ ├── index.ts # Plugin entry with submit_plan tool + review/annotate event handlers
│ │ ├── plannotator.html # Built plan review app
│ │ └── review-editor.html # Built code review app
│ ├── marketing/ # Marketing site, docs, and blog (plannotator.ai)
│ │ └── astro.config.mjs # Astro 5 static site with content collections
│ ├── paste-service/ # Paste service for short URL sharing
│ │ ├── core/ # Platform-agnostic logic (handler, storage interface, cors)
│ │ ├── stores/ # Storage backends (fs, kv, s3)
│ │ └── targets/ # Deployment entries (bun.ts, cloudflare.ts)
│ ├── review/ # Standalone review server (for development)
│ │ ├── index.html
│ │ ├── index.tsx
│ │ └── vite.config.ts
│ └── vscode-extension/ # VS Code extension — opens plans in editor tabs
│ ├── bin/ # Router scripts (open-in-vscode, xdg-open)
│ ├── src/ # extension.ts, cookie-proxy.ts, ipc-server.ts, panel-manager.ts, editor-annotations.ts, vscode-theme.ts
│ └── package.json # Extension manifest (publisher: backnotprop)
├── packages/
│ ├── server/ # Shared server implementation
│ │ ├── index.ts # startPlannotatorServer(), handleServerReady()
│ │ ├── review.ts # startReviewServer(), handleReviewServerReady()
│ │ ├── annotate.ts # startAnnotateServer(), handleAnnotateServerReady()
│ │ ├── storage.ts # Re-exports from @plannotator/shared/storage
│ │ ├── share-url.ts # Server-side share URL generation for remote sessions
│ │ ├── remote.ts # isRemoteSession(), getServerPort()
│ │ ├── browser.ts # openBrowser()
│ │ ├── draft.ts # Re-exports from @plannotator/shared/draft
│ │ ├── integrations.ts # Obsidian, Bear integrations
│ │ ├── ide.ts # VS Code diff integration (openEditorDiff)
│ │ ├── editor-annotations.ts # VS Code editor annotation endpoints
│ │ └── project.ts # Project name detection for tags
│ ├── ui/ # Shared React components + theme
│ │ ├── theme.css # Single source of truth for color tokens + Tailwind bridge
│ │ ├── components/ # Viewer, Toolbar, Settings, etc.
feat(plan): unified header dropdown + Agent Instructions (#515) * feat(plan): unify header settings into combined dropdown Replace the desktop sprawl (ModeToggle, Settings button, Export sub-dropdown) and the separate MobileMenu with a single PlanHeaderMenu modeled on ReviewHeaderMenu — one ActionMenu rendered at all breakpoints. Move version + release notes into the dropdown footer, drop the origin/agent badge, and stub an "Agent Instructions" item that copies the current plan plus an /api/external-annotations URL for external agents (real protocol body lands in a follow-up). Also fix the annotate-folder Send button: it was hidden whenever a file was opened via linkedDoc, so users in `plannotator annotate ./` couldn't submit feedback. Gate now allows linked-doc state through in annotate mode. Settings is always mounted instead of skipping when a linked doc is active, so the dropdown's Settings item works in every state. For provenance purposes, this commit was AI assisted. * feat(plan): real Agent Instructions clipboard payload Replace the placeholder string in handleCopyAgentInstructions with a real, contract-accurate markdown payload that teaches an external agent (Claude Code, Codex, custom scripts) how to: - read the current plan via GET /api/plan - POST single or batch annotations to /api/external-annotations - choose COMMENT vs DELETION vs GLOBAL_COMMENT and use originalText for inline highlighting (or skip it for sidebar-only) - list, delete-by-id, and delete-by-source for cleanup before reposting The payload lives in packages/ui/utils/planAgentInstructions.ts as buildPlanAgentInstructions(origin) — a single pure function that takes the base URL and returns the markdown. Plan and code-review modes have different annotation shapes, so each owns its own instructions module; the review counterpart will live alongside this file when it's added. For provenance purposes, this commit was AI assisted. * docs: list planAgentInstructions.ts in AGENTS.md utils enumeration For provenance purposes, this commit was AI assisted. * fix(plan): restore 'system' theme option in header dropdown The unified header dropdown only exposed light/dark, dropping the 'system' (follow OS) option that the previous ModeToggle and MobileMenu both supported. Clicking either explicit mode would silently overwrite a prior 'system' setting. Add it back as a third segmented control, matching the old MobileMenu's three-way layout. For provenance purposes, this commit was AI assisted. * refactor(ui): extract shared theme-mode icons PlanHeaderMenu and ThemeTab each inlined their own Sun/Moon/System SVGs (and the deleted MobileMenu had its own copy too). Pull them into a shared icons/themeIcons.tsx module so the iconography stays consistent across the dropdown and the settings tab. Use the cleaner Heroicons paths from ThemeTab as the canonical art. ReviewHeaderMenu still inlines its own copies — left alone for this PR since the broader review/plan menu unification is a separate follow-up. For provenance purposes, this commit was AI assisted. * fix(plan): use ReviewAgentsIcon for Agent Instructions menu item Reuse the magnifying-glass-with-cog icon already used for the Review Agents tab so the same visual marker identifies agent-related affordances across plan and review modes. For provenance purposes, this commit was AI assisted. * fix(plan): drop DELETION + unanchored COMMENT from agent instructions Plannotator's existing render and export pipeline only handles two shapes well: an anchored COMMENT with originalText, and a GLOBAL_COMMENT with no anchor. The previous instructions also documented: - COMMENT without originalText — sidebar shows an empty quote bubble ("") and the export header reads `Feedback on: ""`. The text survives but the framing is broken. - DELETION with explanatory text — the text is invisible in the sidebar and silently dropped on export, replaced by a generic template. Real information loss. Rather than expand the export pipeline to honor those edge cases, narrow the documented surface to the two shapes that work today: inline COMMENT (requires originalText) and GLOBAL_COMMENT (no anchor). DELETION is omitted entirely; agents that need to suggest a removal can post an inline COMMENT pointing at the phrase. For provenance purposes, this commit was AI assisted. * fix(plan): clear current new-settings hints, surface pulse on menu trigger The new-settings indicator infrastructure (hasNewSettings / version constant / markNewSettingsSeen) stays — it's the scaffolding for future hint flagging — but every current marker is removed: - Drop the four inline 'new' badges in Settings.tsx (Plan Width row, Quick Labels row, mobile + desktop tab navigators). - Drop the dead pulse on the standalone gear button — that button now lives inside <div className="hidden"> after the header refactor, so the pulse was unreachable anyway. Surface the pulse on the new PlanHeaderMenu trigger instead. App.tsx seeds local hasNewSettingsHints state from hasNewSettings(), passes it to the menu, and clears it (plus calls markNewSettingsSeen) when the user opens Settings from the dropdown. For provenance purposes, this commit was AI assisted. * docs: list icons/ subdirectory in AGENTS.md components tree For provenance purposes, this commit was AI assisted. * fix(server): require originalText for plan COMMENT annotations The plan-mode external-annotation contract documents that COMMENT annotations must carry an originalText anchor; sidebar-only feedback uses GLOBAL_COMMENT instead. transformPlanInput already enforced this for DELETION but silently defaulted COMMENT's originalText to "" when missing — producing a broken render (empty quote bubble in the sidebar, exported as `Feedback on: ""`). Reject COMMENT without a non-empty originalText and steer the caller toward GLOBAL_COMMENT in the error message so the fix is self-evident to misbehaving agents. For provenance purposes, this commit was AI assisted. * chore: drop dead new-hints scaffolding leftovers After clearing the four current inline hint markers, two pieces of support code were unreachable: - The destructured setShowNewHints setter in Settings.tsx — the state itself stays as a stable mount-time snapshot for any future hint markers, but the setter has no callers. Drop it and add a comment explaining why the useState wrapper is intentional scaffolding. - The settings-ping keyframe in editor/index.css — only the deleted gear-button pulse referenced it; the new pulse on PlanHeaderMenu's trigger uses Tailwind's built-in animate-ping instead. For provenance purposes, this commit was AI assisted.
2026-04-07 15:03:30 -07:00
│ │ │ ├── icons/ # Shared SVG icon components (themeIcons, etc.)
│ │ │ ├── plan-diff/ # PlanDiffBadge, PlanDiffViewer, clean/raw diff views
│ │ │ └── sidebar/ # SidebarContainer, SidebarTabs, VersionBrowser, ArchiveBrowser
feat(plan): unified header dropdown + Agent Instructions (#515) * feat(plan): unify header settings into combined dropdown Replace the desktop sprawl (ModeToggle, Settings button, Export sub-dropdown) and the separate MobileMenu with a single PlanHeaderMenu modeled on ReviewHeaderMenu — one ActionMenu rendered at all breakpoints. Move version + release notes into the dropdown footer, drop the origin/agent badge, and stub an "Agent Instructions" item that copies the current plan plus an /api/external-annotations URL for external agents (real protocol body lands in a follow-up). Also fix the annotate-folder Send button: it was hidden whenever a file was opened via linkedDoc, so users in `plannotator annotate ./` couldn't submit feedback. Gate now allows linked-doc state through in annotate mode. Settings is always mounted instead of skipping when a linked doc is active, so the dropdown's Settings item works in every state. For provenance purposes, this commit was AI assisted. * feat(plan): real Agent Instructions clipboard payload Replace the placeholder string in handleCopyAgentInstructions with a real, contract-accurate markdown payload that teaches an external agent (Claude Code, Codex, custom scripts) how to: - read the current plan via GET /api/plan - POST single or batch annotations to /api/external-annotations - choose COMMENT vs DELETION vs GLOBAL_COMMENT and use originalText for inline highlighting (or skip it for sidebar-only) - list, delete-by-id, and delete-by-source for cleanup before reposting The payload lives in packages/ui/utils/planAgentInstructions.ts as buildPlanAgentInstructions(origin) — a single pure function that takes the base URL and returns the markdown. Plan and code-review modes have different annotation shapes, so each owns its own instructions module; the review counterpart will live alongside this file when it's added. For provenance purposes, this commit was AI assisted. * docs: list planAgentInstructions.ts in AGENTS.md utils enumeration For provenance purposes, this commit was AI assisted. * fix(plan): restore 'system' theme option in header dropdown The unified header dropdown only exposed light/dark, dropping the 'system' (follow OS) option that the previous ModeToggle and MobileMenu both supported. Clicking either explicit mode would silently overwrite a prior 'system' setting. Add it back as a third segmented control, matching the old MobileMenu's three-way layout. For provenance purposes, this commit was AI assisted. * refactor(ui): extract shared theme-mode icons PlanHeaderMenu and ThemeTab each inlined their own Sun/Moon/System SVGs (and the deleted MobileMenu had its own copy too). Pull them into a shared icons/themeIcons.tsx module so the iconography stays consistent across the dropdown and the settings tab. Use the cleaner Heroicons paths from ThemeTab as the canonical art. ReviewHeaderMenu still inlines its own copies — left alone for this PR since the broader review/plan menu unification is a separate follow-up. For provenance purposes, this commit was AI assisted. * fix(plan): use ReviewAgentsIcon for Agent Instructions menu item Reuse the magnifying-glass-with-cog icon already used for the Review Agents tab so the same visual marker identifies agent-related affordances across plan and review modes. For provenance purposes, this commit was AI assisted. * fix(plan): drop DELETION + unanchored COMMENT from agent instructions Plannotator's existing render and export pipeline only handles two shapes well: an anchored COMMENT with originalText, and a GLOBAL_COMMENT with no anchor. The previous instructions also documented: - COMMENT without originalText — sidebar shows an empty quote bubble ("") and the export header reads `Feedback on: ""`. The text survives but the framing is broken. - DELETION with explanatory text — the text is invisible in the sidebar and silently dropped on export, replaced by a generic template. Real information loss. Rather than expand the export pipeline to honor those edge cases, narrow the documented surface to the two shapes that work today: inline COMMENT (requires originalText) and GLOBAL_COMMENT (no anchor). DELETION is omitted entirely; agents that need to suggest a removal can post an inline COMMENT pointing at the phrase. For provenance purposes, this commit was AI assisted. * fix(plan): clear current new-settings hints, surface pulse on menu trigger The new-settings indicator infrastructure (hasNewSettings / version constant / markNewSettingsSeen) stays — it's the scaffolding for future hint flagging — but every current marker is removed: - Drop the four inline 'new' badges in Settings.tsx (Plan Width row, Quick Labels row, mobile + desktop tab navigators). - Drop the dead pulse on the standalone gear button — that button now lives inside <div className="hidden"> after the header refactor, so the pulse was unreachable anyway. Surface the pulse on the new PlanHeaderMenu trigger instead. App.tsx seeds local hasNewSettingsHints state from hasNewSettings(), passes it to the menu, and clears it (plus calls markNewSettingsSeen) when the user opens Settings from the dropdown. For provenance purposes, this commit was AI assisted. * docs: list icons/ subdirectory in AGENTS.md components tree For provenance purposes, this commit was AI assisted. * fix(server): require originalText for plan COMMENT annotations The plan-mode external-annotation contract documents that COMMENT annotations must carry an originalText anchor; sidebar-only feedback uses GLOBAL_COMMENT instead. transformPlanInput already enforced this for DELETION but silently defaulted COMMENT's originalText to "" when missing — producing a broken render (empty quote bubble in the sidebar, exported as `Feedback on: ""`). Reject COMMENT without a non-empty originalText and steer the caller toward GLOBAL_COMMENT in the error message so the fix is self-evident to misbehaving agents. For provenance purposes, this commit was AI assisted. * chore: drop dead new-hints scaffolding leftovers After clearing the four current inline hint markers, two pieces of support code were unreachable: - The destructured setShowNewHints setter in Settings.tsx — the state itself stays as a stable mount-time snapshot for any future hint markers, but the setter has no callers. Drop it and add a comment explaining why the useState wrapper is intentional scaffolding. - The settings-ping keyframe in editor/index.css — only the deleted gear-button pulse referenced it; the new pulse on PlanHeaderMenu's trigger uses Tailwind's built-in animate-ping instead. For provenance purposes, this commit was AI assisted.
2026-04-07 15:03:30 -07:00
│ │ ├── utils/ # parser.ts, sharing.ts, storage.ts, planSave.ts, agentSwitch.ts, planDiffEngine.ts, planAgentInstructions.ts
│ │ ├── hooks/ # useAnnotationHighlighter.ts, useSharing.ts, usePlanDiff.ts, useSidebar.ts, useLinkedDoc.ts, useAnnotationDraft.ts, useCodeAnnotationDraft.ts, useArchive.ts
│ │ └── types.ts
│ ├── ai/ # Provider-agnostic AI backbone (providers, sessions, endpoints)
│ ├── shared/ # Shared types, utilities, and cross-runtime logic
│ │ ├── storage.ts # Plan saving, version history, archive listing (node:fs only)
│ │ ├── draft.ts # Annotation draft persistence (node:fs only)
│ │ └── project.ts # Pure string helpers (sanitizeTag, extractRepoName, extractDirName)
│ ├── editor/ # Plan review App.tsx
│ └── review-editor/ # Code review UI
│ ├── App.tsx # Main review app
│ ├── components/ # DiffViewer, FileTree, ReviewSidebar
│ ├── dock/ # Dockview center panel infrastructure
│ ├── demoData.ts # Demo diff for standalone mode
│ └── index.css # Review-specific styles
├── .claude-plugin/marketplace.json # For marketplace install
└── legacy/ # Old pre-monorepo code (reference only)
```
## Server Runtimes
There are two separate server implementations with the same API surface:
- **Bun server** (`packages/server/`) — used by both Claude Code (`apps/hook/`) and OpenCode (`apps/opencode-plugin/`). These plugins import directly from `@plannotator/server`.
- **Pi server** (`apps/pi-extension/server/`) — a standalone Node.js server for the Pi extension. It mirrors the Bun server's API but uses `node:http` primitives instead of Bun's `Request`/`Response` APIs.
When adding or modifying server endpoints, both implementations must be updated. Runtime-agnostic logic (store, validation, types) lives in `packages/shared/` and is imported by both.
## Installation
**Via plugin marketplace** (when repo is public):
```
/plugin marketplace add backnotprop/plannotator
```
**Local testing:**
```bash
claude --plugin-dir ./apps/hook
```
## Environment Variables
| Variable | Description |
|----------|-------------|
| `PLANNOTATOR_REMOTE` | Set to `1` / `true` for remote mode, `0` / `false` for local mode, or leave unset for SSH auto-detection. Uses a fixed port in remote mode; browser-opening behavior depends on the environment. |
| `PLANNOTATOR_PORT` | Fixed port to use. Default: random locally, `19432` for remote sessions. |
| `PLANNOTATOR_BROWSER` | Custom browser to open plans in. macOS: app name or path. Linux/Windows: executable path. |
| `PLANNOTATOR_SHARE` | Set to `disabled` to turn off URL sharing entirely. Default: enabled. |
| `PLANNOTATOR_SHARE_URL` | Custom base URL for share links (self-hosted portal). Default: `https://share.plannotator.ai`. |
| `PLANNOTATOR_PASTE_URL` | Base URL of the paste service API for short URL sharing. Default: `https://plannotator-paste.plannotator.workers.dev`. |
**Legacy:** `SSH_TTY` and `SSH_CONNECTION` are still detected when `PLANNOTATOR_REMOTE` is unset. Set `PLANNOTATOR_REMOTE=1` / `true` to force remote mode or `0` / `false` to force local mode.
**Devcontainer/SSH usage:**
```bash
export PLANNOTATOR_REMOTE=1
export PLANNOTATOR_PORT=9999
```
## Plan Review Flow
```
Claude calls ExitPlanMode
↓
PermissionRequest hook fires
↓
Bun server reads plan from stdin JSON (tool_input.plan)
↓
Server starts on random port, opens browser
↓
User reviews plan, optionally adds annotations
↓
Approve → stdout: {"hookSpecificOutput":{"decision":{"behavior":"allow"}}}
Deny → stdout: {"hookSpecificOutput":{"decision":{"behavior":"deny","message":"..."}}}
```
## Code Review Flow
```
User runs /plannotator-review command
↓
Claude Code: plannotator review subcommand runs
OpenCode: event handler intercepts command
↓
git diff captures unstaged changes
↓
Review server starts, opens browser with diff viewer
↓
User annotates code, provides feedback
↓
Send Feedback → feedback sent to agent session
Approve → "LGTM" sent to agent session
```
## Annotate Flow
```
User runs /plannotator-annotate <file.md> command
↓
Claude Code: plannotator annotate subcommand runs
OpenCode: event handler intercepts command
↓
Markdown file read from disk
↓
Annotate server starts (reuses plan editor HTML with mode:"annotate")
↓
User annotates markdown, provides feedback
↓
Send Annotations → feedback sent to agent session
```
## Archive Flow
```
User runs plannotator archive (CLI) or /plannotator-archive (Pi)
↓
Server starts in mode:"archive", reads ~/.plannotator/plans/
↓
Browser opens read-only archive viewer (sharing disabled)
↓
User browses saved plan decisions with approved/denied badges
↓
Done → POST /api/done closes the browser
```
During normal plan review, an Archive sidebar tab provides the same browsing via linked doc overlay without leaving the current session.
## Server API
### Plan Server (`packages/server/index.ts`)
| Endpoint | Method | Purpose |
| --------------------- | ------ | ------------------------------------------ |
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
| `/api/plan` | GET | Returns `{ plan, origin, previousPlan, versionInfo }` (plan mode) or `{ plan, origin, mode: "archive", archivePlans }` (archive mode) |
| `/api/plan/version` | GET | Fetch specific version (`?v=N`) |
| `/api/plan/versions` | GET | List all versions of current plan |
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
| `/api/archive/plans` | GET | List archived plan decisions (`?customPath=`) |
| `/api/archive/plan` | GET | Fetch archived plan content (`?filename=&customPath=`) |
| `/api/done` | POST | Close archive browser (archive mode only) |
| `/api/approve` | POST | Approve plan (body: planSave, agentSwitch, obsidian, bear, feedback) |
| `/api/deny` | POST | Deny plan (body: feedback, planSave) |
| `/api/image` | GET | Serve image by path query param |
| `/api/upload` | POST | Upload image, returns `{ path, originalName }` |
| `/api/obsidian/vaults`| GET | Detect available Obsidian vaults |
| `/api/reference/obsidian/files` | GET | List vault markdown files as nested tree (`?vaultPath=<path>`) |
| `/api/reference/obsidian/doc` | GET | Read a vault markdown file (`?vaultPath=<path>&path=<file>`) |
| `/api/plan/vscode-diff` | POST | Open diff in VS Code (body: baseVersion) |
| `/api/doc` | GET | Serve linked .md/.mdx file (`?path=<path>`) |
| `/api/draft` | GET/POST/DELETE | Auto-save annotation drafts to survive server crashes |
| `/api/editor-annotations` | GET | List editor annotations (VS Code only) |
| `/api/editor-annotation` | POST/DELETE | Add or remove an editor annotation (VS Code only) |
| `/api/external-annotations/stream` | GET | SSE stream for real-time external annotations |
| `/api/external-annotations` | GET | Snapshot of external annotations (polling fallback, `?since=N` for version gating) |
| `/api/external-annotations` | POST | Add external annotations (single or batch `{ annotations: [...] }`) |
| `/api/external-annotations` | PATCH | Update fields on a single annotation (`?id=`) |
| `/api/external-annotations` | DELETE | Remove by `?id=`, `?source=`, or clear all |
### Review Server (`packages/server/review.ts`)
| Endpoint | Method | Purpose |
| --------------------- | ------ | ------------------------------------------ |
| `/api/diff` | GET | Returns `{ rawPatch, gitRef, origin, diffType, gitContext }` |
| `/api/file-content` | GET | Returns `{ oldContent, newContent }` for expandable diff context |
| `/api/git-add` | POST | Stage/unstage a file (body: `{ filePath, undo? }`) |
| `/api/feedback` | POST | Submit review (body: feedback, annotations, agentSwitch) |
| `/api/image` | GET | Serve image by path query param |
| `/api/upload` | POST | Upload image, returns `{ path, originalName }` |
| `/api/draft` | GET/POST/DELETE | Auto-save annotation drafts to survive server crashes |
| `/api/editor-annotations` | GET | List editor annotations (VS Code only) |
| `/api/editor-annotation` | POST/DELETE | Add or remove an editor annotation (VS Code only) |
| `/api/ai/capabilities` | GET | Check if AI features are available |
| `/api/ai/session` | POST | Create or fork an AI session |
| `/api/ai/query` | POST | Send a message and stream the response (SSE) |
| `/api/ai/abort` | POST | Abort the current query |
| `/api/ai/permission` | POST | Respond to a permission request |
| `/api/ai/sessions` | GET | List active sessions |
| `/api/external-annotations/stream` | GET | SSE stream for real-time external annotations |
| `/api/external-annotations` | GET | Snapshot of external annotations (polling fallback, `?since=N` for version gating) |
| `/api/external-annotations` | POST | Add external annotations (single or batch `{ annotations: [...] }`) |
| `/api/external-annotations` | PATCH | Update fields on a single annotation (`?id=`) |
| `/api/external-annotations` | DELETE | Remove by `?id=`, `?source=`, or clear all |
feat(review): AI review agents, local worktree, and UI polish (#491) * feat(review): add Codex AI review agent with live logs, --local worktree, and panel UI Hook up Codex as the first AI review agent in the code review system: - Spawn `codex exec` with Codex's native review prompt and output schema - Parse structured findings (ReviewOutputEvent) and push as external annotations - Annotations appear inline in the diff viewer pinned to specific lines - Review verdict (correct/incorrect + confidence + explanation) displayed in panel Agent job infrastructure enhancements: - Server-side command building via `buildCommand` callback (providers don't need frontend commands) - Result ingestion via `onJobComplete` callback (reads output file, transforms findings) - `addAnnotations` method on external annotation handler (bypasses HTTP for server-internal producers) - Live stderr streaming via `job:log` SSE events with 200ms buffer-and-flush - `cwd` and `summary` fields on AgentJobInfo PR review with --local worktree: - `plannotator review <PR_URL> --local` creates a temp git worktree with the PR branch - Agent gets full local file access without touching the user's working tree - Hybrid server mode: both prMetadata (platform features) and gitContext (local access) - Automatic worktree cleanup on session end - Runtime-agnostic worktree primitives in packages/shared/worktree.ts Panel UI redesign: - Findings | Logs tab system with underline-style tabs - LiveLogViewer component with auto-scroll, truncation, and copy - Review verdict card (correct/incorrect with confidence and explanation) - Pending state with labeled "Review Verdict — Pending..." (not skeleton bars) - Job card click opens detail panel directly (removed separate icon button) - Dismissed annotation tracking (deleted annotations persist as "dismissed" in panel) - Copy all annotations as formatted markdown - Worktree badge in header with info dialog showing path - CopyButton extended with inline variant for reuse - ConfirmDialog extended with wide option For provenance purposes, this commit was AI assisted. * style(review): UX polish pass — visual quality improvements across code review UI - VerdictCard: remove AI-template left-border, use background-only tint - Inline annotations: 6px radius, subtle shadow, hover elevation, action button scale - File tree: tighter indentation (4 + depth*10), reduced container padding - Select dropdowns: normalized to 4px border-radius matching pierre diffs - Dockview tabs: close button pushed to far right with margin-left auto, visible at 0.25 opacity - PR icons moved from sidebar to header (next to PR link) - AnnotationRow: translate-x hover feedback - Border-radius normalized to `rounded` (4px) across all components - Type scale consolidated: text-[8px]/[9px] → text-[10px], text-[11px] → text-xs - Sidebar tab hit targets increased (px-2.5 py-1.5, w-4 icons) - Sticky file group headers in annotation sidebar - FileTree controls collapsed (worktree + diff selectors share one row) - Tab micro-animations (transition-all duration-150) - ScrollFade component for gradient indicators on scrollable containers - Prose containment: max-w-2xl + px-6 padding on PR Summary/Comments/Checks panels - MarkdownBody: leading-relaxed for comfortable reading - PR Comments: surface lift (bg-muted/10), hover feedback, author font-semibold - PR Checks: link affordance (text-primary, underline on hover, external link icon) For provenance purposes, this commit was AI assisted. * feat(review): PR comments panel — search, filter, collapse, navigation, and polish Comments panel enhancements: - Search: real-time text filter across author and body, match count display - Keyboard navigation: j/k to move between comments, scroll-to-selected - Sort: toggle between oldest/newest first - Collapsible comments: click header to collapse, collapse/expand all controls - Author exclusion filter: click authors to hide their comments (not inclusion) - Comment actions: hover-reveal "View on GitHub" link + copy button (bottom-right) - Review URLs: PRReview type now includes optional url field, populated from GitHub API PR Summary fixes: - Label contrast: use theme foreground color for label text instead of raw GitHub hex - Linked issues: replaced broken hardcoded SVG with proper GitHub Octicons issue-opened icon Data plumbing: - platformUser exposed through ReviewStateContext for "Mine" filtering - Panel wrapper changed to overflow-hidden for sticky toolbar support - "Commented" review badge hidden (noise — only show Approved/Changes Requested/Dismissed) For provenance purposes, this commit was AI assisted. * feat(review): inline review threads with outdated/resolved state and diff hunk previews PR Review Threads: - Fetch inline code review comments via GitHub GraphQL (reviewThreads query) - PRReviewThread and PRThreadComment types with isResolved, isOutdated, path, line, diffSide - ThreadCard component: file/line context, Outdated/Resolved badges, nested replies - Resolved/outdated threads: gradient fade on body with "Show full comment" expand - GitLab: reviewThreads placeholder (TODO: parse DiffNote positions from notes) DiffHunkPreview: - Renders diff hunks using @pierre/diffs FileDiff component (read-only, compact) - Full theme integration: reads computed CSS vars, injects via unsafeCSS (same as main DiffViewer) - Respects user font settings from ReviewState context - Handles bare GitHub diffHunk format (prepends synthetic file headers for pierre parsing) Comments Panel Polish: - Comment cards: bg-card + subtle shadow for depth and isolation from panel background - Hover: shadow elevation (0_2px_6px) for interactive feedback - Thread cards: dimmed shadow for resolved/outdated, full shadow for active - Prose padding: px-8 (32px) across all dockview panels (Summary, Comments, Checks, Findings) For provenance purposes, this commit was AI assisted. * feat(review): Claude Code agent, cross-repo --local, render fixes Claude Code review agent: - claude-review.ts: prompt (adapted from code-review plugin), command builder (dontAsk + granular allowedTools/disallowedTools), JSONL stream output parser - Prompt sent via stdin (not argv) to avoid quoting/variadic flag conflicts - stream-json --verbose for live JSONL streaming + final structured_output - Same schema as Codex — transformReviewFindings is now provider-agnostic Agent jobs infrastructure: - stdout capture (captureStdout option) for providers that return results on stdout - stdin prompt writing (stdinPrompt option) for providers that read prompt from stdin - cwd override in buildCommand return for providers without -C flag - await stdoutDone before onJobComplete to prevent drain race condition - job.prompt field for transparent prompt display in detail panel Cross-repo --local: - Detect same-repo vs cross-repo via parseRemoteUrl comparison - Cross-repo: shallow clone via gh/glab repo clone (--depth 1 --no-checkout + targeted fetch) - Cross-repo uses platform diff (gh pr diff) for display, clone for agent file access - Same-repo: existing worktree path unchanged - Cleanup: rmSync for clones, worktree remove for same-repo Performance: jobLogs context split - Separate JobLogsContext to prevent high-frequency log SSE from re-rendering all panels - Only ReviewAgentJobDetailPanel subscribes to JobLogsProvider - Standard React pattern: split contexts by update frequency Image error handling: - SafeHtmlBlock component wraps dangerouslySetInnerHTML with img onerror handlers - Broken images (expired GitHub JWTs) hide on first 404 instead of flickering - Prevents console 404 flood from re-render retry loops For provenance purposes, this commit was AI assisted. * fix(review): decontaminate --local from diff pipeline, fix worktree setup, default local for PRs The --local flag was setting gitContext from the worktree, which contaminated the diff rendering pipeline — causing pierre "trailing context mismatch" errors because /api/file-content read worktree files instead of using the GitHub API. Root cause: gitContext serves two purposes — diff pipeline (file contents, diff switching, staging) and agent sandbox (cwd for agent processes). These are now properly separated via a new agentCwd option on ReviewServerOptions. Changes: - Add agentCwd to ReviewServerOptions, independent of gitContext - Agent handler (getCwd, buildCommand, onJobComplete) prefers agentCwd - Stop setting gitContext in --local PR path — diff pipeline untouched - Revert band-aid !isPRMode guards (no longer needed) - Fix same-repo worktree: fetch origin/<baseBranch> so agents see correct diff - Fix cross-repo clone: create local branch at baseSha for git diff accuracy - Fix FETCH_HEAD ordering: fetch base branch before PR head (createWorktree needs PR tip) - Fix macOS path mismatch: realpathSync(tmpdir()) so agent paths strip correctly - Change buildCodexReviewUserMessage signature from GitContext to focused options - Make --local the default for PR/MR reviews (--no-local to opt out) - Pass agentCwd to client for worktree badge display For provenance purposes, this commit was AI assisted. * style(review): unify panel headers, responsive buttons, dockview polish - Unify all panel headers at 33px via --panel-header-h CSS variable - FileHeader now uses shared variable instead of hardcoded 30px - Dockview tab bar height, font size, and padding aligned with sidebars - FileTree header uses fixed height instead of padding-based sizing - Consistent border opacity (border-border/50) across all panels - Consistent font weight (font-semibold) on all header labels - Remove dockview tab focus outline (::after pseudo-element) - Dockview tab close button pushed to right edge - Tab bar void area uses muted background - Top app header compacted from h-12 to py-1 - Sidebar footer: copy button and diff stats side by side - FeedbackButton responsive labels (Send/Post at md, full labels at lg) - Move ReviewAgentsIcon to packages/ui for shared use - Agent empty state uses shared ReviewAgentsIcon instead of hardcoded SVG - Sidebar header label truncates when narrow (tabs never clip) - Detail panel prompt disclosures get proper spacing - React.memo on PR tab components (PRSummaryTab, PRCommentsTab) - Inline onerror on img tags for broken GitHub image handling For provenance purposes, this commit was AI assisted. * fix: type assertion for Bun stdin FileSink Bun's proc.stdin is typed as `number | FileSink` but we need to call .write() and .end() on it. Cast to FileSink to satisfy tsc --noEmit. For provenance purposes, this commit was AI assisted. * fix(review): XSS in sanitizeHtml, git flag injection, cross-repo ref mismatch Security: - Remove `onerror` from DOMPurify ALLOWED_ATTR — was allowing arbitrary JS execution via PR descriptions containing `<img onerror="...">`. Replace with SafeHtml component that attaches error handlers via useEffect + ref. - Add `--` end-of-options separator to git fetch and git branch calls to prevent flag injection via crafted branch names from API responses. Bug fix: - Cross-repo clones now create both local branch AND remote-tracking ref (`refs/remotes/origin/<baseBranch>`) at baseSha, so agents can use either `git diff main...HEAD` or `git diff origin/main...HEAD`. Polish: - Add copy button to verdict card in agent detail panel - Remove hover:translate-x animation from finding rows - Reduce file tree indent per level, remove extra file offset - Add pr-action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * chore: upgrade @pierre/diffs from 1.1.0-beta.19 to ^1.1.12 The beta pin was needed for processFile() API (expandable diff context), which shipped in 1.1.0 stable on March 14. We were 13 releases behind. Notable fixes in the upgrade path: - 1.1.5: Fix diffAcceptRejectHunk with partial FileDiffMetadata - 1.1.6: Patch parsing fix for renames and dotfiles - 1.1.8: Fix maxLineDiffLength regression May resolve intermittent "trailing context mismatch" errors in diff rendering. For provenance purposes, this commit was AI assisted. * fix(review): remove shell provider, flag injection, Claude log formatting, copy UX Security: - Remove shell provider from agent capabilities (unauthenticated RCE vector) - Move `--` before prRepo in `gh repo clone` to prevent flag injection Features: - Wire up formatClaudeLogEvent — Claude live logs now show readable text instead of raw JSONL - Sidebar annotations: copy + delete buttons appear on hover (no overlap) - Agent finding rows: copy button on hover (progressive disclosure) - Verdict card: copy button pushed to the right - File tree: reduced indent per level, files aligned with folders Infra: - PR action endpoint logging for debugging submit failures For provenance purposes, this commit was AI assisted. * fix: validate repo identifier to prevent flag injection in gh repo clone The `--` separator in `gh repo clone` separates gh args from git args, not positional args from flags. Using `--` before prRepo would break the git flags. Instead, validate that the repo identifier doesn't start with `-` to prevent flag injection via crafted PR URLs. For provenance purposes, this commit was AI assisted. * feat(review): Claude-specific review model with severity, reasoning, and multi-agent prompt Claude review agent now has its own schema, prompt, and transform — separate from Codex's P0-P3 priority model. Each provider uses its natural review style. Schema changes: - Claude findings use severity (important/nit/pre_existing) instead of priority (0-3) - Flat structure: file, line, end_line instead of nested code_location - description (single field) instead of title + body - reasoning field captures the validation chain per finding - summary with counts instead of overall_correctness/confidence Prompt: Converges the open-source Claude Code review prompt with the remote review service model. 4 parallel agents (Bug+Regression at Opus, Security at Opus, Code Quality at Sonnet, Guideline Compliance at Haiku), validation step, deduplication, severity classification. CLAUDE.md and REVIEW.md awareness. UI: Severity markers (colored dots) on finding rows. Collapsible reasoning section via <details>. New optional severity/reasoning fields on CodeAnnotation and the external annotation store — backward compatible, only set by Claude. Transform: transformClaudeFindings normalizes Claude output into the shared annotation format. Codex path (transformReviewFindings) is completely untouched. For provenance purposes, this commit was AI assisted. * fix: use bg-amber-500 for nit severity dot (bg-warning may not be defined) For provenance purposes, this commit was AI assisted. * fix: security hardening, debug cleanup, deduplication, Pi mirroring, findings UX Security: - Add -- separator to ensureObjectAvailable git fetch (worktree.ts) - Validate baseBranch against path traversal (..) before git ref operations - Use process.once('exit') instead of process.on for worktree cleanup Debug: - Gate debugLog behind PLANNOTATOR_DEBUG env var (no more unconditional writes) - Remove PARSE_OUTPUT_RAW dump that logged full JSON output to disk Deduplication: - Extract toRelativePath to packages/server/path-utils.ts (was duplicated in codex-review.ts and claude-review.ts) Pi extension: - Remove shell provider from capabilities - Add buildCommand callback to AgentJobHandlerOptions - POST handler calls buildCommand for server-side command synthesis UI: - Findings sorted by severity (important → nit → pre_existing) - Severity legend under findings header (colored dots) - Reasoning always visible (not collapsible) — fixes click navigation bug where <details> captured click events and broke annotation linkage - Full finding text shown (removed line-clamp-2 truncation) - Sidebar annotation hover actions aligned to the right - DiffHunkPreview: cancel requestAnimationFrame on unmount For provenance purposes, this commit was AI assisted. * fix: move toRelativePath import to top of claude-review.ts For provenance purposes, this commit was AI assisted. * fix: same-repo detection compares host, platform-aware comment links, remove design docs - Same-repo detection now compares both owner/repo AND hostname from the git remote URL against prMetadata.host. Prevents false positives on GitHub Enterprise where different instances share org/repo names. - "View on GitHub" label in PR comments tab now shows "View on GitLab" for GitLab MR comments based on the comment URL. - Remove internal design docs (PR_LOCAL_WORKTREE.md, AGENT_LIVE_LOGS.md) that were development artifacts, not user-facing documentation. For provenance purposes, this commit was AI assisted. * fix(review): show severity markers and reasoning in inline diff annotations The severity and reasoning fields from Claude findings were only visible in the agent detail panel, not in the inline diff annotations. Now: - DiffAnnotationMetadata carries severity and reasoning fields - DiffViewer passes them through when mapping annotations - InlineAnnotation renders colored severity dot and reasoning text For provenance purposes, this commit was AI assisted. * fix: prefix Claude findings text with [severity] tag Findings now show as "[important] description", "[nit] description", "[pre_existing] description" — consistent with Codex's [P0]/[P1] tags. For provenance purposes, this commit was AI assisted. * feat(pi): full agent review mirroring — stdin, stdout, live logs, result ingestion Pi extension agent-jobs handler now mirrors the Bun server's full capabilities: - stdin piping for Claude prompt delivery - stdout capture for Claude JSONL stream parsing - Live stderr streaming with 200ms buffer-and-flush for job:log events - Claude JSONL formatting via vendored formatClaudeLogEvent - onJobComplete callback for result parsing and annotation push - Full buildCommand integration in POST handler - jobOutputPaths tracking with cleanup on kill Pi serverReview.ts now wires buildCommand and onJobComplete with the same logic as the Bun review server — Codex and Claude commands are built server-side, results are parsed and transformed into external annotations. Runtime compatibility: replaced Bun.file/Bun.write in codex-review.ts with node:fs/promises equivalents (writeFile, readFile, existsSync) that work on both Bun and Node. Verified Bun build passes. Vendoring: vendor.sh now copies codex-review.ts, claude-review.ts, and path-utils.ts from packages/server/ with import path rewriting for the generated/ layout. Also: Review Prompt label, px-8 padding on agent detail header/tabs/logs. For provenance purposes, this commit was AI assisted. * fix: remove duplicate isPRMode declaration in Pi serverReview.ts For provenance purposes, this commit was AI assisted. * fix: include reasoning in all copy and feedback export paths - exportReviewFeedback: appends **Reasoning:** after finding text - Per-finding copy button: appends reasoning to copy text - Sidebar annotation copy: appends reasoning to copy text This ensures reasoning flows through Copy All, Send Feedback, and individual copy actions — not just the visual rendering. For provenance purposes, this commit was AI assisted. * fix: six verified findings — navigation, dedup, cleanup, copy, diff match, Windows paths 1. openDiffFile: clicking a finding now navigates to the correct file before selecting the annotation (was silently selecting in wrong file) 2. SEVERITY_STYLES: extracted to packages/ui/types.ts as shared constant, imported in both ReviewAgentJobDetailPanel and InlineAnnotation (was duplicated with per-render rebuild in InlineAnnotation) 3. killJob: added jobOutputPaths.delete calls to match Pi's version (was leaking two strings per killed job) 4. CommentActions: replaced hand-rolled copy with CopyButton inline variant (was reimplementing useState/clipboard/setTimeout pattern) 5. Branch mode prompt: changed from three-dot to two-dot to match the UI's actual diff computation (agent was reviewing different diff) 6. toRelativePath: uses path.relative + forward-slash normalization for Windows compatibility (was string prefix matching with / only) For provenance purposes, this commit was AI assisted. * perf: wrap ReviewSidebar in React.memo to prevent re-renders during log streaming Every job:log SSE event triggers setJobLogs in useAgentJobs, which re-renders App.tsx. Without memo, the sidebar re-renders on every event (~5/sec) even though its props (agentJobs.jobs, capabilities, callbacks) haven't changed. This caused visible flickering when a review tab was open during agent runs. React.memo shallow-compares props — all sidebar props are stable references (jobs array only changes on status events, callbacks are useCallback-wrapped), so the sidebar correctly skips re-renders during log streaming. For provenance purposes, this commit was AI assisted. * fix(security): remove find/ls/cat from Claude allowed tools, add glab CLI Security: Bash(find:*) allowed find -exec to spawn arbitrary subprocesses that bypassed --disallowedTools. Removed find, ls, and cat — Claude has Glob, Read, and Grep built-in which cover file access without shell exec. Feature: Added glab mr view/diff/list and glab api to allowed tools so Claude can inspect GitLab MR context in remote-mode reviews. For provenance purposes, this commit was AI assisted. * fix: Pi addAnnotations, Pi stdout drain, cross-repo exit codes Pi extension: - Add addAnnotations() to external-annotations.ts return object — serverReview.ts calls it when agent jobs complete but the method was missing (build/runtime error) - Change proc.on('exit') to proc.on('close') in agent-jobs.ts — Node's 'exit' fires before stdio streams drain, so stdoutBuf could be incomplete when onJobComplete parses Claude's JSONL result Cross-repo --local: - Check git checkout FETCH_HEAD exit code — throw if it fails so the outer catch falls back to remote-only with a clear warning - Log warning if baseSha fetch fails (non-fatal, agents just can't diff locally) For provenance purposes, this commit was AI assisted. * fix: FETCH_HEAD ordering, Pi worktree-aware cwd, SEVERITY_ORDER hoisted Critical: - Move ensureObjectAvailable before PR head fetch — it can overwrite FETCH_HEAD if baseSha needs fetching, causing createWorktree to check out the base commit instead of the PR head - Pi serverReview.ts: extract resolveAgentCwd() helper used by getCwd, buildCommand, and onJobComplete — was bypassing worktree-aware path resolution, causing agents to run in wrong directory Cleanup: - Hoist SEVERITY_ORDER to module scope in ReviewAgentJobDetailPanel (was recreated inside component body on every render) For provenance purposes, this commit was AI assisted. * fix: Bun/Pi parity — provider default, annotation error logging - Bun agent-jobs: change provider default from "shell" to "" (shell was removed from capabilities, default should match Pi) - Pi serverReview: log errors from addAnnotations in onJobComplete (Bun logs them, Pi was silently ignoring) For provenance purposes, this commit was AI assisted. * docs: add AI Code Review Agents guide with full prompt transparency New docs page covering: - Overview of Codex and Claude review agents - How findings work (severity/priority, reasoning, navigation) - Local worktree behavior (same-repo vs cross-repo) - Full transparency section with: - Claude multi-agent pipeline prompt (all 6 steps) - Claude command and allowed/blocked tools - Codex review prompt and command - Both output schemas (Claude severity + Codex priority) - Security notes (read-only, no network, local execution, no commenting) - Customization via CLAUDE.md and REVIEW.md For provenance purposes, this commit was AI assisted. * docs: add provenance links for Claude and Codex review integrations Credit Anthropic's Claude Code Review service, the open-source code-review plugin, and OpenAI's Codex CLI as the foundations for our review agent integrations. For provenance purposes, this commit was AI assisted. * fix: temp clone leak, j/k key conflict, thread header null line - Cross-repo: clean up localPath in catch block when fetch/checkout fails after clone succeeds (directory was leaking in /tmp) - Remove j/k/arrow keyboard navigation from PR comments panel — these shortcuts belong to the file tree only, both registering global handlers caused double-navigation - Thread header null guard: check thread.line before building range label to prevent "L12–null" for outdated GitHub threads For provenance purposes, this commit was AI assisted. * fix: hoist localPath for catch-block scope, validate baseSha format The previous rmSync(localPath) in the catch block was dead code — const declarations inside try are not in scope in catch (separate lexical environments per ECMAScript spec). The ReferenceError was silently swallowed by the inner try/catch, so temp directories still leaked on failed fetch/checkout. Fix: hoist `let localPath` before the try block so it's accessible in catch. Guard with `if (localPath)` since the error could occur before assignment. Also: validate baseSha is a hex SHA (40-64 chars) to prevent git flag injection via crafted API responses. Validate baseBranch rejects both '..' and '-' prefixes. For provenance purposes, this commit was AI assisted. * docs: rewrite AI Code Review guide for clarity and readability Restructured for a technical audience: shorter paragraphs, cleaner tables, removed em-dashes and filler prose, tightened the pipeline diagram, streamlined security section into scannable single-line items. For provenance purposes, this commit was AI assisted. * docs: rewrite transparency section with exact prompts and commands Replaced summarized/paraphrased transparency section with the actual prompts, commands, schemas, and tool allowlists as they exist in the code. One short security note at the top, then raw content. For provenance purposes, this commit was AI assisted. * docs: add mini TOC to transparency section For provenance purposes, this commit was AI assisted. * fix: stdout drain hang, Codex verdict override, Claude parse logging, memo removal Critical: - Race stdoutDone against 2s timeout after proc.exited — prevents permanent job hang when Bun's ReadableStream doesn't close after process exit. The process is dead; 2s is a cleanup deadline. Bug fix: - Codex verdict: override to "Issues Found" when P0/P1 findings exist, regardless of the freeform overall_correctness string. Prevents green "Correct" badge when Codex says "mostly correct but has issues." P2/P3-only findings still trust Codex's verdict. Observability: - Log Claude parse failures with buffer size and last 200 bytes so we can diagnose empty-findings cases. Performance: - Remove React.memo from ReviewSidebar — was blocking legitimate re-renders (job status, findings) to prevent cosmetic log flickering. The tradeoff was wrong. Docs: - Remove "shell" from CLAUDE.md capabilities table (provider was removed). For provenance purposes, this commit was AI assisted. * fix: type assertions for Bun ReadableStream async iteration Bun's proc.stdout/stderr support for-await at runtime but TypeScript's ReadableStream type doesn't declare [Symbol.asyncIterator]. Cast through unknown to AsyncIterable<Uint8Array> — standard Bun workaround, same pattern as the FileSink cast for stdin. For provenance purposes, this commit was AI assisted.
2026-04-06 12:15:27 -07:00
| `/api/agents/capabilities` | GET | Check available agent providers (claude, codex) |
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
| `/api/agents/jobs/stream` | GET | SSE stream for real-time agent job status updates |
| `/api/agents/jobs` | GET | Snapshot of agent jobs (polling fallback, `?since=N` for version gating) |
| `/api/agents/jobs` | POST | Launch an agent job (body: `{ provider, command, label }`) |
| `/api/agents/jobs` | DELETE | Kill all running agent jobs |
| `/api/agents/jobs/:id` | DELETE | Kill a specific agent job |
### Annotate Server (`packages/server/annotate.ts`)
| Endpoint | Method | Purpose |
| --------------------- | ------ | ------------------------------------------ |
| `/api/plan` | GET | Returns `{ plan, origin, mode: "annotate", filePath }` |
| `/api/feedback` | POST | Submit annotations (body: feedback, annotations) |
| `/api/image` | GET | Serve image by path query param |
| `/api/upload` | POST | Upload image, returns `{ path, originalName }` |
| `/api/draft` | GET/POST/DELETE | Auto-save annotation drafts to survive server crashes |
| `/api/external-annotations/stream` | GET | SSE stream for real-time external annotations |
| `/api/external-annotations` | GET | Snapshot of external annotations (polling fallback, `?since=N` for version gating) |
| `/api/external-annotations` | POST | Add external annotations (single or batch `{ annotations: [...] }`) |
| `/api/external-annotations` | PATCH | Update fields on a single annotation (`?id=`) |
| `/api/external-annotations` | DELETE | Remove by `?id=`, `?source=`, or clear all |
All servers use random ports locally or fixed port (`19432`) in remote mode.
### Paste Service (`apps/paste-service/`)
| Endpoint | Method | Purpose |
| --------------------- | ------ | ------------------------------------------ |
| `/api/paste` | POST | Store compressed plan data, returns `{ id }` |
| `/api/paste/:id` | GET | Retrieve stored compressed data |
Runs as a separate service on port `19433` (self-hosted) or as a Cloudflare Worker (hosted).
## Plan Version History
Every plan is automatically saved to `~/.plannotator/history/{project}/{slug}/` on arrival, before the user sees the UI. Versions are numbered sequentially (`001.md`, `002.md`, etc.). The slug is derived from the plan's first `# Heading` + today's date via `generateSlug()`, scoped by project name (git repo or cwd). Same heading on the same day = same slug = same plan being iterated on. Identical resubmissions are deduplicated (no new file if content matches the latest version).
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
This powers the version history API (`/api/plan/version`, `/api/plan/versions`) and the plan diff system.
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
History saves independently of the `planSave` user setting (which controls decision snapshots in `~/.plannotator/plans/`). Storage functions live in `packages/shared/storage.ts` (runtime-agnostic, re-exported by `packages/server/storage.ts`). Pi copies the shared files at build time. Slug format: `{sanitized-heading}-YYYY-MM-DD` (heading first for readability).
## Plan Diff
When a user denies a plan and Claude resubmits, the UI shows what changed between versions. A `+N/-M` badge appears below the document card; clicking it toggles between normal view and diff view.
**Diff engine** (`packages/ui/utils/planDiffEngine.ts`): Uses the `diff` npm package (`diffLines()`) to compute line-level diffs. Groups consecutive remove+add into "modified" blocks. Returns `PlanDiffBlock[]` and `PlanDiffStats`.
**Two view modes** (toggle via `PlanDiffModeSwitcher`):
- **Rendered** (`PlanCleanDiffView`): Color-coded left borders — green (added), red (removed/strikethrough), yellow (modified)
- **Raw** (`PlanRawDiffView`): Monospace `+/-` lines, git-style
**State** (`packages/ui/hooks/usePlanDiff.ts`): Manages base version selection, diff computation, and version fetching. The server sends `previousPlan` with the initial `/api/plan` response; the hook auto-diffs against it. Users can select any prior version from the sidebar Version Browser.
**Diff annotations:** The clean diff view supports block-level annotation — hover over added/removed/modified sections to annotate entire blocks. Annotations carry a `diffContext` field (`added`/`removed`/`modified`). Exported feedback includes `[In diff content]` labels.
**Annotation hook** (`packages/ui/hooks/useAnnotationHighlighter.ts`): Annotation infrastructure used by `Viewer.tsx`. Manages web-highlighter lifecycle, toolbar/popover state, annotation creation, text-based restoration, and scroll-to-selected. The diff view uses its own block-level hover system instead.
**Sidebar** (`packages/ui/hooks/useSidebar.ts`): Shared left sidebar with three tabs — Table of Contents, Version Browser, and Archive. The "Auto-open Sidebar" setting controls whether it opens on load (TOC tab only). In archive mode, the sidebar opens to the Archive tab automatically.
## Data Types
**Location:** `packages/ui/types.ts`
```typescript
enum AnnotationType {
DELETION = "DELETION",
COMMENT = "COMMENT",
GLOBAL_COMMENT = "GLOBAL_COMMENT",
}
interface ImageAttachment {
path: string; // temp file path
name: string; // human-readable label (e.g., "login-mockup")
}
interface Annotation {
id: string;
blockId: string;
startOffset: number;
endOffset: number;
type: AnnotationType;
text?: string; // For comment
originalText: string; // The selected text
createdA: number; // Timestamp
author?: string; // Tater identity
images?: ImageAttachment[]; // Attached images with names
source?: string; // External tool identifier (e.g., "eslint") — set when annotation comes from external API
diffContext?: 'added' | 'removed' | 'modified'; // Set when annotation created in plan diff view
startMeta?: { parentTagName; parentIndex; textOffset };
endMeta?: { parentTagName; parentIndex; textOffset };
}
interface Block {
id: string;
type: "paragraph" | "heading" | "blockquote" | "list-item" | "code" | "hr";
content: string;
level?: number; // For headings (1-6)
language?: string; // For code blocks
order: number;
startLine: number;
}
```
## Markdown Parser
**Location:** `packages/ui/utils/parser.ts`
`parseMarkdownToBlocks(markdown)` splits markdown into Block objects. Handles:
- Headings (`#`, `##`, etc.)
- Code blocks (``` with language extraction)
- List items (`-`, `*`, `1.`)
- Blockquotes (`>`)
- Horizontal rules (`---`)
- Paragraphs (default)
`exportAnnotations(blocks, annotations, globalAttachments)` generates human-readable feedback for Claude. Images are referenced by name: `[image-name] /tmp/path...`. Annotations with `diffContext` include `[In diff content]` labels.
## Annotation System
**Selection mode:** User selects text → toolbar appears → choose annotation type
**Redline mode:** User selects text → auto-creates DELETION annotation
Text highlighting uses `web-highlighter` library. Code blocks use manual `<mark>` wrapping (web-highlighter can't select inside `<pre>`).
## URL Sharing
**Location:** `packages/ui/utils/sharing.ts`, `packages/ui/hooks/useSharing.ts`
Shares full plan + annotations via URL hash using deflate compression. For large plans, short URLs are created via the paste service (user must explicitly confirm).
**Payload format:**
```typescript
// Image in shareable format: plain string (old) or [path, name] tuple (new)
type ShareableImage = string | [string, string];
interface SharePayload {
p: string; // Plan markdown
a: ShareableAnnotation[]; // Compact annotations
g?: ShareableImage[]; // Global attachments
d?: (string | null)[]; // diffContext per annotation, parallel to `a`
}
type ShareableAnnotation =
| ["D", string, string | null, ShareableImage[]?] // [type, original, author, images?]
| ["C", string, string, string | null, ShareableImage[]?] // [type, original, comment, author, images?]
| ["G", string, string | null, ShareableImage[]?]; // [type, comment, author, images?]
```
**Compression pipeline:**
1. `JSON.stringify(payload)`
2. `CompressionStream('deflate-raw')`
3. Base64 encode
4. URL-safe: replace `+/=` with `-_`
**On load from shared URL:**
1. Parse hash, decompress, restore annotations
2. Find text positions in rendered DOM via text search
3. Apply `<mark>` highlights
4. Clear hash from URL (prevents re-parse on refresh)
## Settings Persistence
**Location:** `packages/ui/utils/storage.ts`, `planSave.ts`, `agentSwitch.ts`
Uses cookies (not localStorage) because each hook invocation runs on a random port. Settings include identity, plan saving (enabled/custom path), and agent switching (OpenCode only).
## Syntax Highlighting
Code blocks use bundled `highlight.js`. Language is extracted from fence (```rust) and applied as `language-{lang}`class. Each block highlighted individually via`hljs.highlightElement()`.
## Requirements
- Bun runtime
- Claude Code with plugin/hooks support, or OpenCode
- Cross-platform: macOS (`open`), Linux (`xdg-open`), Windows (`start`)
## Development
```bash
bun install
# Run any app
bun run dev:hook # Hook server (plan review)
bun run dev:review # Review editor (code review)
bun run dev:portal # Portal editor
bun run dev:marketing # Marketing site
bun run dev:vscode # VS Code extension (watch mode)
```
## Build
```bash
bun run build:hook # Single-file HTML for hook server
bun run build:review # Code review editor
bun run build:opencode # OpenCode plugin (copies HTML from hook + review)
bun run build:portal # Static build for share.plannotator.ai
bun run build:marketing # Static build for plannotator.ai
bun run build:vscode # VS Code extension bundle
bun run package:vscode # Package .vsix for marketplace
bun run build # Build hook + opencode (main targets)
```
**Important: Build order matters.** The hook build (`build:hook`) copies pre-built HTML from `apps/review/dist/`. If you change UI code in `packages/ui/`, `packages/editor/`, or `packages/review-editor/`, you **must** rebuild the review app first, then the hook:
```bash
bun run --cwd apps/review build && bun run build:hook # For review UI changes
bun run build:hook # For plan UI changes only
bun run build:hook && bun run build:opencode # For OpenCode plugin
```
Running only `build:hook` after review-editor changes will copy stale HTML files. When testing locally with a compiled binary, the full sequence is:
```bash
bun run --cwd apps/review build && bun run build:hook && \
bun build apps/hook/server/index.ts --compile --outfile ~/.local/bin/plannotator
```
Running only `build:opencode` will copy stale HTML files.
## Marketing Site
`apps/marketing/` is the plannotator.ai website — landing page, documentation, and blog. Built with Astro 5 (static output, zero client JS except a theme toggle island). Docs are markdown files in `src/content/docs/`, blog posts in `src/content/blog/`, both using Astro content collections. Tailwind CSS v4 via `@tailwindcss/vite`. Deploys to S3/CloudFront via GitHub Actions on push to main.
## Test plugin locally
```
claude --plugin-dir ./apps/hook
```