2025-12-27 18:14:10 -08:00
|
|
|
{
|
2025-12-27 21:24:05 -08:00
|
|
|
"name": "plannotator",
|
2026-04-11 12:00:07 -07:00
|
|
|
"version": "0.17.9",
|
2025-12-27 18:14:10 -08:00
|
|
|
"private": true,
|
2025-12-28 13:17:15 -08:00
|
|
|
"description": "Interactive Plan Review for Claude Code - annotate plans visually, share with team, automatically send feedback",
|
|
|
|
|
"author": "backnotprop",
|
2026-02-12 09:55:14 -08:00
|
|
|
"license": "MIT OR Apache-2.0",
|
2025-12-28 13:17:15 -08:00
|
|
|
"repository": {
|
|
|
|
|
"type": "git",
|
|
|
|
|
"url": "git+https://github.com/backnotprop/plannotator.git"
|
|
|
|
|
},
|
|
|
|
|
"homepage": "https://github.com/backnotprop/plannotator",
|
|
|
|
|
"bugs": {
|
|
|
|
|
"url": "https://github.com/backnotprop/plannotator/issues"
|
|
|
|
|
},
|
2025-12-27 21:24:05 -08:00
|
|
|
"workspaces": ["apps/*", "packages/*"],
|
2025-12-27 18:14:10 -08:00
|
|
|
"scripts": {
|
2025-12-28 09:54:48 -08:00
|
|
|
"dev:hook": "bun run --cwd apps/hook dev",
|
2025-12-27 21:24:05 -08:00
|
|
|
"dev:portal": "bun run --cwd apps/portal dev",
|
|
|
|
|
"dev:marketing": "bun run --cwd apps/marketing dev",
|
2026-01-12 19:36:09 -08:00
|
|
|
"dev:review": "bun run --cwd apps/review dev",
|
2025-12-28 09:54:48 -08:00
|
|
|
"build:hook": "bun run --cwd apps/hook build",
|
2025-12-27 21:24:05 -08:00
|
|
|
"build:portal": "bun run --cwd apps/portal build",
|
2025-12-30 21:25:46 -08:00
|
|
|
"build:marketing": "bun run --cwd apps/marketing build",
|
|
|
|
|
"build:opencode": "bun run --cwd apps/opencode-plugin build",
|
2026-01-12 19:36:09 -08:00
|
|
|
"build:review": "bun run --cwd apps/review build",
|
2026-02-21 11:43:46 -08:00
|
|
|
"build:pi": "bun run build:review && bun run build:hook && bun run --cwd apps/pi-extension build",
|
2026-01-05 09:14:31 -08:00
|
|
|
"build": "bun run build:hook && bun run build:opencode",
|
feat: VS Code extension for in-editor plan review (#229)
* feat: integrate VS Code extension from community (7tg/plannotator-vscode)
Opens Plannotator plan reviews, code reviews, and annotations inside VS Code
tabs instead of an external browser. Intercepts PLANNOTATOR_BROWSER via env
var injection in integrated terminals, with cookie persistence and auto-close.
Original repository: https://github.com/7tg/plannotator-vscode
Closes #91
Co-Authored-By: Barbaros Gören <tayyipgoren@gmail.com>
* chore: adapt VS Code extension for monorepo
- Update package.json: publisher → backnotprop, repo → plannotator, add private
- Replace node -e URL encoding with curl --data-urlencode in router script
- Simplify panel-manager tests to keep only behavioral tests
- Add dev:vscode, build:vscode, package:vscode scripts to root
- Add *.vsix to .gitignore
- Update bun.lock with new workspace member
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
* fix: address code review and duplicate panel issue
- Fix macOS browser: detect script paths in PLANNOTATOR_BROWSER and
invoke directly instead of via 'open -a' (which only accepts app
names/.app bundles)
- Update CLAUDE.md: add vscode-extension to project structure,
development, and build sections
- Fix command title: 'Simple Browser' -> 'Open URL in Editor'
- Add 1s debounce to panel opens: Claude Code fires ExitPlanMode hook
twice, spawning two plannotator processes on different ports that
both hit the IPC server simultaneously
- Add .vscode/launch.json + tasks.json for F5 debugging
---------
Co-authored-by: Barbaros Gören <tayyipgoren@gmail.com>
Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 16:56:57 -08:00
|
|
|
"dev:vscode": "bun run --cwd apps/vscode-extension watch",
|
|
|
|
|
"build:vscode": "bun run --cwd apps/vscode-extension build",
|
|
|
|
|
"package:vscode": "bun run --cwd apps/vscode-extension package",
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
"test": "bun test",
|
|
|
|
|
"typecheck": "tsc --noEmit -p packages/shared/tsconfig.json && tsc --noEmit -p packages/ai/tsconfig.json && tsc --noEmit -p packages/server/tsconfig.json"
|
2026-01-12 19:36:09 -08:00
|
|
|
},
|
|
|
|
|
"dependencies": {
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
"@anthropic-ai/claude-agent-sdk": "^0.2.81",
|
|
|
|
|
"@openai/codex-sdk": "^0.116.0",
|
feat(ai): OpenCode provider via HTTP + SSE (#379)
* feat(ai): add OpenCode provider via HTTP + SSE
Bundle @opencode-ai/sdk to spawn `opencode serve` and communicate via
HTTP REST + SSE. Richest provider: fork, resume, streaming, tools, and
runtime permission approvals all work natively.
- OpenCodeProvider: lazy server spawn, shared HTTP client, dynamic model
discovery via GET /provider
- OpenCodeSession: SSE event drain loop, system prompt via API field,
permission reply (once/reject), abort via HTTP
- mapOpenCodeEvent: SSE → AIMessage mapping (text deltas, tool lifecycle,
permissions, session status, errors)
- 11 new event mapping tests (78 total, 157 expect calls)
For provenance purposes, this commit was AI assisted.
* docs(ai): add OpenCode to AI features guide and code review docs
For provenance purposes, this commit was AI assisted.
* fix(ai): prevent double server spawn in OpenCode ensureServer()
Use a promise-mutex pattern so concurrent callers (e.g. fetchModels +
createSession) share a single server spawn instead of racing to create two.
Also remove empty finally block from SSE drain loop.
For provenance purposes, this commit was AI assisted.
* fix(ai): await SSE subscribe in OpenCode provider
The SDK's event.subscribe() is async — must be awaited before
destructuring the stream.
For provenance purposes, this commit was AI assisted.
* fix(ui): scrollable model dropdown with search filter
Cap dropdown height at min(320px, 50vh) so it doesn't overflow the
viewport when providers expose many models (e.g. OpenCode with 20+).
Add a search/filter input when there are more than 8 models.
For provenance purposes, this commit was AI assisted.
* fix(ai): close SSE stream, rename to opencode-sdk, move dep to root
- Close SSE stream in finally block to prevent connection leak on
abort/early return
- Rename provider from opencode to opencode-sdk for consistency with
claude-agent-sdk, codex-sdk, pi-sdk
- Move @opencode-ai/sdk dependency to root package.json alongside the
other SDK dependencies
For provenance purposes, this commit was AI assisted.
* feat(ui): add first-run AI setup dialog for provider selection
Show a one-time modal on first review when AI providers are available.
Users pick a default provider and model from a 2-column grid, with a
brief feature intro and auth disclaimer. Persists via cookie, can be
changed later in Settings.
For provenance purposes, this commit was AI assisted.
* fix(ai): clear startPromise on failure so OpenCode provider can retry
If doStart() fails (port conflict, timeout, binary crash), the cached
rejected promise prevented all future ensureServer() calls from
retrying. Now cleared on failure and on dispose().
Also updates stale "future" comment in types.ts.
For provenance purposes, this commit was AI assisted.
2026-03-23 17:37:56 -07:00
|
|
|
"@opencode-ai/sdk": "^1.3.0",
|
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
|
|
|
"@pierre/diffs": "^1.1.12",
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
"diff": "^8.0.3",
|
2026-04-01 14:58:45 -07:00
|
|
|
"dockview-react": "^5.2.0",
|
feat(ai): AI backbone + inline chat for code review (#363)
* feat(ai): add provider-agnostic AI backbone for inline chat
Introduces @plannotator/ai — a pluggable provider layer that powers
AI features (inline chat, plan Q&A, code review assistance) across
all Plannotator surfaces.
- ProviderRegistry: class-based, multi-instance provider management
- SessionManager: in-memory session tracking with eviction, ID aliasing
- Context builders: system prompts and fork preambles for all three modes
- SSE streaming endpoints: session create/fork, query, abort, list
- Claude Agent SDK provider: fork from parent sessions, read-only tools,
per-query abort, cached SDK import, concurrent query guard
- 34 passing tests covering all layers
For provenance purposes, this commit was AI assisted.
* fix(ai): address code review findings from PR #363
- Concurrent query race: reject with session_busy error instead of
racing; add query generation counter so stale finally blocks don't
clobber newer query state
- Text dropped before tool_use: mapSDKMessage now returns AIMessage[]
and flushes accumulated text before each tool_use block
- defaultProvider returns instance ID: ProviderRegistry.getDefault()
returns { id, provider } so capabilities endpoint sends the correct
key for multi-instance setups
- Fork preamble re-sent on error: use _firstQuerySent boolean instead
of _resolvedId to guard preamble injection
- Dead abortController params: remove unused abortController from
CreateSessionOptions and AIProvider.resumeSession
- Unused context in memory: remove context from SessionConfig and
baseConfig — already consumed to build systemPrompt/forkPreamble
- Fix tool_result mapping: SDK wraps tool results in SDKUserMessage
(type "user"), not a "tool_result" type
For provenance purposes, this commit was AI assisted.
* feat(ai): inline AI chat on code review diffs
Add "Ask AI" to the code review toolbar — select lines, ask questions
about agent-written code, get streaming responses. Conversation persists
across file switches with inline markers on the diff showing where
questions were asked.
- useAIChat hook: SSE streaming, lazy session creation, multi-turn
- AskAIInput: question input with per-selection AI history
- InlineAIMarker: compact sparkle markers on diff lines via @pierre
- AITab: sidebar conversation grouped by file with collapsible sections
- SparklesIcon: shared 3-star sparkle from automations branch
- ReviewPanel: AI tab with message count badge, file group flash highlight
- Server: mount AI endpoints in review server with graceful fallback
- Support three question scopes: line, file, and general
- Toolbar ergonomics: typed text submits as AI question, no double popover
For provenance purposes, this commit was AI assisted.
* fix(ai): toolbar popover ergonomics and visual consistency
- X button closes entire toolbar in both modes (no ghost popover)
- Comment/Ask AI toggle is inline in the action row, same position
in both modes (left side, mirrored layout)
- AI history appears below the input, not above
- File group flash highlight uses --muted to match file tree hover
For provenance purposes, this commit was AI assisted.
* fix(ai): visual consistency, shared primitives, markdown rendering
Visual consistency:
- AI tab file group headers match FileTree pattern (sizing, hover, badges)
- Q&A bubbles match annotation card padding and border-radius
- Empty state uses circle-bg icon (same as annotations)
- General input matches search input styling
- Removed redundant CSS classes, moved to Tailwind
Shared primitives:
- Extract formatTimestamp to shared utility (was duplicated)
- CountBadge component for consistent badge styling
- CopyButton component with hover-reveal + "Copied" flash
Affordances:
- Copy button on AI responses (hover-reveal)
- Send button on general input with keyboard shortcut hint
- Timestamps on Q&A pairs
- Keyboard shortcut title on Ask button
Markdown rendering:
- Add marked dependency for full block-level markdown in AI responses
- renderMarkdown utility using marked + DOMPurify
- Scoped .ai-markdown CSS for headings, lists, code blocks, blockquotes
For provenance purposes, this commit was AI assisted.
* feat(ai): permission inheritance + inline approval UI
The inline AI agent now inherits the user's existing Claude Code
permission rules via settingSources: ['user', 'project']. Tools
already approved in ~/.claude/settings.json auto-approve silently.
For tools not covered by existing rules, the SDK emits control_request
messages. These are mapped to a new AIPermissionRequestMessage type and
surfaced as inline approval cards in the AI tab — showing the tool name,
command/input, and Allow/Deny buttons.
Backend:
- Map control_request to AIPermissionRequestMessage in provider
- Store Query object on session for sending control_response back
- respondToPermission() method on AISession sends allow/deny
- POST /api/ai/permission endpoint for frontend → backend decisions
- Add settingSources to ClaudeSDKQueryOptions
Frontend:
- PermissionCard component with Allow/Deny buttons + resolved state
- useAIChat tracks permissionRequests array
- respondToPermission() POSTs decision to server
- AITab renders pending permission cards inline in conversation
For provenance purposes, this commit was AI assisted.
* fix(ai): streaming reactivity, maxTurns, popover→sidebar linking
Streaming fixes:
- State updates now create new object references via prev.map()
instead of mutating objects inside the array — fixes React not
re-rendering the sidebar during streaming
- Complete assistant text messages only used as fallback when no
streaming deltas received (prevents duplicate text)
- Result text used as fallback when response is empty (agent spent
all turns on tools)
Config:
- maxTurns raised to 99 (was 3 — agent ran out of turns reading
files and never got to write its answer)
Popover → sidebar linking:
- Clicking AI history items in comment popover now passes questionId
through to handleViewAIResponse, triggering the file group flash
highlight in the sidebar (same behavior as clicking inline markers)
Debug logging (temporary):
- Server-side: [AI STREAM] logs every message the provider yields
- Client-side: [AI SSE] logs every message received in the browser
For provenance purposes, this commit was AI assisted.
* refactor(ai): simplification pass — types, perf, cleanup
From the three-agent code review analysis:
Quality:
- Rename AIMessage → AIChatEntry in review-editor to avoid collision
with the wire-protocol AIMessage from packages/ai
- Type permissionMode as union (not string) in SessionConfig + QueryOptions
- Type _activeQuery with narrow interface instead of any
- Make toolUseId optional on AIToolResultMessage (SDK doesn't populate it)
- Remove redundant sessionIdRef double-write in useAIChat
- Fix handleAskGeneral useCallback dep: [aiChat] → [aiChat.ask]
Performance:
- Wrap QAPair in React.memo to prevent re-renders on sibling updates
- Memoize renderMarkdown output via useMemo (avoid re-parsing on every token)
- Fix auto-scroll useEffect: depend on messages.length not messages ref
(prevents querySelectorAll on every streaming token)
Cleanup:
- Remove debug console.log from SSE endpoint and browser parser
- Extract isMac/submitHint to shared utils/platform.ts
- Extract generateId to shared utils/generateId.ts
Net: -2 lines. No behavior changes.
For provenance purposes, this commit was AI assisted.
* chore: biome lint fixes — import types, button a11y, unused import
- Use `import type` where only types are consumed (endpoints, CountBadge,
CopyButton, renderMarkdown)
- Remove unused AIContext import from session-manager
- Template literal instead of string concat in context.ts truncate()
- Add type="button" + aria-hidden on CopyButton SVGs
For provenance purposes, this commit was AI assisted.
* feat(ai): Codex SDK provider + multi-provider backend
- Add CodexSDKProvider implementing AIProvider interface
- Maps Codex ThreadEvents to AIMessage types
- Delta tracking for streaming text from cumulative item.updated events
- Supports resume, abort, sandbox modes
- Factory self-registration pattern matching Claude provider
- Enhance capabilities endpoint with provider models + metadata
- Register both providers in review server (graceful degradation)
- Add CodexSDKConfig type, models list (GPT-5.4 family)
- Add reasoningEffort to CreateSessionOptions (Codex only)
- Extract DiffFile interface to shared types.ts
- Update CLAUDE.md with build order documentation
- 54 tests passing (20+ new for Codex event mapping)
For provenance purposes, this commit was AI assisted.
* feat(ai): provider settings UI + inline config bar
- Settings → AI tab: provider cards with per-provider model dropdowns
- Inline config bar in AI chat sidebar (provider, model, reasoning effort)
- Provider icons: Claude SVG + Codex PNG from marketing assets
- Cookie-based persistence for provider + per-provider model preferences
- useAIChat accepts providerId, model, reasoningEffort from props
- Session reset on provider/model switch (next question starts fresh)
- Reasoning effort selector (Codex only: Low/Medium/High/Max)
- Update code review docs with AI provider documentation
For provenance purposes, this commit was AI assisted.
* fix(ai): review fixes — reasoning props, input blocking, cwd resolution, codex-sdk dep
- Add missing selectedReasoningEffort + onReasoningEffortChange props to
populated-state AIConfigBar (was only on empty-state, causing crash)
- Disable GeneralInput while streaming to prevent concurrent queries
- Thread cwd through CreateSessionOptions so AI sessions use the correct
working directory (worktree-aware via getCwd resolver)
- Add @openai/codex-sdk as a real dependency (was only an optional peer)
- Eagerly verify codex-sdk importability at startup to avoid advertising
a broken provider
For provenance purposes, this commit was AI assisted.
* fix(ai): polish config bar, input, and sidebar header
- Replace native <select> dropdowns with custom popover menus that show
provider icons, model names, and checkmarks on active selection
- Remove disabled gear placeholder button
- Auto-grow textarea upward on multi-line input (capped at 6 lines)
- Push tab icons to far right in sidebar header (w-full on flex container)
- Add centered divider between file-scoped and general questions
For provenance purposes, this commit was AI assisted.
* fix(ai): honest fork capability + permissionMode doc accuracy
- Endpoint now checks capabilities.fork before calling forkSession(),
falling back to createSession() for providers that can't truly fork
- Codex forkSession() now throws as the interface contract requires
(was silently faking a fork with no history — misleading UX)
- Fixed permissionMode JSDoc: said "plan" but code defaults to "default"
For provenance purposes, this commit was AI assisted.
* fix(review): move search result count inside input field
Count now appears inline to the left of the X button instead of
squeezing the input from outside. Dynamic right padding accommodates
the count + clear button when a query is active.
For provenance purposes, this commit was AI assisted.
* fix(ai): use claude_code preset, pass selected code to queries
- Claude provider now uses { preset: "claude_code", append } instead of
a raw system prompt, so inline chat inherits Claude Code's full
built-in capabilities
- Stripped custom role/guidelines preamble from context builders — just
emit the review context (diff, plan, document)
- handleAskAI now extracts selected code via extractLinesFromPatch and
sends it with the query, fixing hallucinations on large PRs where the
file's diff was truncated out of the system prompt
For provenance purposes, this commit was AI assisted.
* fix(ai): bundle both SDKs, remove peer dependencies
Both @anthropic-ai/claude-agent-sdk and @openai/codex-sdk are now
direct imports (no string indirection) so bun build --compile bundles
them into the binary. Users don't need to install SDKs separately.
Removed peer dependency declarations from packages/ai/package.json —
meaningless for a compiled binary.
For provenance purposes, this commit was AI assisted.
* refactor: canonical platform.ts, file renames, file-level comments
- Created packages/ui/utils/platform.ts as the single source for
isMac, modKey, altKey, submitHint, isWindows
- Consolidated inline navigator.platform checks from 6 files
- Renamed renderMarkdown → renderChatMarkdown (distinct from plan editor)
- Renamed formatTimestamp → formatRelativeTime (clearer purpose)
- Added file-level comments to InlineAIMarker, PermissionCard, generateId
For provenance purposes, this commit was AI assisted.
* docs(ai): add AI features guide + link from settings
New docs page at guides/ai-features covering providers, models,
configuration, session behavior, permissions, and available settings.
AISettingsTab now links to the docs in both empty and populated states.
For provenance purposes, this commit was AI assisted.
2026-03-23 12:13:03 -07:00
|
|
|
"dompurify": "^3.3.3",
|
|
|
|
|
"marked": "^17.0.5"
|
feat(review): PR context panel — summary, comments, and checks (#350)
* feat(review): add PR context panel with summary, comments, and checks tabs
When reviewing a GitHub PR, the ReviewPanel now shows icon tabs for
Summary (PR body, labels, linked issues), Comments (chronological
thread of comments + reviews), and Checks (CI status, merge readiness).
Tabs only appear in PR mode; local review is unchanged.
Data fetched lazily via new /api/pr-context endpoint on first tab click.
Uses DOMPurify for safe HTML rendering of GitHub markdown content.
Inline markdown renderer extended with link and bare URL support.
Closes #348
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(review): reset fetch guard on error and detect inline HTML in PR bodies
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-19 23:14:21 -07:00
|
|
|
},
|
|
|
|
|
"devDependencies": {
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
"@types/dompurify": "^3.2.0",
|
|
|
|
|
"@types/node": "^25.5.0",
|
feat(annotate): support HTML files and URL annotation (#545)
* fix(annotate): sanitize dangerous link protocols in markdown renderer
Block javascript:, data:, and vbscript: URLs in InlineMarkdown link
rendering. Links with dangerous protocols render as plain text instead
of clickable anchors. Uses a blocklist approach so existing links with
custom protocols (obsidian://, vscode://, Windows C:\ paths) continue
to work.
For provenance purposes, this commit was AI assisted.
* feat(annotate): add HTML-to-markdown and URL-to-markdown utilities
- html-to-markdown.ts: Turndown wrapper with GFM table rule, strips
script/style/noscript tags
- url-to-markdown.ts: Jina Reader (free, returns markdown) with
fetch+Turndown fallback. Warns on Jina failure, auto-skips Jina for
local/private URLs (localhost, 192.168.*, 10.*, etc.)
- config.ts: add jina setting and resolveUseJina() with priority chain
--no-jina flag > PLANNOTATOR_JINA env > config.json > default true
For provenance purposes, this commit was AI assisted.
* feat(annotate): support HTML files and URLs in annotate command
Extend the annotate subcommand to accept .html/.htm local files
(converted via Turndown) and https:// URLs (fetched via Jina Reader
with fetch+Turndown fallback). URL content is fetched terminal-side
before opening the browser.
Add --no-jina global flag to disable Jina Reader per-invocation.
Add 10MB file size guard for local HTML files.
For provenance purposes, this commit was AI assisted.
* feat(annotate): HTML files in folder browser and on-demand conversion
- Widen file browser glob to include .html/.htm alongside markdown
- handleDoc converts HTML files via Turndown on demand when selected
- hasMarkdownFiles accepts optional extensions param for folder validation
- Add sourceInfo field to annotate server API response
- Add _site/, public/, out/, .docusaurus/, .jekyll-cache/,
storybook-static/ to FILE_BROWSER_EXCLUDED
For provenance purposes, this commit was AI assisted.
* feat(annotate): source attribution badge for HTML/URL annotations
Show a subtle badge in DocBadges displaying the URL hostname or HTML
filename for converted content. Thread sourceInfo from API response
through App → Viewer → DocBadges.
Also update Pi extension to accept HTML-only folders in annotate mode.
For provenance purposes, this commit was AI assisted.
* test: update CLI help text assertion for HTML/URL annotate support
For provenance purposes, this commit was AI assisted.
* fix(annotate): address PR review findings
Security:
- Add project-root containment check for HTML files in /api/doc handler
using exported isWithinProjectRoot() from resolve-file.ts
- Blocks path traversal via absolute paths or ../ escapes
isLocalUrl fixes:
- Add bracketed IPv6 loopback [::1] detection
- Replace hostname.startsWith('10.') with proper IPv4 regex to avoid
matching public hostnames like 10.example.com
Revert Pi extension change:
- Pi server doesn't implement HTML file browsing or conversion yet
- Keep Pi folder validation markdown-only until both implementations
are updated per CLAUDE.md guidelines
Cleanup:
- Remove dead el.children || el.childNodes fallback in table rule
- Extract hostnameOrFallback() helper to @plannotator/shared/project
replacing duplicated try/catch IIFEs in DocBadges and index.ts
For provenance purposes, this commit was AI assisted.
* feat(annotate): Pi extension HTML annotation parity
Bring the Pi extension to full parity with the Bun server for HTML
annotation support:
- Vendor html-to-markdown and url-to-markdown via vendor.sh
- walkMarkdownFiles now scans .html/.htm alongside markdown
- handleDocRequest converts HTML files on-demand via Turndown with
isWithinProjectRoot containment check
- serverAnnotate includes sourceInfo in /api/plan response
- index.ts supports URL detection (Jina Reader + fallback), HTML file
detection with Turndown conversion, folder HTML validation, and 10MB
file size guard
- openMarkdownAnnotation accepts and threads sourceInfo
- Add turndown as a Pi extension dependency
For provenance purposes, this commit was AI assisted.
* fix(pi): Obsidian vault walks stay markdown-only, add try/catch for HTML
- Add extensions param to walkMarkdownFiles (default: HTML-inclusive)
- Obsidian callers pass /\.mdx?$/i to match Bun server behavior
- Add try/catch around HTML file reads in handleDocRequest
For provenance purposes, this commit was AI assisted.
* fix(annotate): address second review — base-block traversal, metadata IP, dead code
Security:
- Add isWithinProjectRoot check to the base-relative block for HTML
files in both Bun and Pi /api/doc handlers. Previously HTML files
served via the base query param bypassed the containment guard.
- Add 169.254.0.0/16 (link-local / cloud metadata) to isLocalUrl
private IP ranges
Cleanup:
- Remove dead hostname === "[::1]" check (WHATWG URL parser strips
brackets; hostname === "::1" already handles it)
- Remove dead parent?.childNodes fallback in table cell() function
For provenance purposes, this commit was AI assisted.
* refactor(annotate): replace custom table rules with turndown-plugin-gfm
Drop ~60 lines of hand-rolled GFM table conversion that had a bug
(tables without explicit <thead> produced invalid GFM). Use the
official turndown-plugin-gfm plugin (24KB) which correctly handles
all table patterns plus adds strikethrough and task list support.
For provenance purposes, this commit was AI assisted.
* fix(annotate): handle all CommonMark backslash escapes in InlineMarkdown
Expand the backslash escape regex to cover all CommonMark-defined
escapable characters (. ) - # > + | { } &), not just the subset
the parser uses for formatting. Fixes literal backslashes appearing
in rendered output for Turndown-escaped content like "1\." → "1.".
For provenance purposes, this commit was AI assisted.
* fix(annotate): prevent SSRF via redirect to private/local URLs
Replace redirect: "follow" with redirect: "manual" in fetchViaTurndown
and validate each redirect hop against isLocalUrl. Blocks attacks where
an external URL redirects to cloud metadata endpoints (169.254.169.254)
or other private IPs. Limits redirect chain to 10 hops.
For provenance purposes, this commit was AI assisted.
* chore: update lockfile for turndown-plugin-gfm in Pi extension
bun install needed to resolve turndown-plugin-gfm in the Pi extension
workspace after adding it to apps/pi-extension/package.json.
For provenance purposes, this commit was AI assisted.
* fix(annotate): switch to @joplin/turndown-plugin-gfm, fix TS errors
Replace unmaintained turndown-plugin-gfm (2017, v1.0.2) with the
actively maintained Joplin fork (2025, v1.0.64, 16KB).
Fix TypeScript errors that broke CI:
- Add @ts-expect-error for untyped @joplin/turndown-plugin-gfm import
- Restructure fetchViaTurndown redirect loop to avoid uninitialized
variable — first fetch before loop, loop only for redirects
For provenance purposes, this commit was AI assisted.
* fix(annotate): use proper declarations.d.ts instead of ts-expect-error
Add declarations.d.ts for @joplin/turndown-plugin-gfm with typed
function signatures, remove the ts-expect-error suppression.
For provenance purposes, this commit was AI assisted.
* fix: explicitly include declarations.d.ts in shared tsconfig
CI's tsc wasn't finding the ambient module declaration with implicit
include. Add explicit include to ensure declarations.d.ts is always
picked up regardless of environment.
For provenance purposes, this commit was AI assisted.
* fix: use ts-expect-error for @joplin/turndown-plugin-gfm types
CI's tsc does not pick up ambient declarations.d.ts files despite
local tsc finding them — likely a module resolution discrepancy
between environments. Revert to @ts-expect-error which passes in
both CI and local typecheck.
For provenance purposes, this commit was AI assisted.
* fix(annotate): body size limit for URL fetches, redirect error, file: protocol
- Add 10MB body size limit to both Jina and fetch+Turndown URL paths,
matching the local HTML file guard. Streams response body and aborts
if limit exceeded.
- Distinguish "Too many redirects" from a genuine 3xx response after
redirect loop exhaustion.
- Add file: to the dangerous protocol blocklist in sanitizeLinkUrl.
For provenance purposes, this commit was AI assisted.
* fix(annotate): HTML folder outside cwd, HTML linked doc navigation
- Remove containment check from base-relative block for HTML files in
both Bun and Pi /api/doc handlers. Matches markdown behavior so HTML
files in annotated folders outside cwd are served correctly.
Standalone block (no base) retains its cwd check as fallback.
- Widen isLocalMd → isLocalDoc to treat .html/.htm links as linked
documents. Clicking [Next](next.html) in a converted page now opens
it via /api/doc with Turndown conversion instead of a new browser tab.
For provenance purposes, this commit was AI assisted.
* fix(annotate): full loopback range, drain redirect bodies, document env vars
- Expand loopback check from just 127.0.0.1 to the full 127.0.0.0/8
range so all loopback addresses skip Jina Reader
- Cancel redirect response body before re-fetching to avoid leaking
TCP connections back to the pool
- Document PLANNOTATOR_JINA and JINA_API_KEY in CLAUDE.md env var table
For provenance purposes, this commit was AI assisted.
* fix(annotate): IPv6 loopback, readBodyWithLimit fallback, env var docs, comments
- Add [::1] back to isLocalUrl — WHATWG URL hostname getter preserves
brackets for IPv6 (verified: Bun and Node both return "[::1]").
Add comment explaining the empirical verification so future reviewers
don't re-flag.
- Fix readBodyWithLimit null-body fallback to still enforce the 10MB
limit via text length check instead of silently falling through.
- Document PLANNOTATOR_JINA and JINA_API_KEY in AGENTS.md env var table
(CLAUDE.md is a symlink to AGENTS.md).
- Add comments to base-relative blocks in both Bun and Pi handleDoc
explaining the intentional lack of containment check (matches
pre-existing markdown behavior, base is set server-side).
For provenance purposes, this commit was AI assisted.
* fix(annotate): block IPv4-mapped IPv6 and private IPv6 ranges in isLocalUrl
Add PRIVATE_IPV6 regex matching bracketed IPv6 private/reserved ranges:
- ::ffff: (IPv4-mapped — embeds private IPv4 as hex, e.g. [::ffff:c0a8:1])
- fe80: (link-local)
- fc00::/7 (unique-local, covers fc00:: through fdff::)
Closes the redirect-SSRF bypass where a public URL redirects to a
private address expressed as IPv4-mapped IPv6, e.g.
http://[::ffff:169.254.169.254]/latest/meta-data/
For provenance purposes, this commit was AI assisted.
* fix(annotate): document IPv6 hostname verification, sourceInfo type, annotate flow
- Expand isLocalUrl comment with full empirical verification table
showing actual hostname getter output for every IPv6 format in both
Bun and Node — prevents false-positive review findings about brackets
- Add sourceInfo to /api/plan response type in App.tsx for type safety
- Update CLAUDE.md annotate flow diagram to reflect HTML/URL/folder
input types
For provenance purposes, this commit was AI assisted.
* fix(annotate): escape \(, cancel response bodies on error, doc sourceInfo
- Add ( to backslash escape regex alongside existing ) — Turndown
emits \( in link-adjacent contexts
- Cancel response body before throwing on !res.ok in both fetchViaJina
and fetchViaTurndown error paths (redirect loop already did this)
- Document sourceInfo field in AGENTS.md annotate server API table
For provenance purposes, this commit was AI assisted.
* fix(annotate): skip base injection for URL annotations, body cleanup
- Skip dirname(filePath) base injection when filePath is a URL in both
Bun and Pi annotate servers. dirname on a URL string produces a
nonsensical filesystem path, causing linked doc clicks to 404.
URL annotations now let links open normally instead.
- Cancel response body before throwing on content-type mismatch and
content-length overflow in fetchViaTurndown/readBodyWithLimit.
- Fix double parseInt in readBodyWithLimit content-length check.
- Correct AGENTS.md flow diagram: OpenCode not yet implemented for
HTML/URL annotation.
For provenance purposes, this commit was AI assisted.
* feat(annotate): OpenCode HTML file and URL annotation support
Add URL detection (Jina Reader + fallback), HTML file detection with
Turndown conversion, 10MB file size guard, and sourceInfo threading
to OpenCode's handleAnnotateCommand. Uses the same shared utilities
as the Bun CLI and Pi extension.
OpenCode uses the Bun server directly (startAnnotateServer from
@plannotator/server/annotate), so no server-side changes needed —
only the command handler routing was missing.
Note: folder annotation mode is not added (OpenCode didn't have it
before this PR for markdown either — separate scope).
For provenance purposes, this commit was AI assisted.
* chore(annotate): update slash command description, align fetch log messages
- OpenCode plannotator-annotate.md description now mentions HTML/URL
- Align fetch progress messages across all three clients: all now show
"(via Jina Reader)" or "(via fetch+Turndown)" consistently
For provenance purposes, this commit was AI assisted.
* fix(annotate): skip conversion for .md URLs, wikilink HTML targets, cleanup
- URLs ending in .md/.mdx are fetched raw — no Jina, no Turndown.
Content is already markdown. Removes text/plain from fetchViaTurndown
content-type whitelist since .md URLs are now short-circuited.
- Wikilink regex widened to preserve .html/.htm targets instead of
appending .md (e.g. [[page.html]] no longer becomes page.html.md)
- Remove redundant existsSync before statSync in OpenCode handler
For provenance purposes, this commit was AI assisted.
* test(annotate): add htmlToMarkdown conversion tests
Tests cover the core conversion utility that all three clients depend on:
- Basic HTML → markdown (headings, paragraphs, links, code blocks)
- Tables with and without <thead> (the GFM plugin bug that was caught)
- Script/style/noscript stripping
- Strikethrough (GFM)
- Empty HTML handling
- Dangerous links preserved (sanitization is in the renderer, not here)
For provenance purposes, this commit was AI assisted.
* fix(annotate): check content-type before treating .md URLs as raw markdown
URLs ending in .md/.mdx (e.g. GitHub's viewer page for README.md)
may return HTML instead of raw markdown. fetchRawText now checks the
response content-type — if the server returns HTML, returns null so
the caller falls through to Jina/Turndown for proper conversion.
For provenance purposes, this commit was AI assisted.
* fix(annotate): add SSRF redirect protection to fetchRawText
fetchRawText (for .md/.mdx URLs) was using default redirect: "follow"
with no isLocalUrl validation on redirect hops — a .md URL redirecting
to 169.254.169.254 would be followed and credentials returned as
"markdown". Now uses redirect: "manual" with per-hop isLocalUrl checks,
matching fetchViaTurndown's SSRF protection.
For provenance purposes, this commit was AI assisted.
2026-04-12 18:56:28 -07:00
|
|
|
"@types/turndown": "^5.0.6",
|
feat(pi): complete Pi server rewrite — modular architecture, full Bun parity, shared code extraction (#382)
* feat(pi): add missing endpoints to plan, review, and annotate servers
Phase 1-3 of Pi endpoint parity:
Plan server: image, upload, draft, editor-annotations, agents, favicon,
linked documents, Obsidian vaults/files/doc, file browser, VS Code diff
Annotate server: image, upload, draft, favicon, linked documents, file browser
Review server: extract shared handlers, add favicon
Shared utilities extracted from review server inline code into reusable
functions (handleImageRequest, handleUploadRequest, handleDraftRequest,
handleFavicon). Reference handlers (doc, Obsidian, file browser)
implemented using Node.js fs APIs replacing Bun.Glob/Bun.file.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): add PR review endpoints and Node.js PR runtime adapter
Phase 4 of Pi endpoint parity:
- Node.js PRRuntime using child_process.spawn (matches Bun adapter pattern)
- GET /api/pr-context — fetch PR summary, comments, checks
- POST /api/pr-action — submit review to GitHub/GitLab
- PR mode guards on /api/diff/switch and /api/git-add
- /api/diff response includes prMetadata and platformUser in PR mode
- /api/file-content fetches from platform API in PR mode
- Build script copies pr-provider, pr-github, pr-gitlab from shared
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): wire AI backbone with Node.js Pi SDK provider
Phase 5 of Pi endpoint parity:
- Create packages/ai/providers/pi-sdk-node.ts — PiProcessNode class
using child_process.spawn instead of Bun.spawn, same RPC protocol
- Register 4 AI providers in Pi review server (claude-agent-sdk,
codex-sdk, pi-sdk-node, opencode-sdk) with graceful degradation
- Route /api/ai/* endpoints through createAIEndpoints handlers
- Pipe Web Response → node:http response with ReadableStream support
for SSE streaming
- Dispose AI sessions and registry on server stop
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): address parity audit findings across all three servers
Plan server:
- /api/plan: add repoInfo and projectRoot to response
- /api/approve: pass agentSwitch and permissionMode in decision
- Update decision promise type to include agentSwitch, permissionMode
Review server:
- /api/diff/switch: pass gitContext.cwd to runGitDiff
- /api/file-content: pass gitContext.cwd to getFileContentsForDiffCore
- /api/git-add: add fallback to gitContext.cwd when worktree parse fails
Annotate server:
- /api/plan: add repoInfo and projectRoot to response
- /api/feedback: capture annotations array (was silently dropped)
- Update decision promise type to include annotations
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* feat(pi): complete parity — integrations, planSave, save-notes
Ports all remaining missing functionality:
- Node.js versions of saveToObsidian, saveToBear, saveToOctarine
(Bun.write → writeFileSync, Bun.$ → spawn)
- Node.js detectProjectNameSync (Bun.$ → execSync)
- extractTags, generateFrontmatter, generateFilename, extractTitle
- POST /api/save-notes — decoupled note saving
- POST /api/approve — full implementation: note integrations,
planSave snapshots, saveAnnotations, saveFinalSnapshot
- POST /api/deny — planSave snapshots on denial
- Import saveAnnotations, saveFinalSnapshot from storage.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): wire domain module imports and fix type errors
- Add all missing imports from ./server/* domain modules to server.ts
- Export interfaces from integrations.ts (ObsidianConfig, BearConfig, etc.)
- Move toWebRequest to helpers.ts, remove duplicate from handlers.ts
- Add git() helper to project.ts (was in server.ts, needed by getRepoInfo)
- Fix os default import → named imports in handlers.ts and network.ts
- Fix readdirSync Dirent type in reference.ts
- Fix Headers.entries() → forEach for Node compat in AI endpoint piping
- Fix ReadableStream type cast in AI SSE streaming
- Fix matchAll iterator compat in integrations.ts (use while + exec)
- Cast pi-sdk provider config to any (PiSDKConfig not in base union)
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): move generated shared files to generated/ directory
Moves all build-time copied shared files (feedback-templates, review-core,
storage, draft, project, pr-provider, pr-github, pr-gitlab) from the
pi-extension root into generated/ subdirectory.
Updates build script to output there. Updates all imports in server.ts,
index.ts, and server/ domain modules to use ./generated/ paths.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): replace hand-maintained utils.ts with generated checklist
utils.ts was a manual copy of parseChecklist, extractDoneSteps, and
markCompletedSteps from packages/shared/checklist.ts. Add checklist
to the build-time copy list and import from generated/checklist.js.
Delete the redundant utils.ts.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* chore(pi): gitignore generated/ and built HTML files
These are build artifacts created by `bun run build:pi`. Untrack them
and add .gitignore to prevent re-adding.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* refactor(pi): split server.ts into domain-organized modules
- server.ts is now a barrel re-exporting from server/ modules
- server/serverPlan.ts — plan review server
- server/serverReview.ts — code review server
- server/serverAnnotate.ts — annotate server
- server/helpers.ts — add requestUrl() to eliminate non-null assertions
- server/project.ts — linter fix (sanitizeTag import path)
- packages/ai/package.json — add pi-sdk-node export entry
- index.ts — fix waitForDone non-null assertion with guard check,
update imports for generated/checklist.js
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
* fix(pi): parity audit fixes + shared code extraction
Systematic side-by-side audit of Pi vs Bun servers (A1-A22, B1-B2 complete).
Fixes found during audit:
- PlanServerResult.waitForDecision missing savedPath/agentSwitch/permissionMode
- Missing permissionMode option and /api/plan response field
- editorAnnotations created unnecessarily in archive mode
- repoInfo called per-request instead of cached at init
- Approve handler missing effectivePermissionMode fallback
- Deny handler missing savedPath in decision resolution
- Archive /api/plan response had extra pasteApiUrl
- Missing GET method guards on archive/plans, archive/plan, doc, obsidian/files, obsidian/doc, reference/files
- Review server had stray pasteApiUrl option/response field
- AI getCwd missing worktree support
Shared code extraction:
- packages/shared/favicon.ts — single source for favicon SVG
- packages/shared/integrations-common.ts — note app pure functions
- packages/shared/reference-common.ts — file tree building
- packages/shared/repo.ts — git remote parsing
- Updated all consumers to import from shared sources
For provenance purposes, this commit was AI assisted.
* fix: parity audit B3-C10 — review + annotate server fixes
Review server (B3-B17):
- diff/switch missing try/catch error handling
- git-add parseBody outside try/catch
- feedback missing try/catch error handling
- Unknown /api/ai/* paths now return 404 (both Bun and Pi)
Annotate server (C1-C10):
- Bun annotate server missing pasteApiUrl (short URL sharing broken)
- Added pasteApiUrl to Bun options, response, and both hook callers
- Pi repoInfo called per-request instead of cached at init
- Pi feedback missing try/catch error handling
- Missing GET method guards on doc and reference/files
For provenance purposes, this commit was AI assisted.
* fix: parity audit D3-D5 — draft error handling, editor annotations, resolve-file extraction
D3: Pi draft save handler missing error handling — added .catch() with 500 + console.error
D4: Pi editor annotation POST missing try/catch — added with "Invalid JSON" 400
D5: Extracted resolveMarkdownFile to packages/shared/resolve-file.ts
- Replaced Bun.Glob with runtime-agnostic walkMarkdownFiles (readdirSync)
- Made function sync (no longer async)
- Pi handleDocRequest now uses shared resolveMarkdownFile instead of inline resolution
- Gains Windows path normalization, isWithinProjectRoot security check
- Deleted packages/server/resolve-file.ts re-export, consumers import from shared
- Cleaned up stale await calls in hook entry, reference handler, and tests
- All 19 resolve-file tests pass
For provenance purposes, this commit was AI assisted.
* fix: parity audit D6-D10 — integrations, PR naming, shared modules
D6: Fixed broken detectProjectNameSync — was using require() for
non-existent exports. Now uses basename + sanitizeTag directly.
D7: Renamed checkAuth → checkPRAuth, getUser → getPRUser across
Bun server, hook, and OpenCode plugin to match Pi naming.
Also fixed stale resolve-file import in OpenCode plugin.
D8-D10: Verified clean — ide, project detection, network.
For provenance purposes, this commit was AI assisted.
* update openpackage.yml
* fix: bump Pi git-add test timeout to 15s for parallel suite stability
For provenance purposes, this commit was AI assisted.
* test: add route parity test — Bun ↔ Pi server route drift detection
For provenance purposes, this commit was AI assisted.
* fix(ci): update Pi generate step to use generated/ directory with full file list
The Pi extension was refactored to use generated/ subdirectory but the CI
generate step still used the old flat layout with a subset of files.
For provenance purposes, this commit was AI assisted.
* fix(ci): update release workflow Pi generate step to match new layout
Same stale generate step as test.yml — old flat layout, missing files.
For provenance purposes, this commit was AI assisted.
* fix(pi): update files array for modular server layout
The files array still referenced the old flat layout (server.ts monolith,
root-level generated files, deleted utils.ts). npm publish would have
produced a broken package missing server/ and generated/ directories.
For provenance purposes, this commit was AI assisted.
* feat: add TypeScript type-checking to CI pipeline
- Fix broken barrel export: buildFileTree/VaultNode re-exported from
@plannotator/shared instead of reference-handlers (P1 bug)
- Fix server.port type narrowing in all 3 servers
- Fix AI provider type errors (claude-agent-sdk, codex-sdk, opencode-sdk, pi-sdk)
- Extract mapPiEvent to pi-events.ts to break Bun→Node type chain
- Add tsconfig.json to packages/shared, packages/ai, packages/server, apps/pi-extension
- Add `typecheck` script to root package.json
- Add type-check step to test.yml and release.yml CI workflows
For provenance purposes, this commit was AI assisted.
* fix(ci): use bun-types instead of @types/node for typecheck
CI environment has bun-types (includes Node types) but not
@types/node as a standalone package.
For provenance purposes, this commit was AI assisted.
* fix(ci): add @types/node for Node-runtime type checks
Pi extension and packages/shared run on Node, not Bun — they should
type-check against @types/node, not bun-types. Added @types/node as
a dev dependency so CI resolves it.
For provenance purposes, this commit was AI assisted.
* fix: cast Uint8Array.buffer to ArrayBuffer for TS 5.9 compat
crypto.subtle.importKey expects BufferSource, but TS 5.9 is stricter
about Uint8Array.buffer being ArrayBufferLike (includes SharedArrayBuffer)
vs ArrayBuffer. Explicit cast resolves the overload mismatch.
Astro pulls in TS 5.9 transitively, so CI resolves a different
TypeScript version than local dev. This fix works on both 5.8 and 5.9.
For provenance purposes, this commit was AI assisted.
* fix(ci): add bun-types as explicit devDependency
CI's bun install doesn't hoist bun-types to root node_modules when
it's only a transitive dep of @types/bun. Adding it as a direct
devDependency guarantees tsc can resolve it.
For provenance purposes, this commit was AI assisted.
* fix(ci): remove Pi extension from typecheck
Pi extension depends on @mariozechner/pi-* peer dependencies that
aren't installed in CI. Type-checking it requires Pi's runtime
environment. The three packages we check (shared, ai, server) are
sufficient to catch barrel export bugs and type errors. Pi extension
coverage comes from route parity tests and bun test.
For provenance purposes, this commit was AI assisted.
---------
Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-24 00:44:54 -07:00
|
|
|
"bun-types": "^1.3.11"
|
2025-12-27 18:14:10 -08:00
|
|
|
}
|
|
|
|
|
}
|