Skip to content

Latest commit

 

History

History
214 lines (171 loc) · 53.5 KB

annotate.md

File metadata and controls

214 lines (171 loc) · 53.5 KB

Annotate Flow

User runs /plannotator-annotate <file.md | file.html | https://... | folder/>
        ↓
Claude Code: plannotator annotate subcommand runs
OpenCode/Pi: event handler intercepts command
        ↓
Input type detected:
  .md/.mdx/.txt → file read from disk
  plain-text config/data formats (.yaml .yml .json .jsonc .json5 .toml .ini .cfg .conf .properties .csv .tsv .log .xml .env.example)
             → read from disk, shown as ONE code block in the file's language (see
               "Config and data files" below) — not as markdown. A .env file
               (.env, .env.local, …; isSecretEnvPath) opens the same way, but only by
               its explicit path, never by name search, the folder browser or a link,
               and its session writes nothing to the data dir (no history copy, no
               submit record, no feedback archive); source-code extensions stay with
               code review
             All single-file annotate reads and /api/doc document serves are capped at
             2MB (`MAX_ANNOTATABLE_FILE_BYTES` in `packages/core/annotatable.ts`) —
             larger files get a clear "File too large to annotate (max 2MB)" error.
             Extra extensions listed in `markdownExtensions` (config-only setting,
             e.g. `.livemd`) join this set and render as markdown, frontmatter stripped.
  .mmd/.mermaid → file read, rendered as ONE Mermaid diagram in the full
             diagram viewer (see "Diagram files" below) — not as text
  .dot/.gv   → same, through the Graphviz engine
  .adoc/.asciidoc → file read, parsed by the AsciiDoc block parser (see
             "AsciiDoc files" below) — not as markdown
  .html/.htm → file read, rendered as raw HTML by default (or converted to markdown with --markdown)
  https://   → fetched via Jina Reader (default) or fetch+Turndown (--no-jina)
  http://localhost:* (also 127.x and [::1])
             → LIVE app annotation by default when a quick probe returns HTML:
               the running app is mirrored through a loopback reverse proxy and
               annotated in place (see "Live app annotation" below). --static
               forces the classic conversion pipeline; --app forces live mode
               and fails loudly when it cannot apply.
  folder/    → file browser opened, files converted on demand
  a.md b.html c.md (several existing file paths)
             → ONE review of all of them, in that order (mode
               "annotate-bundle"; see "Several files in one review" below)
        ↓
Annotate server starts (reuses plan editor HTML with mode:"annotate")
        ↓
User annotates content, provides feedback
        ↓
Send Feedback → annotations sent to agent session
Done / Approve (gate) → positive decision recorded (see the decision control below)

Opening view. config.json annotateView ("wide" / "focus" / "edit") opens an annotate session in that toolbar view, once, when the document first loads; a view the document cannot use (toolbar hidden, Edit on a read-only document, Edit while a draft is offered, folders and bundles) falls back to today's default, and a click in the session wins and is never written back (see annotateView in environment.md).

AsciiDoc files

.adoc/.asciidoc take the diagram path through packages/core/annotatable.ts: they are annotatable plain text everywhere on the server (resolution, 2MB cap, folders, file browser, bundles, version history), and both servers set renderAs: "asciidoc" on /api/plan and /api/doc with the RAW file as the body (annotateDocumentRenderKind / documentRenderKindForPath). The editor's blocksForRenderAs (packages/editor/feedbackDocuments.ts) sends that text through parseAsciidocToBlocks (packages/ui/utils/asciidocParser.ts), which maps AsciiDoc onto the markdown Block model with each block's real source span, so annotations, export line labels, drafts and linked docs need no special case. A share payload carries r: 'asciidoc'. No asciidoctor.js: it would bloat the single-file page.

