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
In this repository35 other files it gives its agents.
- AGENTS.mdAGENTS.md
- .cursor/rules/glassbox.mdcCursor rule
- .cursor/rules/hotsheet-instructions.mdcCursor rule
- .cursor/rules/hotsheet.mdcCursor rule
- .cursor/rules/hs-bug.mdcCursor rule
- .cursor/rules/hs-feature.mdcCursor rule
- .cursor/rules/hs-investigation.mdcCursor rule
- .cursor/rules/hs-issue.mdcCursor rule
- .cursor/rules/hs-requirement-change.mdcCursor rule
- .cursor/rules/hs-task.mdcCursor rule
- hotsheetSkill
- hotsheet-workerSkill
- hs-bugSkill
- hs-featureSkill
- hs-investigationSkill
- hs-issueSkill
- hs-requirement-changeSkill
- hs-taskSkill
- absorb-ticketsSkill
- analyze-code-qualitySkill
- check-code-hygieneSkill
- check-requirements-against-codeSkill
- glassboxSkill
- hotsheetSkill
- hotsheet-workerSkill
- hs-bugSkill
- hs-featureSkill
- hs-investigationSkill
- hs-issueSkill
- hs-requirement-changeSkill
- hs-taskSkill
- kerf-appSkill
- prep-major-releaseSkill
- technical-changelogSkill
- ux-reviewSkill
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
- Very specific: line 29
All project documentation lives in docs/.
- Distinctive: line 90
If a change affects existing requirements, update the relevant requirements document.
- Distinctive: line 91
If a change introduces a new major area not covered by existing documents, create a new numbered requirements document.
- Distinctive: line 92
If a change affects architecture or system design, update the relevant architecture document.
- Very specific: line 149
When writing TSX components, they return SafeHtml (which is JSX.Element).
- Distinctive: line 251
CRITICAL: When adding a new server-side npm dependency that is kept external (not bundled by tsup), you MUST update three places or the …
- Very specific: line 284
Import paths use .js extension (TypeScript convention for ESM)
- Very specific: line 285
No ORM — raw SQL queries via PGLite's query() method
- Very specific: line 292
Git: commit freely, never push without permission: Commit changes as needed without asking first (follow the project commit style: no …
- Very specific: line 335
When a feature touches DOM state that should survive re-renders (input focus + value, contenteditable cursor, <details open> state), kerf …
- Very specific: line 348
Not adopted: kerfjs/list (no each()/virtualized lists here), kerfjs/attach, kerfjs/scope.
- Distinctive: line 366
When the user gives you work directly (not via the Hot Sheet channel or events), create Hot Sheet tickets before starting implementation — …
- Very specific: line 369
Create via the Hot Sheet API (prefer the hotsheet_* MCP tools), mark Up Next, then work through them: set status started → implement → set …
- Distinctive: line 378
Double coverage: every feature covered by both unit tests AND E2E tests.
- Distinctive: line 384
Adversarial pass on stateful changes: when adding or altering a stateful code path, deliberately try to break it with out-of-order / …
≈ “Common” is an estimate: at least 1 in 5 of the 28,633 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.
Files
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 viamount()/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:
- Parses CLI args to determine review mode (uncommitted, staged, commit, branch, etc.)
- Runs git commands to collect file diffs
- Creates a review record in PGLite
- 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, history2-cli-and-server.md— CLI options, HTTP server, API endpoints, browser launch3-git-integration.md— Repository detection, diff generation, review modes4-diff-viewing.md— Split/unified modes, syntax highlighting, context expansion, image comparison5-annotations.md— Categories, CRUD, drag-and-drop, stale handling6-export.md— Markdown export format and AI tool instructions7-ai-analysis.md— Risk scoring, narrative ordering, guided review, API keys8-user-interface.md— Layout, navigation, settings dialog, keyboard shortcuts9-data-storage.md— PGLite schema, config files, data locality10-desktop-app.md— Tauri sidecar, launch flows, CLI install, updates11-build-and-distribution.md— Build pipeline, npm/desktop packaging, CI/CD12-demo-mode.md— Demo scenarios and isolation13-navigation.md— Go-to-definition, navigation stack (back/forward)14-security.md— Network binding, input validation, command execution safety15-themes.md— Theme system, built-in themes, custom themes, theme editor16-share-prompt.md— Share prompt trigger, share button, Web Share API17-claude-channel.md— Claude Code MCP channel integration, channel server, completion modal18-direct-comparison.md— Diffing two arbitrary files or folders by path (--diff), independent of git history19-difftool-integration.md— Using Glassbox as a registeredgit difftool; theglassbox-difftoolcompanion binary,--dir-diffvs per-file modes, and the accumulating single-session model for per-file mode20-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 + theglassbox noteproducer CLI, the reader/render path with load-time re-anchoring (stale/outdated notes are hidden — GB-1140), threaded human replies viareply_to_note_id, analysis-prompt + markdown-export folding, and the P4 artifact foundation — text/diagram-source inline blocks + image artifacts viaGET /api/review-notes/artifactwith sha-256 + Git LFS wiring. Live diagram rendering of diagram-source artifacts shipped via the doc-29 content plugins:renderNoteArtifactsoffers 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 vianotedSourcesInFiles/noteSourceForShardPath— the review's own note shards mapped to sources, not every file with notes on disk →notedFileIdson/api/files), a file whose note shard is in this review's diff but whose source wasn't changed still shows asunchangedwith its full content as context so notes anchor (collectNoteOnlyFilesinsrc/review-notes/unchanged-files.ts, scoped vianoteSourceForShardPathto the review's own note changes — not the whole on-disk.pr-notestree — injected incli.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" action22-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 inrunAnalysisBatch;APPLE_FM_ANALYSIS_ENABLEDis 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 theannotationstable withline_number = 0+ aregion_dataJSON column; client UI undersrc/client/diff/imageDiff/(imageFeedback.tsx+ pureregionGeometry.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 theimage_sxs_orientationuser 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 anattachmentstable; image chips show a thumbnail and open a shared lightbox (src/client/lightbox.tsx); other types open via OS Quick Look (qlmanage -pon 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 inregion_data(decode/group insrc/utils/artifactRegions.ts, rendered bysrc/components/reviewNoteRegionThumb.tsx). Client UI:src/client/annotations/attachments.tsx26-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 viaglassbox --ground-truth <manifest.json>(no git repo required); the manifest (src/ground-truth/manifest.ts— JSONversion:1+comparisons[]ofactual/expected/optionallabel+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-jsdecode +pixelmatch): a difference score (fraction of changed pixels, anti-aliasing-tolerant) stored onreview_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: theversion: 2manifest loader adds an optional orderedsets[].steps[]array (back-compat with v1), flattening each step into oneGroundTruthEntrykeyedset:<i>/<j>-<basename>carryingsetIndex/setLabel/stepIndex/stepCount(steps inherit the set'sexpectedKind); 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;buildGroundTruthSourceListinsrc/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 optionalglassbox ground-truth promote <manifest>subcommand (src/ground-truth/promote.ts) rotates baselines by copying current actuals overprevious-actualexpecteds (specs/references never overwritten; no server, no review DB). Doc 26 P1–P3 are fully shipped27-gitignore.md— Automatic.gitignoremanagement. At launch, inside a git repo, Glassbox ensures the project.gitignorecarries/.glassbox/*+!/.glassbox/settings.json(ignore the directory's contents so the negation can keep the per-projectsettings.jsontracked — a bare.glassbox/can't, since git won't descend into a fully-ignored dir). PurecomputeGitignore+ gatedensureGlassboxGitignoredinsrc/git/gitignore.ts, called fromsrc/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 removed28-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"insrc/components/imageDiff.tsx);a/badded toImageModeSchemaand persisted via the existinglast_image_modepreference (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 CSS29-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 indiffView.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 asimage/svg+xml, the/file/:idview=renderedbranch builds<ImageDiff data-is-svg>, and/filesflags 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.tsPLUGINS_ENABLED(+GLASSBOX_PLUGINS_DISABLED). Loaded at startup inserver.ts. Dev guide:docs/plugin-development-guide.md. First-party plugins live at repo-rootplugins/<id>/(source undersrc/), built byscripts/build-plugins.mjs(npm run build:plugins) → self-contained bundles indist/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 localjava -jar plantuml.jar -pipe -tsvgsubprocess (no pure-JS/WASM engine exists; a local subprocess keeps it offline/local-first). It's separately installable — manifestautoInstall: false(new field;installBundledPluginsskips it) so nobody's forced to have Java — with asetup.mjshelper (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 realjava -jarrender when a JRE + jar are present (PLANTUML_JARenv or the installed jar) and skips otherwise — NOT a hardware gate like Apple FM (Java is provisionable in CI, and.github/workflows/live-render.ymldoes 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 needsGLASSBOX_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 localmmdc(@mermaid-js/mermaid-cliover puppeteer/Chromium) subprocess (Mermaid is a browser library — measures text via DOMgetBBox, 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 asetup.mjsthat installs the plugin +npm install @mermaid-js/mermaid-cli + puppeteerinto the install dir (fetches Chromium on demand; not committed). Plugin spawnsnode <cli.js> -i in.mmd -o out.svg -q(viaprocess.execPathto sidestep shebang/.cmd quirks);MERMAID_MMDCoverrides the CLI path,MERMAID_PUPPETEER_CONFIGpasses a-pconfig for rootless/--no-sandbox. Fail-soft to the code block whenmmdcabsent 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,mmdcCliresolver, every fail-soft path, and a browser-gated live-render test (describe.skipIf(!live||!mmdc),MERMAID_MMDCenv or the installed cli) — verified live rendering real Mermaid source to SVG via headless Chromium. Like PlantUML it also needsGLASSBOX_LIVE_RENDER_TESTS(npm run test:live);.github/workflows/live-render.ymlprovisions Chromium and runs both on demand. Note@viz-js/vizis 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.shcopies toserver/plugins→src/plugins/install.tsinstallBundledPlugins()auto-installs into~/.glassbox/plugins/at startup (version + content-hash freshness +dismissed-plugins.json);installPluginFromDisk/uninstallPluginback 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 getsstatus:'disabled', isn't registered);reloadContentPluginsre-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-declaredpreferencespersist per-scope (global config / project settings), backPluginContext.getSetting/setSetting, render in the Plugins tab (auto-save →POST /api/plugins/:id/preferences→ reload), worked example = graphvizengineselect; secret prefs (secret: true) → OS keychain (GB-1054,src/ai/keychain.tsgenericgetSecretFromKeychain/saveSecretToKeychain/deleteSecretFromKeychain, accountplugin-<id>-<key>), masked in the UI/API (onlysecretConfiguredreported). Native folder picker (GB-1048): apick_plugin_folderTauri command (src-tauri/src/lib.rs,tauri-plugin-dialog; registered ingenerate_handler!+build.rsAppManifest.commands+ granted incapabilities/remote-localhost.json) + a Browse… button in the Plugins tab (desktop only; text-path field is the fallback) — compile-verified viacargo 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 theautoInstall:falsebundled plugins not yet installed; clicking Install runs a server-side (local Node sidecar — no Rust) action (src/plugins/install-action.tsinstallAvailablePlugin) that checks system readiness (manifestinstall.requirements[]probed bycommand <checkArgs>—src/plugins/readiness.ts), auto-fixes what it can (copy the bundle + runinstall.provision[]:fetcha file always,npm-installonly ifnpmpresent), and for the rest returns specific instructions (requirement hint + skipped/failed step + acliHintfallback) so the user finishes + clicks Install again (idempotent, non-destructive re-copy preserves provisioned assets). Manifest schema:PluginInstallSchema(requirements[]+provision[]union offetch/npm-install+cliHint) inmanifest.ts; the available list issrc/plugins/available.ts(listAvailablePlugins= opt-in bundled not-yet-installed, with a readiness report); routesGET /api/plugins/available+POST /api/plugins/:id/install-bundled; UI inpluginsTab.tsx(doInstallBundled).bundledPluginsDir()is overridable viaGLASSBOX_BUNDLED_PLUGINS_DIR. image-codecs is self-contained (copy only); PlantUML declares ajavarequirement + aplantuml.jarfetch; Mermaid declares annpmrequirement + an npm-install (Chromium download). Verified live against the real built plugins (image-codecs installs toready; PlantUML/Mermaid list with java/npm readiness + provision notes). Image-decoder capability (GB-1063, FR-29.19): beyond renderers/differs,PluginRegistrationis additive with animageDecoders?key — anImageDecoder({ name, match, priority?, decode({ bytes, path }) → DecodedImage|null }, bytes → RGBA) registered/dispatched by the same(priority, specificity)rule (ContentPluginRegistry.findImageDecoder) + exposed viadecodeImageWithPlugin(bytes, path, mime?)inindex.ts. The perceptual diff (doc 26 P2,src/ground-truth/perceptual-diff.ts) consumes it:comparePerceptualis now async and, when core (PNG/JPEG viapngjs/jpeg-js) can't decode a format, consults an installed decoder before returningundecodable— 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 + AVIFimageDecoders(bytes → RGBA) via the jSquash WASM codecs (@jsquash/webp,@jsquash/avif), esbuild-bundled into a self-containedindex.js(the.wasminlined via a newloader: { '.wasm': 'binary' }inscripts/build-plugins.mjs; codec bytes injected through aWasmLoader—src/decoder.ts+src/plugin.ts— so the decoders unit-test in plain Node without the bundler's.wasmimport). No system dep, but separately installable (autoInstall: false, ~1.8 MB codec WASM;setup.mjsjust 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.tsdrives 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 throughcomparePerceptual; the built self-contained bundle was verified live decoding the fixtures. Committed fixture-plugin e2e (GB-1043, shipped): a Playwrightchromium-pluginproject (tests/e2e/plugin-render.test.ts) boots a--diffserver with a real fixture content plugin (tests/fixtures/plugin/fixture-diagram/, handling.fdiag) copied into an isolatedGLASSBOX_CONFIG_DIRbefore 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 servedimage/svg+xml) and the artifact path (review-note.fdiagartifact → inlinedata:image/svg+xml<img>). Management-tab UI e2e (GB-1070, shipped):tests/e2e/plugin-manage.test.ts(samechromium-pluginserver) 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 inGLASSBOX_BUNDLED_PLUGINS_DIR— installed list, global enable/disable (UI element show/hide),selectpreference 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'sasInputthrew on a<select>, so no select preference (incl. graphvizengine) saved from the UI (src/client/settings/dialog.tsx); also made uninstall return the refreshedavailablelist 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/hotsheetdocs/18-plugins.md+src/plugins/): directory discovery in~/.glassbox/plugins/(symlink-aware), a zod-validated manifest as the single trust boundary, anactivate(context) → { renderers?, differs? }lifecycle, self-contained esbuild-bundled plugins loaded by dynamicimport(file://)(so they load against the frozen sidecarnode_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 therenderContentchoke point (src/plugins/svgSize.ts; Mermaid emits viewBox-onlywidth="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 viacontext.registerUI([...])inactivate. Locations:header(main-content top bar),diff-toolbar(bottom toolbar),sidebar-footer— fixed server-rendered slots insrc/components/reviewShell.tsx(#plugin-ui-*). Element union insrc/plugins/types.ts(PluginUIElement): all five render —button+link(GB-1058) and the statefultoggle/switch/segmented-control(GB-1068). Stateful controls carry astateKey: the host persists the new value there (via the plugin-settings store) and resolves it into each element'svalueinGET /api/plugins/ui, so authors get persistence free; the client posts{ actionId, value }andonAction(actionId, ctx, value?)receives it. Segmented selection math is pure + unit-tested (src/client/plugins/segmentSelection.ts; modesexactly-one/zero-or-one/zero-or-more/one-or-more). Registry: a process-global map inloader.ts(getPluginUIElements/clearPluginUIElements/clearAllPluginUIElements), cleared on every reload so disabled plugins drop out;listPluginUIElements()(index.ts) flattens loaded plugins' elements withpluginId. API:GET /api/plugins/ui; a click round-trips toonActionvia the existingPOST /api/plugins/:id/action, whose response now carries the optionalresult(aUIActionResult { message }) the client shows as a toast (sharedsrc/client/toast.tsxshowToast). Client render:src/client/plugins/uiExtensions.tsx(initPluginUi/refreshPluginUi) — a singledelegateondocument.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 byplugin-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 Sheetdocs/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'sactivateregistration may includereviewHooks: { 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. DispatchersnotifyReviewCreated/notifyReviewCompleted(src/plugins/index.ts) iterate loaded plugins fail-soft (a throwing hook is logged + skipped, never blocks the review). Wiring:onReviewCreatedfires fromserver.tsright afterinitContentPlugins(the review is created in the CLI before the server starts, so this is the first point a plugin can see it);onReviewCompletedfires from thePOST /api/review/completeroute aftergenerateReviewExport, 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). NowGET /context/:fileIdreturns server-rendered note rows for notes in the revealed range (notes:[{line,html}],src/api/context.ts) andhunkExpandersplices them in — a sibling row after the line in unified, a partition of the.split-columnsblock (before-columns · full-width note · after-columns) in split, so the full-width note escapes the two-column layout. Server helpers insrc/review-notes/context-notes.ts(reanchorNotesForRangere-anchors against the revealed lines + range-scopes + drops stale notes;renderContextNotesgroups by line + renders rows with nested replies); the shared server renderer is exposed viarenderReviewNoteRowsHtml(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 dedicatedchromium-notese2e 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()) passnative: trueso 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:autorestored (the* { margin:0 }reset defeats the UA centering), inner box widths mademin(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), notdocument.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, inNoteCommitLabel,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) reuseslaunchReview's create-and-populate body (getFileDiffs({type:'commit'})→createReview→addReviewFile+ note-only files) and de-dupes viagetLatestReviewByMode(reuses any existingcommit:<sha>review — in-progress OR completed, GB-1149 — safe because the reviewed sha is immutable), canonicalizing the sha to full 40-char (resolveCommitShainsrc/git/repo.ts) so short/full spellings map to onecommit:<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 (parseDeepLinkinsrc/client/diff/deepLink.ts→ existingnavigateToLocation), 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, writeglassbox notereview 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, aglassbox noteflag, 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, theactivate(context) → { renderers?, differs? }entry, theContentRenderer/ContentDiffer/PluginContextshapes + a copy-paste standalonetypes.ts, the safe-output (inert SVG/HTML) contract, a diagram-plugin skeleton, and install/trust. Cross-linked fromdocs/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) andglassbox ground-truth promote <manifest>(doc 26 P3d baseline rotation viasrc/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 intoai/shared.tsprompts + theexport/generate.tsmarkdown), theglassbox noteCLI (cli.ts;add/update/remove/coalesce/instructions), and the inbound AI-instructions contract (instructions.ts). P2 render lives insrc/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 theannotations.reply_to_note_idcolumn, rendered nested beneath the note). Note bodies render as markdown via the safe escape-firstsrc/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-difftoolbin entry (git-difftool bridge). Dereferences symlinks ingit difftool --dir-diff's asymmetric snapshot dirs, then exec'sglassbox --diffon the resolved tree. See README "Use asgit difftool" for setup.src/server.ts— Hono app setup, middleware injectionsrc/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 zodXReqSchema/XRespSchemafor each endpoint and exports the inferred TS types alongside the typed client caller functions. Client callers go throughapiCall(RespSchema, path, ...)(seesrc/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 withparseBody(c, ReqSchema)and validate non-empty path params withrequirePathParam(c, name)(both insrc/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 fromsrc/api/.src/routes/ai-api.ts— AI analysis, configuration, and preferences API. Handlers consume Req/Resp types fromsrc/api/ai.ts.src/routes/pages.tsx— Server-rendered HTML pagessrc/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) plusparseRow/parseRows/parseJsonColumnhelpers. The SSOT for runtime row validation;queries.tsandai-queries.tsroute every PGLite result through these.src/db/queries.ts— All database operationssrc/db/ai-queries.ts— AI analysis and preferences database operationssrc/ai/models.ts— Static AI model lists per platform — now the fallback for live discovery (seelist-models.ts); also holds defaults, context windows, andresolveModelId()(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; powersGET /api/ai/modelssrc/ai/config.ts— API key resolution (env → keychain → config file) and config managementsrc/ai/client.ts— Unified client for Anthropic, OpenAI, Google, Local (OpenAI-compatible), and Apple (on-device) AI providerssrc/ai/apple-foundation.ts— Apple Foundation Models bridge (doc 22 P2): a thin wrapper over theapple-fmnpm package (probe/generate/isPlatformSupported). Glassbox no longer ships its own Swift helper —apple-fmprovides a tested Node library over its own Developer-ID signed + notarized helper binary, which it resolves viaAPPLE_FM_BIN, then its bundledbin/apple-fm-helper, thenPATH.isAppleFoundationAvailable()gates onisPlatformSupported()thenprobe(), cached;runAppleFoundationInfer()callsgenerate({system, messages}). Platform-gated + cached; the on-device path is unverifiable in CI (macOS-26 + Apple Intelligence only) and is unit-tested against a mockedapple-fm.apple-fmis a bundled external runtime dep — its package (with the helper) is copied into the sidecar bybuild-sidecar.sh; the Tauri launcher pointsAPPLE_FM_BINatserver/node_modules/apple-fm/bin/apple-fm-helper; in dev it resolves straight from the project'snode_modules. The 4096-token window can't fit the analysis prompt + output for larger diffs, so whenappleis the platform the user picks a secondary fallback model (fallbackPlatform/fallbackModelin config →AIConfig.fallbackresolved byloadAIConfig):runAnalysisBatchruns 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 analysissrc/ai/analyze-risk.ts— Risk analysis orchestration with multi-turn context loopsrc/ai/analyze-narrative.ts— Narrative ordering analysis with multi-turn context loopsrc/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/getModeFileContentbranch onmode.typesrc/git/image.ts— Image diff support: old/new image retrieval from git, metadata extraction from headers.getOldImage/getNewImagealso 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:1comparisons[], orversion:2adding optional orderedsets[].steps[]) and resolves each actual↔expected image pair into a flatGroundTruthEntry[](paths relative to the manifest dir, may live outside the repo). v2 steps flatten in carrying set grouping (setIndex/setLabel/stepIndex/stepCount, keyedset:<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 runspixelmatch(YIQ, anti-aliasing-tolerant) → a difference score (fraction of changed pixels); SVG/WebP/corrupt areundecodable(no score). Score computed at launch, stored onreview_files.difference_score. Format helpers insrc/utils/diffScore.tssrc/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 rawimage/svg+xmland 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-wasmrasterizer, 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 safesrc/themes/built-in.ts— Built-in theme definitions (Dark, Light, High Contrast, Dracula, Tokyo Night), ThemeColors typesrc/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 themessrc/client/themes.ts— Client-side theme switching: applyThemeColors(), switchTheme()src/export/generate.ts— Generates.glassbox/latest-review.mdon review completionsrc/types.ts— Shared Hono environment typessrc-tauri/— Tauri desktop app (Rust backend, loading screens, CLI wrappers) — seedocs/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 writebody as XReqorjson as XResp; useparseBody(c, XReqSchema)on the server andapiCall(XRespSchema, ...)on the client. - DB rows are validated by
parseRow/parseRowsinsrc/db/schemas.ts. Never declaredb.query<X>(...)and trust the cast; the helpers return parsed values whose TS type is guaranteed. - JSON columns (the
dimension_scores/notescolumns inai_file_scores, plusreview_files.diff_data) are validated byparseJsonColumn(schema, raw)andFileDiffSchemarespectively. - JSON config files (
~/.glassbox/config.json, project.glassbox/settings.json, custom theme files in~/.glassbox/themes/*.json) are validated byConfigFileSchema/ProjectSettingsSchema/StoredCustomThemeSchemaat 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 setsoptions.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 bannerstyles.scss— Entry point, imports all partials
TypeScript (src/client/): Modular files using TSX and SafeHtml for HTML building:
app.tsx— Entry point, initstate.ts— Shared types, default factories, andCATEGORIESconstants (no runtime state — seestores/)stores/index.ts— Reactive state via kerfjsdefineStore:reviewStore,diffViewStore,aiStore,dragStore. Reads usestore.state.value.X; writes usestore.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 insrc/api/*(the legacy untypedapi()helper was removed)sidebar/index.tsx—initSidebar()orchestrator: two kerfmount()trees (sort control + file list),delegate()handlers for every sidebar interaction,effect()-driven auto-scroll-to-selectedsidebar/fileListView.tsx— JSX for folder / risk / narrative file lists (keyed withdata-key)sidebar/sortControl.tsx— JSX for the sort-mode segmented control and risk dimension selectsidebar/sortMode.tsx— Analysis polling logic:switchSortMode,triggerAnalysis,loadAnalysisResults,invalidateAnalysisCachesidebar/riskPopover.tsx— Per-file risk dimension popoversidebar/fileTree.tsx—loadFiles()API call (populatesreviewStore)diff/index.tsx—initDiffView()orchestrator: kerfmount()onto#diff-container, async fetch effect that requests/file/:idwhen(currentFileId, diffMode, ignoreWhitespace, svgViewMode)change, post-render effect that runs highlight + outline + annotation binding, a separate reactivesetupAINotesEffectthat (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), anddelegate()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 underdata-morph-skipso 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(): updatescurrentFileId, navStack, marks-as-reviewed. All DOM/fetch work flows through the diff mount.diff/hunkExpander.tsx—handleHunkExpand(el): surgicalreplaceWith()to splice fetched context lines into the live tree (safe underdata-morph-skip).diff/imageDiff/— Image comparison:index.ts(orchestration + zoom wiring),zoom.ts(zoom state viaWeakMap, 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)registersdelegate()handlers for every annotation interaction (delete / edit / dblclick-to-edit / reclassify / keep / dragstart / textarea input / Ctrl+Enter save / Escape cancel). No per-elementaddEventListener.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 carriesdata-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 incategoryPickerSignalinstores/index.ts; mid-edit form content/category lives ineditFormSignal(not in DOM, so a sibling annotation update doesn't clobber an open form).review/modal.tsx— Completion modal driven bystage = signal<ModalStage>+ kerfmount()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 viadelegate(.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 aneffect()overreviewStore.state.value.files. Adding/removing a file or marking one as reviewed updates the fill width + summary text automatically — no more manualupdateProgress()calls.settings/dialog.tsx— Settings modal driven by a single kerfmount(). Per-dialogui = signal<SettingsUIState>holds the live form state; centralizeddelegate()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-returningrender(ctx);bind()is no longer used. Theme editor (themeEditor.tsx) usessignal<Record<string,string>>for the in-progress colors plus aneffect()that pushes CSS custom properties todocument.documentElementfor 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 categoriesai_analyses— AI analysis runs (per review, risk or narrative)ai_file_scores— per-file AI scores and orderinguser_preferences— sort mode, risk dimension, score visibility
Annotation Categories
bug— code defectfix— specific fix neededstyle— stylistic preferencepattern-follow— good pattern to replicatepattern-avoid— anti-pattern to stop usingnote— informationalremember— 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 appThe 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 SCSSdist/plugins/<id>/— First-party content plugins (doc 29), self-contained esbuild bundles (index.js+manifest.json). Built bybuild:plugins(folded intobuild,dev,tauri:dev, andprepublishOnly), copied into the sidecar bybuild-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:
tsup.config.ts— Add to thenoExternalexclusion regex so tsup keeps it external (e.g.,/^(?!@electric-sql|hono|@hono|@modelcontextprotocol)/)scripts/build-sidecar.sh— Add to thefor pkg in ...loop that copies external deps into the sidecar'snode_modules/- 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, excludestests/e2e/, coverage via@vitest/coverage-v8playwright.config.ts— E2E config, Chromium only, starts the server in demo mode (--demo:4 --ai-service-test) on port 4183. The--ai-service-testflag 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 viaGLASSBOX_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-testthe server also reportsappleAvailable: trueso 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 testtests/e2e/memoryHelper.ts— Heap-stability helpers (measureHeap,expectStableHeap) used bystability.test.ts. Forces V8 GC via CDP and readsperformance.memory.usedJSHeapSizeto 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 coveragescripts/test-e2e-coverage.sh— Manages server lifecycle for E2E coverage collectionscripts/test-e2e-docker.sh(npm run test:e2e:docker) — Runs the Playwright e2e suite inside the samemcr.microsoft.com/playwright:vX.Y.Z-nobleLinux image CI uses (version pinned frompackage.json), so a local sweep reproduces CI faithfully — including environment-dependent failures (no macOS keychain → no API key, Linux paths/fonts,/dev/shmsize). Mounts the repo read-write but shadowsnode_moduleswith an anonymous volume so the container's Linux-native binaries don't clobber the host's. Pass-through args go toplaywright 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
.jsextension (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 viaAppEnvinsrc/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/grayover 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 insrc/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-Bytrailer, no hard-wrapped body lines). Do not rungit pushunless 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:
- 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.- 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.scssfiles 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 (
.tsxfiles) rather than manual string concatenation. Useraw()fromkerfjsfor pre-rendered HTML strings in JSX - Use
toElement()instead ofdocument.createElement()— when creating DOM elements in client code, use thetoElement()helper fromdom.tswith JSX:toElement(<div className="foo">bar</div>). Resolve JSX to DOM elements only at the last moment. Never usedocument.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
defineStoremodules insrc/client/stores/index.ts(reviewStore,diffViewStore,aiStore,dragStore), plus per-featuresignal()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 localsignal()inside the opener's closure, then pass the signal value (not the signal ref) into the JSX-returning render function consumed bymount(). 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 viaoverlay.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 writingel.innerHTML = jsx.toString()and then a re-bind step, you wantmount()(ormorph()for one-shot reconciliation). - Event handlers use
delegate()/delegateCapture()from a single stable root per surface (sidebar,#diff-container, modal overlay, etc.). Inside amount()tree, per-elementaddEventListenersilently disappears on the next re-render. The exceptions — same precedent across every phase — aredocument-level listeners for drag lifecycle, popup outside-click dismiss, and global keyboard shortcuts. - List items must carry
data-key(or a stableid). 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-skipis 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-childrenkeeps the element's attributes morphing but leaves the subtree alone (for server-rendered shells whose loading-state classes still need to flow).data-morph-preservekeeps an imperatively-injected child surviving the trailing-removal pass when the new template doesn't emit it. Seedocs/4-render.mdin 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—positionAnchoredbacks the shared anchored-popup placement insrc/client/popup.ts;confirm+overlayback the theme-manager dialogs (src/client/settings/themeManager.tsx); the completion modal's stale-handling prompt is the N-waychoice()(src/client/review/modal.tsx). GB-1127 extended theoverlay()migration to the remaining hand-rolled modals — the theme editor (src/client/settings/themeEditor.tsx) and the completion modal shell (openCompletionModalinreview/modal.tsx): each dropped its hand-rolled append +mount/disposeMount+ manual Escape/backdrop listeners in favor ofoverlay(renderFn, { className: 'modal-overlay', dismiss: ['escape','backdrop'], trap: true }), delegating onhandle.eland cleaning up viahandle.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 + asyncbuild()+ 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 amin-heightsignal read in the template (an imperativestyle.minHeightwould be clobbered by child morphs since the.modalis 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 skipdisplay:nonesubtrees — 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 samedocumenttarget, so the settings dialog keeps a bubble-phase Escape (dismiss: ['backdrop']+ own listener) — a child's capture-phasestopPropagation()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, sosrc/client/styles/_kerf-overlay.scssmaps.kerf-overlay/.kerf-confirm*/.kerf-choice*/.kerf-toast*onto Glassbox's existing modal + button variables (imported fromstyles.scss). Note this means the "breaking (beta)"toast()→{ el, dismiss }return change does matter if you call the overlaytoast(); the app's ownsrc/client/toast.tsxis 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 fitdelegateActions's single-attribute, nearest-match dispatch:annotations/events.tsxmixes event types (click/dblclick/dragstart/input/keydown, only click is foldable) and itsdata-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.tsxkeys 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—debouncereplaces the hand-rolledclearTimeout/setTimeoutauto-save/search debouncers insrc/client/settings/dialog.tsxandsrc/client/sidebar/index.tsx.kerfjs/actions—delegateActionscollapses the sidebar's separatedelegate()calls into onedata-actiontable (src/client/sidebar/index.tsx).kerfjs/async+kerfjs/remount— the diff view's/file/:idfetch is now aresource()with the stale-response guard built in, andremountOn()replaces the hand-rolleddata-key={gen-${n}}+data-morph-skipgeneration-counter trick for wholesale diff-subtree replacement (src/client/diff/index.tsx).- Not adopted:
kerfjs/list(noeach()/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, andautocorrecttake keyword strings, not booleans: writedraggable="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 toauto, andautofor 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, andpopoverstill 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 theirdefaultValueforms) no longer typecheck — neither element has avaluecontent 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 unreaddefaultselected) is also fixed upstream; unused here.href="javascript:void(0)"and its sibling spellings are no longer dropped by the URL screen — dropping thehrefunmade the anchor, losing:linkstyling, 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-kerfjsrequires ESLint 9 or 10 (4.1 dropped ESLint 8, which could not load the ESM-only plugin through.eslintrcat all). Glassbox is on flat config with ESLint 10, so it satisfies this directly; thelegacy-recommendedexport is deprecated and unreachable.- Fine-grained signal bindings are available: passing a signal/
computeditself into a JSX attribute or text hole (class={sig},<span>{count}</span>) inside amount()updates just that node with no render re-run — "values bind, structure re-renders." Opt-in per hole; bind a STABLE signal/computed instance (nevercond ? 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 bydefineStore'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 likedelegate()— pass{ match: 'direct' }where exact-element semantics matter (the split-scroll sync indiff/index.tsxdoes).- URL-bearing attributes are screened:
javascript:/vbscript:and script-executingdata:types (includingdata:image/svg+xml) are dropped fromhref/src/xlink:href/formaction/action/data, with aconsole.warn. For a trusted URL (e.g. the plugin-rendered note-artifact<img>indiffView.tsx),raw(url)is the documented opt-out; pair it with akerfjs/no-raw-with-dynamic-argdisable 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 isundefinedin a browser realm (bundlers substitute the bareprocess.env.NODE_ENVtoken and never create aglobalThis.process), soundefined !== 'production'was true and every Glassbox browser build silently ran the development path — as did the shipped npm CLI's server-side rendering, sinceNODE_ENVis normally unset there. kerf 3.0 removes the inference: absent animport('kerfjs/dev')you get production shape. Concretely that means no dev warnings,defineStore'sget()returns the plain state instead of a deep read-onlyProxy(it is spread on nearly every action insrc/client/stores/index.ts, includingnew Set([...get().collapsedFolders, path])— a Proxy-over-Setiteration we no longer perform), and the URL screen warns instead of throwing.globalThis.KERF_DEVis no longer consulted. Adding the dev entry would mean givingbuild:client/tsup a dev-vs-prod split they don't currently have, for warnings that are mostly abouteach()— 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 useenableWarnings({ … })rather than theKERF_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(), noarraySignal, nokerfjs/array-signal. The bulk of kerf 3.0's changes — theeach(items, render, { key, cacheKey })options form, list identity/key, theKERF_DEV_WARN_STALE_INDEX/LIST_REBINDwarnings, and a long list of list-reconciliation fixes — therefore do not apply here. Our surface isdelegate,signal,raw,mount,effect,morph,attr,toElement,delegateCapture,defineStore,computed. If you reach foreach()in new code, read kerf's docs first —keyis effectively mandatory whenever a conditional list can render before yours. - Inline
on*attributes and malformed attribute names throw (string- or function-valued, any case) — thedelegate()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-preserveis 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 usesdata-morph-skipin ten places (chiefly the diff content, where highlight.js / hunk expansion / the image-diff widgets mutate the DOM imperatively) and currently uses neither-skip-childrennor-preserve, so the fix reaches us throughdata-morph-skipalone — 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-kfbrowattributes andkfb:/kfbr:/kf-list:comment prefixes are kerf-reserved marker names — never emit them from our markup orraw().
<!-- 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 statusstarted→ implement → setcompletedwith 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 aFEEDBACK 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, excludingtests/e2e/; sources live undertests/unit/andtests/integration/): vitest (vitest.config.ts), coverage via@vitest/coverage-v8. Shared fixtures/helpers live intests/fixtures/andtests/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) andtests/e2e/memoryHelper.ts(measureHeap/expectStableHeap). - Smoke tests (
tests/smoke/*.sh): shell scripts run vianpm run test:smoke,npm run test:smoke:difftool, andnpm run test:smoke:ground-truth. The smoke tests run the builtdist/cli.js, so they catch ESM-bundle-only runtime failures the tsx-based e2e suite can't (e.g. a bundled CJS dep callingrequire()— the GB-976 class). With no argumentsmoke-test.shprefers this checkout'sdist/cli.jsand falls back to aglassboxon 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 throughtests/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 rawEADDRINUSEstack dump that reads like a broken bundle. Override per script withGLASSBOX_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 fromdocs/[0-9]*.md(numbered## N.M/### N.Mheadings, or**FR-N.M**/**NFR-N.M**bold ids for the FR-primary docs) and flags any unit with no asserting test in thedocs/testing/feature-coverage.jsonmap — including stateful units that list no state transitions. The map is complete and-- --strictruns as an enforcing CI gate (Type Check job inrelease-candidate.yml): a newly documented behavior shipped without a test or a justifiedwaivedentry fails the build. Genuine untestable NFRs + manual-only UI behaviors (docs/manual-test-plan.md) carry awaivedjustification. Seedocs/testing/9-feature-coverage.md. Structural invariants line coverage misses live intests/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-migrationinrelease-candidate.yml) — it needs no system tooling, so unlike the renders it doesn't need the on-demandlive-render.ymlworkflow; 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 onGLASSBOX_LIVE_RENDER_TESTSin addition to their tooling check, and only this config sets it, sonpm testskips 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 setsfileParallelism: falseso the two heavyweights don't contend with each other. A tooling gate alone is not sufficient andtests/unit/conventions.test.tspins 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 pluginsnpm run test:live· E2Enpm run test:e2e· merged coveragenpm run test:all· CI-parity E2E in Dockernpm run test:e2e:docker· feature coveragenpm run check:features· lintnpm run lint· typesnpm run typecheck. - Coverage merging:
npm run test:all(scripts/test-all.sh) collects server V8 coverage (NODE_V8_COVERAGE), browser coverage (Playwrightpage.coverage+ esbuild source maps), and unit coverage (vitest), concatenates them as lcov, and runsgenhtmlfor 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 -->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
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.

