agentleFS
brianwestphalbrianwestphal/glassbox/CLAUDE.md

glassbox

CLAUDE.md34 starsChanged 3 months agoMITView on GitHub

A locally-running web application for reviewing AI-generated code. Launched from the CLI inside any git repository, it opens a browser-based diff viewer where users annotate lines with categorized feedback. On completion, annotations are exported as structured markdown that AI tools (Claude Code, Cursor, etc.) can read and act on. The app is a single-entry CLI (src/cli.ts) that: All project documentation lives in docs/. There are three types: AI-oriented summaries (docs/ai/) are the fastest way for a fresh AI session to…

  • Reads credentials
  • Installs packages
  • Commits and pushes

The file

Show its rules and text

We split this CLAUDE.md into the rules it gives an agent

15 rules. About 0 are common, 7 are distinctive, and 8 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈7

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 8

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All project documentation lives in docs/.

    line 29
  2. Distinctive:

    If a change affects existing requirements, update the relevant requirements document.

    line 90
  3. Distinctive:

    If a change introduces a new major area not covered by existing documents, create a new numbered requirements document.

    line 91
  4. Distinctive:

    If a change affects architecture or system design, update the relevant architecture document.

    line 92
  5. Very specific:

    When writing TSX components, they return SafeHtml (which is JSX.Element).

    line 149
  6. Distinctive:

    CRITICAL: When adding a new server-side npm dependency that is kept external (not bundled by tsup), you MUST update three places or the …

    line 251
  7. Very specific:

    Import paths use .js extension (TypeScript convention for ESM)

    line 284
  8. Very specific:

    No ORM — raw SQL queries via PGLite's query() method

    line 285
  9. Very specific:

    Git: commit freely, never push without permission: Commit changes as needed without asking first (follow the project commit style: no …

    line 292
  10. Very specific:

    When a feature touches DOM state that should survive re-renders (input focus + value, contenteditable cursor, <details open> state), kerf …

    line 335
  11. Very specific:

    Not adopted: kerfjs/list (no each()/virtualized lists here), kerfjs/attach, kerfjs/scope.

    line 348
  12. Distinctive:

    When the user gives you work directly (not via the Hot Sheet channel or events), create Hot Sheet tickets before starting implementation — …

    line 366
  13. Very specific:

    Create via the Hot Sheet API (prefer the hotsheet_* MCP tools), mark Up Next, then work through them: set status started → implement → set …

    line 369
  14. Distinctive:

    Double coverage: every feature covered by both unit tests AND E2E tests.

    line 378
  15. Distinctive:

    Adversarial pass on stateful changes: when adding or altering a stateful code path, deliberately try to break it with out-of-order / …

    line 384

≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
CLAUDE.md

Glassbox

Project Overview

A locally-running web application for reviewing AI-generated code. Launched from the CLI inside any git repository, it opens a browser-based diff viewer where users annotate lines with categorized feedback. On completion, annotations are exported as structured markdown that AI tools (Claude Code, Cursor, etc.) can read and act on.

Tech Stack

  • Runtime: Node.js 20+
  • Language: TypeScript (strict mode)
  • Server: Hono framework with @hono/node-server
  • Desktop: Tauri v2 (Rust) — wraps the Node.js server in a native window
  • Database: PGLite (embedded PostgreSQL) — data stored in ~/.glassbox/data/
  • Rendering: kerfjs JSX runtime (no React) — produces HTML strings server-side via SafeHtml; client-side reactivity via mount() / delegate() / signal() / defineStore
  • Build: tsup (server CLI + client JS bundles) + sass (SCSS → CSS)
  • Dev: tsx for direct TypeScript execution (client assets pre-built)

Architecture

The app is a single-entry CLI (src/cli.ts) that:

  1. Parses CLI args to determine review mode (uncommitted, staged, commit, branch, etc.)
  2. Runs git commands to collect file diffs
  3. Creates a review record in PGLite
  4. Starts a Hono HTTP server on port 4183

Documentation

All project documentation lives in docs/. There are three types:

AI-oriented summaries (docs/ai/) are the fastest way for a fresh AI session to orient. Read these at the start of a session before diving into individual docs or source files:

  • docs/ai/code-summary.md — codebase map: directory tree, routes catalog, schema, client modules, build pipeline, and a "Where do I look to…" reverse index. Also human-readable for sanity checking.
  • docs/ai/requirements-summary.md — synthesized view of every requirements doc, organized by theme with status markers.

Both summaries are actively maintained. Update them in the same pass whenever you make a relevant change (see triggers listed in each file's final section). If you add, rename, or renumber a requirements doc, also update the index below.

Requirements documents (docs/N-topic.md) define what the application does. They are numbered for linear reading order and contain functional (FR-) and non-functional (NFR-) requirements:

  • 1-review-workflow.md — Review creation, resumption, completion, history
  • 2-cli-and-server.md — CLI options, HTTP server, API endpoints, browser launch
  • 3-git-integration.md — Repository detection, diff generation, review modes
  • 4-diff-viewing.md — Split/unified modes, syntax highlighting, context expansion, image comparison
  • 5-annotations.md — Categories, CRUD, drag-and-drop, stale handling
  • 6-export.md — Markdown export format and AI tool instructions
  • 7-ai-analysis.md — Risk scoring, narrative ordering, guided review, API keys
  • 8-user-interface.md — Layout, navigation, settings dialog, keyboard shortcuts
  • 9-data-storage.md — PGLite schema, config files, data locality
  • 10-desktop-app.md — Tauri sidecar, launch flows, CLI install, updates
  • 11-build-and-distribution.md — Build pipeline, npm/desktop packaging, CI/CD
  • 12-demo-mode.md — Demo scenarios and isolation
  • 13-navigation.md — Go-to-definition, navigation stack (back/forward)
  • 14-security.md — Network binding, input validation, command execution safety
  • 15-themes.md — Theme system, built-in themes, custom themes, theme editor
  • 16-share-prompt.md — Share prompt trigger, share button, Web Share API
  • 17-claude-channel.md — Claude Code MCP channel integration, channel server, completion modal
  • 18-direct-comparison.md — Diffing two arbitrary files or folders by path (--diff), independent of git history
  • 19-difftool-integration.md — Using Glassbox as a registered git difftool; the glassbox-difftool companion binary, --dir-diff vs per-file modes, and the accumulating single-session model for per-file mode
  • 20-ai-review-notes.md — AI-authored, line-anchored review notes (rationale/proof) emitted by the generating AI, stored as committed SARIF in .pr-notes/, rendered review-comment-style in the diff (P1–P5 shipped: the .pr-notes/ SARIF format + the glassbox note producer CLI, the reader/render path with load-time re-anchoring (stale/outdated notes are hidden — GB-1140), threaded human replies via reply_to_note_id, analysis-prompt + markdown-export folding, and the P4 artifact foundation — text/diagram-source inline blocks + image artifacts via GET /api/review-notes/artifact with sha-256 + Git LFS wiring. Live diagram rendering of diagram-source artifacts shipped via the doc-29 content plugins: renderNoteArtifacts offers each text artifact to the plugin dispatcher and a matching renderer shows it inline as an actual diagram, falling soft to the code block otherwise. Sidebar surfacing shipped (§20.6, GB-1135/1136/1137): a file whose notes belong to THIS review gets a message icon (scoped via notedSourcesInFiles/noteSourceForShardPath — the review's own note shards mapped to sources, not every file with notes on disk → notedFileIds on /api/files), a file whose note shard is in this review's diff but whose source wasn't changed still shows as unchanged with its full content as context so notes anchor (collectNoteOnlyFiles in src/review-notes/unchanged-files.ts, scoped via noteSourceForShardPath to the review's own note changes — not the whole on-disk .pr-notes tree — injected in cli.ts, git modes only), and the committed .pr-notes/ folder is collapsed by default on first visit (noteStorageFolderKeys))
  • 21-sidebar-context-menu.md — Right-click context menu on sidebar file rows; the cross-platform "reveal in file manager" action
  • 22-local-and-on-device-models.md — Local OpenAI-compatible (Ollama/LM Studio) and Apple Foundation Models (on-device) as AI platforms (P1 local platform shipped; Apple FM shipped — its 4096-token window can't fit larger diffs, so selecting Apple lets the user pick a secondary fallback model that absorbs any batch the on-device model can't handle, applied per-batch in runAnalysisBatch; APPLE_FM_ANALYSIS_ENABLED is the kill-switch, §22.10)
  • 23-image-feedback.md — Textual feedback on images: general image comments + comments anchored to reviewer-drawn rectangle regions (normalized {x,y,w,h} coords, shown on both A/B sides). Reuses the annotations table with line_number = 0 + a region_data JSON column; client UI under src/client/diff/imageDiff/ (imageFeedback.tsx + pure regionGeometry.ts)
  • 24-image-comparison-layouts.md — Side by Side image-comparison mode (old A / new B in two panes) with a single sub-option to flip between left/right (default) and over/under layouts. The new default mode for two-sided image (and rendered-SVG) changes; synced zoom/pan; each pane sized to its own image; doc-23 drawn-region feedback works per-pane (A-only on the A pane, B-only on the B pane). Orientation persists as the image_sxs_orientation user preference. Layout-only (no new server route)
  • 25-attachments.md — Reviewer file attachments on any annotation (line comment, image comment/region, note reply). Attach via a button, drag-drop, or paste; bytes stored under <dataDir>/attachments/ with an attachments table; image chips show a thumbnail and open a shared lightbox (src/client/lightbox.tsx); other types open via OS Quick Look (qlmanage -p on macOS, default opener elsewhere — the local Node server shells out, like "reveal in file manager"); the markdown export lists each attachment's absolute path so the AI tool can read it. Wired on line annotations, note replies, and image-feedback comments/regions. Also (GB-953, GB-959) a reviewer marks region(s) on an AI review-note image artifact — inline by dragging on the thumbnail (src/client/diff/noteArtifactRegions.tsx) or in the full-screen lightbox — and they ride into the reply as marked thumbnail(s); a reply can carry several regions, stored as a JSON array in region_data (decode/group in src/utils/artifactRegions.ts, rendered by src/components/reviewNoteRegionThumb.tsx). Client UI: src/client/annotations/attachments.tsx
  • 26-ground-truth-comparison.md — P1 + P2 shipped. A separate mode to compare an actual image against an expected/ground-truth image (design spec, reference render, or previous-actual baseline), even when the expected lives outside the repo. Launched via glassbox --ground-truth <manifest.json> (no git repo required); the manifest (src/ground-truth/manifest.ts — JSON version:1 + comparisons[] of actual/expected/optional label+expectedKind, paths relative to the manifest dir) becomes one synthetic binary image pair per entry (expected = old/A, actual = new/B) served by the existing image route, so the doc-24 comparison modes + doc-23 region marking + doc-18 arbitrary-path plumbing all reuse unchanged. P2 adds a perceptual diff (src/ground-truth/perceptual-diff.ts — pngjs/jpeg-js decode + pixelmatch): a difference score (fraction of changed pixels, anti-aliasing-tolerant) stored on review_files.difference_score, shown per source-list entry + in the diff header, used to sort most-different-first; identical pairs are hidden by default with a toggle. PNG/JPEG only (other formats: no score). P3a + P3b shipped: the version: 2 manifest loader adds an optional ordered sets[].steps[] array (back-compat with v1), flattening each step into one GroundTruthEntry keyed set:<i>/<j>-<basename> carrying setIndex/setLabel/stepIndex/stepCount (steps inherit the set's expectedKind); the flat array rides the existing mode round-trip so the image route + scoring are unchanged. The sidebar renders sets as collapsible named groups (max-aggregate score badge + ordered step rows; buildGroundTruthSourceList in src/client/sidebar/groundTruthGroups.ts, shared with keyboard-nav order) and the diff header shows a "Step k of N — ‹ Prev · Next ›" navigator bounded to the set (groundTruthStepNav). P3c shipped: proof-export guidance (docs/proof-export-guidance.md) + a portable per-project AI skill (docs/skills/export-review-proof/SKILL.md) — screenshots → ground-truth, flows → animated SVG / per-frame sets, logs → doc-20 note artifacts; Glassbox stays consumer-only. P3d shipped: an optional glassbox ground-truth promote <manifest> subcommand (src/ground-truth/promote.ts) rotates baselines by copying current actuals over previous-actual expecteds (specs/references never overwritten; no server, no review DB). Doc 26 P1–P3 are fully shipped
  • 27-gitignore.md — Automatic .gitignore management. At launch, inside a git repo, Glassbox ensures the project .gitignore carries /.glassbox/* + !/.glassbox/settings.json (ignore the directory's contents so the negation can keep the per-project settings.json tracked — a bare .glassbox/ can't, since git won't descend into a fully-ignored dir). Pure computeGitignore + gated ensureGlassboxGitignored in src/git/gitignore.ts, called from src/cli.ts; idempotent, replaces stale .glassbox-style lines, opt-out via a commented matching rule. Replaced the old completion-time prompt (/api/gitignore/add+/dismiss + 30-day cooldown), now removed
  • 28-image-side-focus.md — Single-side image focus (A / B). Two image-comparison modes that show only one side at a time — A = old image only, B = new image only — sitting between Metadata and Side by Side in the segmented control (Metadata · A · B · Side by Side · Difference · Slice). Structurally the existing single-image Image viewer, gated on a two-sided change (data-panel="a"/"b" in src/components/imageDiff.tsx); a/b added to ImageModeSchema and persisted via the existing last_image_mode preference (falls back to Image on single-side files). Per-side region overlays (data-region-side) make doc-23 feedback work like the Side-by-Side panes. View-only: no new server route, no new CSS
  • 29-content-plugins.md — Content plugins (renderers & differs). Shipped (core + delivery + management UI + reference plugins). A plugin boundary so specialized content renderers (file/blob → safe HTML/SVG) and differs (old vs new → diff view) live outside core and are installed opt-in, keeping the local-first core + desktop bundle lean instead of baking in multi-MB format libraries (trigger: diagram-source rendering, GB-910). Shipped: src/plugins/ — the contract (types.ts), zod manifest (manifest.ts), symlink-aware discovery + fail-soft dynamic-import() activation (loader.ts), priority/specificity dispatcher (registry.ts), the process-global registry + renderContent/diffContent/initContentPlugins (index.ts), the review-note artifact integration (artifacts.ts → renderNoteArtifacts, rendered inertly in diffView.tsx), and the file-diff-viewer integration (fileView.ts → renderPluginSvgSide, GB-1052): a plugin-rendered file (e.g. .dot) is treated like an SVG file — the image route serves the rendered SVG as image/svg+xml, the /file/:id view=rendered branch builds <ImageDiff data-is-svg>, and /files flags it (pluginRendered) so the client shows the Code | Rendered toggle (Code = source text diff; Rendered = the SVG in the image viewer with zoom + A/B/difference/side-by-side/slice). So both FR-29.2 integration points are wired. Kill-switch: src/feature-flags.ts PLUGINS_ENABLED (+ GLASSBOX_PLUGINS_DISABLED). Loaded at startup in server.ts. Dev guide: docs/plugin-development-guide.md. First-party plugins live at repo-root plugins/<id>/ (source under src/), built by scripts/build-plugins.mjs (npm run build:plugins) → self-contained bundles in dist/plugins/<id>/. First reference plugin shipped: plugins/graphviz/ (GB-1044) — Graphviz .dot/.gv → SVG via @viz-js/viz (WASM, no DOM). Second: plugins/plantuml/ (GB-1046) — PlantUML .puml/.plantuml/.pu/.iuml → SVG via a local java -jar plantuml.jar -pipe -tsvg subprocess (no pure-JS/WASM engine exists; a local subprocess keeps it offline/local-first). It's separately installable — manifest autoInstall: false (new field; installBundledPlugins skips it) so nobody's forced to have Java — with a setup.mjs helper (checks Java, installs, fetches the ~11 MB jar into the install dir; jar is not committed) and a README documenting the JRE requirement. Fail-soft to the code-block fallback when Java/jar absent. Tests cover the fail-soft paths + a Java-gated live-render test (plugins/plantuml.test.ts, describe.skipIf(!java||!jar)) that runs the real java -jar render when a JRE + jar are present (PLANTUML_JAR env or the installed jar) and skips otherwise — NOT a hardware gate like Apple FM (Java is provisionable in CI, and .github/workflows/live-render.yml does exactly that on demand); out of the default suite because the ~22 MB GPL jar isn't committed AND because a JVM spawned alongside the suite's ~150 concurrent files lost the CPU race, so it also needs GLASSBOX_LIVE_RENDER_TESTS (npm run test:live). PlantUML plugin dep is only Node builtins (child_process/fs) — no core external dep. Third: plugins/mermaid/ (GB-1045) — Mermaid .mmd/.mermaid → SVG via a local mmdc (@mermaid-js/mermaid-cli over puppeteer/Chromium) subprocess (Mermaid is a browser library — measures text via DOM getBBox, no pure-JS/WASM engine; a local subprocess keeps it offline/local-first). Same model as PlantUML: separately installable (autoInstall: false) so nobody's forced to have Chromium, with a setup.mjs that installs the plugin + npm install @mermaid-js/mermaid-cli + puppeteer into the install dir (fetches Chromium on demand; not committed). Plugin spawns node <cli.js> -i in.mmd -o out.svg -q (via process.execPath to sidestep shebang/.cmd quirks); MERMAID_MMDC overrides the CLI path, MERMAID_PUPPETEER_CONFIG passes a -p config for rootless/--no-sandbox. Fail-soft to the code block when mmdc absent or render fails. Plugin dep is only Node builtins (child_process/fs/os) — no core external dep. Tests (tests/unit/plugins/mermaid.test.ts) cover the SVG extractor, mmdcCli resolver, every fail-soft path, and a browser-gated live-render test (describe.skipIf(!live||!mmdc), MERMAID_MMDC env or the installed cli) — verified live rendering real Mermaid source to SVG via headless Chromium. Like PlantUML it also needs GLASSBOX_LIVE_RENDER_TESTS (npm run test:live); .github/workflows/live-render.yml provisions Chromium and runs both on demand. Note @viz-js/viz is a devDependency bundled into the plugin, NOT a core external dep — it does not go in the three-place external-deps list. Desktop delivery (GB-1039): build:plugins → dist/plugins/<id>/ → build-sidecar.sh copies to server/plugins → src/plugins/install.ts installBundledPlugins() auto-installs into ~/.glassbox/plugins/ at startup (version + content-hash freshness + dismissed-plugins.json); installPluginFromDisk/uninstallPlugin back the UI. Enablement (GB-1040, src/plugins/enablement.ts): installed = enabled by default; two independent disable lists — global (~/.glassbox/config.json) + per-project (.glassbox/settings.json), global precedence — gate the loader (a disabled plugin gets status:'disabled', isn't registered); reloadContentPlugins re-applies after a toggle. Management UI: Settings Plugins tab (src/client/settings/pluginsTab.tsx) + GET/POST/DELETE /api/plugins. Preferences (GB-1047, src/plugins/settings.ts): manifest-declared preferences persist per-scope (global config / project settings), back PluginContext.getSetting/setSetting, render in the Plugins tab (auto-save → POST /api/plugins/:id/preferences → reload), worked example = graphviz engine select; secret prefs (secret: true) → OS keychain (GB-1054, src/ai/keychain.ts generic getSecretFromKeychain/saveSecretToKeychain/deleteSecretFromKeychain, account plugin-<id>-<key>), masked in the UI/API (only secretConfigured reported). Native folder picker (GB-1048): a pick_plugin_folder Tauri command (src-tauri/src/lib.rs, tauri-plugin-dialog; registered in generate_handler! + build.rs AppManifest.commands + granted in capabilities/remote-localhost.json) + a Browse… button in the Plugins tab (desktop only; text-path field is the fallback) — compile-verified via cargo check, dialog opening pending a desktop smoke-test. Opt-in install from the UI (GB-1069, FR-29.20): an Available to install section (Settings → Plugins) lists the autoInstall:false bundled plugins not yet installed; clicking Install runs a server-side (local Node sidecar — no Rust) action (src/plugins/install-action.ts installAvailablePlugin) that checks system readiness (manifest install.requirements[] probed by command <checkArgs> — src/plugins/readiness.ts), auto-fixes what it can (copy the bundle + run install.provision[]: fetch a file always, npm-install only if npm present), and for the rest returns specific instructions (requirement hint + skipped/failed step + a cliHint fallback) so the user finishes + clicks Install again (idempotent, non-destructive re-copy preserves provisioned assets). Manifest schema: PluginInstallSchema (requirements[] + provision[] union of fetch/npm-install + cliHint) in manifest.ts; the available list is src/plugins/available.ts (listAvailablePlugins = opt-in bundled not-yet-installed, with a readiness report); routes GET /api/plugins/available + POST /api/plugins/:id/install-bundled; UI in pluginsTab.tsx (doInstallBundled). bundledPluginsDir() is overridable via GLASSBOX_BUNDLED_PLUGINS_DIR. image-codecs is self-contained (copy only); PlantUML declares a java requirement + a plantuml.jar fetch; Mermaid declares an npm requirement + an npm-install (Chromium download). Verified live against the real built plugins (image-codecs installs to ready; PlantUML/Mermaid list with java/npm readiness + provision notes). Image-decoder capability (GB-1063, FR-29.19): beyond renderers/differs, PluginRegistration is additive with an imageDecoders? key — an ImageDecoder ({ name, match, priority?, decode({ bytes, path }) → DecodedImage|null }, bytes → RGBA) registered/dispatched by the same (priority, specificity) rule (ContentPluginRegistry.findImageDecoder) + exposed via decodeImageWithPlugin(bytes, path, mime?) in index.ts. The perceptual diff (doc 26 P2, src/ground-truth/perceptual-diff.ts) consumes it: comparePerceptual is now async and, when core (PNG/JPEG via pngjs/jpeg-js) can't decode a format, consults an installed decoder before returning undecodable — so WebP/AVIF ground-truth pairs become scorable once a codec plugin is installed (heavy/rare codecs stay out of core, opt in by install). The ground-truth launch branch (cli.ts) inits plugins before scoring; fail-soft (a throwing/null decoder → undecodable, no crash). First reference decoder plugin: image-codecs (GB-1064, shipped) — plugins/image-codecs/ registers WebP + AVIF imageDecoders (bytes → RGBA) via the jSquash WASM codecs (@jsquash/webp, @jsquash/avif), esbuild-bundled into a self-contained index.js (the .wasm inlined via a new loader: { '.wasm': 'binary' } in scripts/build-plugins.mjs; codec bytes injected through a WasmLoader — src/decoder.ts + src/plugin.ts — so the decoders unit-test in plain Node without the bundler's .wasm import). No system dep, but separately installable (autoInstall: false, ~1.8 MB codec WASM; setup.mjs just copies the self-contained build — no runtime npm/download) to keep it out of the default install. Contributes no renderer (browsers show WebP/AVIF natively) — only the decode-to-RGBA the perceptual diff needs; the ground-truth launch branch inits plugins before scoring. @jsquash/* are devDependencies bundled into the plugin, NOT core external deps — they do not go in the three-place external-deps list (exactly like @viz-js/viz). Tests: tests/unit/plugins/image-codecs.test.ts drives the real jSquash decoders (WASM from the on-disk codec) — decode fixtures to RGBA, fail-soft on garbage, and make an otherwise-undecodable WebP pair scorable through comparePerceptual; the built self-contained bundle was verified live decoding the fixtures. Committed fixture-plugin e2e (GB-1043, shipped): a Playwright chromium-plugin project (tests/e2e/plugin-render.test.ts) boots a --diff server with a real fixture content plugin (tests/fixtures/plugin/fixture-diagram/, handling .fdiag) copied into an isolated GLASSBOX_CONFIG_DIR before startup + a committed .pr-notes/ note (tests/fixtures/plugin-diff-notes/), driving both FR-29.2 integration points end-to-end — the file-diff path (Code|Rendered toggle → plugin SVG served image/svg+xml) and the artifact path (review-note .fdiag artifact → inline data:image/svg+xml <img>). Management-tab UI e2e (GB-1070, shipped): tests/e2e/plugin-manage.test.ts (same chromium-plugin server) drives Settings → Plugins against the fixture plugin (now declaring a preference + config-layout Test button + a diff-toolbar UI element) + a self-contained opt-in fixture in GLASSBOX_BUNDLED_PLUGINS_DIR — installed list, global enable/disable (UI element show/hide), select preference save+persist, config-layout Test→label, UI-element click→toast, and Available→Install→ready→uninstall. It caught + fixed a real bug: the preference-change delegate's asInput threw on a <select>, so no select preference (incl. graphviz engine) saved from the UI (src/client/settings/dialog.tsx); also made uninstall return the refreshed available list so a bundled opt-in plugin reappears as installable. Remaining-manual: install-from-arbitrary-folder, per-project enablement scope, stateful UI controls. Modeled on the sibling Hot Sheet plugin system (~/Documents/hotsheet docs/18-plugins.md + src/plugins/): directory discovery in ~/.glassbox/plugins/ (symlink-aware), a zod-validated manifest as the single trust boundary, an activate(context) → { renderers?, differs? } lifecycle, self-contained esbuild-bundled plugins loaded by dynamic import(file://) (so they load against the frozen sidecar node_modules), bundled/official plugins auto-installed into the user dir (version + content-hash freshness + dismiss-list) + install-from-disk, in-process full trust (opt-in install = the boundary, no runtime sandbox — doc 14), per-project opt-in enablement, server-side rendering to safe HTML/SVG, and graceful fallback (code block / <img> / "install X" hint) when no plugin matches. One API serves both the file diff viewer AND review-note artifacts (doc 20) — and the host normalizes every plugin SVG to have an intrinsic size at the renderContent choke point (src/plugins/svgSize.ts; Mermaid emits viewBox-only width="100%" SVG that otherwise collapses to ~0×0 in <img> contexts)
  • 30-plugin-ui-extensions.md — Plugin main-app UI extensions (GB-1058). A plugin's second UI surface (beyond content rendering, doc 29): it contributes declarative interactive elements to predefined host locations via context.registerUI([...]) in activate. Locations: header (main-content top bar), diff-toolbar (bottom toolbar), sidebar-footer — fixed server-rendered slots in src/components/reviewShell.tsx (#plugin-ui-*). Element union in src/plugins/types.ts (PluginUIElement): all five render — button + link (GB-1058) and the stateful toggle/switch/segmented-control (GB-1068). Stateful controls carry a stateKey: the host persists the new value there (via the plugin-settings store) and resolves it into each element's value in GET /api/plugins/ui, so authors get persistence free; the client posts { actionId, value } and onAction(actionId, ctx, value?) receives it. Segmented selection math is pure + unit-tested (src/client/plugins/segmentSelection.ts; modes exactly-one/zero-or-one/zero-or-more/one-or-more). Registry: a process-global map in loader.ts (getPluginUIElements/clearPluginUIElements/clearAllPluginUIElements), cleared on every reload so disabled plugins drop out; listPluginUIElements() (index.ts) flattens loaded plugins' elements with pluginId. API: GET /api/plugins/ui; a click round-trips to onAction via the existing POST /api/plugins/:id/action, whose response now carries the optional result (a UIActionResult { message }) the client shows as a toast (shared src/client/toast.tsx showToast). Client render: src/client/plugins/uiExtensions.tsx (initPluginUi/refreshPluginUi) — a single delegate on document.body; re-renders after enable/disable/install/uninstall. Icon = inert plugin-supplied SVG (trusted via opt-in install, doc 29 §29.6). Worked example: the e2e fixture plugin's diff-toolbar button (tests/fixtures/plugin/fixture-diagram/, driven by plugin-manage.test.ts); shipped first-party plugins register no UI elements — the slots are global chrome, visible on every review regardless of file type, so a content plugin must not occupy one without an always-relevant action (the graphviz demo button + Grid toggle were removed for exactly this, GB-1074; enforced by a conventions test). Modeled on Hot Sheet docs/18-plugins.md §18.12 (which likewise declares but doesn't render the stateful controls)
  • 31-plugin-lifecycle-hooks.md — Plugin review lifecycle hooks (GB-1065). The first general (non-content) plugin capability: a plugin's activate registration may include reviewHooks: { onReviewCreated?, onReviewCompleted? } (src/plugins/types.ts; a hooks-only registration is valid, no renderer needed). Hooks get stable plugin-facing shapes — ReviewHookInfo (id/repoPath/repoName/mode/status) + AnnotationHookInfo (id/filePath/lineNumber/side/category/content) — not raw DB rows, plus the plugin context. Dispatchers notifyReviewCreated / notifyReviewCompleted (src/plugins/index.ts) iterate loaded plugins fail-soft (a throwing hook is logged + skipped, never blocks the review). Wiring: onReviewCreated fires from server.ts right after initContentPlugins (the review is created in the CLI before the server starts, so this is the first point a plugin can see it); onReviewCompleted fires from the POST /api/review/complete route after generateReviewExport, with the review + all annotations + the export path. Not a new trust grant (plugins already run at full trust) but a hook doing outbound network shifts the local-first posture — documented in doc 29 §29.6. Reference example (JSON summary next to the export) in the dev guide. The heavier bidirectional integration-backend tier is deferred (GB-1066)
  • 32-review-note-reveal.md — Revealing review notes in the diff body (GB-1139). A companion to doc 20's §20.6 for one viewing case: a note anchored to a line inside a collapsed context region. Before this, such a note existed in .pr-notes/ but never rendered (the diff placed notes only on already-shown lines, and expansion revealed code but not notes). Now GET /context/:fileId returns server-rendered note rows for notes in the revealed range (notes:[{line,html}], src/api/context.ts) and hunkExpander splices them in — a sibling row after the line in unified, a partition of the .split-columns block (before-columns · full-width note · after-columns) in split, so the full-width note escapes the two-column layout. Server helpers in src/review-notes/context-notes.ts (reanchorNotesForRange re-anchors against the revealed lines + range-scopes + drops stale notes; renderContextNotes groups by line + renders rows with nested replies); the shared server renderer is exposed via renderReviewNoteRowsHtml (src/components/diffView.tsx). Reveal-on-demand (not pre-expand); stale notes are hidden everywhere (GB-1140 removed the in-diff "outdated" badge + Keep/Discard, so the inline diff hides them too, relative to the reviewed content). Tested: unit (context-notes.test.ts), integration (context-notes-routes.test.ts), and a dedicated chromium-notes e2e project (notes-reveal.test.ts, both modes)
  • 33-native-overlay-hosting.md — Native modal overlay hosting (GB-1143 / GB-1145, shipped on kerf 4.3.0). The 6 modal surfaces (settings dialog, theme manager, theme editor, completion modal, confirm(), choice()) pass native: true so kerf hosts them in a real <dialog>.showModal() — top-layer stacking + document inerting; ARIA is implicit. CSS rework in _modal.scss/_kerf-overlay.scss: dim moved to .<class>::backdrop, UA <dialog> chrome reset, inset:0; margin:auto restored (the * { margin:0 } reset defeats the UA centering), inner box widths made min(90vw, Npx) (they'd collapse inside a shrink-to-fit dialog); .<class>:not(dialog) keeps the div-overlay fallback. Because a native modal inerts everything outside it, the theme manager's context menu is appended to the dialog (handle.el), not document.body (themeManager.tsx), or it'd be non-interactive. Verified in Chromium (behavior e2e + screenshots incl. centering-rect + the stacked context menu) and in the Tauri desktop webview (GB-1145)
  • 34-open-commit-as-review.md — Open a commit as a review (GB-1144, shipped). The follow-on to doc 20 §20.6's origin-commit label: an Open commit button (.ai-note-open-commit, in NoteCommitLabel, diffView.tsx) opens a review note's origin commit as its own review, jumping to the note's file+line. Needed two new capabilities: (1) runtime review creation — POST /api/reviews/from-commit → openCommitReview (src/review-open/commit-review.ts) reuses launchReview's create-and-populate body (getFileDiffs({type:'commit'}) → createReview → addReviewFile + note-only files) and de-dupes via getLatestReviewByMode (reuses any existing commit:<sha> review — in-progress OR completed, GB-1149 — safe because the reviewed sha is immutable), canonicalizing the sha to full 40-char (resolveCommitSha in src/git/repo.ts) so short/full spellings map to one commit:<sha> review; unknown sha → 404 (CommitNotFoundError). This is the only route that creates a review (the CLI is otherwise the sole creator); the created review is normal (shows in history). (2) file+line deep-link — a review page honors ?file=&line= at load (parseDeepLink in src/client/diff/deepLink.ts → existing navigateToLocation), skipping auto-select-first, then cleans the query (history.replaceState); the /review/:id→/ redirect preserves the query. Fail-soft + in-place: an unresolvable commit shows a toast, no navigation, identical in browser + Tauri (window.location.assign, no second window)

Architecture documents describe system design and setup:

  • ARCHITECTURE.md — Overall software architecture (components, data flow, build pipeline)
  • tauri-architecture.md — Tauri desktop integration (sidecar, launch flows, CLI wrappers)
  • tauri-setup.md — Tauri setup guide (certificates, signing keys, GitHub secrets)

AI-integration docs target an AI tool/agent consuming Glassbox from another project (distinct from docs/ai/*, which target an AI working on this codebase, and from this CLAUDE.md):

  • AGENTS.md (repo root) — one-screen router: contributors → CLAUDE.md + docs/ai/; integrators → docs/ai-integration.md. Keep its quick-reference table in sync with the integration surfaces.
  • docs/ai-integration.md — the integration hub: launch a review, write glassbox note review notes (.pr-notes/), export ground-truth proof, consume .glassbox/latest-review.md, MCP/Claude channel. Cross-links the deep docs (2/3/6/17/18/20/26). Update it when a launch mode, a glassbox note flag, the export path/format, or the channel contract changes.
  • docs/proof-export-guidance.md + docs/skills/export-review-proof/SKILL.md — proof-export convention + portable per-project agent skill (doc 26 P3c).
  • docs/plugin-development-guide.md — how a third party builds a Glassbox content plugin (renderer/differ) for doc 29: directory + manifest, the activate(context) → { renderers?, differs? } entry, the ContentRenderer/ContentDiffer/PluginContext shapes + a copy-paste standalone types.ts, the safe-output (inert SVG/HTML) contract, a diagram-plugin skeleton, and install/trust. Cross-linked from docs/ai-integration.md §6. Update it when the doc-29 contract changes.

When making changes, keep docs in sync:

  • If a change affects existing requirements, update the relevant requirements document.
  • If a change introduces a new major area not covered by existing documents, create a new numbered requirements document. Insert it at the appropriate position in the reading order and renumber subsequent documents.
  • If a change affects architecture or system design, update the relevant architecture document.
  • For complex new subsystems, create a dedicated architecture document rather than overloading existing ones.

Key Directories

  • src/cli.ts — CLI entry point, arg parsing. Also dispatches standalone subcommands before normal arg parsing: glassbox note (producer-side review-note writer, doc 20) and glassbox ground-truth promote <manifest> (doc 26 P3d baseline rotation via src/ground-truth/promote.ts).
  • src/review-notes/ — AI-authored review notes (doc 20): the .pr-notes/ SARIF format (sarif.ts), the path-sharded on-disk store + reader (store.ts; writeReviewNote … loadReviewNotesForFile), the diff-anchored view shape (view.ts), the load-time re-anchorer (reanchor.ts, P3), the analysis/export folding (format.ts, P5 — feeds notes into ai/shared.ts prompts + the export/generate.ts markdown), the glassbox note CLI (cli.ts; add / update / remove / coalesce / instructions), and the inbound AI-instructions contract (instructions.ts). P2 render lives in src/components/diffView.tsx (ReviewNoteRows, server-rendered full-width; stale/outdated notes are hidden — GB-1140; a Reply button threads a human annotation onto a note via the annotations.reply_to_note_id column, rendered nested beneath the note). Note bodies render as markdown via the safe escape-first src/utils/noteMarkdown.ts (shared with the risk/narrative/guided AI notes). Glassbox is the consumer of a tool-neutral, producer-written format.
  • src/cli-difftool.ts — glassbox-difftool bin entry (git-difftool bridge). Dereferences symlinks in git difftool --dir-diff's asymmetric snapshot dirs, then exec's glassbox --diff on the resolved tree. See README "Use as git difftool" for setup.
  • src/server.ts — Hono app setup, middleware injection
  • src/api/ — Typed API layer (shared by client + server). Each per-resource module (annotations.ts, reviews.ts, themes.ts, files.ts, context.ts, outline.ts, image.ts, project-settings.ts, share-prompt.ts, system.ts, ai.ts, channel.ts, review-notes.ts) defines a zod XReqSchema / XRespSchema for each endpoint and exports the inferred TS types alongside the typed client caller functions. Client callers go through apiCall(RespSchema, path, ...) (see src/api/_runner.ts) which validates the response against the schema before returning — a bad response fails loudly at the boundary. Server route handlers parse incoming bodies with parseBody(c, ReqSchema) and validate non-empty path params with requirePathParam(c, name) (both in src/utils/parseBody.ts), returning a structured 400 on failure. The schema is the single source of truth; drift fails at compile time AND at runtime.
  • src/routes/api.ts — JSON API (annotations CRUD, file status, review management). Handlers consume Req/Resp types from src/api/.
  • src/routes/ai-api.ts — AI analysis, configuration, and preferences API. Handlers consume Req/Resp types from src/api/ai.ts.
  • src/routes/pages.tsx — Server-rendered HTML pages
  • src/components/ — TSX components (layout, diffView, fileList, reviewHistory)
  • src/db/connection.ts — PGLite setup and schema initialization (raw SQL, no ORM)
  • src/db/schemas.ts — Zod schemas for every DB row shape (Review, ReviewFile, Annotation, AIAnalysis, AIFileScore, UserPreferences) plus parseRow / parseRows / parseJsonColumn helpers. The SSOT for runtime row validation; queries.ts and ai-queries.ts route every PGLite result through these.
  • src/db/queries.ts — All database operations
  • src/db/ai-queries.ts — AI analysis and preferences database operations
  • src/ai/models.ts — Static AI model lists per platform — now the fallback for live discovery (see list-models.ts); also holds defaults, context windows, and resolveModelId() (best-effort old→new id mapping). Keep reasonably current as a fallback, but live discovery means it no longer needs daily updates.
  • src/ai/list-models.ts — Live model discovery from each provider's models API (fetchAvailableModels), with the static list as fallback; powers GET /api/ai/models
  • src/ai/config.ts — API key resolution (env → keychain → config file) and config management
  • src/ai/client.ts — Unified client for Anthropic, OpenAI, Google, Local (OpenAI-compatible), and Apple (on-device) AI providers
  • src/ai/apple-foundation.ts — Apple Foundation Models bridge (doc 22 P2): a thin wrapper over the apple-fm npm package (probe / generate / isPlatformSupported). Glassbox no longer ships its own Swift helper — apple-fm provides a tested Node library over its own Developer-ID signed + notarized helper binary, which it resolves via APPLE_FM_BIN, then its bundled bin/apple-fm-helper, then PATH. isAppleFoundationAvailable() gates on isPlatformSupported() then probe(), cached; runAppleFoundationInfer() calls generate({system, messages}). Platform-gated + cached; the on-device path is unverifiable in CI (macOS-26 + Apple Intelligence only) and is unit-tested against a mocked apple-fm. apple-fm is a bundled external runtime dep — its package (with the helper) is copied into the sidecar by build-sidecar.sh; the Tauri launcher points APPLE_FM_BIN at server/node_modules/apple-fm/bin/apple-fm-helper; in dev it resolves straight from the project's node_modules. The 4096-token window can't fit the analysis prompt + output for larger diffs, so when apple is the platform the user picks a secondary fallback model (fallbackPlatform/fallbackModel in config → AIConfig.fallback resolved by loadAIConfig): runAnalysisBatch runs each batch on-device and retries any failed batch once with the fallback (rebuilding contexts against the fallback's larger window). APPLE_FM_ANALYSIS_ENABLED (src/ai/models.ts) is the platform kill-switch (doc 22 §22.10)
  • src/ai/context-builder.ts — Builds diff context payloads for AI analysis
  • src/ai/analyze-risk.ts — Risk analysis orchestration with multi-turn context loop
  • src/ai/analyze-narrative.ts — Narrative ordering analysis with multi-turn context loop
  • src/git/diff.ts — Git operations: diff generation, parsing, file listing. Also the repo-less --diff (doc 18) and --ground-truth (doc 26) modes: getFileDiffs / getModeString / parseModeString / getModeArgs / getModeFileContent branch on mode.type
  • src/git/image.ts — Image diff support: old/new image retrieval from git, metadata extraction from headers. getOldImage/getNewImage also serve disk bytes for --diff (rootA/rootB) and --ground-truth (expected→old, actual→new, looked up by manifest key)
  • src/ground-truth/manifest.ts — Ground-truth comparison (doc 26 P1 + P3a): loadGroundTruthManifest(path) reads/validates the JSON manifest (version:1 comparisons[], or version:2 adding optional ordered sets[].steps[]) and resolves each actual↔expected image pair into a flat GroundTruthEntry[] (paths relative to the manifest dir, may live outside the repo). v2 steps flatten in carrying set grouping (setIndex/setLabel/stepIndex/stepCount, keyed set:<i>/<j>-<basename>)
  • src/ground-truth/perceptual-diff.ts — Ground-truth perceptual diff (doc 26 P2): comparePerceptual(actual, expected) decodes PNG/JPEG to RGBA (pngjs/jpeg-js) and runs pixelmatch (YIQ, anti-aliasing-tolerant) → a difference score (fraction of changed pixels); SVG/WebP/corrupt are undecodable (no score). Score computed at launch, stored on review_files.difference_score. Format helpers in src/utils/diffScore.ts
  • src/git/svg-meta.ts — Pure SVG metadata helpers (parseSvgDimensions, svgUsesExternalFonts) for the rendered-view shell. No rendering. SVGs are rendered live in the browser (GB-932): the image route serves them as raw image/svg+xml and the diff view shows them in a native <img>, so animated SVGs animate and the same image-comparison modes (difference/slice/metadata) apply. The old @resvg/resvg-wasm rasterizer, its worker thread (svg-rasterize*.ts), and the dependency were removed — <img> with an SVG source neither executes scripts nor loads external resources, so passing the bytes through is safe
  • src/themes/built-in.ts — Built-in theme definitions (Dark, Light, High Contrast, Dracula, Tokyo Night), ThemeColors type
  • src/themes/config.ts — Theme persistence: active theme in config.json, custom themes in ~/.glassbox/themes/
  • src/routes/theme-api.ts — Theme REST API: list, get/set active, create/update/delete custom themes
  • src/client/themes.ts — Client-side theme switching: applyThemeColors(), switchTheme()
  • src/export/generate.ts — Generates .glassbox/latest-review.md on review completion
  • src/types.ts — Shared Hono environment types
  • src-tauri/ — Tauri desktop app (Rust backend, loading screens, CLI wrappers) — see docs/tauri-architecture.md

Type safety: validating, not asserting

The codebase prefers runtime validation over as assertions for any data crossing a trust boundary (the network, the file system, PGLite, a JSON column). The mechanics:

  • Wire data flows through zod schemas in src/api/*.ts. Never write body as XReq or json as XResp; use parseBody(c, XReqSchema) on the server and apiCall(XRespSchema, ...) on the client.
  • DB rows are validated by parseRow / parseRows in src/db/schemas.ts. Never declare db.query<X>(...) and trust the cast; the helpers return parsed values whose TS type is guaranteed.
  • JSON columns (the dimension_scores / notes columns in ai_file_scores, plus review_files.diff_data) are validated by parseJsonColumn(schema, raw) and FileDiffSchema respectively.
  • JSON config files (~/.glassbox/config.json, project .glassbox/settings.json, custom theme files in ~/.glassbox/themes/*.json) are validated by ConfigFileSchema / ProjectSettingsSchema / StoredCustomThemeSchema at read time.

When as is genuinely the right tool — DOM casts inside delegate(root, 'click', selector, (_e, el) => ...) where the selector is the runtime check, or framework-bridging casts like appFetch as never — keep the cast tight (one line, with the runtime guarantee visible right beside it). Avoid as on anything that started life as JSON.parse, c.req.json, fetch().json(), db.query, or user input.

JSX Runtime

The project uses kerfjs (kerfjs/jsx-runtime) as its JSX runtime — both for server-side HTML rendering and for client-side mount()-driven reactivity. Configured via:

  • tsconfig.json: "jsx": "react-jsx", "jsxImportSource": "kerfjs"
  • tsup.config.ts: esbuild sets options.jsxImportSource = 'kerfjs' (both server and client configs)

When writing TSX components, they return SafeHtml (which is JSX.Element). Import SafeHtml and helpers from kerfjs:

import type { SafeHtml } from 'kerfjs';
import { raw } from 'kerfjs';

Use raw() to inject pre-escaped HTML strings. All string children are auto-escaped. In client code, convert JSX to a DOM element with toElement(jsx) (from src/client/dom.ts); avoid document.createElement and innerHTML = jsx.toString(). For in-place reconciliation of an existing DOM subtree against a new JSX template, use morph(liveRoot, template) from kerfjs.

Client-Side Code

Client-side CSS and JavaScript are built as separate resources, organized into modular files by concern.

SCSS (src/client/styles/): Split into partials by concern:

  • _variables.scss — CSS custom properties (colors, fonts, spacing)
  • _base.scss — Reset and body/layout defaults
  • _sidebar.scss — Sidebar, file list, folder tree, filter, progress bar
  • _diff.scss — Diff view, split/unified modes, hunk separators, line wrapping
  • _annotations.scss — Annotation rows, categories, forms, drag handles, popups
  • _buttons.scss — Button base and variants
  • _history.scss — Review history page
  • _modal.scss — Modal dialogs
  • _scrollbar.scss — Custom scrollbar
  • _ai-sort.scss — Sort mode control, risk badges, score bars, analysis loading
  • _highlight.scss — Syntax highlight token colors
  • _image-diff.scss — Image diff modes (metadata, difference, slice) + zoom/pan
  • _lightbox.scss — Shared full-screen lightbox (attachments + note artifacts)
  • _plugin-ui.scss — Plugin UI-extension slots + controls (doc 30)
  • _settings.scss — Settings dialog (tabs, theme manager/editor, profile, experimental, plugins)
  • _update-banner.scss — Tauri update notification banner
  • styles.scss — Entry point, imports all partials

TypeScript (src/client/): Modular files using TSX and SafeHtml for HTML building:

  • app.tsx — Entry point, init
  • state.ts — Shared types, default factories, and CATEGORIES constants (no runtime state — see stores/)
  • stores/index.ts — Reactive state via kerfjs defineStore: reviewStore, diffViewStore, aiStore, dragStore. Reads use store.state.value.X; writes use store.actions.update({ X: y }) plus named actions for collection mutations (pushFileOrder, setAnnotationCount, setStaleCount, addCollapsedFolder, removeCollapsedFolder, setFileNote, setGuidedNote, setAnalysisState). getAnalysisModeState(mode) resolves a mode's analysis sub-state. Computed: filteredFiles, aiEnabled. New per-concern state goes here; pick the matching store or split a new one off when it's clearly a separate domain.
  • api.ts — client-side debug logging (initDebug / clientLog); all real API traffic goes through the typed callers in src/api/* (the legacy untyped api() helper was removed)
  • sidebar/index.tsx — initSidebar() orchestrator: two kerf mount() trees (sort control + file list), delegate() handlers for every sidebar interaction, effect()-driven auto-scroll-to-selected
  • sidebar/fileListView.tsx — JSX for folder / risk / narrative file lists (keyed with data-key)
  • sidebar/sortControl.tsx — JSX for the sort-mode segmented control and risk dimension select
  • sidebar/sortMode.tsx — Analysis polling logic: switchSortMode, triggerAnalysis, loadAnalysisResults, invalidateAnalysisCache
  • sidebar/riskPopover.tsx — Per-file risk dimension popover
  • sidebar/fileTree.tsx — loadFiles() API call (populates reviewStore)
  • diff/index.tsx — initDiffView() orchestrator: kerf mount() onto #diff-container, async fetch effect that requests /file/:id when (currentFileId, diffMode, ignoreWhitespace, svgViewMode) change, post-render effect that runs highlight + outline + annotation binding, a separate reactive setupAINotesEffect that (re)draws inline AI notes (risk/narrative/guided) on AI-store changes — clearing the prior set first — so a sidebar sort-mode flip redraws them without a diff refetch (the sort mode isn't in the fetch key), and delegate() handlers for hunk-separator clicks, diff-line clicks → annotation form, and drag-and-drop. The mount renders a single <div data-key="gen-N" data-morph-skip>{raw(html)}</div> wrapper — the server-rendered diff HTML lives under data-morph-skip so highlight.js, hunk expansion, and image-diff widgets can mutate it freely without kerf undoing them. Bumping the generation forces the whole subtree to be replaced (file/mode/whitespace switch).
  • diff/selection.ts — selectFile(): updates currentFileId, navStack, marks-as-reviewed. All DOM/fetch work flows through the diff mount.
  • diff/hunkExpander.tsx — handleHunkExpand(el): surgical replaceWith() to splice fetched context lines into the live tree (safe under data-morph-skip).
  • diff/imageDiff/ — Image comparison: index.ts (orchestration + zoom wiring), zoom.ts (zoom state via WeakMap, pan, clamp), sliceTool.ts (slice geometry + clip-path), metadata.tsx (metadata diff loading). Runs imperatively inside the morph-skipped diff content.
  • annotations/events.tsx — bindAnnotationEvents(diffContainer) registers delegate() handlers for every annotation interaction (delete / edit / dblclick-to-edit / reclassify / keep / dragstart / textarea input / Ctrl+Enter save / Escape cancel). No per-element addEventListener.
  • annotations/form.tsx — bindCreateFormEvents(diffContainer) registers the create-form delegates; showAnnotationForm() inserts the form DOM and seeds the edit-form signal.
  • annotations/render.tsx — buildAnnotationItemHtml(annotation) + renderAnnotationInline(). Each annotation row carries data-key={id} for kerf morph identity.
  • annotations/reclassifyPopup.tsx — Shared category-picker popup used by both the row-level reclassify badge and the edit/create form badge.
  • annotations/categories.tsx — buildCategoryBadge(value) + re-exports of the picker entry points. The picker open state lives in categoryPickerSignal in stores/index.ts; mid-edit form content/category lives in editFormSignal (not in DOM, so a sibling annotation update doesn't clobber an open form).
  • review/modal.tsx — Completion modal driven by stage = signal<ModalStage> + kerf mount() on the modal element. The three stages (stale-prompt, completing, done) render different JSX from the same render fn; delegate() on the overlay handles every interaction (cancel / discard stale / keep stale / done / copyable / send to Claude). Complete/Reopen toolbar buttons are wired via delegate(.review-app, …) so the freshly-inserted Reopen button doesn't need re-binding.
  • review/progress.tsx — Progress bar is now reactive. initProgress() creates the bar once (idempotent) and registers an effect() over reviewStore.state.value.files. Adding/removing a file or marking one as reviewed updates the fill width + summary text automatically — no more manual updateProgress() calls.
  • settings/dialog.tsx — Settings modal driven by a single kerf mount(). Per-dialog ui = signal<SettingsUIState> holds the live form state; centralized delegate() handlers cover every tab interaction (tab switch, theme select, platform/model picker, API key save/remove, guided/channel checkboxes, profile tags, share link, app-name input, updates check). Auto-save uses debounced timers. Each tab is a pure JSX-returning render(ctx); bind() is no longer used. Theme editor (themeEditor.tsx) uses signal<Record<string,string>> for the in-progress colors plus an effect() that pushes CSS custom properties to document.documentElement for live preview.
  • dom.ts — toElement() helper for converting JSX to DOM elements

Both are served as static files via /static/styles.css and /static/app.js routes in src/server.ts. The JSX runtime is shared between server and client builds.

Database

Raw PGLite queries (no ORM). Six tables:

  • reviews — review sessions (repo, mode, status)
  • review_files — files in each review (with serialized diff JSON)
  • annotations — line-level annotations with categories
  • ai_analyses — AI analysis runs (per review, risk or narrative)
  • ai_file_scores — per-file AI scores and ordering
  • user_preferences — sort mode, risk dimension, score visibility

Annotation Categories

  • bug — code defect
  • fix — specific fix needed
  • style — stylistic preference
  • pattern-follow — good pattern to replicate
  • pattern-avoid — anti-pattern to stop using
  • note — informational
  • remember — should be persisted to AI config (CLAUDE.md, .cursorrules, etc.)

Build

npm run build          # tsup -> dist/cli.js + build:plugins -> dist/plugins/<id>/ ; plus client bundles
npm run build:client   # Build only client assets (JS + CSS) into dist/client/
npm run build:plugins  # esbuild first-party content plugins -> dist/plugins/<id>/ (doc 29)
npm run dev            # Build client assets + plugins, then run via tsx
npm run tauri:dev      # Build client + plugins + run Node server + Tauri window (dev mode)
npm run tauri:build    # Build sidecar + package native desktop app

The build produces:

  • dist/cli.js — Server ESM bundle with Node shebang. External deps (@electric-sql/pglite, hono, @hono/node-server, @modelcontextprotocol/sdk, kerfjs, apple-fm) are kept external.
  • dist/client/app.global.js — Client JS bundle (IIFE, minified, es2020 target)
  • dist/client/styles.css — Compiled and compressed CSS from SCSS
  • dist/plugins/<id>/ — First-party content plugins (doc 29), self-contained esbuild bundles (index.js + manifest.json). Built by build:plugins (folded into build, dev, tauri:dev, and prepublishOnly), copied into the sidecar by build-sidecar.sh, and auto-installed into ~/.glassbox/plugins/ at startup. So a provided plugin (e.g. graphviz) "just works" in dev, npm installs, and the desktop app with no manual step.

External Dependencies and Production Builds

CRITICAL: When adding a new server-side npm dependency that is kept external (not bundled by tsup), you MUST update three places or the production desktop app will break:

  1. tsup.config.ts — Add to the noExternal exclusion regex so tsup keeps it external (e.g., /^(?!@electric-sql|hono|@hono|@modelcontextprotocol)/)
  2. scripts/build-sidecar.sh — Add to the for pkg in ... loop that copies external deps into the sidecar's node_modules/
  3. This section — Update the list above

In dev mode (npm run dev or tauri:dev), external packages resolve from the project's node_modules/ automatically. In production Tauri builds, the sidecar runs from src-tauri/server/ with only the explicitly copied packages available. Forgetting step 2 causes "module not found" errors that only appear in production.

Current external deps: @electric-sql/pglite, hono, @hono/node-server, @modelcontextprotocol/sdk, kerfjs (pulls in @preact/signals-core), apple-fm (carries the on-device helper binary it resolves relative to its own package, so it must stay external)

Note: the ground-truth perceptual-diff deps (pixelmatch, pngjs, jpeg-js, doc 26 P2) are pure JS and are bundled by tsup (they are not in the noExternal exclusion), so they need none of the three-place external-dep handling above — adding them to the external list would be wrong. The same applies to pglite-migrate (doc 9 §9.1a): zero runtime deps, pure ESM, ~212 KB, fully bundled — verified by grepping dist/cli.js for a residual bare from "pglite-migrate" (there is none). Its one dynamic import(specifier) survives bundling by design: that is how it loads the on-demand-downloaded old PGlite engine from an absolute file:// path outside the bundle.

Testing

npm test              # Unit tests with coverage (vitest)
npm run test:e2e      # E2E tests (Playwright, Chromium)
npm run test:all      # Unit + E2E with merged coverage report (lcov + genhtml)

Test Infrastructure

  • vitest.config.ts — Unit test config, excludes tests/e2e/, coverage via @vitest/coverage-v8
  • playwright.config.ts — E2E config, Chromium only, starts the server in demo mode (--demo:4 --ai-service-test) on port 4183. The --ai-service-test flag mocks AI analysis and bypasses the API-key check so the suite is hermetic (never makes real AI calls, never depends on a key existing on the machine). The demo server's global config dir is redirected to a disposable pid-scoped tmpdir via GLASSBOX_CONFIG_DIR (GB-923), so settings tests can change platform/keys/themes without touching the developer's real ~/.glassbox/config.json (and every run starts from a clean default platform). Under --ai-service-test the server also reports appleAvailable: true so the Apple + fallback-model settings UI is reachable in CI where the on-device helper can't run.
  • tests/e2e/coverage-fixture.ts — Playwright fixture that collects browser V8 coverage per test
  • tests/e2e/memoryHelper.ts — Heap-stability helpers (measureHeap, expectStableHeap) used by stability.test.ts. Forces V8 GC via CDP and reads performance.memory.usedJSHeapSize to assert that repeated interaction (file switching, modal open/close, sort-mode cycling) doesn't grow the heap proportionally with iteration count — catches per-cycle DOM / listener retention of the GB-800 / GB-748 class.
  • scripts/test-all.sh — Orchestrates unit + E2E runs and merges coverage
  • scripts/test-e2e-coverage.sh — Manages server lifecycle for E2E coverage collection
  • scripts/test-e2e-docker.sh (npm run test:e2e:docker) — Runs the Playwright e2e suite inside the same mcr.microsoft.com/playwright:vX.Y.Z-noble Linux image CI uses (version pinned from package.json), so a local sweep reproduces CI faithfully — including environment-dependent failures (no macOS keychain → no API key, Linux paths/fonts, /dev/shm size). Mounts the repo read-write but shadows node_modules with an anonymous volume so the container's Linux-native binaries don't clobber the host's. Pass-through args go to playwright test (e.g. npm run test:e2e:docker -- stability.test.ts). Requires Docker running.

Conventions

  • ESM modules ("type": "module" in package.json)
  • Import paths use .js extension (TypeScript convention for ESM)
  • No ORM — raw SQL queries via PGLite's query() method
  • IDs are generated with Date.now().toString(36) + Math.random().toString(36).slice(2, 10)
  • Hono context variables (reviewId, repoRoot) are typed via AppEnv in src/types.ts
  • Server-rendered HTML for initial page load; client JS for interactivity
  • Client CSS and JS are built separately and served as static files — never inlined in layout
  • Always use American-English spelling and grammar in all source files — code, comments, identifiers, log/error messages, UI strings, documentation, and commit messages. Prefer color/behavior/canceled/canceling/finalize/organize/customize/optimize/analyze/initialize/center/gray over their British variants (colour/behaviour/cancelled/cancelling/finalise/organise/customise/optimise/analyse/initialise/centre/grey). This applies equally to TypeScript, Rust, SCSS, Markdown, and shell scripts.
  • No emoji or decorative Unicode glyphs in the UI — they look unprofessional and render inconsistently across platforms. Use an SVG icon from src/icons.tsx (lucide-style, stroke="currentColor") instead. This covers emoji (📎, ✅, …) and dingbat/geometric glyphs pressed into service as icons (✎, ✕, ▭, ▾, ▸, …). If a needed icon isn't in src/icons.tsx, add it there. (Legitimate text content — e.g. a ✓ inside a mocked test-runner transcript — is fine; this rule is about UI chrome.)
  • Git: commit freely, never push without permission. Commit changes as needed without asking first (follow the project commit style: no Co-Authored-By trailer, no hard-wrapped body lines). Do not run git push unless the user explicitly asks for it.

Ticket References Are Local-Only

Hot Sheet tickets are local-only. Only .hotsheet/settings.json (shareable Hot Sheet config) is tracked in git; the rest of .hotsheet/ — the ticket database and the worklist — is gitignored and lives only on the project maintainer's machine. Ticket IDs (e.g. GB-774) are meaningless to anyone else and there is no shared issue tracker to look them up in.

This has two consequences for everything you write:

  1. Never tell a reader to "see .hotsheet/", "check the worklist", or "look up GB-N" in committed files — code comments, requirements docs, architecture docs, AI summaries, commit messages, PR descriptions, etc. Those references go nowhere for any other reader.
  2. A bare ticket number is not context. If a code comment or doc needs to reference past work, write the reasoning inline. If a ticket ID is included at all, it must be accompanied by a short, self-contained summary of what the ticket was about — written so a reader who can't open the ticket still understands the point. Prefer dropping the ID entirely when the summary already conveys the why.

Both rules apply to committed files (code, docs, commit messages, PR descriptions). They do not apply when writing inside Hot Sheet itself — ticket notes, ticket details, and other Hot-Sheet-only surfaces can reference sibling tickets by bare ID freely, since any reader who is seeing a ticket already has Hot Sheet available to look the reference up.

This section itself, and any other guidance about how you should interact with the local Hot Sheet workflow, is the exception — it is addressed to the AI assistant running against the maintainer's machine.

(The ticket-creation workflow, follow-up rules, incomplete-work checklist, and FEEDBACK NEEDED mechanism live in the Ticket-Driven Work section below.)

Code search (prefer ast-grep for structure)

For structural / syntax-aware searches over source (.ts / .tsx / .rs), use ast-grep (the ast-grep skill, or the CLI: ast-grep run --lang <ts|tsx|rust> -p '<pattern>' <path>) rather than text grep — it matches the AST, so it skips comments/strings and catches multi-line/nested shapes. This is the same mindset as the project's preference for runtime validation over as assertions (§ "Type safety: validating, not asserting"). Good fits in this codebase: $A as $B casts, JSON.parse($X) as $T, db.query<$T>($$$) / c.req.json() as $T trust-boundary casts the conventions forbid, innerHTML = $X, document.createElement($X) (banned in favor of toElement()), inline api<{…}>() / apiCall($$$) shapes, Tauri-unsafe window.confirm / window.open / window.prompt, process.platform / #[cfg(target_os)] branches, specific call/JSX shapes, and codemod-style rewrites. --lang matters: tsx ≠ ts ≠ rust — pick per file extension (.tsx client components are tsx, server .ts is ts, src-tauri/** is rust).

Keep text search (ripgrep / the editor's grep / the Explore agent) for what it's best at: literal strings (e.g. FEEDBACK NEEDED, an error message), identifier/symbol lookups, filenames, and non-code files (Markdown docs / JSON config / SCSS / logs) — there AST has nothing to match and text is simpler + faster.

Code Organization

  • One primary export per file — each file should have one main exported function/concept, with supporting private (non-exported) functions as needed
  • Files should not be excessively long — break up large files by concern into smaller, focused modules
  • Use sub-folders for specialization — group related modules under descriptive directories (e.g., sidebar/, diff/, annotations/, review/)
  • SCSS uses partials — split into _partial.scss files by concern, imported from a single entry point
  • Use TSX/SafeHtml for HTML building — client-side code that builds HTML strings should use the JSX runtime (.tsx files) rather than manual string concatenation. Use raw() from kerfjs for pre-rendered HTML strings in JSX
  • Use toElement() instead of document.createElement() — when creating DOM elements in client code, use the toElement() helper from dom.ts with JSX: toElement(<div className="foo">bar</div>). Resolve JSX to DOM elements only at the last moment. Never use document.createElement() directly

Client reactivity conventions (kerfjs)

The client uses kerfjs for state, render, and event delegation. Follow these patterns when writing new client features:

  • State lives in defineStore modules in src/client/stores/index.ts (reviewStore, diffViewStore, aiStore, dragStore), plus per-feature signal() instances for transient UI state (e.g. editFormSignal). Do not introduce module-scope mutable objects.
  • Per-modal-session signals are a sanctioned exception to "state lives in module-scope signals or stores." Imperative show*Modal() openers (showSettingsDialog, showThemeManager, showThemeEditor, showCompleteModal) declare their reactive state as a local signal() inside the opener's closure, then pass the signal value (not the signal ref) into the JSX-returning render function consumed by mount(). This is intentional and is NOT a kerf Rule 6 violation: the opener is not a JSX-returning component, the render function doesn't close over the signal, and per-session lifetime is exactly what these transient modals want — every open should start fresh, and the signal is disposed when the modal closes via overlay.remove() + disposeMount(). Hoisting these to module scope would create stale-state-on-reopen footguns; keep them local.
  • Re-renders happen via mount(), not by manually calling rebuild functions. mount(rootEl, () => renderJsx()) re-runs the render fn whenever a signal it reads changes, and morphs the live tree against the new template. If you find yourself writing el.innerHTML = jsx.toString() and then a re-bind step, you want mount() (or morph() for one-shot reconciliation).
  • Event handlers use delegate() / delegateCapture() from a single stable root per surface (sidebar, #diff-container, modal overlay, etc.). Inside a mount() tree, per-element addEventListener silently disappears on the next re-render. The exceptions — same precedent across every phase — are document-level listeners for drag lifecycle, popup outside-click dismiss, and global keyboard shortcuts.
  • List items must carry data-key (or a stable id). Required for kerf's keyed reconciler to preserve identity across re-renders. Without a key, items match positionally by tag name — fine for static lists, broken for anything that reorders.
  • data-morph-skip is the escape hatch for library-owned subtrees (the diff content where highlight.js / hunk expansion / image-diff zoom mutate the DOM imperatively). data-morph-skip-children keeps the element's attributes morphing but leaves the subtree alone (for server-rendered shells whose loading-state classes still need to flow). data-morph-preserve keeps an imperatively-injected child surviving the trailing-removal pass when the new template doesn't emit it. See docs/4-render.md in the kerfjs repo for the full taxonomy.

When a feature touches DOM state that should survive re-renders (input focus + value, contenteditable cursor, <details open> state), kerf preserves these automatically during morph — you don't need to manage them imperatively. See kerfjs §4.4.

kerf is on 4.4.0 (GB-1162). The bump from 4.3.0 is purely additive — 4.4.0 = 4.3.0 plus a new opt-in kerfjs/router subpath and nothing else (verified by diffing the package exports); Glassbox doesn't use it (server-rendered, full-page navigation, no SPA routing), so no code changed. The earlier 4.3.0 notes still hold: the bump from 4.2.0 was backward-compatible; 4.3 brought a positionAnchored fix (helps our anchored popups, src/client/popup.ts), transparent moveBefore() state-preserving keyed morphs, and the opt-in kerfjs/overlay native: true adopted for the app's modal surfaces (doc 33). The 4.2 specifics below still hold.

kerf 4.2 specifics (upgraded from 4.1, which came from 3.0, 2.0, and 0.16):

  • 4.2.0 is additive, and Glassbox now uses several of its new subpaths (GB-1123). The release ships a renderDocument(node, options?) SSR helper on the main barrel plus eight new optional, tree-shakeable subpaths — kerfjs/list, kerfjs/async, kerfjs/attach, kerfjs/remount, kerfjs/timing, kerfjs/scope, kerfjs/overlay, kerfjs/actions. The 4.2 adoption replaced hand-rolled idioms with these blessed helpers:
    • renderDocument (src/routes/pages.tsx) — replaces the "<!DOCTYPE html>" + page.toString() string concatenation at each SSR route.
    • kerfjs/overlay — positionAnchored backs the shared anchored-popup placement in src/client/popup.ts; confirm + overlay back the theme-manager dialogs (src/client/settings/themeManager.tsx); the completion modal's stale-handling prompt is the N-way choice() (src/client/review/modal.tsx). GB-1127 extended the overlay() migration to the remaining hand-rolled modals — the theme editor (src/client/settings/themeEditor.tsx) and the completion modal shell (openCompletionModal in review/modal.tsx): each dropped its hand-rolled append + mount/disposeMount + manual Escape/backdrop listeners in favor of overlay(renderFn, { className: 'modal-overlay', dismiss: ['escape','backdrop'], trap: true }), delegating on handle.el and cleaning up via handle.result.then(...). This adds a real focus trap + focus restore and Escape dismissal for free. GB-1132 completed the set by migrating the settings dialog (settings/dialog.tsx) too, despite its render-first shell + async build() + module cache + LIFO teardown registry + channel poll + per-tab height measurement: the overlay's content is driven by a swappable render-fn signal (spinner → real shell once data loads), the GB-1130 height pin became a min-height signal read in the template (an imperative style.minHeight would be clobbered by child morphs since the .modal is now part of the mounted template), and each inactive tab panel renders empty ({active ? tab.render(ctx) : null}) because overlay()'s focus trap detects focusables by DOM query and does not skip display:none subtrees — leaving hidden controls rendered would let Tab escape the dialog. One sharp edge: the settings dialog spawns child overlays (theme manager/editor), and kerf's capture-phase Escape doesn't compose across stacked overlays on the same document target, so the settings dialog keeps a bubble-phase Escape (dismiss: ['backdrop'] + own listener) — a child's capture-phase stopPropagation() then prevents the settings dialog closing underneath it, while the focus trap (topmost trap wins) + focus restore stay from overlay(). kerf ships no CSS for overlays, so src/client/styles/_kerf-overlay.scss maps .kerf-overlay / .kerf-confirm* / .kerf-choice* / .kerf-toast* onto Glassbox's existing modal + button variables (imported from styles.scss). Note this means the "breaking (beta)" toast() → { el, dismiss } return change does matter if you call the overlay toast(); the app's own src/client/toast.tsx is separate and unchanged.
    • delegateActions — not rolled out to the remaining delegate surfaces (GB-1127 investigated, deferred). Beyond the sidebar (a clean homogeneous file-row action table) the candidate surfaces don't fit delegateActions's single-attribute, nearest-match dispatch: annotations/events.tsx mixes event types (click/dblclick/dragstart/input/keydown, only click is foldable) and its data-action="delete"|"edit"|"keep"|"reclassify" names are shared with image-feedback (imageDiff/imageFeedback.tsx) inside the same diff container, so the .annotation-item-scoping is load-bearing — a broadened dispatch would misfire; diff/toolbar.tsx keys on heterogeneous payload-carrying attributes (data-svg-mode/data-diff-mode/ids), not an action-name table. Left as-is; converting would add markup + risk for negative clarity.
    • kerfjs/timing — debounce replaces the hand-rolled clearTimeout/setTimeout auto-save/search debouncers in src/client/settings/dialog.tsx and src/client/sidebar/index.tsx.
    • kerfjs/actions — delegateActions collapses the sidebar's separate delegate() calls into one data-action table (src/client/sidebar/index.tsx).
    • kerfjs/async + kerfjs/remount — the diff view's /file/:id fetch is now a resource() with the stale-response guard built in, and remountOn() replaces the hand-rolled data-key={gen-${n}} + data-morph-skip generation-counter trick for wholesale diff-subtree replacement (src/client/diff/index.tsx).
    • Not adopted: kerfjs/list (no each()/virtualized lists here), kerfjs/attach, kerfjs/scope. The core main-barrel surface (delegate, signal, raw, mount, effect, morph, attr, toElement, delegateCapture, defineStore, computed) is unchanged.
  • Enumerated attributes are not boolean attributes — this is the 4.0 break, and it was a live bug here. draggable, spellcheck, contenteditable, writingsuggestions, translate, and autocorrect take keyword strings, not booleans: write draggable="true" / spellCheck="false" / translate="no" / autocorrect="off", and omit the attribute for the default state. 4.0 rejects the boolean form in the types because it rendered the opposite of what it read — draggable={true} emitted a bare <span draggable>, whose empty value is invalid, so the element fell back to auto, and auto for a span is not draggable. All five Glassbox sites were wrong in exactly that way and are now fixed: the annotation drag handle (annotations/render.tsx, components/diffView.tsx) was not natively draggable at all, and the note-artifact and lightbox images (draggable={false} → omitted → auto → draggable for an <img>) were, which fought the drag-to-mark-a-region gesture. Real boolean attributes (hidden, checked, disabled, autofocus, required, inert) are unaffected, and popover still accepts booleans. A signal-valued attribute is opaque to the types — put the string in the signal (signal('true')). Note this is a types-only change: the runtime still renders a forced boolean the old way, so nothing catches it but the typechecker.
  • <select value> / <textarea value> (and their defaultValue forms) no longer typecheck — neither element has a value content attribute, so that markup was inert. Glassbox already used the correct <option selected> and <textarea>{content}</textarea> forms everywhere, so this cost nothing here. defaultSelected (previously emitted as the unread defaultselected) is also fixed upstream; unused here.
  • href="javascript:void(0)" and its sibling spellings are no longer dropped by the URL screen — dropping the href unmade the anchor, losing :link styling, focusability, and the pointer cursor. Matched whole, so nothing can ride along after the inert body. Glassbox uses no such placeholder links.
  • Bundle size is ~12 KB min+gzip for a realistic import (~13 KB with arraySignal) — the ~6.1 KB figure the older Cursor rules advertised was wrong and is corrected in the refreshed drop-ins.
  • eslint-plugin-kerfjs requires ESLint 9 or 10 (4.1 dropped ESLint 8, which could not load the ESM-only plugin through .eslintrc at all). Glassbox is on flat config with ESLint 10, so it satisfies this directly; the legacy-recommended export is deprecated and unreachable.
  • Fine-grained signal bindings are available: passing a signal/computed itself into a JSX attribute or text hole (class={sig}, <span>{count}</span>) inside a mount() updates just that node with no render re-run — "values bind, structure re-renders." Opt-in per hole; bind a STABLE signal/computed instance (never cond ? sigA : sigB). The existing .value-read-in-render pattern still works. A 2026-07 measured audit (dev-warning sweep + 400-file review benchmark) found only two value-only re-render sites — the sidebar selection flip and the sort-control active segment — and both are gated by defineStore's single state signal: the mount re-runs because the store changed, so a binding only pays after splitting the changing field into its own signal. The attainable win measured ~1.6 ms at a 400-file tail case on a click interaction (~4 µs/row), so bindings were deliberately NOT adopted; re-evaluate only if a surface becomes update-hot (per-frame or per-keystroke on large lists) — and then split the driving field out of the store first.
  • delegateCapture() now walk-up matches like delegate() — pass { match: 'direct' } where exact-element semantics matter (the split-scroll sync in diff/index.tsx does).
  • URL-bearing attributes are screened: javascript:/vbscript: and script-executing data: types (including data:image/svg+xml) are dropped from href/src/xlink:href/formaction/action/data, with a console.warn. For a trusted URL (e.g. the plugin-rendered note-artifact <img> in diffView.tsx), raw(url) is the documented opt-out; pair it with a kerfjs/no-raw-with-dynamic-arg disable comment stating why the value is trusted. (Under kerf 2.x this screen threw rather than warned, because kerf inferred dev mode and always guessed "dev" — see the dev-diagnostics bullet below. It now warns and drops, which is the documented default.)
  • kerf no longer infers dev mode — diagnostics are opt-in by import, and Glassbox deliberately does not opt in. kerf 2.x decided dev-vs-prod by reading globalThis.process?.env?.NODE_ENV; that read is undefined in a browser realm (bundlers substitute the bare process.env.NODE_ENV token and never create a globalThis.process), so undefined !== 'production' was true and every Glassbox browser build silently ran the development path — as did the shipped npm CLI's server-side rendering, since NODE_ENV is normally unset there. kerf 3.0 removes the inference: absent an import('kerfjs/dev') you get production shape. Concretely that means no dev warnings, defineStore's get() returns the plain state instead of a deep read-only Proxy (it is spread on nearly every action in src/client/stores/index.ts, including new Set([...get().collapsedFolders, path]) — a Proxy-over-Set iteration we no longer perform), and the URL screen warns instead of throwing. globalThis.KERF_DEV is no longer consulted. Adding the dev entry would mean giving build:client/tsup a dev-vs-prod split they don't currently have, for warnings that are mostly about each() — which Glassbox never calls (see the next bullet) — so the trade isn't worth it. If you ever do want them, gate the import on your own build flag and use enableWarnings({ … }) rather than the KERF_DEV_WARN_* env vars: the env vars can't be read from a browser realm at all.
  • Glassbox uses none of the list APIs. No each(), no arraySignal, no kerfjs/array-signal. The bulk of kerf 3.0's changes — the each(items, render, { key, cacheKey }) options form, list identity/key, the KERF_DEV_WARN_STALE_INDEX/LIST_REBIND warnings, and a long list of list-reconciliation fixes — therefore do not apply here. Our surface is delegate, signal, raw, mount, effect, morph, attr, toElement, delegateCapture, defineStore, computed. If you reach for each() in new code, read kerf's docs first — key is effectively mandatory whenever a conditional list can render before yours.
  • Inline on* attributes and malformed attribute names throw (string- or function-valued, any case) — the delegate() convention above is now runtime-enforced.
  • The morph no longer positionally adopts a protected node. An element carrying data-morph-skip / data-morph-skip-children / data-morph-preserve is never reused as a positional stand-in for an unrelated template element; the template element is inserted fresh beside it, and a keyed match still morphs in place. Glassbox uses data-morph-skip in ten places (chiefly the diff content, where highlight.js / hunk expansion / the image-diff widgets mutate the DOM imperatively) and currently uses neither -skip-children nor -preserve, so the fix reaches us through data-morph-skip alone — under kerf 2.x a conditional sibling reappearing at one of those positions could have the widget swallow it, duplicate the widget, or leak a bound hole's text into it.
  • The data-kfb/data-kfbrow attributes and kfb:/kfbr:/kf-list: comment prefixes are kerf-reserved marker names — never emit them from our markup or raw().
<!-- hotsheet:begin section=ticket-driven-work v=1 -->

Ticket-Driven Work

When the user gives you work directly (not via the Hot Sheet channel or events), create Hot Sheet tickets before starting implementation — especially for substantial or multi-step work.

  • Do create tickets for: features, bug fixes, refactoring, multi-step tasks, anything changing code. Don't for: simple questions, git commits, quick lookups, trivial one-liners. When in doubt, create them.
  • Create via the Hot Sheet API (prefer the hotsheet_* MCP tools), mark Up Next, then work through them: set status started → implement → set completed with notes.
  • Always create follow-up tickets for incomplete work (unfinished steps, open design questions, known gaps, designed-but-unbuilt features). If it's not in a ticket, it's forgotten.
  • Incomplete-work checklist — before marking a ticket completed, file follow-ups for any: (1) UI placeholder text ("coming soon"), (2) TODO/FIXME comments, (3) documented-but-unimplemented requirements, (4) empty/stub functions returning mock data.
  • Use FEEDBACK NEEDED before deferring or asking about follow-ups. When about to (a) defer a ticket needing more work, (b) ask whether to file follow-ups, or (c) close with a question buried in notes — DON'T. Leave the ticket started, add a FEEDBACK NEEDED: note (per .hotsheet/worklist.md), signal channel done, and wait. It's the only reliable way to surface a question.
<!-- hotsheet:end section=ticket-driven-work --><!-- hotsheet:begin section=testing-philosophy v=2 -->

Testing Philosophy

  • Double coverage: every feature covered by both unit tests AND E2E tests. Unit = logic in isolation; E2E = real user flows through the running app with minimal mocking.
  • Unit tests: Mock external deps (filesystem, network), test real logic.
  • E2E tests: As much as possible, use test automation tools to run realistic, user-facing flows. Minimize mocks.
  • Coverage: Merge all test coverage (e.g. unit, E2E server, E2E browser) into one report. Low-coverage files should get more of both test types. Aim for 100% coverage of code lines, 100% coverage of branches, and 100% of features described in the requirements documentation.
  • Coverage is a floor, not a ceiling: 100% line/branch coverage shows every line ran, not that every behavior — or every sequence of behaviors — is asserted. It is structurally blind to a missing state transition: a bug living in an untested interaction sails through a green 100% report because the individual lines still get hit by isolated, single-operation tests.
  • Transition-matrix testing for stateful modules: for anything with modes / multiple code paths / a cache / a state machine, enumerate the states AND the transitions between them, then write tests that walk realistic multi-step sequences crossing state boundaries — not just each operation from a clean initial state.
  • Adversarial pass on stateful changes: when adding or altering a stateful code path, deliberately try to break it with out-of-order / interleaved / repeated / empty-then-refill sequences; pin any that would have failed as permanent regression tests.
  • Manual test plan: keep a manual test plan doc (e.g. docs/manual-test-plan.md) for features that can't be reliably automated. Keep it up to date — add such features there; when you add automated coverage for a previously-manual item, remove it and note it in an "Automated Coverage Summary".
  • Always fix lint and type errors before finishing: Fix as you go, don't batch.
<!-- hotsheet:begin specifics=testing-philosophy v=1 -->

This project's test setup

  • Unit tests (tests/**/*.test.ts, excluding tests/e2e/; sources live under tests/unit/ and tests/integration/): vitest (vitest.config.ts), coverage via @vitest/coverage-v8. Shared fixtures/helpers live in tests/fixtures/ and tests/helpers/.
  • E2E tests (tests/e2e/*.test.ts): Playwright, Chromium only (playwright.config.ts). They run against a real server started in demo mode (--demo:4 --ai-service-test) on port 4183 — no real AI calls, no dependency on a machine API key, and a disposable per-pid config dir. Always use the shared fixtures: tests/e2e/coverage-fixture.ts (per-test browser V8 coverage) and tests/e2e/memoryHelper.ts (measureHeap / expectStableHeap).
  • Smoke tests (tests/smoke/*.sh): shell scripts run via npm run test:smoke, npm run test:smoke:difftool, and npm run test:smoke:ground-truth. The smoke tests run the built dist/cli.js, so they catch ESM-bundle-only runtime failures the tsx-based e2e suite can't (e.g. a bundled CJS dep calling require() — the GB-976 class). With no argument smoke-test.sh prefers this checkout's dist/cli.js and falls back to a glassbox on PATH; CI passes the binary explicitly when it means to exercise the installed package. Each script serves on its own default port (4199 / 4197 / 4196) resolved through tests/smoke/smoke-lib.sh, which pre-checks the port and fails with a readable message naming it — the servers run with --strict-port, so a port held by an unrelated local service would otherwise abort the run with a raw EADDRINUSE stack dump that reads like a broken bundle. Override per script with GLASSBOX_SMOKE_PORT / GLASSBOX_DIFFTOOL_SMOKE_PORT / GLASSBOX_GT_SMOKE_PORT.
  • Feature-coverage report (npm run check:features, scripts/check-features.ts): the coverage axis orthogonal to line coverage. Extracts a requirement unit per documented behavior from docs/[0-9]*.md (numbered ## N.M / ### N.M headings, or **FR-N.M**/**NFR-N.M** bold ids for the FR-primary docs) and flags any unit with no asserting test in the docs/testing/feature-coverage.json map — including stateful units that list no state transitions. The map is complete and -- --strict runs as an enforcing CI gate (Type Check job in release-candidate.yml): a newly documented behavior shipped without a test or a justified waived entry fails the build. Genuine untestable NFRs + manual-only UI behaviors (docs/manual-test-plan.md) carry a waived justification. See docs/testing/9-feature-coverage.md. Structural invariants line coverage misses live in tests/unit/conventions.test.ts.
  • Live tests (npm run test:live, vitest.config.live.ts): tests that spawn real external tooling or reach the network. Two families, each with its own gate so neither can rejoin the default suite by accident: live render (GLASSBOX_LIVE_RENDER_TESTS) for the PlantUML/Mermaid renders, and live migration (GLASSBOX_LIVE_MIGRATION_TESTS) for the real PG17→PG18 data-directory migration (tests/integration/db/major-migration.test.ts), which downloads the ~25 MB old PGlite engine from the npm registry and boots two Postgres WASM clusters. Separate flags because the two fail for unrelated reasons (missing JRE vs. no network) and one shared flag would make a skip ambiguous. The migration test also runs in CI as a release gate (test-migration in release-candidate.yml) — it needs no system tooling, so unlike the renders it doesn't need the on-demand live-render.yml workflow; the job asserts from the JSON reporter that tests actually ran and none were pending, so a drifted gate can't report green having executed nothing. The PlantUML and Mermaid live renders spawn a real JVM and a real headless Chromium. They are gated on GLASSBOX_LIVE_RENDER_TESTS in addition to their tooling check, and only this config sets it, so npm test skips them. Run alongside the ~150 concurrent files of the default suite they lost the CPU race — the JVM blew a 30s timeout and Chromium failed to launch (so the Mermaid test's 60s timeout could never have helped) — while both passed in seconds alone. The config also sets fileParallelism: false so the two heavyweights don't contend with each other. A tooling gate alone is not sufficient and tests/unit/conventions.test.ts pins this: describe.skipIf(!hasJava) still runs on any machine that happens to have the tool, which is how it regressed.
  • Commands: unit npm test · live-render plugins npm run test:live · E2E npm run test:e2e · merged coverage npm run test:all · CI-parity E2E in Docker npm run test:e2e:docker · feature coverage npm run check:features · lint npm run lint · types npm run typecheck.
  • Coverage merging: npm run test:all (scripts/test-all.sh) collects server V8 coverage (NODE_V8_COVERAGE), browser coverage (Playwright page.coverage + esbuild source maps), and unit coverage (vitest), concatenates them as lcov, and runs genhtml for a combined HTML report.
  • Manual test plan: docs/manual-test-plan.md — features that can't be reliably automated, plus the Automated Coverage Summary of items later promoted to automated tests. Keep it current as features move in and out.
<!-- hotsheet:end specifics=testing-philosophy --><!-- hotsheet:end section=testing-philosophy --><!-- hotsheet:begin section=requirements-documentation v=1 -->

Requirements Documentation

Keep human-readable requirements documents as the source of truth for what the project does, and keep them up to date in the same change as the code (add/remove/modify a requirement → update its doc). Create new docs for major new functional areas. Cross-reference related docs with relative links.

AI Summaries

Maintain two synthesis docs an AI assistant reads at the start of a fresh session — keep them in sync with reality (source doc/code wins on conflict), and prefer small targeted edits over rewrites:

  • A codebase map — directory tree, entry points, data schema, build, tests, settings, and a "where do I look for X" index. Update it in the same change when you add a file or directory, add a route/endpoint, change the schema, add a client module, or add a setting key.
  • A requirements summary — a synthesized view of every requirements doc with status markers (e.g. Shipped / Partial / Design only / Deferred). Update it in the same change when you add a requirements doc, ship a design-only feature, or defer/regress a shipped one.
<!-- hotsheet:begin specifics=requirements-documentation v=1 -->

This project's docs layout

  • Docs folder: docs/.
  • Requirements docs: numbered docs/N-topic.md (linear reading order), containing functional (FR-) and non-functional (NFR-) requirements. The full index lives in the Documentation section near the top of this file. Architecture docs sit alongside them: docs/ARCHITECTURE.md, docs/tauri-architecture.md, docs/tauri-setup.md.
  • Codebase map: docs/ai/code-summary.md — directory tree, routes catalog, schema, client modules, build pipeline, and a "where do I look for X" index.
  • Requirements summary: docs/ai/requirements-summary.md — synthesized view of every requirements doc with status markers.

Both AI-summary files already exist and are actively maintained; update them in the same change as the code (see the per-file triggers in each).

<!-- hotsheet:end specifics=requirements-documentation --><!-- hotsheet:end section=requirements-documentation -->

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.