- Terminal-first diff viewer for understanding coding-agent changesets.
- Product target is "modern desktop diff tool in a terminal", not a pager-style TUI.
packages/hunk/ published CLI, application, and public extension/OpenTUI facades
packages/hunk-vcs/ private dependency-bottom VCS helpers
packages/hunk-{git,jj,sapling}/ private bundled VCS providers
packages/hunk-gh/ private bundled GitHub review extension
packages/session-broker-core/ low-level broker protocol and state
packages/session-broker/ runtime-neutral broker, daemon, auth, and connection lifecycle
packages/session-broker-{bun,node}/ runtime listener adapters
packages/term-video/ private terminal capture tooling
website/ product/documentation site, not the browser review client
main.tsx -> app/startup.ts -> app/cli.ts
-> headless command/history plan returned to main.tsx, or
-> app plan: extensionBootstrap.ts -> sessionBootstrap.ts -> normalized Changeset / DiffFile[]
-> main.tsx lazy-loads runInteractiveApp.tsx -> HunkSessionHost -> AppHost -> App
-> pane/diff planning -> Pierre-backed terminal rows
-> web plan (`--web`, hidden): same bootstrap, no TTY or OpenTUI
-> main.tsx lazy-loads app/session/headlessReviewRunner.ts -> ReviewSessionHost +
ReviewReloadCoordinator + session bridge -> review URL on stdout until SIGINT/SIGTERM
Terminal, agent/session, broker/protocol, extension, and HTTP/SSE consumers share review semantics. The browser client and UI remain planned. Do not recreate semantic review behavior in a surface:
DiffFile[] -> projectReviewDocument -> ReviewDocument -> ReviewStore
ReviewIntent + caller facts -> planReviewIntent -> ReviewAction[] -> reducer -> surface projection
-
Model:
packages/hunk/src/core/review/{types,document,identity}.tsowns the ordered, JSON-safe document. File order is review/sidebar order; usekey(referenced asfileKeyelsewhere),contentIdentity, andsourceIdentity(cached source text additionally requiressourceAttested) — not runtime IDs or indexes — across reloads/surfaces. -
Shared derivations:
geometry.ts,expansion.ts,anchors.ts,stml.ts, andcontentManifest.tsown ranges, gaps, source splitting, note targets/ownership, tag roles, and parity manifests. Consume them; never re-derive those facts in a renderer. -
State:
state.tsis semantic state;actions.tstransitions;reducer.tspure/no-I/O;selectors.tsshared policies;store.tssynchronous observable storage. New cross-surface operations start as intents. Callers supply mutable-note IDs/timestamps; core derives identities. -
Surfaces/publishers:
app/review/reviewSessionHost.tsowns one live review without React: the store, intent facts, live-comment ingestion, agent navigation/highlights, gap source loading, file replacement, and session-export summaries.useTerminalReview.tsis the TUI adapter over it andreviewNoteMapping.tsis terminal-only. Rows, measurement, scrolling, layout, themes, and DOM mechanics stay local; renderer facts reach the host as explicit optional inputs.useHunkSessionBridge.tspublishes the current terminal session export;registration.tsbuilds its metadata/initial snapshot andbridge.tsreceives agent commands. This broker export is not a fullReviewStatemirror. -
Other consumers: Web/API consumers reuse the model, derivations, state, intents, and the producer/protocol tier. Never build a parallel protocol. Keep presentation/client-local state local; host/extension commands need explicit remote capabilities. See
docs/browser-review-rebuild.mdfor the landed phases and current boundaries, anddocs/web-review-plan.mdfor the remaining rollout. -
Conformance:
test/review-conformance/has hand-authored semantic fixtures covering every registered core, terminal, producer, broker, protocol, and extension projection. Every new semantic consumer registers its real projection and runs the whole corpus.scripts/quality/source-boundaries.test.tskeeps the seam renderer/platform-free; its Node-debt list is shrink-only and tombstone lists append-only. A repaid seam finding deletes copies, adds a file or banned-symbol tombstone and adversarial fixture, registers consumers, and updatesdocs/browser-review-seam-audit.md. -
Bundled VCS implementations live in the private
packages/hunk-{git,jj,sapling}workspaces and consume the publichunkdiff/extensioncontract plus explicit@hunk/vcs/*implementation leaves;packages/hunk/src/appcomposes their registrations into the provider-neutral core VCS catalog. Do not add provider commands, spawning, or source readers underpackages/hunk/src/core. -
hunk daemon serveis the one loopback daemon for all live sessions; sessions auto-start and register with it rather than opening per-TUI ports. ReuseclassifyReviewPublicationandReviewChunkAssemblerfor publication ordering and bounded, digest-verified resources. Browser review stays same-origin with no CORS; each session mints its capability and gives the daemon only its digest. Transport semantics come from the browser-safe review protocol modules and the existing intent path. Seedocs/browser-review-rebuild.mdand the relevant module headers. -
User extensions, bundled VCS providers, bundled core commands, and bundled UI share one public registration API and registry model. VCS and UI use dedicated registries; bundled core commands load first into each session-owned extension registry so delegated resources share its lifecycle.
ExtensionSessionowns the user registry across routed surfaces. Keeppackages/hunk/src/extension-api/types.tsimport-free, bundled VCS renderer-free, repo-local extensions trust-gated, and bundled extensions active under--no-extensions. Seedocs/extension-architecture.md,docs/extensions.md, andpackages/hunk/skills/hunk-extensions/SKILL.md. -
Sidecar file order is intentional sidebar and review-stream order.
-
Session wire: the daemon and every window exchange
HUNK_SESSION_DAEMON_VERSION(packages/hunk/src/session/protocol.ts) in the signed hello and require an exact match. Any change to what a session registers or snapshots — underpackages/hunk/src/session/**,packages/hunk/src/core/reviewDescriptor.ts,packages/hunk/src/app/session/registration.ts, or anything else that appears inpackages/hunk/src/session/broker/fixtures/session-wire.v<N>.json— requires a bump.wire.snapshot.test.tsenforces it; bump, runbun run generate:session-wire, and delete the previous fixture in the same change. The cross-revision admin scope (status/stop) is frozen separately and never grows in place. -
Derive shared rendering, navigation, scrolling, and note behavior from one planning layer. Make shared geometry explicit, and remove obsolete paths instead of retaining parallel implementations.
bun run deps:checkenforces both thepackages/*workspace graph andpackages/hunk/src/*tiers;.dependency-cruiser.cjsis authoritative anddocs/module-boundaries.mdexplains the model. Standalone packages do not import Hunk internals. Bundled providers use only provider-local modules, platform built-ins,hunkdiff/extension, and explicit@hunk/vcs/*leaves. The known-violations baseline is shrink-only: fix an edge, rerunbun run deps:baseline, and never add to it.- Keep the app review-first: the main pane is a single top-to-bottom stream of all visible file diffs.
- The sidebar is for navigation. Selecting a file jumps to that file in the main review stream; it should not collapse the main pane to one file.
- Keep Pierre as the diff engine and renderer foundation. Do not switch the main renderer back to OpenTUI's built-in
<diff>widget. - Keep split and unified views terminal-native and driven from the same normalized diff model.
- Preserve mouse + keyboard parity for primary actions.
- Keep the chrome restrained: top menu bar, minimal borders, no redundant metadata headers.
HunkSessionHostowns history/review routing in one React root.ReviewReloadCoordinator(app/session/reloadCoordinator.ts) owns reload serialization, shutdown refusal, loading, extension adoption, and broker/producer publication ordering for every reload trigger;AppHostdrives it and keeps the React commit, post-layout lifecycle ordering, notices, and live view preferences.Appowns review interaction, navigation, layout, theme, filtering, and pane coordination; review-semantic operations it triggers go through theReviewSessionHostthatuseTerminalReviewmounts. Pane and diff modules own rendering and geometry.InteractiveSessionInitializationinpackages/hunk/src/core/session/initialization.tscarries finalized launch inputs whose lifetime spans routed surfaces. Add a concern there only whenHunkSessionHostowns that cross-surface lifetime; keep surface-local bootstrap data out.- Confirmation prompts with a small set of choices should reuse
ConfirmDialog(body rows plus a clickable key-legend action row) instead of composingModalFramewith a hand-rolled footer; keyboard handling for its actions stays inuseAppKeyboardShortcuts. - Extend existing components or add focused components rather than growing
Appinto a monolith. - Shared formatting, ids, and small derivations belong in helpers, not repeated inline.
- When refactoring logic that spans helpers and UI components, add tests at the level where the user-visible behavior actually lives, not only at the lowest helper layer.
- Built-in theme ids and source metadata live in
packages/hunk/src/core/theme/catalog.ts;packages/hunk/src/ui/themes.tsderives Hunk's semanticAppThemevalues. - When adding or renaming a built-in theme, update validation, public exports, docs/examples, the appropriate Changeset, and tests. Keep source palette tokens separate from semantic mappings and cover non-trivial derived colors.
BUNDLED_SHIKI_THEME_DIFF_COLORSinpackages/hunk/src/core/theme/catalog.tsis generated. Edit the sourcing policy inscripts/generate/generate-theme-diff-colors.ts, then runbun run generate:theme-colors.
- Colocate unit tests with the code they cover (
packages/hunk/src/core/foo.ts+packages/hunk/src/core/foo.test.ts,packages/hunk/src/ui/AppHost.*.test.tsx,packages/hunk/src/ui/lib/*.test.ts). - Put shared unit-test helpers in
test/helpers/. - Name test helpers so they explicitly include
Testand are clearly test-only (createTestDiffFile). - Use repo-level
test/directories by intent:test/cli/for black-box CLI contract coverage.test/session/for daemon/session integration and end-to-end flows.test/pty/for PTY-backed live UI integration tests.test/review-conformance/for the shared review model's golden fixtures and per-consumer conformance suites.test/session-broker-node/for real Node listener/adapter conformance.test/session-broker-runtime/for shared Bun/Node broker fixtures.test/smoke/for opt-in terminal transcript smoke coverage.test/web/for Playwright browser tests of the daemon-served review page.
bun run testdoes not include review conformance, PTY, TTY smoke, browser (test/web/), or real-Node adapter conformance undertest/session-broker-node/. Run the dedicated command documented intest/README.mdwhen changing those areas.
- Separate functions, class methods, nested helpers, and test declarations with a blank line; keep JSDoc and test-specific comments attached to their declaration.
- Use blank lines between logical phases inside functions. Keep related statements grouped rather than packing an entire workflow into one dense block.
- Add short JSDoc-style comments to functions and helpers.
- Write header comments in active voice: the first sentence says what the module or function does ("Applies one action to the review state and returns the next state."), followed by its invariants. Avoid passive or self-important framing ("The one place where…", "the single source of truth for…") — name the behavior, not the architecture's opinion of itself.
- For orchestration and controller modules, explain the product workflow before the mechanics: name the user-visible triggers that converge there, state what the module owns, identify the neighboring authority it deliberately leaves elsewhere, and call out preservation or non-reloadable invariants. Prefer concrete flows ("watch changes and manual refresh both rebuild the mounted review") over abstract labels ("handles refresh").
- Add inline comments for intent, invariants, ownership, or non-obvious tradeoffs. Do not narrate syntax, praise the implementation, address the reader conversationally, or record temporary implementation history that belongs in Git or maintainer docs.
- Prefer names that match the role the code plays in the product and architecture.
- Use
layoutfor structural placement or arrangement data. - Use
geometryfor aggregate spatial data used by rendering, scrolling, or interaction. - Use
boundsfor one concrete visible extent within a larger structure. - Serialized formats carry their version in the payload (
protocolVersion,formatVersion,version), not in the type name. Add aV<N>suffix only where code must hold two versions side by side, as the session-broker admin scope does (SessionBrokerAdminStatusV1). - Prefix a type by its role:
Review*for review concepts on every tier (model, resources, envelopes, HTTP bodies, events, shared state);Session*for the daemon/window session wire;Hunk*only for the app's specialization of a runtime-neutral package type (HunkSessionRegistration) and product-level public names;Client*for the browser page's copy of a session-side concept (ClientReviewStore);Web*for page-only presentation. - Name a top-level message by its transport role —
Envelope(client request),Body(HTTP response body),Result(producer answer),Manifest/Index(build file) — and use model names for what it contains. Core review types are deliberately both model and wire; do not add DTO copies of them. - Name a string union inside a format as a vocabulary noun (
…Kind,…Code,…Tone,…Origin,…Type,…Phase); a code union takes the name of the failure shape whosecodecarries it. - A function named after a type follows the type's name. SCREAMING constants keep the shared
HUNK_*namespace.
- Default behavior is a multi-file review stream in sidebar order.
- Layout modes are
auto,split, andunified.autochooses split on wide terminals and unified on narrow ones; explicit modes override it. [and]navigate hunks across the full review stream. Do not reintroducej/khunk navigation unless the user asks.- Agent context belongs beside the code, not hidden in a separate mode or workflow.
- Agent notes are hunk-specific: show notes for the selected hunk, render them in the diff flow near the annotated row, and keep a clear spatial relationship to the code they explain.
- Keep note behavior explicit. If the UI intentionally prioritizes one note, one selection, or one active target, encode that as a named policy rather than scattering array-index assumptions through the codebase.
- STML markup notes (experimental) live in
packages/hunk/src/ui/lib/stml/, with parsing and the layout engine inpackages/hunk/src/core/stml/so the headless host validates markup too. The layout engine is deliberately a deterministic line layout, not OpenTUI flexbox: the row-windowed review stream needs exact note heights before mount, so(markup, width)must always produce the same lines. Colors stay symbolic until render time so measurement never needs a theme. Do not "simplify" this into flexbox renderables, and keep note-card geometry inagentNoteGeometryas the single source for rendering, measurement, and agent-facing width reporting. - Keep temporary sidecars concise and review-oriented. Their file order is intentional, while the visible note UI remains hunk-note driven rather than showing generic explainer cards.
- Agents review via
packages/hunk/skills/hunk-review/SKILL.mdusinghunk session *commands; do not run interactive TUI commands directly. packages/hunk/skills/hunk-review/SKILL.mdis generated. Editpackages/hunk/src/hunk-review/skillDocument.ts,packages/hunk/src/session/agent/surface.ts, orpackages/hunk/src/session/agent/errors.ts, then runbun run generate:skill; never hand-edit the skill file.
- Installed
hunkis a compiled snapshot, not linked to source. - After source changes, rebuild/reinstall with
bun run install:bin. - For rendering verification, prefer a real TTY smoke run over redirected stdout capture.
- For rendering changes: run
bun run typecheck,bun run test,bun run test:integration,bun run test:tty-smoke, and do one real TTY smoke run on an actual diff. - For interaction, layout, scrolling, navigation, windowing, or other terminal-native behavior: add or update PTY integration coverage in
test/pty/*-integration.test.tsand run it withbun run test:integration. - For broker/runtime changes, run
bun run test:session-broker-nodein addition to the relevant Bun tests. - For the browser review page (
packages/hunk/src/web/, its build, or the daemon routes that serve it), runbun run build:web && bun run test:web. - For CLI, config, or pager work: make sure the relevant source invocation still works (
diff,show,patch, orpager). - Preserve current interaction model unless the user asks to change it explicitly.
- Hunk should work on macOS, Linux, and Windows. Keep tests and CI portable unless a case is explicitly Unix-only (PTY/TTY smoke coverage is Unix-only).
- In tests, avoid hard-coded POSIX paths, separators, shell syntax, and filenames invalid on Windows; use Node path helpers for real filesystem paths while preserving user-provided/protocol paths when pass-through is intentional.
- If Windows-only Bun behavior appears around timers, sockets, or line endings, prefer a small compatibility fix or a narrowly scoped skip with a comment over broadening Unix assumptions.
- User-visible changes require a Changeset; maintenance-only changes require an empty Changeset.
Follow
.changeset/README.mdand do not editCHANGELOG.mddirectly. - For release preparation, publishing, backports, and post-release verification, read
skills/hunk-release/SKILL.md. - Never push a release tag or trigger publishing without explicit user confirmation.
hunk.dev/changelogis generated fromCHANGELOG.mdbybun run generate:changelog; hand-author onlywebsite/releases/notes.json, and never edit its output.docs/changelog-on-hunk-dev.mdexplains how release dates and the pre-tag window work.
- Local review artifacts are ignored on purpose. Leave them alone unless the user explicitly wants them updated, and do not commit them.
- Before committing or preparing a PR, follow
CONTRIBUTING.md.