Supported: section titles, the document header (author/revision lines and attribute entries, with {name} substitution), paragraphs and literal (indented) paragraphs, */-/./1. lists with nesting, checklists and + continuation, description lists, ---- .... ++++ and ``` listings with [source,lang], admonition paragraphs and [NOTE] + ==== blocks, ____ quotes, |=== tables (cols, %header, implicit header, colspans), block titles, images, links, cross references (a link when the target is another local .adoc), footnotes and constrained *bold*.

Not supported: include:: and conditionals (ifdef/ifndef/ifeval/endif) are shown as written, never resolved; lists and listings nested inside an admonition block or an a| table cell flatten to text; row spans; CSV/DSV tables; callout lists; counters, macros such as kbd:/btn:/menu:, and inline roles show as plain text. The author and revision lines under the title are not shown. The version diff ("Show changes") compares the text through the markdown view, as it does for diagram files. Editing the file in Plannotator is off (source save is markdown/text only), as it is for diagram files.

Config and data files

The config and data formats (.yaml .yml .json .jsonc .json5 .toml .ini .cfg .conf .properties .csv .tsv .log .xml .env.example) are a fifth family in packages/core/annotatable.ts, wired like AsciiDoc: annotatable plain text everywhere on the server (resolution, 2MB cap, folders, file browser, bundles, version history), and both servers set renderAs: "code" on /api/plan and /api/doc with the RAW file as the body (documentRenderKindForPath). The editor's blocksForRenderAs turns that text into ONE code block (codeDocumentBlocks in packages/ui/utils/parser.ts) in the language codeDocumentLanguage names for the path, highlighted by the same Shiki instance fences use, so annotations, drafts and linked docs need no special case. Before, they went through the markdown parser (#1099's first pass): a # comment became a heading and a backticked name a code chip. .txt stays markdown.

  • .cfg and .conf get no grammar (an nginx .conf is not INI; fences are never guessed, #1212), .properties uses ini, .env.example uses dotenv.
  • Past CODE_DOCUMENT_HIGHLIGHT_LIMIT (128 KB) the block has no language: one Shiki pass over a whole large log or JSON dump would stall the page, so it shows as plain monospace text, still annotatable.
  • The whole file is one block, so a block-span line label would name every line. The block sets contentStartLine, and the export (lineLabelForAnnotation) and Ask AI's lines (selectionSourceLines, given the selected text) count the comment's own lines from its position in the block: a comment on line 6 exports (line 6).
  • That position is measured from the selection, not searched for: CodeBlock marks such a block with data-content-start-line, and the highlighter stores the selection's real offset in it (the annotation's startOffset, and the comment popover's startOffset for Ask AI). A line that appears twice therefore names the copy that was selected. A repeated quote with no offset that still holds it gets the file's span, never a guess at the first copy.
  • A draft saved while config files rendered as markdown points at a markdown block. On restore its stored positions fail the text check, the quote search re-attaches it, and the restore report moves it to block-0 at the painted copy. A quote whose markdown render differs from the raw file text (an escape, an entity, emphasis markers that were dropped) does not match and comes back unanchored. A repeated quote re-attaches to its first copy, because the search has nothing else to go on.
  • Edit Mode stays available, as it was when these rendered as markdown. Source save is still markdown/text only (SOURCE_SAVE_FILE_REGEX).
  • The version diff's Rendered and Classic modes show each chunk as code in the same language, and a changed block takes a comment as in markdown (codeDocument on PlanCleanDiffView; see "Plan Diff" in server-and-storage.md). Raw is unchanged. Diagram and AsciiDoc files still diff through the markdown parse.
  • Not changed: a share link renders the text as markdown (the payload carries no path to pick a grammar from).
  • A configured markdown extra (markdownExtensions) can never be one of these extensions (built-ins win in normalizeMarkdownExtensions), so extras keep rendering as markdown.

Annotate header decision control

Every annotate surface's header decision is one adaptive split control, DecisionControl (packages/ui/components/DecisionControl.tsx), rendered from the pure buildDecisionSpec state→spec mapping (packages/ui/utils/decisionSpec.ts) beside a ghost-X Close: Done (or Approve in gate mode) with nothing to send, Send Feedback otherwise, with the alternate decisions and the in-place note composer behind the caret. One submitPrimaryDecision() callback serves the header primary, the global Mod+Enter handler, and the compact primary row, so keyboard and header can never disagree. Transport routing is pure in packages/editor/annotateDecision.ts: Done and every note post /api/feedback (a note becomes a GLOBAL_COMMENT at submit time with a one-render deferred submit — zero server change), so formatAnnotateOutcome shapes and strict-gate exit codes are byte-identical to the old keyboard-only zero submit; only gate-mode approvals reach /api/approve. The non-gated empty menu carries a single composer, "Send a note…" (maintainer ruling: the old "Done with a note…" / "Request changes…" pair differed only by framing on the same transport and was collapsed into one item); the approval-framing sentence (buildCompleteAnnotateFeedback's approvalFraming) now serves only the non-gated discard path, and the only confirm left is the explicit Done/Approve, discard n annotations… menu item (plus the pre-existing close-with-content warning). Compact/touch rows are generated from the same spec, so a visible positive decision exists in every state; composer rows open DecisionNoteDialog. The header flip predicate is hasFeedbackToSend, so feedback already delivered through the agent terminal shows the positive primary rather than a stale Send Feedback.

The approve-carrying gate items (Approve with a note…, Approve with notes) follow the approvalNotesSupported advert on /api/plan, the same on markdown, raw-HTML and live-app surfaces. The Bun CLI sets it with supportsAnnotateApprovalNotes = --gate and not --hook (apps/hook/server/annotate-output.ts): --json carries the note as feedback, plaintext prints the configured approvedWithNotes prompt instead of The user approved. (a bare approval keeps that line byte for byte), and the Claude Code mod's plaintext --gate launches deliver it from the result file as an approved-with-notes turn. --hook has no message on approval, so the items stay hidden there. Pi and OpenCode advertise it from their own servers. Non-gated annotate has no approve channel: its only composer is "Send a note…" (feedback).

Annotate Options menu and Settings parity

Annotate renders the same document app as plan review, so its Options menu and Settings dialog match plan review item for item; only rows that describe a PLAN decision stay plan-only. Settings mode="annotate" shows General, Theme, Display (width reads "Document Width"), Saving, Labels, Vim, Shortcuts, Files, Obsidian, Bear and Octarine — gated on the optional annotateParity prop, which AppHeader passes and a @plannotator/ui host that omits it does not (hosts keep the pre-parity annotate tab set; see packages/ui/HANDOFF.md). The notes-app enable switches are the SAME cookies plan review's approve reads (body.obsidian/bear/octarine), so enabling one from annotate also makes plan review save every approved plan there; the annotate description says so explicitly. Plan-only, and hidden in annotate: the Hooks tab (plan-time hooks; /api/hooks/status exists only on the plan server), Save Plans (decision snapshots in plans/ are written on approve/deny), the three Auto-save on Plan Arrival switches (the arrival auto-save effect is gated !annotateMode), Permission Mode, and OpenCode Agent Switching (annotate decisions never send agentSwitch). The Archive sidebar tab stays plan-only too (the annotate server has no /api/archive/*).

Agent Instructions (Options menu) is offered in every annotate session. buildAnnotateAgentInstructions(origin, surface) (packages/ui/utils/annotateAgentInstructions.ts) is the annotate twin of buildPlanAgentInstructions (plan text is unchanged): same endpoint and plan-mode validator, "document" not "plan", no deny/resubmit loop, and one section per surface picked by resolveAnnotateInstructionsSurface — its own read command (.plan; .rawHtml for raw HTML; .targetUrl for a live app; /api/doc?path=<p>&doc=1 | jq -r '.markdown // .rawHtml' for a folder, so HTML and data files print too) plus the targeting rules the validator actually supports: diagramAnchor on POST for diagram files, htmlAnchor by PATCH only (POST drops it), pageUrl by PATCH for live-app routes. Folder sessions are stated plainly: an external comment cannot target a document; it lists in the panel whichever document is open, is not highlighted inline, and rides the submitted feedback. Not done yet: POST accepting htmlAnchor, and a path field so a folder-session external comment targets one document. packages/server/annotate-agent-instructions.test.ts executes every curl/JSON example in the text against a real annotate server, so an instruction that drifts from the server fails there.

Save to Obsidian / Bear / Octarine menu items are hidden (a Mod+S quick save toasts instead) when the session has no document text (notesSaveAvailable: raw-HTML, live-app, a folder with no file open) — the server skips an empty plan, so those items were silent no-ops.

Tolerant argument resolution

Slash-command hosts forward raw user words to plannotator annotate verbatim (on Claude Code through a bash-substitution prefix that runs before the model sees anything), so non-strict invocations resolve their arguments in three tiers. The shared logic lives in packages/shared/annotate-target.ts (vendored to Pi) and is wired into the CLI's annotate branch plus the OpenCode and Pi command parsers:

  1. A single-token invocation runs the classic pipeline unchanged: a bare correct path behaves exactly as before, and a lone typo'd path still fails with File not found and exit 1.
  2. With several tokens, each token is probed; exactly one naming an existing file, URL, or folder proceeds with it (annotate look at notes.md please opens notes.md). Bundle rule (0.29), checked first: when EVERY token is an existing regular file named by its path (resolved from the cwd, ~ or an @ prefix; probeAnnotateBundlePath, never a name found only by searching the project, never a URL or folder), they open as one review in the typed order with duplicates dropped (selectAnnotateTokenTarget(..., { bundlePath }) → { kind: "bundle" }; the same file twice is single, on every host); an existing file of an unsupported type or over the 2MB cap among them fails naming it (resolveAnnotateBundleFiles; a .env is named as refused). When every token READS as a file path (looksLikeFilePath from the tool contract: a separator, a leading ~ . @, or an extension) but some name nothing at all (nothing exists at the path, annotatePathExists, and nothing is found by search), the selection is { kind: "missing" } and the host fails naming them (buildMissingAnnotateFilesMessage, exit 1, or 2 under a strict gate): an explicit list of files with a typo never narrows to the files that exist. An existing path is never missing, so a stray . or .. beside a file still opens the file and an existing folder keeps the ambiguity error. Known edge: a dotted word such as Node.js or v2.0 reads as a file path, so annotate notes.md about Node.js is prose (fast path) but annotate notes.md Node.js fails naming Node.js when no such file exists. Otherwise two or more resolving tokens (prose around them, a URL or folder among them, a searched name) error naming every candidate rather than guessing, and the error gains one hint line, ANNOTATE_BUNDLE_HINT ("To review several files together, pass only their paths: plannotator annotate a.md b.html"), on hosts that open bundles. A host that cannot open bundles passes no bundlePath and keeps the #1182 tiers exactly. Bare directory names only count as targets when they are the sole argument, so a stray word matching a directory (or .) cannot hijack the fast path; unrecognized dash-prefixed tokens disable the tolerance entirely so a typo'd flag (--no-jna) errors the way it always did instead of being silently skipped.
  3. When nothing resolves, the CLI emits an agent-addressed handoff that echoes the words tried and asks the reading agent to re-run with a concrete target (content flags such as --markdown / --no-jina / --render-html are echoed for the re-run; transport flags are not). In plain mode the handoff goes to stdout with exit 0, because a non-zero exit from a Claude Code bang-prefix skill aborts the prompt before the model sees any output; with --json / --hook it goes to stderr with exit 1 so machine-readable stdout stays reserved for decision records. OpenCode and Pi surface the same message as a host notification.

Strict invocations (--require-approval / --result-file) bypass all three tiers: args[1] is the target and a typo'd path stays a startup failure with exit 2. With several arguments, a strict gate takes only the bundle rule: several existing file paths make one review (approve covers every file); anything else exits 2 ("File not found: " when the first argument names nothing, else "A strict annotate gate takes one target, or only existing file paths…"), where extra words used to be silently ignored. The refusal is decided by probe and stat only: nothing is fetched, probed live, or reported as resolved first.

Several files in one review (annotate bundles)

plannotator annotate spec.md mock.html notes.md, the plannotator tool's target: [...], a taken-over Bash command with several file paths, and /plannotator-annotate a.md b.md on Pi and OpenCode (embedded and CLI-bridge) open ONE review of the listed files, in the given order, with ONE decision (owner decisions: no flag, no file-count limit, per-file decisions later).

  • Server mode annotate-bundle in both runtimes (packages/server/annotate.ts, mirrored in apps/pi-extension/server/serverAnnotate.ts): options bundleFiles: AnnotateBundleFile[] ({ path, renderAs }, from packages/shared/annotate-bundle.ts, deliberately not in @plannotator/core so the published core export map is unchanged; two or more or the server throws) and filePath = the bundle root (annotateBundleRoot, the deepest directory holding every file, compared by path segment). /api/plan adds bundle (the list, in order) and projectRoot = the bundle root. /api/doc serves the files and what they link to under the single-file rule: reference roots are the cwd plus each file's own directory, and for a symlinked file also its target's whole directory, as a single-file session on that path would (bundlePaths on getAnnotateReferenceRootPaths), so a document beside a bundle file opens as a linked document exactly as from that file alone. A document outside is served to a tab on this machine; a code or data file outside, and anything outside for a reader that keeps the roots, is 403 (see the annotate /api/doc row in server-and-storage.md). The editor never walks the bundle root. Each text file's version history is saved when the review opens (the folder pipeline's per-file memo, run eagerly; raw HTML keeps none, as in folders), and /api/doc returns its version fields.
  • Edit Mode: a bundle file is editable exactly when it would be opened alone (a single-file session): Edit Mode's source save writes back to it. The writable set is the REAL paths of the bundle's own files, captured when the review opens (resolveBundleSourceSavePaths in packages/shared/source-save-node.ts, vendored to Pi): an entry counts when its named and real paths are both a SOURCE_SAVE_FILE_REGEX type (.md, .mdx, .txt) and it is a regular file, so raw HTML, diagram sources and data files stay read-only, as alone. /api/doc grants sourceSave only to a document whose real path is in that set (createBundleSourceSaveCapability, scope folder-file, because the client addresses the save by path as in a folder session; a symlinked entry's capability names its target), and POST /api/source/save writes only when the request's path resolves to a member (resolveBundleSourceSaveTarget: the realpath, or for a deleted file its real parent plus its name, so a file removed mid-review can be recreated), with saveSourceFileAtomic's allowedFiles re-checking the real path at write time. Everything else is 403 not-writable: a document a bundle file links to (read-only, as a document linked from a single file is), a sibling, a new file, anything outside. The 2MB annotate cap and the hash conflict check (409) apply as for a single file. A bundle entry that is a symlink is writable at its target even outside every reference root (the user named that file), but the set is fixed at open: an entry swapped for a symlink to another file afterwards resolves outside it and is 403, and a regular-file entry deleted mid-review is recreated in place by the next save (a symlinked entry whose target was deleted is not: its path no longer resolves to the target). Every session kind's /api/source/save (single file, folder, bundle; both runtimes) also refuses, in this order: a cross-origin request (isSameOriginOrNoOrigin, 403; the VS Code panel's Sec-Fetch-Site: same-origin passes), a serverSession mismatch (409 session_mismatch), and any save once the review is decided, by feedback, approve, Close or the agent's close (409 { ok: false, code: "not-writable", decided: true }, sourceSaveDecidedResponse in packages/core/source-save.ts). Unlike draft saves, an agent close does not let source saves through: a draft is crash recovery the close keeps, while a source save writes a file the agent may already be editing, and the closed tab cannot start a save anyway. The editor needed no new gate: a bundle is a folder session, and canEditMarkdown already allows a folder file the server granted source save; saving, switching files with an unsaved buffer, re-anchoring comments after an edit, drafts and per-document copies follow the folder session.
  • Drafts: the session draft is keyed by the ordered list (bundle:\0<paths>), and every file's comments are also saved under that file's path key (#1710's document copies), so they follow the file into a single-file, folder or other bundle session. Host status documents lists the files.
  • Decision record: the host result record (PLANNOTATOR_HOST_RESULT_FILE) and the feedback archive gain documents: [{ path, annotationCount }] in bundle order (annotateBundleDocumentCounts, counted from each submitted annotation's documentPath). The archive record's surface is annotate-bundle with target.documents and no filePath. The agent message frames the feedback with Files: <path>, <path> (annotateBundleTargetText) on every host.
  • Editor (packages/editor/App.tsx): a folder session (annotateSource stays 'folder') with bundleFiles state. The first file opens by itself; the header's BundleSwitcher (packages/editor/components/BundleSwitcher.tsx, "2 of 3 · mock.html ‹ ›", desktop; the compact shell names the position in its title and offers Previous/Next file in its Options menu) and the Files tab follow the given order: the tab shows the bundle as a synthetic, never-fetched file-browser section (bundleDirState, merged into navigatorFileBrowser beside any configured directories; the filesystem root is the empty dir path so ${dir}/${node} stays absolute). A link from one bundle file to another opens it as that bundle file. A bundle file has no Close pill, no sidebar "Back to…" and no HTML header Back (the switcher moves between the files); a document a bundle file links to goes back to the last bundle file shown (bundleBackPath, the first file before any), never to the folder's empty "choose a file" state (DocBadges' onBack is optional for the folder-file variant). That Back reopens the bundle file with restoreScroll (useLinkedDoc's open), so the reader lands where they left it, as a single-file session's back() does (#2128; the switcher and a link to another bundle file still open a file at its top). The export lists one section per file in bundle order under BUNDLE_DOC_EXPORT_HEADING ("File Feedback"; resolveFeedbackSections({ bundleOrder }), unlisted linked documents after), the All files panel follows the same order (groupAnnotationsByDocument's order), and Ask AI's context carries bundlePosition, so the session-bridge surface line reads "annotating /…/mock.html, file 2 of 3".
  • Version skew: an older CLI answers several paths with the ambiguity error lacking ANNOTATE_BUNDLE_HINT; the Claude Code mod and the OpenCode CLI bridge recognize that (isOlderCliBundleRefusal) and say to update Plannotator to open several files at once. An older host never sends a list.

Tests: the selection table in packages/shared/annotate-target.test.ts; packages/server/annotate-bundle.scenarios.ts (both runtimes; includes Edit Mode saves, the 403 outside the bundle, a symlinked entry, an entry swapped for a symlink after open, a deleted entry recreated, and the cross-origin, VS Code-proxy, serverSession and decided-session guards on source save); apps/hook/server/annotate-bundle-cli.test.ts (the CLI as a process: order, one decision, the host record's documents, strict gates, the hint); packages/shared/annotate-bundle.test.ts; the mod's controller.test.ts and plannotator-tool*.test.ts; OpenCode commands.test.ts and cli-bridge.test.ts; and the DOM test packages/editor/App.bundle.test.tsx (first file opens, switcher and file list in order, one section per file in bundle order; Edit Mode offered on each bundle file and a save reaching the file, against the real server run as a child process by packages/editor/testing/annotateBundleServer.ts, since Bun.serve refuses happy-dom's Response).

The bang prefix in the Claude Code skill is deliberate: #872 (commit aac5aacb, "restore /plannotator-* bash execution on Claude Code") put it back so the slash command never depends on the model choosing to run the binary. Argument-shape problems belong here in the CLI's resolution, not in the skill templates.

Hosts that run the CLI as a child must hand it the words as SEPARATE arguments, or none of this runs: one argument is one path to the CLI (annotate ". notes.md" is "File not found"). The OpenCode CLI bridge (OpenCode 2 native commands and the OpenCode 1 CLI runtime) does this with annotateCliTargets (apps/opencode-plugin/cli-bridge.ts) over the shared annotateTargetWords (packages/shared/annotate-args.ts: quotes group a path with spaces only when they open and close a word, so prose apostrophes stay in their words; an unterminated quote is prose, backslashes are kept, known flags are dropped). It keeps ONE argument, exactly as before, when the whole input names an existing target (an unquoted path with spaces), for a single word, and when a word starts with - (a typo'd or prose flag must never reach the CLI as a real one). The plannotator tool's single target is never re-split. apps/opencode-plugin/annotate-words-cli.test.ts runs the REAL CLI for this. An OpenCode 2 slash command that fails (a refused argument or the CLI's startup error) posts a transcript notice, Plannotator /plannotator-annotate failed: <reason> (createCommandFailureNotifier in v2-client.ts: session.synthetic with a description and resume: false, so no model turn; the context hook drops it from model requests like the session-URL notice, matching only a text that ends with the marker commandFailureNoticeText adds and the visible description lacks, so a copy of the line the person types or pastes is never dropped); the OpenCode 1 CLI runtime shows an error toast. Before this the failure only reached the log, which OpenCode 2 discards. Tool launches report failures as the tool result instead.

Annotate drafts follow the file

Annotate drafts used to be keyed only by a hash of the document text, so an agent edit plus a reopen lost the reviewer's unsent comments. packages/shared/annotate-draft.ts (vendored to Pi; both servers route /api/draft and /api/draft/document through createAnnotateDraftSession) applies the #1590 pattern:

  • Single local file (mode annotate, not a URL): the draft is also saved under annotateFileDraftKey(<abs path>), reusing review-draft.ts's dual-key logic with the content key as the "patch" key. Load prefers the content copy unless the path copy is strictly newer by draftGeneration; the path copy remembers every content key it was saved on (patchKeys, server-stamped, stripped from client bodies and from load responses); its tombstone guards both keys. Restored comments re-anchor by text and one whose text is gone shows the existing Unanchored chip and still exports, with no line label. Because block ids are positional, the highlighter's restore report lists under moved every comment whose stored blockId no longer holds its text (the block its highlight landed in, or '' when the text is gone, which is also reported unanchored whether or not stored positions existed), and App writes that back (applyRestoredAnchors, packages/editor/restoredAnchors.ts), so export line labels name the lines the text is on now; an unchanged document reports nothing and exports byte-identically. Only rows that own a text highlight go through that restore (annotationOwnsHighlight, packages/ui/utils/annotationOwnsHighlight.ts: not diff-view comments with their diff-block-N ids, general comments, checkbox toggles or question answers); every re-apply caller (draft restore, useLinkedDoc's back/re-open, per-document copies) filters with it, and the highlighter and applyRestoredAnchors skip the same rows, so a diff-view comment's blockId is never rewritten. Behavior change worth a release note: any restored comment the restore cannot paint now shows the Unanchored chip, not only one whose stored positions landed on other text, so comments with no stored positions (share-link imports, external/SSE comments, Edit Mode repaints) are chipped when their quote is not in the document. A save refused as stale (another session on the same file decided or saved ahead) answers 409 { ok: false, error, found, draftGeneration }; DraftTransport.save may resolve { staleGeneration } and the hook raises its counter above it and saves once more, so the reviewer's comments are not silently left unsaved.
  • Per-document copies: every document a local-file or folder session holds comments on, other than the session's own root, is saved under that document's path key by the client hook packages/editor/hooks/useDocumentDrafts.ts (pure planning in packages/editor/documentDrafts.ts), and merged in the first time the document opens in a session (ids already held are skipped; a toast says how many came back). So a file's comments follow it between a folder session and a session on the file alone. These writes are generation-stamped by the server (one above whatever the key has seen), so a single-file session that later loads the copy resumes above it. A document is written only after its copy was read, and sent empty only when it was sent with content before. With per-document copies on, the session draft carries the ROOT document's comments even while another document is open (composeSessionDraft in documentDrafts.ts), plus every document the server keeps no copy for: one it refuses (400/403: a path /api/doc would not serve that reader, such as a code or data file outside the roots or any path outside them for a reader that keeps the roots (#2291), a symlink alias of the root, not a regular file) and a copy of the root opened through a self-link, so those stay crash-recoverable as before. Paths are canonicalized with realpath and must name an existing regular file (canonicalDocumentPath), so an alias shares its target's key.
  • Clearing: a decision (/api/feedback, /api/approve, and the reviewer's Close /api/exit, which deleted the draft before this too) clears the session's keys and the path copy of every document the DECIDING PAGE read, wrote or restored. Each page load makes one page id (draftClientId in App) and sends it as ?client= on every /api/draft/document request and on the decision; Restore reads each restored copy once under it (adoptRestoredCopies), since GET /api/draft names no page. So a reloaded or crashed tab's copies that the new page never opened are not deleted by the new page's send: they stay listed and are offered again. This is the same per-page rule code review's local drafts follow (createReviewDraftSession in review-draft.ts). A caller without a page id (an API caller, the scenarios) clears every copy this server wrote, read or offered; a copy only listed in the index is never cleared by it. Then the session refuses session-draft saves (409 { decided: true }, even above the tombstone, so a second tab cannot put back comments that were just sent; never retried by the client) and document writes (409). A client DELETE (everything removed, banner dismissed) clears only the session draft's keys. The client-lease auto-dismiss keeps everything, as before. An agent close (POST /api/host/close, closedBy: "agent") is the other exception: it KEEPS the session draft, its path copy and every document copy (closeKeepingDraft), so they come back when the file is reopened, even after an edit. Saves and document writes that arrive after it still land (the tab also flushes its pending debounced saves when the session-closed event arrives, flushPendingSave / flushPendingWrite), so a comment typed just before the close is kept; only the closed tab's DELETE is ignored. The closed-tab copy (packages/ui/utils/agentClosed.ts) says per case what brings the draft back: a local file or folder even after edits, a URL or agent message only unchanged, a live app by its address. The host status/close unsentAnnotations count is the session draft the session would restore plus every document copy it covered (countUnsent).
  • Draft Recovered offers every document (#1545): every session with per-document copies (a local file, a folder, a bundle, a URL, the last message) also keeps a durable index of the copies it wrote or read (documentDraftIndexKey(<session key>), createDocumentDraftStore), and GET /api/draft offers every listed document's comments as documents (loadSessionDraftWithDocuments), as in plan review (see "Linked documents in plan review" in plan-review.md). Draft Recovered counts them, Restore puts each on its own document (useLinkedDoc.restoreStoredDocuments, so they count, list and export before the document is opened), and Dismiss also clears their copies. URL and annotate-last sessions have no path key (their session draft is keyed by the content); annotateSessionHasRootlessDocuments gives them copies at all. Before #2263 the session draft carried only the open document. Before this change folder, local-file and bundle sessions had copies but no index: after a reload a document's comments came back only when it was opened again, nothing showed they existed, and a send then deleted the unopened ones.
  • Scope: live-app sessions have no path key and no document copies. Drafts are crash recovery, not history, so PLANNOTATOR_ANNOTATE_HISTORY does not govern them. Known edges: two open sessions on the same file write the same path key and the last save wins; the key is the file's path only, so a raw-HTML session and a --markdown session on the same .html share one copy (raw-HTML pinpoints restored into the converted view, or the other way round, show as Unanchored); and the key follows the path's spelling after realpath, so a file reached through a hard link or a different mount is a different key.

Tests: packages/server/annotate-draft.scenarios.ts (run against both runtimes by packages/server/annotate-draft.test.ts and apps/pi-extension/server/serverAnnotate-drafts.test.ts; includes a folder reload that opens one of three files and sends, a second tab's decision, and a single-file session's linked document), packages/server/linked-document-drafts.scenarios.ts (plan review, last-message and URL sessions, both runtimes; includes the same text decided in a second working folder, which must keep the first folder's copies), packages/ui/hooks/useAnnotationDraft.documents.test.tsx, packages/editor/documentDrafts.test.ts, packages/editor/restoredAnchors.test.ts, and the DOM tests packages/editor/App.documentDrafts.test.tsx, packages/editor/annotationDraftStaleRetry.test.tsx (the 409 retry against real draft sessions), packages/editor/App.restoreAcrossEdit.test.tsx (line labels and chips after a restore across an edit), packages/ui/components/Viewer.restoreMovedAnchors.test.tsx and packages/ui/hooks/useLinkedDoc.reapplyFilter.test.tsx.

Strict direct annotate results

Direct plannotator annotate invocations may add --require-approval and/or --result-file <path> only with --gate --json; both reject --hook and are not shared with OpenCode/Pi slash-command parsing. When neither strict option is present, single-target invocations keep the legacy plaintext, JSON, hook, and exit behavior unchanged, with one plaintext exception and three additive JSON fields. The plaintext exception: a gated approval that carries a note (Approve with a note… / Approve with notes, offered by every --gate session except --hook) prints the configured approvedWithNotes prompt, with its File: / Folder: / URL: / Files: context line (annotateContextLine), instead of The user approved.; a bare approval still prints that line byte for byte. First, a non-gated Done with nothing to send prints {"decision":"annotated","feedback":"User reviewed the document and has no feedback.","nothingToSend":true,"annotationCount":0} (nothingToSend appears only in that case and only on the non-strict --json record and the opencode-annotate-last record; decision values, the feedback text, plaintext, --hook output, the strict-gate record and every exit code are unchanged; the OpenCode CLI bridge, Amp and Droid read it; #1701). Second, annotationCount (the number of annotations the decision carried) rides every approved and annotated record of the non-strict --json output, opencode-annotate-last, and opencode-review; the OpenCode bridge names it in its decision heading, and the strict-gate record does not carry it. Third, target (the absolute file or folder path, URL, or a bundle's files, as the CLI resolved them) rides every non-strict --json record and opencode-review (the PR URL, patch file or directory), so the OpenCode bridge names the file the CLI actually opened (see "Decision targets"); plaintext, --hook and the strict-gate record do not carry it. Note for exact-string matchers: the non-strict --json DISMISSED record, which used to be exactly {"decision":"dismissed"}, now also carries target ({"decision":"dismissed","target":"/abs/notes.md"}); parse the JSON and read decision instead of comparing the line. Multi-token invocations go through the tolerant tiers described under "Tolerant argument resolution" above; several existing file paths open one review of all of them (strict gates included).

Strict decisions use one newline-terminated JSON record on stdout and, when requested, identical bytes in the result file. Exit codes follow the grep convention: approval exits 0; with --require-approval, annotated and dismissed decisions are published before exiting 1 (negative human outcome); usage/startup/validation failures — bad flag combinations, strict flags outside annotate --gate --json, a missing --result-file parent, a pre-existing or dangling-symlink destination, and every annotate startup failure (missing path, unreachable URL, empty folder, ambiguous name, missing file, oversized file) — exit 2 (the gate itself was misconfigured or could not start). Those startup sites exit 1 as before for non-strict invocations, with one deliberate exception: the multi-token zero-resolve handoff is not a startup failure, so in plain non-strict mode it prints on stdout and exits 0 (under --json/--hook it stays stderr + exit 1). Under a strict flag 1 is reserved for "the reviewer did not approve", so a typo'd path must never masquerade as a rejection. Post-decision publication failures (destination appears between validation and publish, hard links unavailable) also exit 2: the result file was not published, so they present as environment errors — "the gate could not publish its result" — never as a reviewer outcome, and never as approval (still fail-closed, since only 0 means approved). The stdout decision record is written before result-file publication and is still emitted whenever the decision itself completed; only a stdout write failure leaves no record anywhere. Signal deaths keep 128+n. Result paths resolve from the invocation working directory, require an existing parent and absent destination, and publish via a flushed/closed 0600 same-directory temporary file plus an atomic no-clobber hard link—never copy or overwrite fallback (the 0600 mode is a no-op on Windows, and the atomic link/rename is not followed by a parent-directory fsync, so publication is atomic but not crash-durable). Keep reviewed sources at stable project paths; unique result and diagnostic log files may use a narrow temporary directory. Explicit Close emits dismissed; missing results or process/browser failures are recovery cases, never approval.

Abandoned strict gate sessions

Local direct structured gates (--gate --json, not --hook, not remote) advertise a client lease in /api/plan and serve /api/annotate/client-lease (SSE, ANNOTATE_CLIENT_LEASE_STREAM_PATH). Each open stream is one connected review surface; the server heartbeats every 5s and, once at least one client has connected, starts a 30s reconnect grace when the last one disconnects. A reconnect inside the grace continues the same review; expiry resolves the gate as the same dismissed decision an explicit Close produces, except that it keeps the saved annotation draft so an abandoned review can still be recovered. Approve, feedback, explicit exit, and server stop all cancel a pending expiry. Whichever producer settles the session first wins: every one of them (each connected surface and the expiry itself) goes through a single one-shot settlement, so a decision arriving after the session already resolved is rejected with 409 rather than deleting the draft and reporting success for an outcome the caller never received. Page lifecycle events are deliberately not used: pagehide/beforeunload also fire on reload and navigation, so they cannot distinguish abandonment from a reconnect. A session that never receives its first client never auto-dismisses, so browser-launch failures still need a caller-side timeout, and remote/shared sessions keep the capability off because tunnel disconnects would read as abandonment — as do --tailscale-published sessions, which force local mode but are reached through the serve proxy, whose disconnects would read the same way.

Live app annotation (annotate-app)

Live local app annotation (spec: adr/research/SPIKE-local-app-annotation-20260810.md, section 7; phase 1 shipped it on the Bun path, phase 2 brought the Pi extension to parity). plannotator annotate http://localhost:5173 probes the loopback URL (3s timeout, accept: text/html) and, when the probe returns an HTML page, starts server mode "annotate-app" instead of converting the page: a dedicated loopback reverse proxy mirrors the whole dev-server origin on its own 127.0.0.1 port, injects <script src="/__plannotator__/bridge.js"> into every HTML response (streaming, exactly once per document), and passes WebSockets through so HMR keeps working. Every proxy DECISION — the injector state machine, loopback/Host/Origin predicates, CSP/X-Frame-Options policy, redirect rewrite, WS origin gate, bridge assembly, liveAppDraftIdentity — lives once in packages/shared/live-proxy-core.ts; packages/server/live-proxy.ts is the Bun transport over it and packages/shared/live-proxy-node.ts (vendored to Pi) is the node:http transport, whose WS passthrough replays the client's own handshake upstream over raw TCP and pipes the sockets byte-for-byte. The probe itself (timeout, < 500 status gate, final-response redirect rule) and every user-facing live-mode message are shared too, in packages/shared/live-probe.ts. The editor renders the proxied app full-viewport in an unsandboxed iframe and drives the same pinpoint annotation experience the srcdoc surface provides. --static forces the classic conversion; --app forces live and errors loudly wherever it cannot apply: non-loopback, https, unreachable, non-HTML, off-origin-redirecting, and non-URL (file/folder) targets. "Loopback" means localhost, ::1, or a LITERAL IPv4 address in 127.0.0.0/8 (isLoopbackHostname in live-proxy-core.ts, the single source of truth); DNS names like 127.0.0.1.evil.example are not loopback. Live eligibility is judged on the probe's FINAL response after redirects: a target that 302s off its own loopback origin (auth portal, tunnel splash, another local port) falls back to the static pipeline instead of opening a dead live surface, while same-server redirects stay live-eligible.

The advertised appUrl is the proxy under its LOCALHOST spelling with the target URL's own path and query (http://localhost:<B>/admin?tab=2): localhost keeps the framed app same-site with the editor page and shares the dev app's host-only localhost cookies and storage, which a 127.0.0.1 spelling would not (Safari ITP would then block all cookies in the cross-site iframe). The proxy still BINDS the 127.0.0.1 literal; browsers that resolve localhost to ::1 first fall back to IPv4 on the refused loopback connect. The proxy's port is random unless PLANNOTATOR_LIVE_PORT fixes it (a port or a range), which is for SSH forwarding: fix the editor's port with PLANNOTATOR_PORT too, and forward both ports with the same numbers on both ends (ssh -L 19440:127.0.0.1:19440), since appUrl names the proxy's own port; remote mode stays hard-off for live sessions, so keep PLANNOTATOR_REMOTE=0.

Runtime coverage: the feature ships on the Bun server + Claude Code CLI path AND on the Pi extension (/plannotator-annotate http://localhost:5173 probes live-first through the shared live-probe module, recognizes --app/--static via parseAnnotateArgs's liveFlags opt-in, and surfaces the probe-fallback notice through Pi's notifier; apps/pi-extension/server/serverAnnotate.ts serves the same annotate-app /api/plan payload over the vendored Node live proxy). The OpenCode slash-command parser is still untouched: its URL targets keep static conversion, and it deliberately does NOT opt into liveFlags, so a typo'd --app there stays a visible "File not found" instead of being silently swallowed. Pi has no --tailscale, so its hard-off matrix is remote-mode only (command-side notify + server throw + unconditional loopback bind).

Session shape: the surface opens with pinpoint armed, and it is comment-only; the full interaction contract it shares with raw-HTML sessions is documented once under "## Annotation System" below. Two things are specific to live mode: vim navigation is off outright (vimModeEnabled={liveApp ? false : ...}, packages/editor/App.tsx:5484), because its keyboard cursor writes into the app's own DOM, and the viewer's floating input-method switch is not offered. Text drag-selection commenting is NOT disabled: it stays live in both the armed and Interact states, exactly as on raw HTML. Links follow the same rule as every HTML surface: armed, a plain click (a tap on a phone) on one of the app's links navigates the app for real through the proxy, and Cmd/Ctrl-click (press-and-hold on a phone) pins the link for a comment (see "Links between local HTML documents" under Annotation System). Multi-page sessions are supported in one server session: annotations carry pageUrl (pathname + search, capped at 2048), restore filters to the current page, the export groups feedback under per-page headings while numbering stays global, and the bridge reports SPA navigations via a coalesced page-change message. Version history, durable submission records, URL sharing, portable HTML export, Obsidian/Bear save, and the annotate agent terminal are all off, exactly like URL sessions. Drafts, feedback, approve, gates, and the client lease work unchanged.

Security posture: the proxy binds 127.0.0.1 unconditionally and validates the Host header before touching upstream (DNS-rebinding blunting); PLANNOTATOR_URL_HOST is never applied to the proxy origin. WebSocket upgrades whose browser Origin header is present and does not name the proxy itself are refused before any upstream contact, so a hostile page's cross-site WS connect is never laundered into the origin-less shape dev servers trust as a non-browser client (Vite CVE-2025-24010 class); header-less non-browser clients pass. App CSP on HTML responses is dropped and replaced with a frame-ancestors policy listing exactly the editor origins (amending an arbitrary CSP for an injected script is unpredictable; dev servers rarely ship one; <meta http-equiv> CSP is a documented non-goal); X-Frame-Options is stripped only on those same HTML responses, so non-HTML responses keep whatever framing protection the app shipped. /__plannotator__/bridge.js embeds the per-session token, so its delivery refuses Sec-Fetch-Site values other than same-origin/none (defense in depth against off-origin <script src> token reads; header-less clients pass). Upstream redirect Locations are re-anchored onto the proxy by loopback-host-plus-port equivalence, never by string prefix. A Plannotator server is never proxied, because the proxy passes the browser's Sec-Fetch-Site: same-origin through (mirrored apps need it as sent) and the proxied page would get same-origin writes on it: the probe refuses the Inbox's and live sessions' registered ports before any request (listPlannotatorServerPorts, packages/shared/plannotator-ports.ts) and any response carrying X-Plannotator-Server, which every Plannotator server sets on every response (packages/shared/plannotator-server-marker.ts; --app fails, otherwise static conversion with a notice); the proxy refuses the editor's own port at start and any marked upstream response (502), and tags every forwarded request X-Plannotator-Live-Proxy, which every Plannotator server refuses (403 live_proxy_refused) before any route, so a write never runs even on a server that took the port later. The Inbox's other listeners (the device door's tailnet and Wi-Fi listeners, and "Over your tailnet"'s listener) do not check the tag, and the door listeners do not set the header: they rely on their own guards (the device token with no Origin, TLS, the served Host and owner login), and the tailnet listeners' loopback ports are among the ports the probe refuses. The injected bridge authenticates both message directions with a per-session token plus origin checks, and posts each outbound message once per listed editor origin (the browser delivers only the one matching the parent document, so an editor opened at 127.0.0.1 works too); the parent side keeps every existing size cap. Remote mode is a hard-off with three independent layers and no override env var: the CLI exits with a startup failure suggesting --static (on Pi, the command notifies with the same shared message), startAnnotateServer throws (both the Bun server and the Pi mirror), and neither transport's proxy bind ever follows PLANNOTATOR_REMOTE — both bind the 127.0.0.1 literal unconditionally, asserted at source level by their test suites. --tailscale sessions are hard-off the same way (CLI startup failure + server throw, keyed on tailnetPublished): the annotate server stays loopback-bound but is published across the tailnet through the serve proxy, and a live proxy would relay the user's authenticated dev app to every tailnet peer — the same reasoning that defaults the annotate agent terminal off for tailnet-published sessions. Release-note-worthy behavior change: under PLANNOTATOR_REMOTE, plannotator annotate http://localhost:... previously converted the page silently and now exits with that startup failure asking for --static.

Live restore resilience: a find-and-mark that resolves nothing in live mode keeps its record, seeded with unresolved placeholder targets from the durable anchor/text params, so the mutation-driven reconcile re-acquires the pin once a lazy route or data-dependent tree finishes rendering. Srcdoc restores keep the old fail-closed drop (a static document would never re-resolve).

Known limitations (documented, not bugs): hardcoded absolute origins in the app, origin-pinned CORS to secondary APIs, and OAuth redirect_uri flows land outside the proxy; frame-busting apps break the wrapper; content-encoded HTML that survives the encoding strip renders without the bridge; cross-page annotation clicks do not navigate; a redirect to a DIFFERENT loopback service (another port) is passed through un-rewritten and the iframe leaves the proxy, which is why the probe refuses such targets up front. Manual smoke loop: scripts/live-annotate-smoke.sh (not CI).