repositories / pi-ext

pi-ext

bugabingas pi extensions

owned by bugabinga

docs(diff-review): remove plan

3661a5d4213e3f1048d948040408019de19ceb40

Oliver Jan Krylow <oliver@bugabinga.net> ·

unsigned

Browse filesCompare with HEAD

Changed files (1)

+0 / −845 text lines

Diff layout

extensions/diff-review/PLAN.md

Deleted
deleted file mode 100644

+0 / −845 text lines

1# diff-review plan
2
3Interactive browser review workflow for Pi using Pierre.
4
5## Goal
6
7Add `/diff-review`:
8collect a git diff, open a tokenized localhost browser UI powered by
9`@pierre/diffs` + `@pierre/trees`, let user annotate exact changed lines, then
10persist structured findings and send a user message back to Pi so the agent
11proposes a fix plan before editing.
13## Verdict-driven constraints
15These are blockers, not polish:
17- browser bundle lifecycle must be enforced before command starts
18- Pierre APIs must match installed published typings, not repo assumptions
19- browser opener must be explicit + safe with manual fallback
20- command must never wait forever:
21 timeout, heartbeat, abort, cancel command, shared cleanup
22- static server must serve complete production output dir, not only `app.js`
23- browser smoke test must validate production bundle in real browser before v1
24 is considered done
26## Workspace conventions from `AGENTS.md`
28- New extension path is `agent/extensions/diff-review/`.
29- Required first files:
30 1. `agent/extensions/diff-review/package.json`
31 2. `agent/extensions/diff-review/index.ts`
32 3. run `bun install` after structural/package changes
33- `package.json` must follow workspace template:
34 `@bugabinga/pi-ext-diff-review`, `private`, `type:
35 "module"`, `main:
36 "index.ts"`.
37- Add only deps actually imported by this extension.
38- Pi packages (`@earendil-works/*`) go in `peerDependencies`.
39- Do not import from any `@bugabinga/pi-ext-*` extension; copy local patterns
40 instead.
41- TS source imports local files with `.js` specifiers, matching existing
42 extensions.
43- Use existing extension patterns:
44 - constants in `constants.ts` (`EXTENSION_ID`, command names, status ids)
45 - types in `types.ts`
46 - session helpers in `session-state.ts`, following `q/session-state.ts`
47 - `index.ts` stays orchestration-only where possible
49## Verified research
51### Pi extension APIs
53- Extension entrypoint:
54 `agent/extensions/diff-review/index.ts` exporting `default function (pi:
55 ExtensionAPI)`.
56- Slash command via `pi.registerCommand("diff-review", { handler })`.
57- Command handler should:
58 - require `ctx.hasUI`
59 - `await ctx.waitForIdle()` before starting
60 - block until browser submit/cancel/timeout/abort
61 - call `pi.sendUserMessage([{ type:
62 "text", text:
63 markdown }])` after submit
64- Persist branch-local state via custom session entries:
65 - use `pi.appendEntry(customType, data)` when entry id is not needed
66 - use local helper with `ExtensionContext["sessionManager"]` cast when entry
67 id is needed, matching `q/session-state.ts`
68- Restore state on `session_start` by scanning `ctx.sessionManager.getBranch()`
69 and selecting entries where:
70 - `entry.type === "custom"`
71 - `entry.customType === "diff-review"`
72- Clean up active localhost server on `session_shutdown`.
73- No verified generic Pi URL-open API found.
74 Implement platform opener fallback in extension.
76### Verified `@pierre/diffs@1.1.22` typings
78Installed package inspected from npm tarball under
79`~/.pi/research/extracts/pierre-npm/diffs`.
81Relevant exact API:
83```ts
84import {
85 FileDiff,
86 parsePatchFiles,
87 type DiffLineAnnotation,
88 type FileDiffMetadata,
89 type ParsedPatch,
90 type SelectedLineRange,
91} from "@pierre/diffs";
93const patches: ParsedPatch[] = parsePatchFiles(diffText, "diff-review", true);
95const instance = new FileDiff<{ findingId: string }>({
96 theme: { dark: "pierre-dark", light: "pierre-light" },
97 diffStyle: "split",
98 overflow: "scroll",
99 enableLineSelection: true,
100 enableGutterUtility: true,
101 lineHoverHighlight: "both",
102 onLineSelected(range: SelectedLineRange | null) {},
103 onGutterUtilityClick(range: SelectedLineRange) {},
104 renderAnnotation(annotation: DiffLineAnnotation<{ findingId: string }>) {
105 return document.createElement("div");
106 },
107});
109const ok: boolean = instance.render({
110 fileDiff,
111 containerWrapper,
112 lineAnnotations,
113});
115instance.setLineAnnotations(lineAnnotations);
116instance.setSelectedLines({ start, end, side: "additions", endSide: "additions" });
117instance.rerender();
118instance.cleanUp();
119```
121`FileDiff.render(...)` accepts:
123```ts
124{
125 fileDiff?: FileDiffMetadata;
126 oldFile?: FileContents;
127 newFile?: FileContents;
128 forceRender?: boolean;
129 preventEmit?: boolean;
130 fileContainer?: HTMLElement;
131 containerWrapper?: HTMLElement;
132 lineAnnotations?: DiffLineAnnotation<T>[];
133 renderRange?: RenderRange;
134}
135```
137`SelectedLineRange` is:
139```ts
140{
141 start: number;
142 side?: "deletions" | "additions";
143 end: number;
144 endSide?: "deletions" | "additions";
145}
146```
148`DiffLineAnnotation<T>` is:
150```ts
151{
152 side: "deletions" | "additions";
153 lineNumber: number;
154 metadata: T;
155}
156```
158Important asset note:
160- `@pierre/diffs` ships `dist/style.js`; component code imports CSS through
161 wrapper utilities/web component registration.
162- Worker assets exist under `dist/worker/*`, but v1 will not instantiate
163 `WorkerPoolManager`; no worker route needed unless later enabled.
165### Verified `@pierre/trees@1.0.0-beta.4` typings
167Installed package inspected from npm tarball under
168`~/.pi/research/extracts/pierre-npm/trees`.
170Relevant exact API:
172```ts
173import { FileTree, type GitStatusEntry } from "@pierre/trees";
175const tree = new FileTree({
176 paths,
177 search: true,
178 initialExpansion: "open",
179 initialSelectedPaths: [],
180 gitStatus,
181 onSelectionChange(selectedPaths: readonly string[]) {},
182});
184tree.render({ fileTreeContainer });
185// or tree.render({ containerWrapper });
187tree.getSelectedPaths();
188tree.getFocusedPath();
189tree.focusPath(path);
190tree.scrollToPath(path);
191tree.setGitStatus(gitStatus);
192tree.cleanUp();
193```
195`FileTree` render props are exactly:
197```ts
198{
199 containerWrapper?: HTMLElement;
200 fileTreeContainer?: HTMLElement;
201}
202```
204## Scope
206### Command
208```text
209/diff-review [--base origin/main] [--staged] [--files a.ts,b.ts]
210/diff-review-cancel
211```
213Behavior:
215- interactive-only
216- waits for browser submit/cancel/timeout
217- on submit:
218 1. append `diff-review` custom entry
219 2. shared cleanup
220 3. send markdown review to Pi as user message
221- on browser/user cancel:
222 shared cleanup, no session entry, no user message
223- `/diff-review-cancel`:
224 abort active review server and unblock command
225- starting a second `/diff-review` while one is active:
226 notify error with active URL
228Flag semantics:
230- default:
231 unstaged working tree diff (`git diff`), untracked files ignored in v1
232- `--staged`:
233 staged diff (`git diff --cached`)
234- `--base <ref>`:
235 branch/base comparison (`git diff <ref>...HEAD`)
236- `--staged` and `--base` are mutually exclusive
237- `--files a.ts,b.ts`:
238 path filter, relative paths only, no absolute paths, no `..`
240### Git commands
242Run with `execFile`/`pi.exec` args, never shell interpolation.
244```ts
245// repo check/root
246git rev-parse --show-toplevel
248// default
249git diff --no-ext-diff --find-renames --unified=3 -- [files...]
251// staged
252git diff --cached --no-ext-diff --find-renames --unified=3 -- [files...]
254// base
255git diff --no-ext-diff --find-renames --unified=3 <base>...HEAD -- [files...]
256```
258Empty diff → notify `No diff to review` and return.
260Binary-only/unparseable files:
262- keep raw diff in payload
263- mark file as skipped if no hunks can be rendered
264- do not allow line findings for skipped files
266## Browser bundle lifecycle
268### Chosen policy
270Commit generated production browser assets and also guard against stale/missing
271builds at runtime.
273Implementation layout:
275```text
276agent/extensions/diff-review/
277├── package.json
278├── index.ts # register commands/events; orchestration only
279├── constants.ts # EXTENSION_ID, command/status ids, defaults
280├── types.ts # shared node/browser serializable types
281├── args.ts # slash-arg parser
282├── git.ts # git diff collection + DiffIndex
283├── server.ts # localhost server + token auth + lifecycle
284├── session-state.ts # append/restore helpers, q-style
285├── format.ts # markdown formatting
286├── open-browser.ts # safe opener fallback
287├── scripts/
288│ ├── build-browser.ts
289│ └── smoke-browser.ts
290├── browser/
291│ ├── index.html
292│ ├── index.ts
293│ └── style.css
294└── static/
295 ├── index.html
296 ├── app.js
297 ├── app.css? # if Bun emits/copies one
298 ├── assets/... # any emitted assets
299 └── manifest.json # generated by build script
300```
302Pattern rules:
304- Node files import Pi types from `@earendil-works/pi-coding-agent`.
305- Browser files import Pierre deps only; keep Pi SDK out of browser bundle.
306- Local imports use `.js` specifiers, e.g. `import { EXTENSION_ID } from
307 "./constants.js"`.
308- No imports from sibling extensions.
310`static/` is generated but committed for normal Pi runtime.
311Server serves all of `static/`, not individual hard-coded assets.
313### Build script requirements
315Use a small `scripts/build-browser.ts`, not only raw `bun build`, because it
316must:
3181. copy `browser/index.html` → `static/index.html`
3192. bundle `browser/index.ts` → `static/app.js`
3203. copy/emit any CSS/assets Bun produces
3214. write `static/manifest.json` containing:
322 - source file mtimes + sha256 for `browser/**`
323 - package versions for `@pierre/diffs` and `@pierre/trees`
324 - build timestamp
325 - Bun version
327Runtime `ensureBrowserBundle()`:
329- if `static/index.html`, `static/app.js`, or manifest missing:
330 - try auto-build if `bun` is available and extension dir is writable
331 - otherwise fail fast with exact command:
332 `cd agent/extensions/diff-review && bun install && bun run build`
333- if manifest source hashes/mtimes do not match:
334 - try auto-build in dev workspace
335 - otherwise fail fast with same command
336- if auto-build fails:
337 show stderr + command, do not start server
339### Package scaffold
341Start from `AGENTS.md` template, then add only imported deps:
343```json
344{
345 "name": "@bugabinga/pi-ext-diff-review",
346 "version": "0.0.0",
347 "private": true,
348 "type": "module",
349 "main": "index.ts",
350 "scripts": {
351 "build": "bun ./scripts/build-browser.ts",
352 "smoke:browser": "bun ./scripts/smoke-browser.ts"
353 },
354 "dependencies": {
355 "@pierre/diffs": "^1.1.22",
356 "@pierre/trees": "^1.0.0-beta.4"
357 },
358 "peerDependencies": {
359 "@earendil-works/pi-coding-agent": "*"
360 }
361}
362```
364Notes:
366- `@pierre/diffs` and `@pierre/trees` are `dependencies` because
367 `browser/index.ts` imports them.
368- Do not add `@earendil-works/pi-tui` unless Node-side rendering/widget code
369 imports it.
370- Do not add Playwright unless `scripts/smoke-browser.ts` imports it; if used,
371 add as `devDependencies` only.
372- After creating/changing this package file or build layout, run `bun install`
373 from workspace/extension as required by `AGENTS.md`.
375Run after scaffold/deps/asset changes:
377```bash
378cd agent/extensions/diff-review
379bun install
380bun run build
381bun run smoke:browser
382```
384## Browser launch strategy
386No Pi URL-open API is verified, so use safe platform fallback.
388`openBrowser(url)`:
390- Termux:
391 `termux-open-url <url>` if available
392- macOS:
393 `open <url>`
394- Windows:
395 `cmd.exe /c start "" <url>`
396- Linux/BSD:
397 `xdg-open <url>`
398- WSL fallback if needed:
399 `wslview <url>`
401Rules:
403- use `spawn`/`execFile`, no shell except Windows `cmd.exe /c start`
404- opener failure is non-fatal
405- always show manual URL via `ctx.ui.notify` and status/widget
406- optionally copy URL if a clipboard command exists (`wl-copy`, `xclip`,
407 `pbcopy`, `clip.exe`, `termux-clipboard-set`), but do not depend on clipboard
409UI status while active:
411```text
412diff-review: open http://127.0.0.1:<port>/?token=...
413```
415## Abort / timeout / heartbeat
417All command exits go through one `finish(result)` path guarded by an idempotent
418state flag.
420Active review state:
422```ts
423type ActiveReview = {
424 id: string;
425 url: string;
426 server: Server;
427 controller: AbortController;
428 heartbeatTimer: NodeJS.Timeout;
429 timeoutTimer: NodeJS.Timeout;
430 lastHeartbeatAt: number;
431 resolve(result: BrowserResult): void;
432};
433```
435Timeouts:
437- hard session timeout default:
438 30 min
439- heartbeat interval from browser:
440 5s
441- heartbeat considered lost after 30s
442- heartbeat loss only warns first; hard timeout or explicit cancel ends command
443- `/diff-review-cancel` ends immediately
444- `session_shutdown` aborts active review immediately
446Browser routes:
448```text
449POST /api/heartbeat updates lastHeartbeatAt
450POST /api/cancel explicit browser cancel
451```
453If browser tab closes, heartbeat warning tells user to reopen URL or run
454`/diff-review-cancel`; hard timeout prevents indefinite hang.
456## Local server protocol
458Bind only to localhost:
460```text
461127.0.0.1:0
462```
464Token:
466- `crypto.randomBytes(32).toString("base64url")`
467- browser URL:
468 `http://127.0.0.1:<port>/?token=<token>`
469- all `/api/*` requests require `Authorization:
470 Bearer <token>`
471- static files require either token query on `/` or a same-origin session cookie
472 set by `/`; API still uses bearer token
474Routes:
476```text
477GET / static/index.html; requires token query
478GET /static/* files from static build dir
479GET /api/review JSON review payload
480POST /api/heartbeat heartbeat
481POST /api/finding/validate validate selection + preview anchor
482POST /api/submit submit notes/findings
483POST /api/cancel cancel command
484```
486`GET /api/review` response:
488```ts
489type ReviewPayload = {
490 round: number;
491 source: ReviewSource;
492 diffText: string;
493 files: Array<{
494 path: string;
495 prevPath?: string;
496 status: "added" | "modified" | "deleted" | "renamed" | "binary";
497 additions: number;
498 deletions: number;
499 }>;
500 carriedFindings: Finding[];
501};
502```
504Command awaits one of:
506```ts
507type BrowserResult =
508 | { type: "submit"; notes?: string; findings: FindingDraft[] }
509 | { type: "cancel"; reason: "browser" | "command" | "shutdown" | "timeout" };
510```
512Cleanup:
514- close server
515- abort controller
516- clear timers
517- clear status/widget
518- clean active review global
520## Browser UI
522Layout:
524- left sidebar:
525 `@pierre/trees` changed-file tree
526- main panel:
527 one `@pierre/diffs` `FileDiff` per changed file
528- right drawer:
529 active selection + annotation form
530- footer/header:
531 submit/cancel, round number, source summary
533Review drawer fields:
535- category:
536 `bug | style | perf | question`
537- severity:
538 `high | medium | low`
539- comment:
540 required
541- notes:
542 optional per-finding note or global notes textarea
544Selection rules:
546- use `onLineSelected(range)` and `onGutterUtilityClick(range)`
547- accept only `range.side`/`range.endSide` in `additions | deletions`
548- if mixed sides, reject for v1 with UI hint
549- `startLine = Math.min(range.start, range.end)`
550- `endLine = Math.max(range.start, range.end)`
551- render saved findings as `DiffLineAnnotation<{ findingId, severity, category,
552 comment }>`
554Browser lifecycle:
556- heartbeat starts after successful `/api/review`
557- `beforeunload` tries best-effort `navigator.sendBeacon("/api/cancel")` only if
558 no submit happened; command does not rely on this
559- explicit Cancel button posts `/api/cancel`
560- Submit disables form, posts `/api/submit`, then shows `Submitted — return to
561 Pi`
563Implementation sketch with verified APIs:
565```ts
566import { FileDiff, parsePatchFiles, type SelectedLineRange } from "@pierre/diffs";
567import { FileTree } from "@pierre/trees";
569const review = await apiGetReview();
570const patches = parsePatchFiles(review.diffText, `diff-review-${review.round}`, true);
572const tree = new FileTree({
573 paths: review.files.map((f) => f.path),
574 search: true,
575 initialExpansion: "open",
576 gitStatus: toGitStatus(review.files),
577 onSelectionChange(paths) {
578 const path = paths[0];
579 if (path) scrollToDiff(path);
580 },
581});
582tree.render({ fileTreeContainer: document.getElementById("tree")! });
584for (const patch of patches) {
585 for (const fileDiff of patch.files) {
586 const instance = new FileDiff({
587 theme: { dark: "pierre-dark", light: "pierre-light" },
588 diffStyle: "split",
589 overflow: "scroll",
590 enableLineSelection: true,
591 enableGutterUtility: true,
592 lineHoverHighlight: "both",
593 onLineSelected: (range: SelectedLineRange | null) => openDrawer(fileDiff.name, range),
594 onGutterUtilityClick: (range: SelectedLineRange) => openDrawer(fileDiff.name, range),
595 renderAnnotation: renderFindingAnnotation,
596 });
597 instance.render({ fileDiff, containerWrapper: diffRoot, lineAnnotations: [] });
598 }
599}
600```
602## Agent result
604After submit, send this as a user message:
606```md
607# Diff Review Round N
609## Findings
611- [high][bug] src/foo.ts:43 additions — comment
613## Notes
615...
617Use this review to propose and discuss a fix plan first. Do not edit files yet.
618```
620No findings:
622```md
623# Diff Review Round N
625No findings recorded.
627Use this review result to decide whether any follow-up is needed. Do not edit files yet.
628```
630## Data model
632```ts
633type ReviewCategory = "bug" | "style" | "perf" | "question";
634type ReviewSeverity = "high" | "medium" | "low";
635type ReviewSide = "additions" | "deletions";
636type FindingStatus = "open" | "resolved" | "closed_auto";
638type Finding = {
639 id: string;
640 round: number;
641 file: string;
642 prevFile?: string;
643 side: ReviewSide;
644 startLine: number;
645 endLine: number;
646 category: ReviewCategory;
647 severity: ReviewSeverity;
648 comment: string;
649 notes?: string;
650 status: FindingStatus;
651 statusReason?: "file_removed" | "anchor_missing" | "manual";
652 anchor: {
653 before: string;
654 selected: string;
655 after: string;
656 };
657};
659type ReviewSource = {
660 kind: "working-tree" | "staged" | "base";
661 base?: string;
662 files?: string[];
663};
665type ReviewRoundEntry = {
666 version: 1;
667 kind: "round";
668 round: number;
669 source: ReviewSource;
670 findings: Finding[];
671 notes?: string;
672 diffSummary: {
673 filesChanged: number;
674 additions: number;
675 deletions: number;
676 skippedFiles: string[];
677 };
678 createdAt: string;
679};
680```
682Custom session entry:
684```ts
685pi.appendEntry("diff-review", reviewRoundEntry);
686```
688Restore state:
690```ts
691function restore(branch: SessionEntry[]): ReviewState {
692 const rounds: ReviewRoundEntry[] = [];
693 for (const entry of branch) {
694 if (entry.type !== "custom" || entry.customType !== "diff-review") continue;
695 const data = entry.data as ReviewRoundEntry;
696 if (data?.version === 1 && data.kind === "round") rounds.push(data);
697 }
698 return {
699 round: Math.max(0, ...rounds.map((r) => r.round)),
700 findings: rounds.flatMap((r) => r.findings),
701 };
702}
703```
705## Diff index / anchors
707Server builds a `DiffIndex` from unified patch before opening browser:
709```ts
710type DiffLineMap = Map<number, string>;
712type IndexedFileDiff = {
713 file: string;
714 prevFile?: string;
715 status: "added" | "modified" | "deleted" | "renamed" | "binary";
716 additions: DiffLineMap; // new-file line number → text
717 deletions: DiffLineMap; // old-file line number → text
718};
719```
721Anchor generation on submit:
723- browser sends selection + form data only
724- server looks up selected lines in `DiffIndex`
725- `selected`:
726 selected line texts joined with `\n`
727- `before`:
728 up to 3 available same-side lines before `startLine`
729- `after`:
730 up to 3 available same-side lines after `endLine`
732If lookup fails, reject submit with `400` so browser can show stale-selection
733error.
735## Security
737- bind `127.0.0.1` only
738- random token, required for API writes
739- no filesystem writes from browser
740- sanitize/validate file filters before passing to git
741- never invoke shell with interpolated args
742- render user comments/paths via `textContent`
743- cap diff size for v1, e.g. 5 MiB patch text; notify if too large
744- clear token/session state on submit/cancel/timeout
746## Production browser smoke test
748Add `scripts/smoke-browser.ts` before v1 completion.
750Test must:
7521. run `bun run build`
7532. start extension static server with sample diff fixture
7543. open real browser using Playwright or available Chromium
7554. load tokenized URL
7565. assert no 404s for `static/*`
7576. assert no console errors
7587. assert Pierre tree renders file path
7598. assert Pierre diff renders changed line
7609. create one finding via DOM event/click path if possible, otherwise call UI fn
761 behind test hook
76210. submit and assert server receives finding
764If Playwright browser unavailable, smoke script exits with clear skip only in
765dev; CI/v1 release requires pass.
767## Implementation phases
769### 0. Preflight proof
771- scaffold package
772- install deps
773- inspect local `node_modules/@pierre/*/dist/*.d.ts` after `bun install`
774- build minimal browser bundle
775- run smoke server/page manually or via `smoke:browser`
776- verify no missing assets/console errors
778Acceptance:
780- `bun run build` creates `static/index.html`, `static/app.js`, `manifest.json`
781- `bun run smoke:browser` passes or gives actionable missing-browser skip
783### 1. Minimal command + local server
785- parse args
786- `ensureBrowserBundle()`
787- collect git diff + file summary + `DiffIndex`
788- start tokenized localhost server serving full `static/` dir
789- open browser or show manual URL
790- wait for submit/cancel/timeout
791- append `diff-review` entry
792- send markdown user message
793- `/diff-review-cancel`
795Acceptance:
797- `/diff-review` opens browser for unstaged diff
798- missing/stale browser bundle auto-builds or fails with exact command
799- opener failure still provides usable URL
800- Submit returns to Pi and triggers agent turn with review markdown
801- Cancel/timeout/session shutdown unblocks command and closes server
803### 2. Pierre UI
805- `@pierre/trees` changed-file sidebar with verified `FileTree` API
806- `@pierre/diffs` split diff list with verified `FileDiff` API
807- line/range selection
808- annotation drawer
809- finding chips via `lineAnnotations`
810- tree status badges via `gitStatus`
812### 3. Pi persistence
814- append `diff-review` entries
815- reconstruct current-branch state on `session_start`
816- widget/status:
817 `N open review findings`
819### 4. Reconciliation
821On next review round:
823- file missing → `closed_auto`, `statusReason:
824 "file_removed"`
825- selected anchor missing → `closed_auto`, `statusReason:
826 "anchor_missing"`
827- selected anchor found elsewhere → update line range
828- user can manually resolve carried findings
830### 5. Polish
832- dark/light sync with Pi theme if possible
833- markdown export fallback only if later requested
834- optional prompt injection of open findings before next agent turn
835- optional worker pool for large diffs, only after serving/copying worker assets
836 is verified
838## Non-goals for v1
840- applying fixes directly from browser
841- replacing normal `edit` rendering
842- full Pi session tree browser
843- untracked-file review
844- non-interactive mode
845- Pierre worker pool / WASM highlighter routing