Files
backnotprop__plannotator/apps/hook/server/index.ts
T

589 lines
18 KiB
TypeScript
Raw Normal View History

/**
* Plannotator CLI for Claude Code
*
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
* Supports five modes:
*
* 1. Plan Review (default, no args):
* - Spawned by ExitPlanMode hook
* - Reads hook event from stdin, extracts plan content
* - Serves UI, returns approve/deny decision to stdout
*
* 2. Code Review (`plannotator review`):
* - Triggered by /review slash command
* - Runs git diff, opens review UI
* - Outputs feedback to stdout (captured by slash command)
*
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
* 3. Annotate (`plannotator annotate <file.md>`):
* - Triggered by /plannotator-annotate slash command
* - Opens any markdown file in the annotation UI
* - Outputs structured feedback to stdout
*
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
* 4. Archive (`plannotator archive`):
* - Opens read-only browser for saved plan decisions
* - Lists plans from ~/.plannotator/plans/ with status badges
* - Done button closes the browser
*
* 5. Sessions (`plannotator sessions`):
* - Lists active Plannotator server sessions
* - `--open [N]` reopens a session in the browser
* - `--clean` removes stale session files
*
* Global flags:
* --browser <name> - Override which browser to open (e.g. "Google Chrome")
*
* Environment variables:
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
* PLANNOTATOR_REMOTE - Set to "1" or "true" for remote mode (preferred)
* PLANNOTATOR_PORT - Fixed port to use (default: random locally, 19432 for remote)
*/
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
import {
startPlannotatorServer,
handleServerReady,
} from "@plannotator/server";
import {
startReviewServer,
handleReviewServerReady,
} from "@plannotator/server/review";
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
import {
startAnnotateServer,
handleAnnotateServerReady,
} from "@plannotator/server/annotate";
import { getGitContext, runGitDiff } from "@plannotator/server/git";
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 { parsePRUrl, checkPRAuth, fetchPR, getCliName, getCliInstallUrl, getMRLabel, getMRNumberLabel, getDisplayRepo } from "@plannotator/server/pr";
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
import { writeRemoteShareLink } from "@plannotator/server/share-url";
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 { resolveMarkdownFile } from "@plannotator/shared/resolve-file";
import { registerSession, unregisterSession, listSessions } from "@plannotator/server/sessions";
import { openBrowser } from "@plannotator/server/browser";
import { detectProjectName } from "@plannotator/server/project";
refactor: shared feedback templates + preserve plan title on deny (#296) (#298) * refactor: shared feedback templates across all integrations The deny/feedback prompts sent to LLM agents were duplicated as inline string templates in hook, opencode-plugin, and pi-extension — each with different tone and framing. The hook's directive style (from #224) was the most effective at getting agents to address feedback. This extracts all feedback text into @plannotator/shared/feedback-templates and has every integration import from the single source of truth. Closes #215 follow-up (propagates fix to OpenCode and Pi). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: rewrite feedback template tests around contracts not implementation Tests now verify: cross-integration consistency, verbatim feedback preservation, empty input handling, and that approved messages don't contain directive language. Wording can change freely without breaking tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: instruct agent to preserve plan title on resubmission (#296) Version history slugs are derived from the plan's first # heading. When the agent renames the heading after a deny, the version chain breaks and the user loses diffs. The deny template now tells the agent not to change the title unless explicitly asked. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style: improve plan deny preamble readability Break the dense single-paragraph preamble into structured sections: verdict, directive, and rules list. Easier for agents to parse. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add missing @plannotator/shared workspace dependency Hook and OpenCode plugin imported from @plannotator/shared/feedback-templates without declaring it as a dependency. Worked locally but failed in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * revert: remove code review and annotate from shared templates Scope-crept into code review/annotate feedback which introduced a double heading regression and dropped integration-specific strings. Reverts those paths to their original inline strings; shared module now only covers plan deny feedback. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore Pi plan file hint and vendor template for source installs Add optional planFilePath to planDenyFeedback so Pi can tell the agent to read the plan file before editing. Check in a vendored copy of the template so Pi source installs work without running build:pi first. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 19:38:22 -07:00
import { planDenyFeedback } from "@plannotator/shared/feedback-templates";
import { findSessionLogsForCwd, resolveSessionLogByPpid, findSessionLogsByAncestorWalk, getLastRenderedMessage, type RenderedMessage } from "./session-log";
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
import { findCodexRolloutByThreadId, getLastCodexMessage } from "./codex-session";
import path from "path";
// Embed the built HTML at compile time
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
// @ts-ignore - Bun import attribute for text
import planHtml from "../dist/index.html" with { type: "text" };
const planHtmlContent = planHtml as unknown as string;
// @ts-ignore - Bun import attribute for text
import reviewHtml from "../dist/review.html" with { type: "text" };
const reviewHtmlContent = reviewHtml as unknown as string;
// Check for subcommand
const args = process.argv.slice(2);
// Global flag: --browser <name>
const browserIdx = args.indexOf("--browser");
if (browserIdx !== -1 && args[browserIdx + 1]) {
process.env.PLANNOTATOR_BROWSER = args[browserIdx + 1];
args.splice(browserIdx, 2);
}
// Ensure session cleanup on exit
process.on("exit", () => unregisterSession());
// Check if URL sharing is enabled (default: true)
const sharingEnabled = process.env.PLANNOTATOR_SHARE !== "disabled";
// Custom share portal URL for self-hosting
const shareBaseUrl = process.env.PLANNOTATOR_SHARE_URL || undefined;
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
// Paste service URL for short URL sharing
const pasteApiUrl = process.env.PLANNOTATOR_PASTE_URL || undefined;
if (args[0] === "sessions") {
// ============================================
// SESSION DISCOVERY MODE
// ============================================
if (args.includes("--clean")) {
// Force cleanup: list sessions (which auto-removes stale entries)
const sessions = listSessions();
console.error(`Cleaned up stale sessions. ${sessions.length} active session(s) remain.`);
process.exit(0);
}
const sessions = listSessions();
if (sessions.length === 0) {
console.error("No active Plannotator sessions.");
process.exit(0);
}
const openIdx = args.indexOf("--open");
if (openIdx !== -1) {
// Open a session in the browser
const nArg = args[openIdx + 1];
const n = nArg ? parseInt(nArg, 10) : 1;
const session = sessions[n - 1];
if (!session) {
console.error(`Session #${n} not found. ${sessions.length} active session(s).`);
process.exit(1);
}
await openBrowser(session.url);
console.error(`Opened ${session.mode} session in browser: ${session.url}`);
process.exit(0);
}
// List sessions as a table
console.error("Active Plannotator sessions:\n");
for (let i = 0; i < sessions.length; i++) {
const s = sessions[i];
const age = Math.round((Date.now() - new Date(s.startedAt).getTime()) / 60000);
const ageStr = age < 60 ? `${age}m` : `${Math.floor(age / 60)}h ${age % 60}m`;
console.error(` #${i + 1} ${s.mode.padEnd(9)} ${s.project.padEnd(20)} ${s.url.padEnd(28)} ${ageStr} ago`);
}
console.error(`\nReopen with: plannotator sessions --open [N]`);
process.exit(0);
} else if (args[0] === "review") {
// ============================================
// CODE REVIEW MODE
// ============================================
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
const urlArg = args[1];
const isPRMode = urlArg?.startsWith("http://") || urlArg?.startsWith("https://");
let rawPatch: string;
let gitRef: string;
let diffError: string | undefined;
let gitContext: Awaited<ReturnType<typeof getGitContext>> | undefined;
let prMetadata: Awaited<ReturnType<typeof fetchPR>>["metadata"] | undefined;
if (isPRMode) {
// --- PR Review Mode ---
const prRef = parsePRUrl(urlArg);
if (!prRef) {
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
console.error(`Invalid PR/MR URL: ${urlArg}`);
console.error("Supported formats:");
console.error(" GitHub: https://github.com/owner/repo/pull/123");
console.error(" GitLab: https://gitlab.com/group/project/-/merge_requests/42");
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
process.exit(1);
}
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
const cliName = getCliName(prRef);
const cliUrl = getCliInstallUrl(prRef);
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
try {
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 checkPRAuth(prRef);
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
} catch (err) {
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
const msg = err instanceof Error ? err.message : String(err);
if (msg.includes("not found") || msg.includes("ENOENT")) {
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
console.error(`${cliName === "gh" ? "GitHub" : "GitLab"} CLI (${cliName}) is not installed.`);
console.error(`Install it from ${cliUrl}`);
feat: Approve and review PR to github (#352) * Approve and review PR to github * fix: GitHub review improvements — multi-line ranges, own-PR detection, error handling - Add start_line/start_side to review payload for multi-line annotations - Detect current GitHub user and disable Approve on own PRs with tooltip - Fix loading state: approve button no longer shows "Approving..." during feedback - Fix empty submit: block Post Comments when no annotations and no comment - Fix Cmd+Enter in GitHub comment dialog - Fix completion screen text for GitHub mode ("submitted to GitHub") - Fix agent label fallback to "Your agent" instead of "OpenCode" - Improve gh-not-installed error message with install URL - Fix stale useCallback dependency array on handleGitHubAction Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): destination dropdown, icon components, and UI polish Replace Agent/GitHub toggle with a compact destination dropdown. Buttons stay consistent ("Send Feedback"/"Post Comments" + "Approve") with behavior routed by destination. Double-tap Option to toggle. - Add GitHubIcon, RepoIcon, PullRequestIcon components (currentColor) - Add repo/PR icons to editor header - Add keyboard hint in destination dropdown - Add double-Option shortcut to settings - Hide duplicate filename from Pierre diff header - Refine FileHeader typography (text-xs font-semibold, no mono) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: include VS Code editor annotations in GitHub PR reviews Editor annotations were silently dropped when submitting to GitHub. Now converts them to inline PR comments with selected text as context. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: rename visibility, own-PR keyboard guard, and editor annotation filtering - Keep data-prev-name visible in Pierre header for rename diffs - Block Cmd+Enter approve path for own PRs (was only blocked via mouse) - Filter editor annotations to diff files only to prevent GitHub API rejection Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-21 00:48:26 +01:00
} else {
console.error(msg);
}
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
process.exit(1);
}
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
console.error(`Fetching ${getMRLabel(prRef)} ${getMRNumberLabel(prRef)} from ${getDisplayRepo(prRef)}...`);
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
try {
const pr = await fetchPR(prRef);
rawPatch = pr.rawPatch;
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
gitRef = `${getMRLabel(prRef)} ${getMRNumberLabel(prRef)}`;
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
prMetadata = pr.metadata;
} catch (err) {
console.error(err instanceof Error ? err.message : "Failed to fetch PR");
process.exit(1);
}
} else {
// --- Local Review Mode ---
gitContext = await getGitContext();
const diffResult = await runGitDiff("uncommitted", gitContext.defaultBranch);
rawPatch = diffResult.patch;
gitRef = diffResult.label;
diffError = diffResult.error;
}
const reviewProject = (await detectProjectName()) ?? "_unknown";
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
// Start review server (even if empty - user can switch diff types in local mode)
const server = await startReviewServer({
rawPatch,
gitRef,
error: diffError,
origin: "claude-code",
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
diffType: isPRMode ? undefined : "uncommitted",
gitContext,
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
prMetadata,
sharingEnabled,
shareBaseUrl,
htmlContent: reviewHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleReviewServerReady(url, isRemote, port);
if (isRemote && sharingEnabled && rawPatch) {
await writeRemoteShareLink(rawPatch, shareBaseUrl, "review changes", "diff only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "review",
project: reviewProject,
startedAt: new Date().toISOString(),
feat: GitLab merge request review support (#364) * feat: GitLab merge request review support Add full GitLab MR review parity with existing GitHub PR review: - Auto-detect platform from URL (github.com vs any GitLab host) - Extract GitHub logic into pr-github.ts, new pr-gitlab.ts implementation - Widen PRRef/PRMetadata to discriminated unions for type safety - Dispatch functions route to correct platform implementation - Platform-aware UI labels (PR/MR, #/!, GitHub/GitLab icons) - Self-hosted GitLab support via --hostname flag - Normalize glab diff output to standard git format - Handle glab CLI differences (no --jq, Content-Type header for --input) - Defensive JSON parsing for GitLab context API responses Tested against gitlab.com with inline comments, multi-line ranges, approval, and PR context tabs (summary, comments, checks). For provenance purposes, this commit was AI assisted. * fix: correct GitLab enum mappings and add shared file path encoding - Map GitLab job statuses to UI-expected enums (failed→FAILURE, canceled→NEUTRAL) - Map GitLab detailed_merge_status to CLEAN/BLOCKED/BEHIND/DIRTY/UNKNOWN - Fix false approval state on repos without required approvers - Add shared encodeApiFilePath helper used by both GitHub and GitLab For provenance purposes, this commit was AI assisted. * fix: align panel headers and refine file tree selection style - Use shared --panel-header-h CSS variable for consistent header heights across file tree search, file header, and annotations panel - Update GitLab icon to use official tanuki SVG paths with currentColor - Replace solid primary fill on active file tree items with 30% tinted background for better readability and semantic color preservation For provenance purposes, this commit was AI assisted.
2026-03-22 10:22:36 -07:00
label: isPRMode ? `${getMRLabel(prMetadata!).toLowerCase()}-review-${getDisplayRepo(prMetadata!)}${getMRNumberLabel(prMetadata!)}` : `review-${reviewProject}`,
});
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
if (result.approved) {
console.log("Code review completed — no changes requested.");
} else {
console.log(result.feedback);
feat: PR review support via GitHub URL (#324) * feat(review): add runtime-agnostic PR provider Introduces `packages/shared/pr-provider.ts` with a `PRRuntime` interface (same pattern as ReviewGitRuntime in review-core.ts) and GitHub PR operations: URL parsing, auth check, diff/metadata fetching, and file content retrieval via `gh` CLI. `packages/server/pr.ts` is the Bun wrapper that pre-binds the runtime, matching the git.ts pattern. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): add PR mode to review server When `prMetadata` is provided to `startReviewServer`, the server enters PR mode: `/api/diff` includes PR metadata and omits gitContext, `/api/diff/switch` and `/api/git-add` return 400 (not applicable), and `/api/file-content` fetches from GitHub API using base/head SHAs instead of local git. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR review flow for Claude Code and OpenCode Detects URL argument in `/plannotator-review` command. When a GitHub PR URL is provided, fetches diff and metadata via `gh` CLI and starts the review server in PR mode. Local review mode is unchanged when no URL is passed. Updates slash command definitions to pass $ARGUMENTS through. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): PR metadata display in review UI Shows "PR Review" badge, PR title with link, and owner/repo in the header when reviewing a pull request. Diff switcher and staging controls auto-hide since gitContext is omitted in PR mode. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat(review): contextualized PR feedback for agent In PR mode, the feedback markdown now includes PR metadata (repo, number, title, branches, URL) so the agent has full context about the remote PR being reviewed. Removes the aggressive "address all of them" instruction in PR mode since the content is self-explanatory. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor(review): extract exportReviewFeedback + add tests Moves the pure feedback construction function from App.tsx to utils/exportFeedback.ts so it can be unit tested. Drops the unused `files` parameter. 11 tests covering local/PR headers, annotation grouping, sorting, file-scope ordering, and suggested code rendering. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): strengthen PR/local boundary tests Replaces shallow header checks with comprehensive boundary assertions: local mode must never contain PR-specific content (repo, URL, branches), PR mode must include all context fields and exclude the generic header. Covers null/undefined prMetadata edge cases. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test(review): remove redundant empty-annotations test Covered by the "no annotations: returns generic empty regardless of prMetadata" test which checks all three cases (no arg, null, PR mode). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(review): guard fetchPR, fix UTF-8 decoding, correct useCallback deps - Wrap fetchPR() in try/catch in both hook and OpenCode entry points so network/auth errors show a clean message instead of a stack trace - Replace atob() with Buffer.from() for UTF-8 correct base64 decoding of PR file content from GitHub API - Fix stale useCallback deps in handleCopyFeedback (files → prMetadata) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix(install): add $ARGUMENTS to review command for PR URL support Install scripts were writing the review slash command without $ARGUMENTS, so PR URLs passed to /plannotator-review were silently dropped. Also switches PS1 heredoc to single-quoted to prevent $ARGUMENTS from being expanded as a PowerShell variable. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * docs: add PR review support to docs and READMEs Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-18 06:01:40 -07:00
if (!isPRMode) {
console.log("\nThe reviewer has identified issues above. You must address all of them.");
}
}
process.exit(0);
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
} else if (args[0] === "annotate") {
// ============================================
// ANNOTATE MODE
// ============================================
let filePath = args[1];
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
if (!filePath) {
console.error("Usage: plannotator annotate <file.md>");
process.exit(1);
}
// Strip @ prefix if present (Claude Code file reference syntax)
if (filePath.startsWith("@")) {
filePath = filePath.slice(1);
}
// Use PLANNOTATOR_CWD if set (original working directory before script cd'd)
const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] File path arg: ${filePath}`);
}
// Smart file resolution: exact path, case-insensitive relative, or bare filename search
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 resolved = resolveMarkdownFile(filePath, projectRoot);
if (resolved.kind === "ambiguous") {
console.error(`Ambiguous filename "${resolved.input}" — found ${resolved.matches.length} matches:`);
for (const match of resolved.matches) {
console.error(` ${match}`);
}
process.exit(1);
}
if (resolved.kind === "not_found") {
console.error(`File not found: ${resolved.input}`);
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
process.exit(1);
}
const absolutePath = resolved.path;
console.error(`Resolved: ${absolutePath}`);
const markdown = await Bun.file(absolutePath).text();
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
const annotateProject = (await detectProjectName()) ?? "_unknown";
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
// Start the annotate server (reuses plan editor HTML)
const server = await startAnnotateServer({
markdown,
filePath: absolutePath,
origin: "claude-code",
sharingEnabled,
shareBaseUrl,
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
pasteApiUrl,
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
htmlContent: planHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(markdown, shareBaseUrl, "annotate", "document only").catch(() => {});
}
},
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "annotate",
project: annotateProject,
startedAt: new Date().toISOString(),
label: `annotate-${path.basename(absolutePath)}`,
});
feat: named image references and annotate command (#147) * feat: named image references and annotate command (#67, #109) Add human-readable names to image attachments throughout the annotation pipeline, and add a new `plannotator annotate <file.md>` command for annotating arbitrary markdown files. Image names: ImageAttachment type replaces plain string paths, upload endpoints return originalName, editable name inputs under thumbnails, [name] path format in exported feedback, backward-compatible sharing. Annotate command: new server module reusing plan editor HTML with mode:"annotate", CLI subcommand, slash commands for Claude Code and OpenCode, annotate mode UI (hides Approve, shows Send Annotations). Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * refactor: move image name input to ImageAnnotator screen The name input now appears on the full-screen annotator modal that opens immediately when uploading/pasting an image, pre-populated from the filename. Removes the disruptive inline name editing from thumbnails. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * fix: stale closure in paste handler, update CLAUDE.md for new features Fix race condition where globalAttachments was captured as empty array in the paste event listener (missing dependency). Also update CLAUDE.md to document ImageAttachment type, annotate server/flow, updated sharing format with image support, and new slash commands. Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-12 20:23:49 -08:00
// Wait for user feedback
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output feedback (captured by slash command)
console.log(result.feedback || "No feedback provided.");
process.exit(0);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
} else if (args[0] === "annotate-last" || args[0] === "last") {
// ============================================
// ANNOTATE LAST MESSAGE MODE
// ============================================
const projectRoot = process.env.PLANNOTATOR_CWD || process.cwd();
const codexThreadId = process.env.CODEX_THREAD_ID;
const isCodex = !!codexThreadId;
let lastMessage: RenderedMessage | null = null;
if (codexThreadId) {
// Codex path: find rollout by thread ID
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Codex detected, thread ID: ${codexThreadId}`);
}
const rolloutPath = findCodexRolloutByThreadId(codexThreadId);
if (rolloutPath) {
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Rollout: ${rolloutPath}`);
}
const msg = getLastCodexMessage(rolloutPath);
if (msg) {
lastMessage = { messageId: codexThreadId, text: msg.text, lineNumbers: [] };
}
}
} else {
// Claude Code path: resolve session log
//
// Strategy (most precise → least precise):
// 1. PPID session metadata: ~/.claude/sessions/<ppid>.json gives us the
// exact sessionId and original cwd. Deterministic, O(1), no scanning.
// 2. CWD slug match: existing behavior — works when the shell CWD hasn't
// changed from the session's project directory.
// 3. Ancestor walk: walk up the directory tree trying parent slugs. Handles
// the common case where the user `cd`'d deeper into a subdirectory.
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Project root: ${projectRoot}`);
console.error(`[DEBUG] PPID: ${process.ppid}`);
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
}
/** Try each log path, return the first that yields a message. */
function tryLogCandidates(label: string, getPaths: () => string[]): void {
if (lastMessage) return;
const paths = getPaths();
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] ${label}: ${paths.length ? paths.join(", ") : "(none)"}`);
}
for (const logPath of paths) {
lastMessage = getLastRenderedMessage(logPath);
if (lastMessage) return;
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
}
}
// 1. Try PPID-based session metadata (most reliable)
const ppidLog = resolveSessionLogByPpid();
tryLogCandidates("PPID session metadata", () => ppidLog ? [ppidLog] : []);
// 2. Fall back to CWD slug match
tryLogCandidates("CWD slug match", () => findSessionLogsForCwd(projectRoot));
// 3. Fall back to ancestor directory walk
tryLogCandidates("Ancestor walk", () => findSessionLogsByAncestorWalk(projectRoot));
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
}
if (!lastMessage) {
console.error("No rendered assistant message found in session logs.");
process.exit(1);
}
if (process.env.PLANNOTATOR_DEBUG) {
console.error(`[DEBUG] Found message ${lastMessage.messageId} (${lastMessage.text.length} chars)`);
}
const annotateProject = (await detectProjectName()) ?? "_unknown";
const server = await startAnnotateServer({
markdown: lastMessage.text,
filePath: "last-message",
origin: isCodex ? "codex" : "claude-code",
mode: "annotate-last",
sharingEnabled,
shareBaseUrl,
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
pasteApiUrl,
feat: /plannotator-last — annotate the last agent message (#325) * feat: add /plannotator-last command to annotate last assistant message Adds a new slash command that extracts the last rendered assistant message from Claude Code's session log and opens it in the annotation UI. Session log parser (apps/hook/server/session-log.ts): - Parses Claude Code JSONL logs at ~/.claude/projects/{slug}/*.jsonl - Finds the last assistant message.id with text content blocks - Skips noise entries (progress, system, file-history-snapshot, queue-operation) - Filters system-generated user messages by prefix to avoid false turn boundaries - Walks backward through empty turns when back-to-back user messages exist - No anchoring — reads from end of log since <command-message> isn't written until after the binary completes New files: - apps/hook/commands/plannotator-last.md — slash command definition - apps/hook/server/session-log.ts — Claude-Code-specific log parser - apps/hook/server/session-log.test.ts — 30 tests covering streaming chunks, tool call turns, sub-agent noise, stop hooks, thinking blocks, and edge cases Modified: - apps/hook/server/index.ts — annotate-last subcommand Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: remove 3 redundant real-world scenario tests These duplicated coverage already provided by focused unit tests: - "full conversation" → covered by "grabs last message.id in multi-tool turn" - "stop hook interrupted" → covered by "skips progress and system noise" - "long tool-only sequence" → covered by "skips tool-only assistant entries" Kept the thinking block test (unique coverage). 27 tests remain. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last command to Pi extension Uses Pi's session manager API to find the last assistant message — walks backward through ctx.sessionManager.getEntries(), finds the last entry with role "assistant" and text content, opens it in the annotation UI. Reuses existing isAssistantMessage(), getTextContent(), startAnnotateServer(), and runBrowserReview() from the extension. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add /plannotator-last to OpenCode plugin + extract command handlers Adds annotate-last command that fetches session messages via client.session.messages(), finds the last assistant message with text parts, and opens it in the annotation UI. Refactors command handling: extracts review, annotate, and annotate-last handlers from the inline event hook into commands.ts module. Reduces index.ts by ~120 lines and makes adding future commands cleaner. New files: - apps/opencode-plugin/commands.ts — extracted command handlers - apps/opencode-plugin/commands/plannotator-last.md — command metadata Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: context-aware UI labels for annotate-last mode Adds "annotate-last" mode to the annotate server, passed through to the UI via /api/plan response. The editor uses this to show "Copy message" instead of "Copy plan", and "annotations on the message" in the completion overlay. - packages/server/annotate.ts: new `mode` option on AnnotateServerOptions - packages/editor/App.tsx: annotateSource state derived from mode - packages/ui/components/Viewer.tsx: copyLabel prop for button text - All three harnesses pass mode: "annotate-last" in their callers Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * feat: add Codex support to annotate-last command Detects Codex via CODEX_THREAD_ID env var (injected by Codex into every spawned process). Uses the thread ID to find the rollout file in ~/.codex/sessions/, parses the Codex rollout JSONL format to extract the last assistant message. Also adds `plannotator last` alias for shorter usage in Codex bang commands (!plannotator last). New files: - apps/hook/server/codex-session.ts — Codex rollout parser - apps/hook/server/codex-session.test.ts — 9 tests Modified: - apps/hook/server/index.ts — Codex detection + `last` alias Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: context-aware feedback title + top spacing for paragraph-first content - exportAnnotations now accepts a title param: "Message Feedback" for annotate-last, "File Feedback" for file annotation, "Plan Feedback" for plan review (default) - Adds top spacer when content starts with a paragraph (not a heading) and has no frontmatter, fixing tight spacing in annotate-last mode Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * chore: add sandbox scripts for Pi and Codex testing - sandbox-pi.sh: builds extension, creates temp project, installs via `pi install`, launches Pi with sample files - sandbox-codex.sh: compiles binary, creates temp project, launches Codex. Test with `!plannotator last` Both follow the same pattern as sandbox-opencode.sh. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add hook build step to opencode sandbox script The opencode build copies HTML from hook/dist/ — without building hook first, the sandbox could use stale HTML. Pi and Codex sandboxes already had this step. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remove command body from plannotator-last to prevent agent response The .md body was being sent to the agent as a prompt, causing it to respond with "Opening annotation UI..." before the event handler could fetch messages. That response became the "last message" instead of the actual one. Empty body = agent stays silent, event handler intercepts. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: use command.execute.before hook for OpenCode annotate-last Moves plannotator-last from the passive event hook to the command.execute.before hook. This intercepts the command before the agent sees it, clears output.parts so the agent stays silent, fetches session messages, opens the annotation UI, then sends feedback via client.session.prompt() — same pattern as review/annotate. Previously the agent would respond to the command body before the event handler could fetch messages, polluting the session history. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add Codex to origin type and agent name mapping Origin "codex" was falling through to the default "Coding Agent" label. Added "codex" to the origin union type across annotate server, editor, and removed the `as any` cast in the hook. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: remote share link, plan-specific prose, and codex type unions - Add writeRemoteShareLink to annotate-last onReady callback so remote sessions get a reachable URL - Add subject parameter to exportAnnotations so feedback says "message" or "file" instead of "plan" when appropriate - Add 'codex' to origin type unions in useAgents, Settings, UpdateBanner, and App.tsx fetch handler Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: correct JSDoc for projectSlugFromCwd (leading dash is kept, not stripped) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * refactor: use RenderedMessage type instead of inline structural type Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-17 23:49:34 -07:00
htmlContent: planHtmlContent,
onReady: async (url, isRemote, port) => {
handleAnnotateServerReady(url, isRemote, port);
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(lastMessage.text, shareBaseUrl, "annotate", "message only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "annotate",
project: annotateProject,
startedAt: new Date().toISOString(),
label: `annotate-last`,
});
const result = await server.waitForDecision();
await Bun.sleep(1500);
server.stop();
console.log(result.feedback || "No feedback provided.");
process.exit(0);
feat: plan archive browser (#369) * feat: plan archive browser with in-session sidebar tab (#362) Add `plannotator archive` subcommand and archive sidebar tab for browsing saved plan decisions from ~/.plannotator/plans/. Plans show approved/denied badges and timestamps. In-session mode uses the linked doc overlay pattern so users can reference old plans while reviewing a current one. - New archive server (packages/server/archive.ts) following annotate pattern - New ArchiveBrowser sidebar component, reusable in both contexts - Archive listing/parsing functions in storage.ts (reads decision snapshots) - Archive endpoints on plan server for in-session use (/api/archive/plans) - Remove dead "Other Plans" UI, projectPlans state, /api/plan/history endpoint - Fix resize handle touch area covering scrollbars in sidebar/main content - Fix sidebar tab bar overflow when narrow For provenance purposes, this commit was AI assisted. * fix: code quality sweep for plan archive - Remove `as any` cast: add "archive" to SessionInfo.mode union - Replace inline import() type with proper import for ArchivedPlan - Replace any[] with ArchivedPlan[] in fetch response types - Fix infinite re-fetch when archive is empty (use hasFetched ref) - Cache archive plan list in plan server (avoid re-scanning filesystem) - Document ResizeHandle side prop behavior - Remove redundant comment on Viewer archiveInfo prop For provenance purposes, this commit was AI assisted. * chore: remove dead marketing components Step.astro and Landing.astro are unused — landing page inlines step markup and pages use Base.astro directly. For provenance purposes, this commit was AI assisted. * fix: address code review findings for plan archive - Path traversal: use resolve() + trailing separator guard (matches reference-handlers.ts) - Thread customPath into in-session archive endpoints via query param - Sort same-day archive entries by mtime instead of title - Clear selectedArchiveFile on linked doc back to prevent badge leak - Hide archive tab in annotate mode (server doesn't serve those endpoints) - Add targetTab param to useLinkedDoc.open() to preserve calling sidebar tab - Replace mutable render variable with index-based date grouping For provenance purposes, this commit was AI assisted. * refactor: collapse standalone archive server into plan server Delete packages/server/archive.ts (187 lines) — nearly all duplicated from the plan server. Add mode:"archive" option to startPlannotatorServer instead. Fixes two bugs from code review: - handleArchiveCopy now splits on "# Plan Feedback" marker instead of bare "---", preventing truncation at horizontal rules in plan content - customPath support works in standalone archive mode (was only working in-session because the standalone server never received it) For provenance purposes, this commit was AI assisted. * refactor: extract useArchive hook from App.tsx Move archive state (archiveMode, plans, selectedFile, isLoading) and handlers (select, fetchPlans, done, copy) into a dedicated useArchive hook. Reduces App.tsx by ~75 lines and makes the archive feature self-contained. For provenance purposes, this commit was AI assisted. * feat: Pi archive parity + eliminate server duplication Move runtime-agnostic storage, draft, and project functions from packages/server/ to packages/shared/ — eliminating ~250 lines of duplicated code in Pi's server.ts. Server package becomes thin re-exports, preserving all existing import paths. Add archive mode to Pi's plan review server (mode, routes, waitForDone) and register /plannotator-archive command in the Pi extension. Consolidate ArchivedPlan type to single definition in shared/storage.ts. Simplify archive copy to include full content with feedback. For provenance purposes, this commit was AI assisted. * fix: drop -core suffix from Pi shared copies The -core suffix broke cross-file imports — storage.ts imports from ./project which didn't resolve to project-core.ts. Using the original filenames (no collision) lets relative imports work naturally. For provenance purposes, this commit was AI assisted. * fix: archive custom path bugs, disable sharing, update docs - Normalize planDir via resolve() in getPlanDir() to handle relative paths and trailing slashes in the path traversal guard - Re-fetch archive plans client-side with cookie-backed customPath so standalone archive respects the user's configured save location - Disable sharing in archive mode (read-only viewer, no need) - Remove dead /api/plan/history endpoint and listProjectPlans import from Pi extension - Remove dead /api/plan/history mock from dev-mock-api - Update CLAUDE.md and AGENTS.md: add archive flow, archive API endpoints, shared package structure, correct storage location, sidebar tab count, remove stale /api/plan/history references - Update hook server docstring from four to five modes For provenance purposes, this commit was AI assisted. * fix: empty archive shows demo content, stale viewer after customPath fetch - Clear demo markdown when archive opens with no plans (plan: "" was falsy, so setMarkdown was never called) - Remove redundant fetchPlans() from archive init — server already sends archivePlans in initial response - After fetchPlans() resolves with customPath results, auto-select and load the first plan into the viewer - Remove dead listProjectPlans re-export from server barrel For provenance purposes, this commit was AI assisted. * refactor: gitignore Pi shared copies, add @generated headers Pi's copied .ts files (storage, draft, project, feedback-templates, review-core) are build artifacts generated from packages/shared/. They looked like editable source files, leading to confusion about which file to edit. Now gitignored like the HTML copies, with @generated headers prepended by the build script. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in CI before tests The Pi .ts copies are now gitignored build artifacts. CI needs to generate them before running tests since server.test.ts transitively imports them via server.ts. For provenance purposes, this commit was AI assisted. * fix: generate Pi shared copies in release pipeline test job Same fix as test.yml — the Pi .ts copies are gitignored, so the test job in the release pipeline also needs to generate them before bun test. For provenance purposes, this commit was AI assisted. * fix: use block scalar in CI workflow to avoid YAML parse error The inline `run:` had a colon in the printf string that YAML interpreted as a mapping key. Switch to `run: |` block scalar. For provenance purposes, this commit was AI assisted.
2026-03-23 11:31:38 -07:00
} else if (args[0] === "archive") {
// ============================================
// ARCHIVE BROWSER MODE
// ============================================
const archiveProject = (await detectProjectName()) ?? "_unknown";
const server = await startPlannotatorServer({
plan: "",
origin: "claude-code",
mode: "archive",
sharingEnabled,
shareBaseUrl,
htmlContent: planHtmlContent,
onReady: (url, isRemote, port) => {
handleServerReady(url, isRemote, port);
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "archive",
project: archiveProject,
startedAt: new Date().toISOString(),
label: `archive-${archiveProject}`,
});
await server.waitForDone!();
await Bun.sleep(500);
server.stop();
process.exit(0);
} else {
// ============================================
// PLAN REVIEW MODE (default)
// ============================================
// Read hook event from stdin
const eventJson = await Bun.stdin.text();
let planContent = "";
let permissionMode = "default";
try {
const event = JSON.parse(eventJson);
planContent = event.tool_input?.plan || "";
permissionMode = event.permission_mode || "default";
} catch {
console.error("Failed to parse hook event from stdin");
process.exit(1);
}
if (!planContent) {
console.error("No plan content in hook event");
process.exit(1);
}
const planProject = (await detectProjectName()) ?? "_unknown";
// Start the plan review server
const server = await startPlannotatorServer({
plan: planContent,
origin: "claude-code",
permissionMode,
sharingEnabled,
shareBaseUrl,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
pasteApiUrl,
htmlContent: planHtmlContent,
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
onReady: async (url, isRemote, port) => {
handleServerReady(url, isRemote, port);
Add short URL sharing via paste service to fix URL truncation (#188) * Add short URL sharing via paste service to fix URL truncation on Slack/messaging apps Share URLs for large plans can be 10-40KB+ because the entire plan + annotations are compressed into the URL hash. Services like Slack, WhatsApp, and Twitter truncate these URLs, making shared plans unviewable (related: #142). This adds an optional paste-service backend that stores compressed payloads and returns short ~60-char URLs (e.g. share.plannotator.ai/p/aBcDeFgH). Changes: - Add Cloudflare Worker paste service (apps/paste-worker/) with KV storage and 90-day TTL for stored plans - Add createShortShareUrl() and loadFromPasteId() to sharing utils - Update useSharing hook to auto-generate short URLs with 1s debounce - Update ExportModal to show short URL as primary copy target with full hash URL as backup - Portal automatically supports /p/<id> paths via useSharing hook - Fully backward compatible: hash-based URLs continue to work unchanged - Graceful degradation: falls back to hash URLs if paste service is unavailable * Fix critical bugs found during code review of short URL feature - Worker: return only { id } so client constructs URL with its own shareBaseUrl (fixes self-hosted deployments) - importFromShareUrl: handle /p/<id> short URLs in addition to hash URLs (fixes teammate import via short links) - Anchor /p/<id> regex with ^ to prevent false matches on nested paths - Pass shareBaseUrl to loadFromPasteId (was always defaulting) - replaceState preserves base path instead of hardcoding / - Clear stale shortShareUrl immediately on debounce to prevent showing outdated link during the 1s delay - Add shareBaseUrl to dependency arrays for loadFromHash and importFromShareUrl callbacks - Remove unused url field fallback from paste API response parsing * Fix pasteApiUrl/shareBaseUrl confusion and add remote session share URLs Bug fix (addresses @backnotprop's code review): - useSharing hook now accepts separate `pasteApiUrl` parameter instead of incorrectly passing `shareBaseUrl` to `loadFromPasteId`. These are different domains (share portal vs paste backend). When omitted, the default `https://paste.plannotator.ai` is used correctly. - Fixed in all three call sites: loadFromHash, importFromShareUrl, and generateShortUrl (via createShortShareUrl options). Remote session share URLs (implements #192): - When running on a remote instance (SSH, devcontainer), Plannotator now generates a share.plannotator.ai URL and prints it to stderr so the user can open the plan review in their local browser. - Works for all three modes: plan review, code review, and annotate. - Uses the same deflate-raw + base64url encoding as the client. - Fails silently if URL generation fails — port forwarding still works. - New server utility: packages/server/share-url.ts * Address code review findings: fix spread limit, CORS, deps array - share-url.ts: Replace btoa(String.fromCharCode(...compressed)) with a loop to avoid RangeError on plans >65K compressed bytes - share-url.ts: Add cross-reference comment noting the server-side SharePayload is an intentional subset of the canonical UI type - paste-worker: Only return CORS headers for allowed origins; disallowed origins get no CORS headers instead of misleading partial headers - useSharing.ts: Remove unused shareBaseUrl from loadFromHash dependency array (loadFromHash only uses pasteApiUrl, not shareBaseUrl) * Restructure paste service with pluggable storage, fix consent flow and security issues Replaces monolithic paste-worker with multi-target paste-service architecture: - Core logic (handler, storage interface, CORS) separated from deployment targets - Filesystem store (self-hosted), KV store (Cloudflare), S3 stub (future) - Bun binary target + Cloudflare Worker target - Fix auto-upload removed: short URLs only created on explicit user click - Clear stale short URL state when content changes - Fix require('fs') in ESM module, add path-traversal guard in FsPasteStore - Return 400 (not 500) for malformed JSON in both targets - Fix compress() spread limit for large plans - Updated docs: self-hosting guide, sharing guide, env vars, API endpoints Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Simplify paste service: extract shared router, remove TOCTOU patterns - Extract duplicated HTTP routing from bun.ts and cloudflare.ts into handleRequest() in core/handler.ts — targets are now thin wrappers - Move ID_PATTERN regex to core (was duplicated in both targets) - Remove existsSync guard before mkdirSync({recursive:true}) in fs.ts - Remove file.exists() check before file.json() in fs.ts get() — the try/catch already handles missing files - Extract DEFAULT_SHARE_BASE constant in sharing.ts (was hardcoded twice) Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Deduplicate compression, image parsing, and remote share URL logic - Create packages/shared/ with compress/decompress (single source of truth) — both @plannotator/server and @plannotator/ui import from here - Export parseShareableImages from sharing.ts, remove duplicate parseGlobalAttachments from useSharing.ts - Extract writeRemoteShareLink() helper in share-url.ts, replace 3 near-identical blocks in apps/hook/server/index.ts Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> * Fix modulo bias in paste ID generation and remove nonexistent doc artifacts - Use rejection sampling in generateId() to eliminate modulo bias (bytes >= 248 discarded, uniform distribution over 62 chars) - Remove references to install-paste.sh and Docker image that don't exist yet; point self-hosting docs to GitHub Releases binaries Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com> --------- Co-authored-by: Michael Ramos <mdramos8@gmail.com> Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-01 12:25:55 +05:30
if (isRemote && sharingEnabled) {
await writeRemoteShareLink(planContent, shareBaseUrl, "review the plan", "plan only").catch(() => {});
}
},
});
registerSession({
pid: process.pid,
port: server.port,
url: server.url,
mode: "plan",
project: planProject,
startedAt: new Date().toISOString(),
label: `plan-${planProject}`,
});
// Wait for user decision (blocks until approve/deny)
const result = await server.waitForDecision();
// Give browser time to receive response and update UI
await Bun.sleep(1500);
// Cleanup
server.stop();
// Output JSON for PermissionRequest hook decision control
if (result.approved) {
// Build updatedPermissions to preserve the current permission mode
const updatedPermissions = [];
if (result.permissionMode) {
updatedPermissions.push({
type: "setMode",
mode: result.permissionMode,
destination: "session",
});
}
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "allow",
...(updatedPermissions.length > 0 && { updatedPermissions }),
},
Fix/devcontainer & plan auto switching (opencode) (#31) * Refactor: shared server package with PLANNOTATOR_REMOTE env var - Create packages/server/ with shared server implementation - Add PLANNOTATOR_REMOTE=1 env var for devcontainer/SSH mode - Deprecate SSH_CONNECTION detection (still works with warning) - Both Claude Code and OpenCode now use identical server logic - OpenCode gains Obsidian/Bear integrations and remote detection - Update documentation with environment variables section Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Remove PLANNOTATOR_ORIGIN env var, fix onReady callback timing - Remove PLANNOTATOR_ORIGIN hack from Claude Code hook (hardcode "claude-code") - Fix onReady callback to pass port directly (was referencing undefined server) - Create tests/manual/test-server.ts for testing either origin - Update test-hook-2.sh to use new test server with opencode origin 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer test setup, reduce logging verbosity - Add tests/devcontainer/ with devcontainer.json for testing remote mode - Add tests/opencode-local/ for local OpenCode testing - Update package.json build script for proper bundling - Remove verbose multi-line error messages, keep useful errors - Clean up unused deprecationWarned variable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Add devcontainer support and documentation - Add PLANNOTATOR_REMOTE env var for container/remote detection - Remove console logging (silent operation) - Add devcontainer.md with full setup instructions - Add devcontainer section to OpenCode plugin README - Add port-only test setup to reproduce common misconfiguration - Update test devcontainers to forward port 4096 for opencode web - Bump version to 0.4.1 Fixes #27 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Update CLAUDE.md: legacy SSH detection, not deprecated Removed incorrect mention of deprecation warning - SSH_TTY/SSH_CONNECTION detection is silent by design. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> * Fix OpenCode agent switching after plan approval After approving a plan, the conversation context stayed in "plan" mode even though the TUI showed "build". This caused edits to fail because the plan agent has edit permissions denied. The fix uses session.prompt() to inject a message with agent: "build", which triggers a new agentic loop with proper build agent permissions. Fixes #29 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-06 14:25:19 -08:00
},
})
);
} else {
console.log(
JSON.stringify({
hookSpecificOutput: {
hookEventName: "PermissionRequest",
decision: {
behavior: "deny",
refactor: shared feedback templates + preserve plan title on deny (#296) (#298) * refactor: shared feedback templates across all integrations The deny/feedback prompts sent to LLM agents were duplicated as inline string templates in hook, opencode-plugin, and pi-extension — each with different tone and framing. The hook's directive style (from #224) was the most effective at getting agents to address feedback. This extracts all feedback text into @plannotator/shared/feedback-templates and has every integration import from the single source of truth. Closes #215 follow-up (propagates fix to OpenCode and Pi). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * test: rewrite feedback template tests around contracts not implementation Tests now verify: cross-integration consistency, verbatim feedback preservation, empty input handling, and that approved messages don't contain directive language. Wording can change freely without breaking tests. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: instruct agent to preserve plan title on resubmission (#296) Version history slugs are derived from the plan's first # heading. When the agent renames the heading after a deny, the version chain breaks and the user loses diffs. The deny template now tells the agent not to change the title unless explicitly asked. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * style: improve plan deny preamble readability Break the dense single-paragraph preamble into structured sections: verdict, directive, and rules list. Easier for agents to parse. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: add missing @plannotator/shared workspace dependency Hook and OpenCode plugin imported from @plannotator/shared/feedback-templates without declaring it as a dependency. Worked locally but failed in CI. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * revert: remove code review and annotate from shared templates Scope-crept into code review/annotate feedback which introduced a double heading regression and dropped integration-specific strings. Reverts those paths to their original inline strings; shared module now only covers plan deny feedback. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> * fix: restore Pi plan file hint and vendor template for source installs Add optional planFilePath to planDenyFeedback so Pi can tell the agent to read the plan file before editing. Check in a vendored copy of the template so Pi source installs work without running build:pi first. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-15 19:38:22 -07:00
message: planDenyFeedback(result.feedback || "", "ExitPlanMode"),
},
},
})
);
}
process.exit(0);
}