Files
backnotprop__plannotator/apps/pi-extension/server/serverReview.ts
T

733 lines
22 KiB
TypeScript
Raw Normal View History

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
import { execSync, spawnSync } from "node:child_process";
import { readFileSync, existsSync } from "node:fs";
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
import { createServer } from "node:http";
import os from "node:os";
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
import { Readable } from "node:stream";
import { contentHash, deleteDraft } from "../generated/draft.js";
import { saveConfig, detectGitUser, getServerConfig } from "../generated/config.js";
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
export type {
DiffOption,
DiffType,
GitContext,
} from "../generated/review-core.js";
import {
getDisplayRepo,
getMRLabel,
getMRNumberLabel,
type PRMetadata,
type PRReviewFileComment,
prRefFromMetadata,
} from "../generated/pr-provider.js";
import {
type DiffType,
type GitCommandResult,
type GitContext,
getFileContentsForDiff as getFileContentsForDiffCore,
getGitContext as getGitContextCore,
gitAddFile as gitAddFileCore,
gitResetFile as gitResetFileCore,
parseWorktreeDiffType,
type ReviewGitRuntime,
runGitDiff as runGitDiffCore,
validateFilePath,
} from "../generated/review-core.js";
import { createEditorAnnotationHandler } from "./annotations.js";
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
import { createAgentJobHandler } from "./agent-jobs.js";
import { createExternalAnnotationHandler } from "./external-annotations.js";
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
import {
handleDraftRequest,
handleFavicon,
handleImageRequest,
handleUploadRequest,
} from "./handlers.js";
import { html, json, parseBody, requestUrl, toWebRequest } from "./helpers.js";
import { isRemoteSession, listenOnPort } from "./network.js";
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
import {
fetchPRContext,
fetchPRFileContent,
2026-03-25 21:33:33 +01:00
fetchPRViewedFiles,
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
getPRUser,
2026-03-25 21:33:33 +01:00
markPRFilesViewed,
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
submitPRReview,
} from "./pr.js";
import { getRepoInfo } from "./project.js";
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
import {
CODEX_REVIEW_SYSTEM_PROMPT,
buildCodexReviewUserMessage,
buildCodexCommand,
generateOutputPath,
parseCodexOutput,
transformReviewFindings,
} from "../generated/codex-review.js";
import {
CLAUDE_REVIEW_PROMPT,
buildClaudeCommand,
parseClaudeStreamOutput,
transformClaudeFindings,
} from "../generated/claude-review.js";
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
/** Detect if running inside WSL (Windows Subsystem for Linux) */
function detectWSL(): boolean {
if (process.platform !== "linux") return false;
if (os.release().toLowerCase().includes("microsoft")) return true;
try {
if (existsSync("/proc/version")) {
const content = readFileSync("/proc/version", "utf-8").toLowerCase();
return content.includes("wsl") || content.includes("microsoft");
}
} catch { /* ignore */ }
return false;
}
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
export interface ReviewServerResult {
port: number;
portSource: "env" | "remote-default" | "random";
url: string;
isRemote: boolean;
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
waitForDecision: () => Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
}>;
stop: () => void;
}
export const reviewRuntime: ReviewGitRuntime = {
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
async runGit(
args: string[],
options?: { cwd?: string },
): Promise<GitCommandResult> {
const result = spawnSync("git", args, {
cwd: options?.cwd,
encoding: "utf-8",
});
return {
stdout: result.stdout ?? "",
stderr: result.stderr ?? "",
exitCode: result.status ?? (result.error ? 1 : 0),
};
},
async readTextFile(path: string): Promise<string | null> {
try {
return readFileSync(path, "utf-8");
} catch {
return null;
}
},
};
export function getGitContext(cwd?: string): Promise<GitContext> {
return getGitContextCore(reviewRuntime, cwd);
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
}
export function runGitDiff(
diffType: DiffType,
defaultBranch = "main",
cwd?: string,
): Promise<{ patch: string; label: string; error?: string }> {
return runGitDiffCore(reviewRuntime, diffType, defaultBranch, cwd);
}
export async function startReviewServer(options: {
rawPatch: string;
gitRef: string;
htmlContent: string;
origin?: string;
diffType?: DiffType;
gitContext?: GitContext;
error?: string;
sharingEnabled?: boolean;
shareBaseUrl?: string;
prMetadata?: PRMetadata;
/** Working directory for agent processes (e.g., --local worktree). Independent of diff pipeline. */
agentCwd?: string;
/** Cleanup callback invoked when server stops (e.g., remove temp worktree) */
onCleanup?: () => void | Promise<void>;
/** Called when server starts with the URL, remote status, and port */
onReady?: (url: string, isRemote: boolean, port: number) => void;
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
}): Promise<ReviewServerResult> {
const gitUser = detectGitUser();
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
const draftKey = contentHash(options.rawPatch);
const prMeta = options.prMetadata;
const isPRMode = !!prMeta;
const hasLocalAccess = !!options.gitContext;
const isRemote = isRemoteSession();
const wslFlag = detectWSL();
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
const prRef = prMeta ? prRefFromMetadata(prMeta) : null;
const platformUser = prRef ? await getPRUser(prRef) : null;
2026-03-25 21:33:33 +01:00
// Fetch GitHub viewed file state (non-blocking — errors are silently ignored)
let initialViewedFiles: string[] = [];
if (isPRMode && prRef) {
try {
const viewedMap = await fetchPRViewedFiles(prRef);
initialViewedFiles = Object.entries(viewedMap)
.filter(([, isViewed]) => isViewed)
.map(([path]) => path);
} catch {
// Non-fatal: viewed state is best-effort
}
}
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
const repoInfo = prMeta
? {
display: getDisplayRepo(prMeta),
branch: `${getMRLabel(prMeta)} ${getMRNumberLabel(prMeta)}`,
}
: getRepoInfo();
const editorAnnotations = createEditorAnnotationHandler();
const externalAnnotations = createExternalAnnotationHandler("review");
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
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
let currentPatch = options.rawPatch;
let currentGitRef = options.gitRef;
let currentDiffType: DiffType = options.diffType || "uncommitted";
let currentError = options.error;
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
// Agent jobs — background process manager (late-binds serverUrl via getter)
let serverUrl = "";
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
// Worktree-aware cwd resolver — shared by getCwd, buildCommand, and onJobComplete
function resolveAgentCwd(): string {
if (options.agentCwd) return options.agentCwd;
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
if (currentDiffType.startsWith("worktree:")) {
const parsed = parseWorktreeDiffType(currentDiffType);
if (parsed) return parsed.path;
}
return options.gitContext?.cwd ?? process.cwd();
}
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
const agentJobs = createAgentJobHandler({
mode: "review",
getServerUrl: () => serverUrl,
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
getCwd: resolveAgentCwd,
async buildCommand(provider) {
const cwd = resolveAgentCwd();
const hasAgentLocalAccess = !!options.agentCwd || !!options.gitContext;
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
const userMessage = buildCodexReviewUserMessage(
currentPatch,
currentDiffType,
{ defaultBranch: options.gitContext?.defaultBranch, hasLocalAccess: hasAgentLocalAccess },
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
options.prMetadata,
);
if (provider === "codex") {
const outputPath = generateOutputPath();
const prompt = CODEX_REVIEW_SYSTEM_PROMPT + "\n\n---\n\n" + userMessage;
const command = await buildCodexCommand({ cwd, outputPath, prompt });
return { command, outputPath, prompt, label: "Codex Review" };
}
if (provider === "claude") {
const prompt = CLAUDE_REVIEW_PROMPT + "\n\n---\n\n" + userMessage;
const { command, stdinPrompt } = buildClaudeCommand(prompt);
return { command, stdinPrompt, prompt, cwd, label: "Claude Code Review", captureStdout: true };
}
return null;
},
async onJobComplete(job, meta) {
const cwd = resolveAgentCwd();
if (job.provider === "codex" && meta.outputPath) {
const output = await parseCodexOutput(meta.outputPath);
if (!output) return;
// Override verdict if there are blocking findings (P0/P1) — Codex's
// freeform correctness string can say "mostly correct" with real bugs.
const hasBlockingFindings = output.findings.some((f: any) => f.priority !== null && f.priority <= 1);
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
job.summary = {
correctness: hasBlockingFindings ? "Issues Found" : output.overall_correctness,
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
explanation: output.overall_explanation,
confidence: output.overall_confidence_score,
};
if (output.findings.length > 0) {
const annotations = transformReviewFindings(output.findings, job.source, cwd, "Codex");
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[codex-review] addAnnotations error:`, result.error);
}
return;
}
if (job.provider === "claude" && meta.stdout) {
const output = parseClaudeStreamOutput(meta.stdout);
if (!output) return;
const total = output.summary.important + output.summary.nit + output.summary.pre_existing;
job.summary = {
correctness: output.summary.important === 0 ? "Correct" : "Issues Found",
explanation: `${output.summary.important} important, ${output.summary.nit} nit, ${output.summary.pre_existing} pre-existing`,
confidence: total === 0 ? 1.0 : Math.max(0, 1.0 - (output.summary.important * 0.2)),
};
if (output.findings.length > 0) {
const annotations = transformClaudeFindings(output.findings, job.source, cwd);
const result = externalAnnotations.addAnnotations({ annotations });
if ("error" in result) console.error(`[claude-review] addAnnotations error:`, result.error);
}
return;
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
}
},
});
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
const sharingEnabled =
options.sharingEnabled ?? process.env.PLANNOTATOR_SHARE !== "disabled";
const shareBaseUrl =
(options.shareBaseUrl ?? process.env.PLANNOTATOR_SHARE_URL) || undefined;
let resolveDecision!: (result: {
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
}) => void;
const decisionPromise = new Promise<{
approved: boolean;
feedback: string;
annotations: unknown[];
agentSwitch?: string;
}>((r) => {
resolveDecision = r;
});
// AI provider setup (graceful — AI features degrade if SDK unavailable)
// Types are `any` because @plannotator/ai is a dynamic import
let aiEndpoints: Record<string, (req: Request) => Promise<Response>> | null =
null;
let aiSessionManager: { disposeAll: () => void } | null = null;
let aiRegistry: { disposeAll: () => void } | null = null;
try {
const ai = await import("../generated/ai/index.js");
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
const registry = new ai.ProviderRegistry();
const sessionManager = new ai.SessionManager();
// which() helper for Node.js
const whichCmd = (cmd: string): string | null => {
try {
return (
execSync(`which ${cmd}`, {
encoding: "utf-8",
stdio: ["pipe", "pipe", "pipe"],
}).trim() || null
);
} catch {
return null;
}
};
// Claude Agent SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/claude-agent-sdk.js");
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
const claudePath = whichCmd("claude");
const provider = await ai.createProvider({
type: "claude-agent-sdk",
cwd: process.cwd(),
...(claudePath && { claudeExecutablePath: claudePath }),
});
registry.register(provider);
} catch {
/* Claude SDK not available */
}
// Codex SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/codex-sdk.js");
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
await import("@openai/codex-sdk");
const codexPath = whichCmd("codex");
const provider = await ai.createProvider({
type: "codex-sdk",
cwd: process.cwd(),
...(codexPath && { codexExecutablePath: codexPath }),
});
registry.register(provider);
} catch {
/* Codex SDK not available */
}
// Pi SDK (Node.js variant)
try {
await import("../generated/ai/providers/pi-sdk-node.js");
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
const piPath = whichCmd("pi");
if (piPath) {
const provider = await ai.createProvider({
type: "pi-sdk",
cwd: process.cwd(),
piExecutablePath: piPath,
} as any);
if (provider && "fetchModels" in provider) {
await (
provider as { fetchModels: () => Promise<void> }
).fetchModels();
}
registry.register(provider);
}
} catch {
/* Pi not available */
}
// OpenCode SDK
try {
// @ts-ignore — dynamic import; Bun-only types resolved at runtime
await import("../generated/ai/providers/opencode-sdk.js");
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
const opencodePath = whichCmd("opencode");
if (opencodePath) {
const provider = await ai.createProvider({
type: "opencode-sdk",
cwd: process.cwd(),
});
if (provider && "fetchModels" in provider) {
await (
provider as { fetchModels: () => Promise<void> }
).fetchModels();
}
registry.register(provider);
}
} catch {
/* OpenCode not available */
}
if (registry.size > 0) {
aiEndpoints = ai.createAIEndpoints({
registry,
sessionManager,
getCwd: resolveAgentCwd,
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
});
aiSessionManager = sessionManager;
aiRegistry = registry;
}
} catch {
/* AI backbone not available */
}
const server = createServer(async (req, res) => {
const url = requestUrl(req);
if (url.pathname === "/api/diff" && req.method === "GET") {
json(res, {
rawPatch: currentPatch,
gitRef: currentGitRef,
origin: options.origin ?? "pi",
diffType: hasLocalAccess ? currentDiffType : undefined,
gitContext: hasLocalAccess ? options.gitContext : undefined,
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
sharingEnabled,
shareBaseUrl,
repoInfo,
isWSL: wslFlag,
...(options.agentCwd && { agentCwd: options.agentCwd }),
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
...(isPRMode && { prMetadata: prMeta, platformUser }),
2026-03-25 21:33:33 +01:00
...(isPRMode && initialViewedFiles.length > 0 && { viewedFiles: initialViewedFiles }),
...(currentError && { error: currentError }),
serverConfig: getServerConfig(gitUser),
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
});
} else if (url.pathname === "/api/diff/switch" && req.method === "POST") {
if (!hasLocalAccess) {
json(res, { error: "Not available without local file access" }, 400);
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
return;
}
try {
const body = await parseBody(req);
const newType = body.diffType as DiffType;
if (!newType) {
json(res, { error: "Missing diffType" }, 400);
return;
}
const defaultBranch = options.gitContext?.defaultBranch || "main";
const defaultCwd = options.gitContext?.cwd;
const result = await runGitDiff(newType, defaultBranch, defaultCwd);
currentPatch = result.patch;
currentGitRef = result.label;
currentDiffType = newType;
currentError = result.error;
json(res, {
rawPatch: currentPatch,
gitRef: currentGitRef,
diffType: currentDiffType,
...(currentError ? { error: currentError } : {}),
});
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to switch diff";
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/pr-context" && req.method === "GET") {
if (!isPRMode || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
try {
const context = await fetchPRContext(prRef);
json(res, context);
} catch (err) {
json(
res,
{
error:
err instanceof Error ? err.message : "Failed to fetch PR context",
},
500,
);
}
} else if (url.pathname === "/api/pr-action" && req.method === "POST") {
if (!isPRMode || !prMeta || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
try {
const body = await parseBody(req);
const fileComments = (body.fileComments as PRReviewFileComment[]) || [];
console.error(`[pr-action] ${body.action} with ${fileComments.length} file comment(s), headSha=${prMeta.headSha}`);
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
await submitPRReview(
prRef,
prMeta.headSha,
body.action as "approve" | "comment",
body.body as string,
fileComments,
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
);
console.error(`[pr-action] Success`);
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
json(res, { ok: true, prUrl: prMeta.url });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to submit PR review";
console.error(`[pr-action] Failed: ${message}`);
json(res, { error: message }, 500);
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
}
2026-03-25 21:33:33 +01:00
} else if (url.pathname === "/api/pr-viewed" && req.method === "POST") {
if (!isPRMode || !prMeta || !prRef) {
json(res, { error: "Not in PR mode" }, 400);
return;
}
if (prMeta.platform !== "github") {
json(res, { error: "Viewed sync only supported for GitHub" }, 400);
return;
}
const prNodeId = prMeta.prNodeId;
if (!prNodeId) {
json(res, { error: "PR node ID not available" }, 400);
return;
}
try {
const body = await parseBody(req);
await markPRFilesViewed(
prRef,
prNodeId,
body.filePaths as string[],
body.viewed as boolean,
);
json(res, { ok: true });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to update viewed state";
console.error("[plannotator] /api/pr-viewed error:", message);
json(res, { error: message }, 500);
2026-03-25 21:33:33 +01:00
}
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
} else if (url.pathname === "/api/file-content" && req.method === "GET") {
const filePath = url.searchParams.get("path");
if (!filePath) {
json(res, { error: "Missing path" }, 400);
return;
}
try {
validateFilePath(filePath);
} catch {
json(res, { error: "Invalid path" }, 400);
return;
}
const oldPath = url.searchParams.get("oldPath") || undefined;
if (oldPath) {
try {
validateFilePath(oldPath);
} catch {
json(res, { error: "Invalid path" }, 400);
return;
}
}
// Local mode first (matches Bun server priority)
if (hasLocalAccess && !isPRMode) {
const defaultBranch = options.gitContext?.defaultBranch || "main";
const defaultCwd = options.gitContext?.cwd;
const result = await getFileContentsForDiffCore(
reviewRuntime,
currentDiffType,
defaultBranch,
filePath,
oldPath,
defaultCwd,
);
json(res, result);
return;
}
// PR mode: fetch from platform API using merge-base/head SHAs
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
if (isPRMode && prRef && prMeta) {
try {
const oldSha = prMeta.mergeBaseSha ?? prMeta.baseSha;
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
const [oldContent, newContent] = await Promise.all([
fetchPRFileContent(prRef, oldSha, oldPath || filePath),
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
fetchPRFileContent(prRef, prMeta.headSha, filePath),
]);
json(res, { oldContent, newContent });
} catch (err) {
json(
res,
{
error:
err instanceof Error
? err.message
: "Failed to fetch file content",
},
500,
);
}
return;
}
json(res, { error: "No file access available" }, 400);
} else if (url.pathname === "/api/config" && req.method === "POST") {
try {
feat(review): diff display options with ConfigStore integration (#428) * feat(config): add DiffOptions to PlannotatorConfig with deep-merge support Extends the server-side config system to support diff display options namespaced under `diffOptions` in ~/.plannotator/config.json. The saveConfig deep-merge ensures partial writes (e.g. changing only overflow) don't clobber sibling keys. For provenance purposes, this commit was AI assisted. * feat(server): accept diffOptions in POST /api/config handlers All six server handlers (plan, review, annotate x Bun + Pi) now whitelist diffOptions alongside displayName, forwarding it to saveConfig for deep-merged disk persistence. For provenance purposes, this commit was AI assisted. * feat(config): register diff display settings with deep-merge write batching Adds 6 diff option settings to the ConfigStore registry (diffStyle, diffOverflow, diffIndicators, diffLineDiffType, diffShowLineNumbers, diffShowBackground), all synced to disk under the diffOptions namespace. Fixes write batching for nested server keys — replaces Object.assign with deepMerge so rapid changes to multiple diff options within the 300ms debounce window don't clobber each other. Includes legacy cookie migration for the old review-diff-style key. For provenance purposes, this commit was AI assisted. * feat(review): wire diff display options through to @pierre/diffs Migrates diffStyle from raw cookie storage to ConfigStore. Reads all 6 diff options via useConfigValue and forwards them to FileDiff: overflow, diffIndicators, lineDiffType, disableLineNumbers, disableBackground. Adds a Scroll/Wrap toolbar toggle alongside the existing Split/Unified toggle. Disables the custom resizable split dragger in wrap mode since Pierre manages its own grid layout. Fixes the unsafeCSS grid override to only target scroll mode, preventing per-character wrapping in split view. For provenance purposes, this commit was AI assisted. * feat(review): add Display tab to review-mode Settings dialog Adds a Display tab when Settings is in review mode, exposing all 6 diff options: Diff Style, Line Overflow, Change Indicators, Inline Diff Granularity, Show Line Numbers, and Show Diff Background. Changes take effect immediately and persist via ConfigStore (cookie + disk). Extracts reusable SegmentedControl and ToggleSwitch helpers for the review display controls. For provenance purposes, this commit was AI assisted. * chore: update bun.lock For provenance purposes, this commit was AI assisted. * fix(review): reapply search highlights after display option changes Add new diff display props to the search highlight and scroll-to-match effect dependency arrays so highlights are restored after Pierre re-renders. For provenance purposes, this commit was AI assisted.
2026-03-29 13:20:22 -07:00
const body = (await parseBody(req)) as { displayName?: string; diffOptions?: Record<string, unknown> };
const toSave: Record<string, unknown> = {};
if (body.displayName !== undefined) toSave.displayName = body.displayName;
if (body.diffOptions !== undefined) toSave.diffOptions = body.diffOptions;
if (Object.keys(toSave).length > 0) saveConfig(toSave as Parameters<typeof saveConfig>[0]);
json(res, { ok: true });
} catch {
json(res, { error: "Invalid request" }, 400);
}
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
} else if (url.pathname === "/api/image") {
handleImageRequest(res, url);
} else if (url.pathname === "/api/upload" && req.method === "POST") {
await handleUploadRequest(req, res);
} else if (url.pathname === "/api/agents" && req.method === "GET") {
json(res, { agents: [] });
} else if (url.pathname === "/api/git-add" && req.method === "POST") {
// Staging only available for local diff types that support it (not PR mode, not branch diffs).
// Worktree diff types use composite format "worktree:/path:uncommitted" — extract the base type.
const baseDiffType = currentDiffType.startsWith("worktree:")
? (parseWorktreeDiffType(currentDiffType)?.subType ?? currentDiffType)
: currentDiffType;
const canStage = baseDiffType === "uncommitted" || baseDiffType === "unstaged";
if (isPRMode || !canStage) {
json(res, { error: "Staging not available" }, 400);
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
return;
}
try {
const body = await parseBody(req);
const filePath = body.filePath as string | undefined;
if (!filePath) {
json(res, { error: "Missing filePath" }, 400);
return;
}
let cwd: string | undefined;
if (currentDiffType.startsWith("worktree:")) {
const parsed = parseWorktreeDiffType(currentDiffType);
if (parsed) cwd = parsed.path;
}
if (!cwd) {
cwd = options.gitContext?.cwd;
}
if (body.undo) {
await gitResetFileCore(reviewRuntime, filePath, cwd);
} else {
await gitAddFileCore(reviewRuntime, filePath, cwd);
}
json(res, { ok: true });
} catch (err) {
const message =
err instanceof Error ? err.message : "Failed to stage file";
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
json(res, { error: message }, 500);
}
} else if (url.pathname === "/api/draft") {
await handleDraftRequest(req, res, draftKey);
} else if (url.pathname === "/favicon.svg") {
handleFavicon(res);
} else if (await editorAnnotations.handle(req, res, url)) {
return;
} else if (await externalAnnotations.handle(req, res, url)) {
return;
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
} else if (await agentJobs.handle(req, res, url)) {
return;
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
} else if (aiEndpoints && url.pathname.startsWith("/api/ai/")) {
const handler = aiEndpoints[url.pathname];
if (handler) {
try {
const webReq = toWebRequest(req);
const webRes = await handler(webReq);
// Pipe Web Response → node:http response
const headers: Record<string, string> = {};
webRes.headers.forEach((v, k) => {
headers[k] = v;
});
res.writeHead(webRes.status, headers);
if (webRes.body) {
const nodeStream = Readable.fromWeb(webRes.body as any);
nodeStream.pipe(res);
} else {
res.end();
}
} catch (err) {
json(
res,
{ error: err instanceof Error ? err.message : "AI endpoint error" },
500,
);
}
return;
}
json(res, { error: "Not found" }, 404);
} else if (url.pathname === "/api/feedback" && req.method === "POST") {
try {
const body = await parseBody(req);
deleteDraft(draftKey);
resolveDecision({
approved: (body.approved as boolean) ?? false,
feedback: (body.feedback as string) || "",
annotations: (body.annotations as unknown[]) || [],
agentSwitch: body.agentSwitch as string | undefined,
});
json(res, { ok: true });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to process feedback";
json(res, { error: message }, 500);
}
} else {
html(res, options.htmlContent);
}
});
const { port, portSource } = await listenOnPort(server);
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
serverUrl = `http://localhost:${port}`;
const exitHandler = () => agentJobs.killAll();
process.once("exit", exitHandler);
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
if (options.onReady) {
options.onReady(serverUrl, isRemote, port);
}
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
return {
port,
portSource,
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
url: serverUrl,
isRemote,
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
waitForDecision: () => decisionPromise,
stop: () => {
feat: agentic review — background job runner with SSE streaming (#443) * feat(server): add agent job manager with process lifecycle and SSE streaming Introduces the backend for agentic review — a server-agnostic job runner that spawns agent processes, monitors their lifecycle via proc.exited, and broadcasts status updates over a dedicated SSE stream. New files: - packages/shared/agent-jobs.ts: runtime-agnostic types, SSE helpers, state machine - packages/server/agent-jobs.ts: Bun HTTP adapter with spawn/kill/SSE/REST routes Wired into the review server with late-bound serverUrl, killAll on stop and process exit for defense-in-depth cleanup. Capability detection via Bun.which() for Claude Code, Codex CLI, and shell. For provenance purposes, this commit was AI assisted. * feat(ui): add Review Agents tab with job management and live status Adds the client-side UI for agentic review: - useAgentJobs hook: SSE primary with polling fallback, capabilities fetch - AgentsTab: shared component with provider dropdown, job cards, kill controls - ReviewAgentsIcon: magnifying glass with cog icon - ReviewPanel: new "Review Agents" tab conditional on detected capabilities - App.tsx: initializes hook and passes props to ReviewPanel Jobs show live elapsed time, status badges, annotation counts per source, and expandable error details. Stub command (sleep 10-30s) for initial testing. For provenance purposes, this commit was AI assisted. * fix(server): narrow proc.stderr type to satisfy TS Bun types proc.stderr as ReadableStream | number. Add typeof guard to narrow before passing to Response constructor. For provenance purposes, this commit was AI assisted. * fix(server): prevent stdout deadlock, stderr pipe stall, and worktree cwd mismatch - Change stdout from "pipe" to "ignore" — agents post findings via the annotations API, not stdout. Unconsumed pipe buffer caused deadlock. - Drain stderr continuously instead of reading after exit — prevents pipe-full stall on chatty agents. - Make agent getCwd worktree-aware using the same currentDiffType check the AI endpoints use, so agents spawn in the correct checkout. - Exclude 'agents' tab from PR context fetch guard in ReviewPanel. For provenance purposes, this commit was AI assisted. * feat(pi): mirror agent-job endpoints in Pi review server Add apps/pi-extension/server/agent-jobs.ts — a Node.js port of the Bun agent-jobs handler using child_process.spawn, res.write() SSE, and execFileSync for capability detection. Wire into serverReview.ts: route delegation, killAll in stop(), process.on("exit") guard, worktree-aware getCwd, and serverUrl late-binding. Add agent-jobs to vendor.sh for shared type vendoring. For provenance purposes, this commit was AI assisted. * fix(agents): harden agent jobs — listener leak, provider allowlist, Windows support, docs - Use process.once instead of process.on to prevent exit listener accumulation - Validate provider against known capabilities before spawning (rejects unknown providers) - Use platform-aware which/where for CLI detection on Windows - Broadcast jobs:cleared event from kill-all endpoint (was dead client code) - Document all /api/agents/* endpoints in CLAUDE.md Review Server table For provenance purposes, this commit was AI assisted. * fix(agents): SSE ref reset, jobs:cleared divergence, exit listener cleanup - Reset receivedSnapshotRef/fallbackRef on re-mount so polling fallback activates correctly on subsequent tab switches - Remove jobs:cleared broadcast from kill-all — killAll() already fires individual job:completed events, so the UI shows status transitions instead of going blank - Store exit handler ref so stop() can removeListener, preventing accumulation in long-lived hosts (OpenCode, Pi) For provenance purposes, this commit was AI assisted.
2026-03-31 10:06:18 -07:00
process.removeListener("exit", exitHandler);
agentJobs.killAll();
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
aiSessionManager?.disposeAll();
aiRegistry?.disposeAll();
server.close();
// Invoke cleanup callback (e.g., remove temp worktree)
if (options.onCleanup) {
try {
const result = options.onCleanup();
if (result instanceof Promise) result.catch(() => {});
} catch { /* best effort */ }
}
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
},
};
}