croft-software 0.1.701

VSCode-style TUI written in Rust
# croft architecture

Notes for maintainers and developers. For what croft does and how to use it, see the [README](../README.md); for the keyboard surface see [KEYBINDINGS.md](KEYBINDINGS.md).

croft is built on [ratatui](https://ratatui.rs/) + [crossterm](https://github.com/crossterm-rs/crossterm), with [portable-pty](https://docs.rs/portable-pty/) for the embedded shell, [alacritty_terminal](https://docs.rs/alacritty_terminal/) for terminal-state parsing, [tree-sitter](https://tree-sitter.github.io/tree-sitter/) for incremental syntax highlighting, [calamine](https://docs.rs/calamine/) for spreadsheet parsing, and an inline-image protocol (iTerm2 OSC 1337, the Kitty graphics protocol on Ghostty / kitty, or DEC sixel on terminals whose DA1 reply advertises it) for image / PDF previews.

## How the embedded terminal works

`portable_pty::native_pty_system().openpty(...)` allocates a pseudoterminal and `spawn_command(...)` runs `$SHELL` on the slave side. A background thread reads the master fd and feeds the bytes to an `alacritty_terminal` `Processor::<StdSyncHandler>`, which applies them to an `alacritty_terminal` `Term` that maintains the screen cell grid in memory. The render path walks `term.grid()[point]` for every cell in the pane and emits styled cells to the ratatui buffer with proper foreground / background / bold / italic / underline / reverse styles.

Resizes call `master.resize(...)` and `term.resize(...)` so programs like `htop`, `vim`, or your shell prompt redraw to fit the pane. Keystrokes from `crossterm`'s `Event::Key` are translated back to the byte sequences real terminals send (arrow keys to `\x1b[A`, `Ctrl+letter` to `0x01..0x1a`, `Alt+x` to `\x1b<x>`) and written to the master writer.

## Project layout

```
src/
├── main.rs              entry point + module declarations
├── cli.rs               clap CLI: open path, setup-terminal / setup-iterm2 / setup-cross / remote / keys subcommands
├── clipboard.rs         native macOS clipboard read/write (NSPasteboard) with pbpaste fallback
├── command_history.rs   durable cross-session shell command history (the atuin model, embedded): every command a shell-integrated pane finishes is appended as one JSONL line under ~/.config/croft/command_history.jsonl with cwd / exit / duration / timestamp; the reader thread extracts the typed text from the OSC 133 B→C mark span at the 133;D mark (FinishedCommand) so the record needs no shell-side hooks. `search` is newest-first, case-insensitive substring, deduped to the newest run per command text, with scopes all / this-directory / failed-only; the file compacts back to the newest 10k entries once it doubles past the cap. Ctrl+Shift+H opens the popup (widgets/history_popup.rs); Enter types the pick at the prompt without running it
├── ghostty.rs           Ghostty config keybinds (setup-ghostty): re-emit every croft chord as its CSI-u sequence so Ghostty's own binds don't swallow them
├── file_ref.rs          `path:line[:col]` references detected in terminal text (rustc / grep / pytest / Python-traceback forms); backs Cmd/Ctrl+click-to-jump from any terminal pane with zero per-tool problem-matcher config
├── quickfix.rs          parses the last `grep`/`rg`/`git grep` command line into a pattern + Search toggles + include/exclude glob lists (`-g`/`--glob`s accumulate comma-separated; rg's `!`-negated globs and grep's `--exclude`/`--exclude-dir` land in files-to-exclude; rg/ag `-s` forces case sensitivity while grep's `-s` stays the no-messages flag), so "Terminal: Search & Replace from Last grep/rg" seeds and runs the Search sidebar (reusing its multi-file replace-all) from a terminal search — the seed replaces the panel's query and both filter lists wholesale via `SearchPanel::seed`, which also resets field selections (a stale byte range into shorter seeded text panicked) and refocuses the query
├── git.rs               branch / dirty / ahead-behind status and the full set of working-tree operations the Source Control panel drives: stage(/all), unstage(/all), commit (staged / all / amend), push (/force/to-remote/publish), pull (/rebase), fetch, sync, clone, branch list / checkout / create (/from) / rename / delete / merge / rebase, remote list / add / remove, stash push (/untracked/staged) / list / apply / pop / drop, tag list / create / delete, discard (/all), and diffs; hunk-level staging feeds self-generated single-hunk unified patches to `git apply --cached[/-R]` on stdin, and every read-only poll runs with `GIT_OPTIONAL_LOCKS=0` so background status never takes `index.lock` out from under a user mutation; `blame`/`parse_blame` (`git blame --line-porcelain`) back the editor's GitLens-style inline annotation. The Explorer's greyed-out set is two-step: `ls-files --others --ignored --directory` gives a cheap candidate list (a fully-ignored dir collapses to one entry instead of enumerating `target/`), then `check-ignore -z --stdin` confirms each — the listing also collapses any entirely-untracked directory whose contents merely happen to be ignored, so `logs/` would otherwise grey with no rule matching it. Both calls read RAW bytes (`git_raw`): git sorts a leading-space filename first, so a blanket `trim()` would eat that space, and a filename need not be UTF-8
├── markdown.rs          rendered Markdown preview (Cmd/Ctrl+Shift+V): pulldown-cmark event stream -> styled ratatui lines (pure; the editor holds the `MarkdownPreview` state and paints it through a wrapping Paragraph so text reflows with the pane, rebuilt lazily when `built_seq` falls behind the buffer's edit seq, and rebuilt eagerly by `rehighlight_for_theme` on a theme switch since the lines bake the theme's colors). Headings (H1/H2 accent bold), emphasis/strikethrough, inline code, links (underlined accent), nested + ordered + task lists, blockquote bars, aligned tables with a header rule, horizontal rules, and fenced code blocks highlighted by the same tree-sitter registry the editor uses (`lang_for_fence` maps info strings); images render as a labelled placeholder. The chord is forwarded by setup-iterm2 (which also relocates iTerm2's "Paste Selection" menu item off Cmd+Shift+V) and setup-ghostty
├── merge.rs             merge-conflict machinery: VS Code-regex marker scanning (`<<<<<<<` / `|||||||` diff3 base / `=======` / `>>>>>>>`) into ConflictBlocks, and Accept Current / Incoming / Both resolution line-splicing; the editor caches blocks per edit_seq (every whole-buffer swap, image/sheet/PDF previews included, bumps the seq so the cache can never go stale), tints the regions, and Cmd+. opens the resolve picker; palette merge commands refuse non-text tabs
├── gradient.rs          shared orange→green corner gradient: the welcome activity box border and the Black-theme focused-pane border
├── gui_path.rs          PATH repair for GUI launches, run once at the top of `Cli::run` before anything spawns. macOS launchd starts Croft.app (Dock, Spotlight, an opened document) with only `/usr/bin:/bin:/usr/sbin:/sbin` plus whatever bundle dir the launching app appends, and Ghostty's `--initial-command` runs croft under `bash --noprofile --norc`, so no rc file ever restores the rest: every tool croft shells out to (pdftoppm, pdfinfo, git, ripgrep, the language servers, the pair CLIs) becomes invisible and PDF previews freeze on page 1 with no page count. A PATH holding nothing but those system directories (`.app/` entries discounted, since an app putting its own bundle there is not a shell having run) is taken as a GUI inheritance and repaired by asking the user's login shell (`$SHELL -l -i -c`; csh/tcsh accept `-l` only alone so that family is marked a login shell the way login(1) does it — a leading dash in argv[0] — and runs `-i`, which makes tcsh read `~/.login`, the conventional home of a csh user's `path`; the value is printed by an inner `/bin/sh` reading the environment because fish expands its own quoted `$PATH` space-joined; marker-delimited so rc-file chatter cannot be mistaken for the value, read up to the END marker so a backgrounded grandchild holding the pipe open cannot stall it, bounded by a 3s timeout and reaped off-thread so a wedged rc cannot wedge startup, and run in its own session — an interactive zsh takes the terminal's foreground process group for job control, and a probe left in croft's session stole the TTY and made raw-mode setup fail with EIO once it exited). The pure liveness probes (`session-host --probe`, `collab-relay --probe`) return before the repair runs — the remote launch script fires them on every SSH connect and remote attach never waits; the answer goes in front of what we inherited, deduped, and nothing inherited is dropped. A terminal launch never probes. Same approach VS Code and Zed take
├── highlight.rs         tree-sitter highlight registry per language; every span (captured tokens AND uncaptured source) styles from the active theme's `SyntaxPalette` — the palette is snapshotted once per pass, never a hardcoded Base16 literal, so sparse grammars don't split a themed file into two foregrounds
├── history.rs           local history: per-save snapshots under ~/.config/croft/history (FNV-keyed with legacy-key migration, raw bytes so any encoding round-trips, deduped, capped, saves within a 10s merge window replace the newest entry the way VS Code's mergeWindow does); merges into the Explorer TIMELINE beside git commits (out-of-root files list snapshots only) and backs snapshot diff/restore; recording runs off the render thread
├── icons.rs             Codicon and file-type Nerd Font glyphs and per-language colors
├── install_session.rs   streams install-progress events while a remote host builds / installs the croft binary
├── iterm2.rs            iTerm2 plist mutation helpers for fonts and Croft key mappings; user-keybinding forwarders are recorded in a root-plist ledger (`Croft User Keymap Forwarders`, key → hex) and swept on the next setup run before any inserts while their value is still the exact croft forwarder, so a chord deleted from keybindings.json releases its Cmd chord without destroying an entry the user has since rewired in iTerm2 prefs
├── iterm2_inline.rs     inline-image baking pipeline + protocol dispatch (iTerm2 OSC 1337 / Kitty graphics / DEC sixel via DA1 probe): welcome wordmark, image / PDF preview, activity-bar icons incl. the settings gear, SSH empty-state hero, editor minimap. Stale-image eviction is protocol-keyed (App::image_eviction_needs_screen_wipe): iTerm2/sixel cells need the main loop's full `2J` + repaint, Kitty images are deleted on their own layer (delete-all escape) with the text buffer untouched - a Kitty screen wipe would blank the app for an SSH round trip on every clear latch (the every-keystroke blink bug). Content-only overlay changes (minimap rebake on edit/scroll) re-emit over the same cells and must never arm the clear latch; only a moved or resized placement may. The minimap raster is emitted at Kitty z=0 (above text) after ratatui's diff on EVERY frame, so any pane that ratatui paints over the strip would be painted back over: a menu whose rect actually INTERSECTS the strip (`App::menu_covers`, checked against both `menu_rect` and the further-right `submenu_rect`) evicts it and suppresses the re-emit, the same collision `cb0481b` fixed for the welcome logo. The test is the intersection and not `context_menu.is_some()`, because menus are clamped to the frame rather than snapped to it: gating on any open menu would arm the clear latch on every right-click in the app, which is a full screen wipe and repaint on the cell-buffer protocols. The one unconditional wipe is resize/WINCH (App::consume_resize_repaint): a dtach reattach fires WINCH against a blank physical screen while ratatui's back buffer says every cell is painted, so the next frame must clear and repaint on every protocol, Kitty included. The same WINCH also re-asserts the startup terminal modes (mode_reassert_seq in app/mod.rs: alt screen, mouse tracking, bracketed paste, kitty keyboard flags via the SET form, never a push) when CROFT_SESSION_PERSISTENT is set, because a reattached terminal never received the startup DECSETs and would otherwise have a dead mouse until the next F9 re-exec. takeover_mode_seq is the single source of truth for those modes — startup, the post-scp TUI restore, and the reattach re-assert all emit the same block (a test pins the embedding), so a mode added at startup can never go missing from the reattach path; new startup modes go there, never inline at a call site
├── keymap.rs            user key bindings from ~/.config/croft/keybindings.json: parses chord strings (ctrl/alt/shift/cmd/mod + key) into normalized Chords mapped to palette Command ids, consulted at the top of handle_key ahead of the built-in chords (only off the terminal, only for modifier/function-key chords); tolerant JSONC (strips // comments), reloads on save
├── launcher.rs          macOS `croft install-launcher`: builds a clickable Croft.app via `osacompile` — an AppleScript applet, not a `#!/bin/sh` bundle, because a double-clicked document arrives as an `odoc` Apple Event only an `on open` handler can receive (opened files launch `--zen`) — then brands the plist with PlistBuddy. The cleanup deletes (keys osacompile never emits: `CFBundleIconName` always absent, `CFBundleDocumentTypes` cleared before the rebuild) run as separate best-effort invocations while the required Add/Set batch stays fatal, since PlistBuddy exits non-zero on deleting an absent key and one shared exit status failed every install before signing and registration (#92); finishes with an ad-hoc `codesign` (editing Info.plist invalidates osacompile's signature) and an `lsregister` nudge so Spotlight sees the bundle
├── outline_syntax.rs    tree-sitter outline provider: extracts the OUTLINE panel's symbol tree (functions, structs, methods, fields, etc.) directly from the buffer's syntax tree via hand-written per-language queries, so the panel paints instantly before a cold language server answers documentSymbol; the LSP reply later supersedes it (tree-sitter-first, like Zed and aerial.nvim). Rust / Python / JS / TS / TSX / Go covered; other languages fall back to the LSP outline
├── output.rs            in-process OUTPUT bus behind the panel group's OUTPUT tab: named channels (one per language server, plus Debug Adapter / Git / Server Provisioning / Navigator — the resident AI pair programmer's commentary) each holding a capped ring buffer of levelled lines; producers across the codebase push here while mirroring to the on-disk lsp.log, and a generation counter lets the widget re-pull only on change
├── pdf.rs               PDF rasteriser: prefers pdftoppm (poppler), falls back to macOS sips. Also link extraction (`page_links` via `pdftohtml -xml`, parsed by `parse_pdf2xml_links`): a click on the preview maps its cell back through the fit_image_auto placement (`iterm2_inline::cell_source_fraction`) to page fractions and hit-tests the current page's cached link rects — each `<a>` gets the proportional horizontal slice of its text run's rect (pdf2xml carries no per-anchor geometry, and poppler often wraps only part of a run), and among several overlapping hits (adjacent TOC lines overlap outright) the link covering most of the cell wins. External URLs open with the OS opener behind an http/https/mailto allowlist (a document-supplied `file://` or custom scheme is a one-click app launch and is dropped); internal GoTo targets flip the page. Text-anchored links only, extracted lazily on first click and re-extracted after a page flip. An FS-sync reload (pdflatex rebuilding the open file) comes up on the reader's current page in a single rasterisation (`open_pdf` consumes the editor's `pdf_restore_page` request, clamped to the fresh page count) — restoring the page with a second render after the open left a window where that render's transient failure silently snapped the reader to page 1; now the failure fails the whole open and the failed-reload path keeps the last good render AND the place
├── port_detect.rs       loopback-port detection behind the PORTS panel: a stateful output-stream scraper run in the terminal reader thread (URL banners + `listening on :PORT` lines, emitting each port once) plus a low-cadence lsof/ss socket poll scoped to the shell's process subtree; also the Cmd/Ctrl+click URL resolver. The bare-announce regex requires the number to be introduced by a colon or the word `port`, because an announce verb followed by a plain count is ordinary output (`running 289 tests`, `Started 15 workers`) and fabricating a port from it offers to forward one nothing is listening on. That subtree scoping answers "what should we SURFACE", never "what is still UP" - `poll_all_listening` is the unscoped companion the reconciliation uses, and it returns `None` (no evidence) rather than an empty set when neither tool runs
├── prefs.rs             durable user preferences (color theme, Customize Layout chrome, format-on-save, auto-save) persisted at ~/.config/croft/config.json; the searchable "Preferences: Open Settings" hub toggles these and links to the raw JSON. `host_accents` rules ({pattern glob, accent hex, badge}) drive the per-host terminal pane dressing (compiled to globset matchers in the App, re-read on config.json save)
├── quick_select.rs      WezTerm-style quick-select pure core for the terminal pane (Ctrl+Shift+Space): a priority-ordered pattern set (markdown/scheme URLs, scp git remotes, email, diff paths, sha256 digests, filesystem paths with optional :line:col, UUIDs, IPFS CIDs, git SHAs, IPv4/IPv6, hex colours/addresses, 4+-digit numbers; earlier patterns claim their span so a URL is never shredded into path + number) matched over the visible viewport rows stitched into LOGICAL lines by their soft-wrap flags (`find_matches_wrapped`; the pane hands per-row WRAPLINE bits alongside the text, keeping a wrapping row's trailing spaces since they are real mid-line cells) — a match crossing the pane edge is seen whole, its label anchored on the head span with highlight-only tail segments on the continuation rows, never an invisible head plus a mislabelled path-fragment tail, plus WezTerm's label scheme (home-row alphabet, single chars until they run out, then the alphabet tail reserved as two-char prefixes; `label_matches` pairs bottom-priority: labels are assigned in reverse so the bottom-most match is cheapest to type, and when matches outnumber labels the TOP overflow is dropped, never the prompt-adjacent bottom — the status line counts the unlabelled). The app owns the mode (App::terminal_quick_select: pane-bound like copy mode — a per-frame invariant in sync_focus_flags closes it whenever anything moves the active pane; typed chars filter the labels, a completed label copies via the clipboard, UPPERCASE also pastes into the shell) and pushes HintSpans into the pane at the open-time scroll-clock reading (one visible_lines_and_clock snapshot), which the render loop re-bases every frame so labels follow their matches through streaming output, whose render loop paints match spans green and overlays black-on-gold label cells through the same char-index colmap the find highlight uses
├── release_notes.rs     hand-curated "IN THIS RELEASE" highlights (feature / fix, glyph + summary) shown on the welcome panel; baked-in data, updated on every version bump (no git log, no network)
├── remote.rs            remote (SSH) target metadata and launch dispatch: an installed remote croft is attached to immediately (presence probe fires the launch signal within one roundtrip) while any update cross-builds and ships on a background thread, surfacing as the running croft's F9 reload (the install must never read the terminal the attached session is reading, or the two split the user's keystrokes between them: every ssh command it runs directly carries `-n`, and rsync and the zig cross-build — whose nested ssh has no `-n` of its own — are spawned with stdin closed, which their children inherit. The one exception is the throughput probe, which pipes its payload into a remote `cat` and so must keep the stdin it feeds); the toolchain-sensitive rustup queries on this path run FROM THE CHECKOUT (`cross_tool_command_in_checkout`; plain availability probes stay directory-neutral via `cross_tool_command`), because `rust-toolchain.toml` resolves per working directory: a probe run elsewhere answers for the DEFAULT toolchain while `cargo zigbuild` answers for the pinned one, so a target present on only one of them made the "target missing" guard pass immediately before the build died with E0463 (four days of silent fallback to remote `cargo install` after the 1.95.0 to 1.97.1 bump; rustup targets are per-toolchain and a bump orphans them all, which `.github/workflows/ci.yml` and `remote::tests::the_pinned_toolchain_has_every_cross_target` now catch); the source sync ships an ALLOW-list built from the same `SOURCE_STAMP_INPUTS` the stamp hashes (`source_sync_filter_args`), never a deny-list: the old `--exclude=target` never matched this repo's real build dir `target.noindex`, so every fallback install pushed 176 GB of artifacts to the box at the bulk lane's throttle, and three servers sat 23 to 27 GB deep in it (each sync first clears the remote source dir of everything but the `target/` build cache and the inputs the local checkout still contains — `remote_source_dir_prep` — since `--exclude=*` protects stale unlisted files from `--delete` and the tar fallback never deletes; current inputs stay so a concurrent install's source is never yanked and rsync stays incremental); the source stamp gating reinstalls hashes only the build inputs (src/, assets/, Cargo.toml/lock, build.rs, rust-toolchain.toml), never build artifacts or docs; the drop-relay pump (local launcher tails the remote requests.log and runs each verb locally): pull / clipboard / open, plus forward (adds an `-L` to the live SSH master via `ssh -O forward`, opens the local browser) and unforward (`ssh -O cancel`)
├── remote_bulk.rs       bulk lane for background installs: dedicated BatchMode SSH connection when key auth works (throttled shared mux otherwise) so update bytes never queue ahead of live-session keystrokes
├── remote_connect.rs    interactive SSH connect flow (host + password prompt phases) behind the connect dialog
├── session.rs           local session persistence: `croft attach` / `croft ls` run croft under the session host (session_host.rs) so terminals/LSP/DAP survive closing the window; live legacy dtach sessions keep reattaching through dtach; `ls` skips the workspace's collab relay socket (`<hash>.collab.sock`, same directory + keying but not a session — listing it printed a phantom row and pruning belongs to the relay's own bind path)
├── session_host.rs      the multiplayer session mux (docs/MULTIPLAYER.md): a hidden `croft session-host` subcommand whose server owns the inner croft's PTY and broadcasts output verbatim to N unix-socket clients (byte-transparent, so Kitty graphics survive); per-connection input attribution with server-enforced write control (first attacher holds it, Grant/Revoke frames move it, read-only input is dropped at the host), min-of-clients winsize with a same-size repaint jiggle on attach (the role dtach's `-r winch` played), a presence roster (atomic sidecar JSON next to the socket + Presence frames), and inner exit-code propagation (drop-to-local's 88 survives the mux; dtach swallowed it). Wire framing both ways: [type u8][len u32 be][payload], type 0 = raw PTY bytes, type 1 = one compact-JSON Control message. A token-authenticated privileged channel (CROFT_SESSION_TOKEN, InnerChannel; the env read is inert under `cfg(test)` so test-built Apps never authenticate to a live host) lets the inner croft grant/revoke/kick and receive Typing attribution frames (sent on writer change, ordered before that client's bytes reach the PTY), which drive per-participant parked carets and the editor's colored ghost carets. The remote launcher prefers it behind a `--probe` guard and falls back to dtach A stale server that survived binary upgrades can no longer strand an attach (#53): Hello carries the client version, the server answers with ServerHello before any PTY bytes, and a mismatch (or a pre-0.1.698 server, detected by a 2s reply timeout) shows a plain-text banner — continue / restart (SIGTERM via the socket-unique argv, then respawn) / detach — never a silent blank screen. The attach repaint jiggle runs even when every client is a size-less observer (`min_winsize` None used to skip it), and `broadcast` bounds each client write with poll(2) at WRITE_FRAME_DEADLINE, evicting a non-draining peer and recomputing the shared size so a dead ghost releases the min winsize it pinned — a plain write_all used to wedge the PTY pump forever while holding the clients lock.
├── collab.rs            multiplayer Phase D (docs/MULTIPLAYER.md), the whole collab layer below the app: a replicated text document (`CollabDoc`) over the `cola` text CRDT, so participants editing the same buffer from independent viewports converge without a central authority. Owns the canonical text next to a `cola::Replica` (positions only); `text_delta_ops` diffs a buffer's last-synced text against its current text and emits convergent ops, so the editor needs no apply-edit chokepoint (multi-cursor, paste, undo, and wholesale reloads all reduce to text-state transitions), and `apply_remote` integrates inbound ops (draining cola's causal backlog, with insertion text stashed by run identity) into sequentially replayable spans. `byte_offset`/`position` bridge `(row, char-column)` to byte offsets (UTF-8 aware). `CollabMsg` (ops, the SnapshotRequest/SnapshotReply bootstrap handshake, carets, and the AI-stream pair StreamState/StreamCancel — unknown variants are skipped at drain, so peers across versions interoperate) rides `relay_serve`, a dumb attach-or-create fan-out over `<hash>.collab.sock` (forwarding writes are bounded — `SO_SNDTIMEO` 2s — and a wedged peer is shut down and dropped, since forwarding holds the global client mutex and one SIGSTOPped peer used to deadlock relay and participants alike); `CollabChannel` is a participant's non-blocking framed connection (CROFT_COLLAB_SOCKET/CROFT_COLLAB_ROLE, exported by the launch tails — the read is inert under `cfg(test)` so a suite launched from a croft session never hands test-built Apps a live seat; EOF or a failed send latches it dead, and the app drops the session — harvesting each live doc's last replicated text as a merge base — and reconnects, replaying offline buffer divergence into the re-bootstrapped doc as a three-way merge against that base (`merge_offline_texts`, line-level, ours wins a same-line conflict) so neither the offline work nor edits the owner made during the outage are wiped — a killed relay used to read exactly like an idle one) and `CollabSession` the per-file state machine: guests bootstrap each opened workspace file from the owner (input-gated until the snapshot lands, timing out to local-only when no owner answers — a latch that plain re-requests respect, exempts the file from the guest save gate, and only the collab agent's `collab_open` rejoins), the owner allocates site ids (pid-seeded, so a restarted owner never re-issues an id a surviving guest holds), contains every wire file key (`contained_path`: plain components plus canonical containment of the deepest existing ancestor, so symlinks cannot smuggle a path outside the root) before touching the filesystem, and is the single writer to disk. `App::poll_collab` pumps it per tick: extract-before-apply (the echo-storm invariant), remote spans into every attached tab via `apply_span_edits` (buffers carry the doc's `text_gen`: a fresh split/reopen of a live file holds stale disk text, never extracts, is input-gated until seeded from the replica, and `Editor::open` drops the attachment on a path change while keeping it for same-path reloads; behind panes mirror, so all panes of a live file converge — text tabs only, every matching one, since diff/image/sheet tabs carry the path without being documents; with the link down the active pane mirrors onto its siblings so offline panes cannot diverge, and a disconnected guest may save), peers' carets as colored ghosts with a name tag (the name rides `CollabMsg::Caret`; the tag paints on the row above the caret and hides 2s after it rests, VS Code Live Share style). Launch: `croft attach --solo` / `croft remote <host> <path> --solo`
├── collab_agent.rs      a headless collab guest exposed as an MCP server on stdio (hidden `croft collab-agent --workspace <path>` subcommand): joins the workspace's relay and serves five `collab_*` tools (open/read/replace/caret/status) over JSON-RPC 2.0 NDJSON, so an external AI (e.g. Claude Code via `claude mcp add croft-collab -- croft collab-agent --workspace <path>`) co-edits with a live named caret. A 30ms pump thread keeps the replica fresh between tool calls; the agent inherits every guest property (owner-only disk writes, per-file site ids, CRDT convergence, the 0600-socket trust boundary) and croft itself contains no LLM code
├── pair.rs              the AI pilot core (docs/MULTIPLAYER.md, "croft pair" / "resident navigator"): spawns the `claude` CLI as a persistent stream-json conversation on stdio and teaches it (--append-system-prompt) a fenced protocol — `<<<EDIT file:R:C-R:C>>>` bodies stream into buffers token by token, `<<<NOTE file:R>>>` bodies anchor commentary to a line, 0-based char coordinates throughout. `FenceMachine` parses the token deltas incrementally (correct across arbitrary splits, even mid-marker); EDIT headers also take a two-integer whole-line form `<file>:SR-ER` (rows inclusive, no column counting — what local models are steered to); edits apply through a regular collab guest seat at a tracked byte anchor, and both the anchor and every note offset shift via `shift_offset` over incoming RemoteEdit spans. Any participant cancels mid-run (gutter `■` / Cmd+K X / palette → `CollabMsg::StreamCancel`): the pilot interrupts claude (`control_request`, feature-detected), reverts the streamed region, and broadcasts `CollabMsg::StreamState` inactive. Yielded turns are comment-only at the host: `PairState::comment_only` discards EDIT fences whatever the model says. The claude child is sandboxed read-only (Read/Grep/Glob + a read-only collab-agent MCP seat, --strict-mcp-config); the fence is the only write path. `seat_pilot` builds the claude seat (child + reader/stderr/pump threads) and `seat_local` the childless local-endpoint seat (pair/local.rs); both return the transport-polymorphic `Pilot` — a shared `TurnSink` for turn injection plus a `Transport` enum for teardown — serving both drivers: the hidden `croft pair --repl` terminal REPL and the in-process PairHost. `Provider` (claude | local base_url) rides `PairConfig` and dispatches the seat. E2e-tested against a scripted python3 fake claude
├── pair/local.rs        the navigator's local-model transport: one minimal Anthropic-compatible `/v1/messages` streaming call per turn (Ollama, LM Studio, llama.cpp, vLLM) — deliberately NOT the claude CLI, whose ~213 KB tool-schema prefill 500s local servers regardless of flags; a per-seat worker owns the conversation (the endpoint is stateless), maps SSE text deltas into the shared fence machine and apply path, fails a turn naming the endpoint when it is down (the seat survives), and reads ANTHROPIC_AUTH_TOKEN from the environment for keyed gateways (a token is never persisted). Selected by `croft pair --provider ollama [--base-url <url>] --model <m>`
├── pair/proactive.rs    the proactive-look detector (pure text-in/row-out): tree-sitter judges that the driver COMPLETED a new construct since the navigator's last look — code languages multiset-compare outline symbols (`outline_syntax::symbols_for`; half-typed code parses as an ERROR node and never fires), markdown walks its block grammar for a new heading or an ADDED paragraph (count growth, so prose edits never re-fire). `App::tick_proactive_navigator` owns the gates (seated, idle, 2s typing pause, file previously yielded, one scan per buffer state) and hands the seat the same comment-only yield turn Cmd+K Y would, anchored at the new construct; opt-out pref `disable_proactive_navigator` + palette "Navigator: Toggle Proactive Comments"
├── pair_host.rs         the resident navigator's in-process host: the App spawns the pilot itself (the way it hosts LSP servers) when the workspace's `<hash>.pair.json` activation record (written by `croft pair`, `session::pair_record_path`) is enabled, self-appointing the collab OWNER seat first on a plain launch (only an owner answers the pilot's snapshot requests; solo guests never host). The pilot's voice arrives as `PairEvent`s drained once per tick (`App::poll_pair`): anchored notes (gutter `◆` diamonds + the anchored note popup, F4 cycles, Esc dismisses), commentary (the Navigator OUTPUT channel), turn ends, and death (unseat, no auto-respawn — the LSP precedent). Ask turns (`Cmd+K Q`, gutter/selection menus) may edit; yield turns (`Cmd+K Y`) carry the diff since the navigator's last look and are comment-only. The seat keeps a persistent visible caret in the navigator's identity orange (`NAVIGATOR_ACCENT`, the comment-box accent): parked at the ask/reply row and at every landed note (`PairState::park_caret`, pending parks resolved by the pump after bootstrap and superseded by any newer explicit caret), streaming along during edits, and identified by the seat's per-file site ids (`caret_sites`, never the display name) both for coloring and for the `collab_carets` cleanup on every unseat path. Dropping the host reverts, hangs up, and grace-kills the claude child (a local seat has no child: its turn queue closes and the worker drains out). The seat's backend comes from the record's provider — claude by default, `ollama` = pair/local.rs — and the idle `◆` badge names the local model (`title()`)
├── session_state.rs     captures open tabs / layout so a self-update re-exec can restore them
├── sheet.rs             CSV / TSV / XLSX / XLS / XLSB / ODS parsing via the csv and calamine crates
├── shell_integration.rs OSC 133 / 7 / 9 shell integration: `OscSniffer` (an incremental scanner the PTY reader thread tees raw bytes through — alacritty drops unknown OSC before any handler, so croft splits its `Processor::advance` at each mark to sample the cursor exactly where it landed) and the zsh `ZDOTDIR` shim writer (`ensure_zsh_shim`, sources the user's real dotfiles then installs precmd/preexec hooks emitting prompt marks + cwd; opt-out `CROFT_SHELL_INTEGRATION=0`; an inherited `ZDOTDIR` pointing at croft's own shim falls back to HOME, and one pointing at another terminal's injection shim — Ghostty/kitty launching croft as their command — is chained through: after sourcing that shim's `.zshenv`, whatever `ZDOTDIR` it restored is taken as the user's true dotfile dir). Bash gets the `$ENV` + `--posix` bootstrap kitty invented and Ghostty copied (`ensure_bash_shim`: posix-mode bash reads only `$ENV`, so the shim leaves posix mode, replays the login/non-login startup files bash itself would have picked, then wires precmd via `PROMPT_COMMAND` — array-aware on 5.1+, exit capture first, arm last — and preexec via funsub `PS0` on 5.3+ or a bash-preexec-style `DEBUG` trap below, joining bash-preexec's hook arrays when that is present; gated on bash >= 4.4 by a version probe because macOS's system 3.2 ignores `$ENV` in posix mode and would lose its startup files). Fish gets a `vendor_conf.d` script injected by prepending `XDG_DATA_DIRS` (`ensure_fish_integration`; the script restores `XDG_DATA_DIRS` first so children never see it, then defers to fish 4's native OSC 133/7 emission — kitty's `forward-char-passive` detection — and installs event hooks only on old fish, since a second emitter double-decorates). Marks power Cmd+Opt+Up/Down command navigation and the command decorations, OSC 7 feeds split-pane cwd inheritance and carries the reporting host (`Cwd(path, Option<host>)` — an in-pane SSH session with integration moves it to the remote hostname, feeding the per-host accents), OSC 9 surfaces in the status bar; the `9;4;state;percent` sub-namespace (ConEmu progress: 0 clear / 1 normal / 2 error / 3 indeterminate / 4 warning, percent clamped) parses to `OscEvent::Progress` instead of a notification and drives the pane's bottom-border gauge (held per pane, cleared on state 0 or the command's 133;D)
├── snippets.rs          user snippets from ~/.config/croft/snippets.json (VS Code format: prefix / body string-or-array / optional language scope); parse_body turns a body's $1/$0/${1:placeholder} tab-stop syntax into insert text + ordered stops the editor drives on Tab; matching snippets are also injected into the completion popup (CompletionItem.is_snippet, expanded on accept — the same path LSP snippet completions take); reloads on save
├── tasks.rs             auto-detected project tasks: reads the manifests the repo already has (.vscode/tasks.json with JSONC tolerated, Makefile, justfile, package.json + lockfile-matched runner, Cargo.toml, pyproject.toml) into runnable Task commands; backs "Tasks: Run Task" and the Cmd+Shift+B default build (tasks.json `isDefault` outranks the first build task), each running in a named terminal pane that is reused only while its shell sits idle inside the current workspace (kernel-reported cwd; the write clears a half-typed prompt line first)
├── terminal_session.rs  terminal session restore: the panel's layout (pane order, per-pane cwd + manual name, active index) persists per workspace root in ~/.config/croft/terminal_sessions.json, saved on structural changes (split / close / undo-close / rename / reorder) and at quit, restored at startup as fresh shells in their directories (running programs are not re-run). The default single-unnamed-pane-at-root layout prunes its key (directory equality through canonicalize, so macOS's /private symlink never defeats the prune); App::terminal_session_path is a field so tests redirect it
├── termux.rs            Termux font auto-install: downloads Meslo Nerd Font Mono into ~/.termux/font.ttf (background, no-clobber) so the activity-bar codicon glyphs render
├── theme.rs             IDE color theme: a `Theme` is a palette (background, accent, selection, button, gradient flag, OSK colors, 16-color ANSI, and a `SyntaxPalette` of eight code-highlight colors) loaded as data from `[[themes]]` blocks in bundled + user extension manifests (Croft Black/Dark ship in assets/extensions/themes/, baked in); `Theme::BLACK` is a const fallback so croft is never themeless. Drives SetColors + baked-image fills; the syntax palette is pushed into `highlight::set_syntax_palette` on every theme switch (and at startup) so tree-sitter + LSP semantic-token colors follow the active theme, with open editors re-highlighted on the switch. Omitted `syn_*` manifest fields fall back to the historical Base16-Ocean-Dark defaults. The editor tab-strip chrome (strip background, inactive/active tab, hover lift, close pill) is per-theme data too (`tab_*` manifest fields): the two built-ins pin their historical constants and every other theme derives them from its palette (strip from `search`, active from `selection`, hover/pill from `accent`), so the tab bar follows the theme instead of staying navy. The integrated terminal follows the theme too: each pane is prefilled with `theme.editor_bg()` before the grid paints (so default-bg cells show the theme background even on Ghostty/Kitty, which ignores the `SetColors` OSC iTerm2 honors), and its 16-color ANSI palette comes from the theme's `ansi` array via `set_palette`
├── triggers.rs          iTerm2-style terminal triggers from ~/.config/croft/triggers.json (tolerant JSONC like keybindings.json; palette "Preferences: Open Terminal Triggers (JSON)"; reloaded on save): each rule = regex + action. `highlight` is painted at render time over the visible rows (per-rule #rrggbb fg/bg under find/quick-select/cursor/selection so those win; free when idle, persists into scrollback); `notify`/`bell` run in the PTY reader thread as a third sniffer beside PortSniffer/OscSniffer — TriggerScanner strips escape sequences (CSI/OSC/DCS state machine), buffers the current line capped at LINE_CAP, treats a lone \r as an in-place rewrite (progress bars never spam) but \r\n as the PTY line ending, matches once per completed line, and tracks alt-screen entry/exit POSITIONALLY (DECSET/DECRST 47/1047/1049 and RIS in the stream itself) so alt-screen content never fires while primary text sharing a chunk with a transition still does — the reader feeds it every chunk unconditionally, or its state machine would desync and splice phantom lines across skipped gaps; hits flow over an mpsc channel drained by the app tick into the status bar with \0-\9 capture interpolation (`capture` hits carry the whole matched line and land in the CAPTURES panel instead — see widgets/captures.rs). Panes get the set via set_triggers (ptr-eq no-op re-pushed every drain tick, so panes are covered wherever they were created; the inner Arc swaps on config reload)
├── update_watch.rs      remote self-update: watch for a newer binary installed under a running remote croft
├── vim.rs               native modal (vim-style) editing: a pure key state machine (modes, counts, operators, text objects, f/t, search, ex-commands) that emits editing intents the app applies; toggled with Cmd+E
├── voice.rs             voice input for the Termux OSK mic key: delegates to `termux-dialog speech` (Android's SpeechRecognizer, the same engine Gboard's mic uses), auto-installs the `termux-api` package (InstallState), and sends the transcript over a channel the app injects via handle_key; a tap opens the system speech dialog, the result is injected when Android finalizes on silence (a second tap cancels, since killing preempts the result); uses `termux-dialog speech`, NOT the `termux-speech-to-text` service, because the service closes its output on onEndOfSpeech and so discards the final onResults transcript; runs in its own process group so cancel kills the whole tree; a tap rather than hold because Termux steals finger-holds for text selection
├── zoxide.rs            zoxide integration: strict query + typo-tolerant fuzzy fallback (Damerau-Levenshtein) + ensure-install (pkg on Termux, curl script elsewhere) with a logged outcome + InstallState surfaced to the Cmd+Z jump popup
│   │                    Saves re-encode through `Editor::encode_for_disk`, which re-emits the file's byte-order mark and hand-rolls UTF-16
│   │                    (`encoding_rs` is decode-only for UTF-16 by the WHATWG spec, so `Encoding::encode` silently falls back to UTF-8, and
│   │                    taking its output at face value wrote a file disagreeing with the encoding the status bar reported). UTF-16 output
│   │                    ALWAYS carries its BOM, and `open` sniffs the BOM BEFORE the `is_binary` heuristic, since UTF-16 text is half NUL
│   │                    bytes and would otherwise be rejected as binary: without both halves croft could write UTF-16 it could never reopen.
│   │                    `reopen_with_encoding` records the encoding `decode` ACTUALLY used, which a BOM overrides, and the choice STICKS
│   │                    across a same-path reload (`open` is also the FS-sync sweep and every revert, so re-detecting there would decode the
│   │                    file as UTF-8 and hand the next save the mojibake to write back). "Reopen with Encoding"
│   │                    refuses on a dirty buffer and points at undo, never at saving: the buffer may hold mojibake from a wrong decode, and
│   │                    saving would write those replacement chars over the real bytes.
│   │                    A save whose encoding cannot represent the buffer is REFUSED (`SaveOutcome::EncodingLoss`): `encoding_rs` substitutes
│   │                    HTML numeric character references (`&#26085;`), not `?`, so the write would be silent irreversible loss. The refusal
│   │                    latches (`encoding_loss`, so auto save stops retrying) and the explicit path arms a one-shot consent
│   │                    (`lossy_save_armed`): the second Cmd+S — told which characters are doomed — writes the substitutions. Any edit revokes
│   │                    both flags (`mark_buffer_changed`): consent named the characters at prompt time, so a changed buffer re-prompts. Force
│   │                    save (disk-conflict overwrite) does NOT bypass the guard; only the armed consent does.
├── app/                 event loop, three-pane layout + activity bar, key dispatch, status bar, mouse, clipboard, splitters, preview overlays, Customize Layout (compute_chrome_layout / panel_band_rect pure geometry, secondary side bar, Zen Mode)
│   ├── mod.rs           the main App: render, key / mouse dispatch, status bar, splitters
│   ├── click.rs         double / triple click detection
│   ├── cursor_blink.rs  caret blink timing
│   ├── fs_watch.rs      filesystem watch + poll fallback feeding tree / editor / terminal refresh. The poll stats the file behind EVERY open tab, not just the focused one: a boundary dir carries no watch at all (see the storm rules — never root a stream at or above `target/`, `node_modules/`, `.git/`) and an in-place write does not move its parent dir's mtime, so for a file sitting directly in one this stat is the only thing that can notice a change; cost is one stat per open tab per (adaptively backed-off) tick
│   ├── git_worker.rs    off-thread git status / changes worker
│   ├── hover.rs         LSP hover dwell timing
│   ├── nav.rs           editor back / forward navigation history
│   ├── overlay.rs       inline-image overlay state + clear-on-hide latches (iTerm2 cell eviction; the Kitty path adds a delete-all on the same clear frames)
│   ├── perf_hud.rs      F8 performance HUD
│   ├── welcome.rs       welcome-screen state: the "IN THIS RELEASE" highlights, read synchronously from `release_notes::RELEASE_NOTES` (no thread, no network)
│   └── tests.rs         unit / integration tests
├── dap/                 debugger stack: Debug Adapter Protocol client. debugpy (Python, 3.14+, no fallback) is the verified mechanism; Rust/C/C++ route to lldb-dap; JS/TS route to vscode-js-debug. Which file types each handles is a data-driven extension axis (see registry.rs)
│   ├── mod.rs
│   ├── transport.rs     DAP wire framing (Content-Length + seq envelope, not JSON-RPC, so async-lsp can't be reused); spawns the adapter detached via setsid (so the debuggee can't tcsetpgrp-background and SIGTTIN-suspend croft, and so teardown can killpg the whole group), blocking reader thread frames stdout into an mpsc channel; Drop/kill signals the process group and reaps the child
│   ├── session.rs       one launch session: the initialize -> setBreakpoints -> configurationDone -> stopped state machine, event classifier, the stackTrace -> scopes -> variables inspection chain, evaluate (REPL / hover / watch), conditional + exception breakpoints and logpoints (SourceBreakpoint carries `condition` and `log_message`; a logpoint's message is interpolated and printed by the adapter instead of pausing — Shift+Alt+F9 / gutter menu, amber diamond in the gutter), breakpoint-verification tracking, pause, reverse-request replies, over one adapter-agnostic launch_with; Value-based request builders (no vendored protocol types). AdapterKind names the launch mechanisms
│   ├── registry.rs      data-driven debug-adapter registry: maps a file extension -> AdapterKind from the [[debug_adapters]] blocks in bundled + user manifests, skipping adapters whose extension is disabled in the Extensions panel (replaces the old hardcoded adapter_for_extension match; the launch mechanisms themselves stay native, like the PDF/CSV viewers)
│   ├── log.rs           optional DAP wire log at ~/.croft/dap.log (gated by CROFT_DAP_LOG), mirroring lsp/log_file.rs
│   ├── install.rs       provisions a private debugpy venv at ~/.croft/debug-venv via uv (PEP 668 forbids pip-ing into the uv-managed CPython; mirrors ~/.croft/servers)
│   ├── remote_attach.rs pure attach planning: parse / gate the CPython version (>=3.14 ships sys.remote_exec), the platform-aware sudo-elevation decision (macOS always, Linux unless Yama ptrace_scope is relaxed), and the `pdb -p` command builder
│   ├── discovery.rs     enumerate attachable CPython 3.14+ processes via sysinfo plus a per-candidate `--version` probe
│   └── reaper.rs        sweeps orphaned vscode-js-debug processes (server + its detached watchdog, which setsids into its own session and survives a group-kill) left behind when croft crashes/force-quits without running Drop; kills only ~/.croft/js-debug scripts reparented to init (pid 1), so a live session is never touched; run async at startup and after each session teardown
├── testing/             Test Runner: a background worker runs the project's test tool off the render loop (`cargo test` for Rust, `pytest` for Python, `vitest` or `jest` for JS/TS — picked per workspace by `registry::runner_for` from `[[test_runners]]` manifest data; when NO enabled runner claims the root the four run entry points refuse with a status, and the worker refuses a queued request with a dedicated `Refused` response BEFORE any `Started` — the panel rolls the Running marks back and keeps its tree, and neither layer ever falls through to cargo, so a disabled runner extension really stops runs) and streams parsed cases into the Testing panel (mirrors app/git_worker + dap drain-per-tick); an Explorer re-root rebinds the worker, resets the panel, and re-discovers, with responses epoch-tagged so a run still streaming for the old root is dropped by the drain (the commit graph's root-tag idea). Debug-a-test (Cmd+K Shift+Enter / Alt+click the gutter ▷) hands a test to the DAP stack: pytest as a debugpy `module` launch under the PROJECT's interpreter (`pytest_debug_launch_request`; the adapter injects debugpy into the debuggee), cargo via `worker::build_test_binary` (`cargo test --no-run --message-format=json`, the bin/lib artifact outranking integration targets) launched under lldb-dap with the test name as its libtest filter argv (`lldb_test_launch_request`)
│   ├── mod.rs           shared NO_RUNNER_STATUS, `suite_pattern` (anchors a suite as `parse::` so cargo's substring filter and the panel's marking cannot sweep `parse_utils::b`), and `regex_escape` (shared by the JS `-t` argv builders and the locator; test titles are arbitrary strings)
│   ├── locate.rs        test-name -> source location: `--list` carries no file/line, so `find_test_source` walks the workspace (`.gitignore` honoured even outside a git checkout via `require_git(false)`; `target`/`node_modules` always skipped — build output can define a same-named fn) grepping `fn <leaf>` and ranking files by module-path match; pytest and JS node IDs carry their file, so those grep just that file with the escaped title (JS prefers a `test(`/`it(` declaration line over a comment or fixture that merely mentions the title, with the bare title as fallback). The app runs it on a background thread (`test_jump_rx` drained in sync_explorer_panels, replies from before a re-root dropped) so a big workspace cannot freeze the render loop. `enclosing_fn_name` (run-at-cursor, total on an empty buffer) and `test_fn_on_line` (the gutter play glyph) scan the open buffer
│   ├── model.rs         TestStatus (NotRun/Running/Passed/Failed/Skipped) + TestCase; suite_and_leaf splits a `module::name` path for the tree
│   ├── registry.rs      data-driven test-runner registry: maps a workspace root -> Runner from the [[test_runners]] blocks in bundled + user manifests (marker files and/or package.json (dev)dependency names), skipping runners whose extension is disabled in the Extensions panel (replaces the old hardcoded runner_for ladder; the run mechanisms — commands, parsers, binary resolution — stay native, like the debug adapters)
│   ├── parse.rs         per-tool output parsers, all node IDs normalised to `::` separators so one panel tree serves every runner: libtest (parse_test_line run lines, parse_list_line discovery), pytest (-v result lines, --collect-only node IDs), vitest (parse_vitest_list_line for `vitest list`, parse_vitest_tap_line for the streaming `--reporter=tap-flat` run lines whose `file > describe > test` IDs are complete per line), and jest (parse_jest_json: jest prints one `--json` document to stdout at run end — human output goes to stderr — yielding every assertion with its describe chain, `pending`/`todo` as the skip family)
│   └── worker.rs        RunAll / RunOne / RunFilter / RunSuite (header click; the cargo arm anchors the suite with `suite_pattern`, pytest gets it positionally as a node-ID prefix, vitest/jest anchor the describe chain via `suite_title_anchor` — their `-t` is an unanchored regex over the space-joined full name) / Discover per runner: cargo (`test --no-fail-fast`, `-- --list`), pytest, vitest (`run --reporter=tap-flat`, `list`, file + regex-escaped `-t` — vitest's `-t` is a regex like jest's) and jest (`--json`, `--listTests` file-level discovery, file + regex-escaped `-t`) — via cargo_cmd / pytest_cmd / js_cmd (absolute binaries for the GUI-stripped PATH, node_modules/.bin first, NO_COLOR + CI for JS) + run_streaming (tees stderr to the Test Runner OUTPUT channel, streams Started(Activity)/Case/Finished over an mpsc channel the app drains each tick; the parse contract is a Vec per line since jest's one JSON line carries the whole run). Debug-a-test builds via `test_binary_candidates` (lib before bin before integration, each carrying its target name and `src_path`) narrowed by the gesture's source file: a file that IS a target's `src_path` owns that target outright (exact even for a renamed `[[test]] path` target the file stem cannot predict), a module file narrows to its side of the build (`tests/` to integration harnesses, anything else to lib/bin, never widening) + a `--list` probe matching the listed name's final `::` segment exactly, so a lib test never claims an integration test's bare name (or vice versa); a nonzero cargo exit is a build error even when partial artifacts came out; the app runs `build_test_binary` on a background thread (`pending_test_debug` drained per tick) so a cold build never freezes the UI; the pending slot remembers its build root, and the drain discards a binary whose workspace was re-rooted mid-build instead of debugging the old project in the new cwd
├── mcp/                 MCP sidecar host (Tier-1 extensions): croft is a DETERMINISTIC MCP host — a human invokes a contributed palette command and croft calls one pre-known tool on one vetted local server (no LLM picks tools), which removes MCP's whole prompt-injection/tool-poisoning attack family
│   ├── mod.rs           module overview + McpOutcome (the off-thread worker's result)
│   ├── transport.rs     JSON-RPC 2.0 over newline-delimited JSON on the server's stdio (the MCP stdio framing; simpler than DAP's Content-Length); setsid-detached child, reader thread -> mpsc, least-privilege env_clear()+envs()
│   ├── client.rs        the MCP lifecycle: initialize -> notifications/initialized -> tools/list -> tools/call, synchronous id-correlated calls; tool_fingerprint for trust-on-first-use rug-pull detection
│   ├── registry.rs      data-driven: contributed_commands() (eager palette registration, skips disabled) + resolve_command() (lazy: tool + spawnable server with pinned Provision) from [[commands]]/[[mcp_servers]] manifests
│   ├── catalog.rs       the curated MCP catalog (AVAILABLE tier of the Extensions panel): bundled CATALOG_MANIFESTS (Web Fetch / Time / MarkItDown) merged with the remote signed index; install() writes a bundled entry's manifest or delegates a remote id to registry_index::install_remote (Available → Add → Installed), uninstall() removes it (Installed → Available), and is_removable() = is_catalog_entry() ‖ registry_index::is_index_entry() — the provenance gate that lets croft remove only what it added (bundled OR vetted-index), never a hand-dropped user manifest. Add via the panel's +Add; remove via the trash button / Delete, which both open a confirmation popup (InputPurpose::ExtensionUninstall — Enter uninstalls, Esc keeps) so a destructive action never fires from a single click/keypress
│   └── registry_index.rs the remote vetted index (extensions.croft.software): fetches index.json + index.json.sig over Cloudflare HTTPS, verifies an ed25519 signature against a baked public key (INDEX_PUBLIC_KEY) BEFORE caching (verify-at-write, trust-on-read under ~/.cache/croft), gates entries by api_version, and on install fetches the manifest and checks its sha256 against the signed index. Disarmed (no network, bundled-only) when the key is all-zero. Stale-while-revalidate: the cached entries render synchronously while a background refresh always refetches (App::drain_ext_index_refresh signals a panel rebuild only when the verified index changed), so a new extension appears on the next launch with no TTL wait; the panel's ⟳ button (App::refresh_extension_index) re-pulls mid-session. The index is git-hosted at codeberg.org/vitali87/croft-extensions and published to the VPS by a systemd timer mirroring croft-docs
├── lsp/                 LSP client stack
│   ├── mod.rs
│   ├── client.rs        async-lsp client wrapper; router forwards diagnostics + work-done progress ($/progress, e.g. rust-analyzer "Indexing…") to the status bar and acknowledges the workspace refresh requests (semanticTokens/refresh, inlayHint/refresh) into shared re-pull flags the app polls; server stderr lines land in OUTPUT at the severity of their tracing level token (stderr_level), not a blanket info
│   ├── config.rs        per-language LSP config (basedpyright, ruff, ty, vtsls, rust-analyzer, gopls); the ServerConfig factories are the executable spec the bundled manifests reproduce. Language is an open newtype (interned lsp_id, not a closed enum) so an extension can contribute a new language with no Rust change; per-language data (extensions, root markers, family) lives in the language table
│   ├── install.rs       croft-managed server provisioning: lazy background installs into ~/.croft/servers via three backends — npm (vtsls, JSON/HTML/CSS, yaml, bash), uv (ty/ruff, rerouted to Termux's pkg on Android, incl. the uv bootstrap), and Binary (clangd/taplo/rust-analyzer: download + unzip/gunzip a host-agnostic per-platform release binary, PATH-first incl. ~/.cargo/bin; a Binary can carry a termux_pkg so Android — where the glibc release can't run on bionic — reroutes to pkg, as rust-analyzer does)
│   ├── languages.rs     language table: file-extension -> language, root markers, and server family, all built from extension manifests' [[languages]] blocks (replaces the old hardcoded Language enum match arms)
│   ├── log_file.rs      LSP stderr / debug log sink at ~/.croft/lsp.log
│   ├── manager.rs       lifecycle: workspace pre-warm at startup (`prewarm_workspace`, VS Code's `workspaceContains` activation: every language whose root marker sits in the workspace root gets its servers spawned before any file opens, so rust-analyzer's cold indexing overlaps with tree browsing instead of starting at the first `.rs` open; the scan is non-recursive stat calls and the command is inert under `cfg(test)` so test-built Apps never spawn real servers) / spawn / did_open / did_change / did_save (Cmd+S → rust-analyzer re-runs check-on-save so PROBLEMS refreshes) / completion / documentSymbol (Outline) / inlay hints (whole-document textDocument/inlayHint once per edit-batch, capability-gated, labels normalised — parts joined, padding folded to spaces — and the reply seq-tagged so the app drops a batch computed against older text) / documentHighlight (the occurrences of the symbol under a resting caret, fired by the app's 250ms idle tick, request-id + edit-seq gated so a reply for a moved caret or edited text never paints) / call hierarchy (prepareCallHierarchy + incomingCalls/outgoingCalls, one level per Cmd+K H / Cmd+K Shift+H invocation into the shared location picker — incoming rows jump to the call expression, outgoing to the callee's definition) / shutdown
│   ├── manifest.rs      declarative extension.toml loader (extension system): parses a manifest's [[languages]], [[language_servers]], [[themes]], [[debug_adapters]], [[test_runners]], [[mcp_servers]], and [[commands]] blocks; also discovers user extensions under ~/.config/croft/extensions/<id>/
│   ├── registry.rs      ServerRegistry (language -> ordered servers); built from the bundled manifests in assets/extensions/* plus user-installed extensions, instead of hardcoding configs
│   ├── runtime.rs       Tokio runtime owned by the LSP manager
│   ├── semantic_cache.rs content-keyed disk cache of semantic-token batches at ~/.croft/sem-cache. Only a batch whose `seq` still matches the live buffer is applied OR stored: a reply can sit in the request retry backoff while an external tool rewrites the file, and decoding it over the new lines would both mis-colour and persist that under the NEW content's key, replaying it on every future open
│   └── trace.rs         raw JSON-RPC trace tee (OUTPUT panel RPC toggle): TraceRead/TraceWrite wrap a server's stdio and, only while tracing is enabled, reassemble Content-Length frames each way into the server's "<name> (trace)" channel (Zed's RPC-messages equivalent)
└── widgets/
    ├── mod.rs
    ├── command_palette.rs   VS Code Command Palette (Cmd/Ctrl+Shift+P): a static command registry + fuzzy-filtered picker; the App's run_command dispatches each entry
    ├── commit_graph.rs  the Source Control COMMITS section: repo-wide commit graph with box-drawing lane rails (VS Code's Source Control Graph in the tig idiom). `layout_graph` is the pure classic lane algorithm — each lane holds the hash it expects next; a commit lands on the first lane expecting it, duplicate expectations close into the node (╯/╰), a merge's extra parents open lanes (╮/╭) or junction into a lane already expecting that parent (┤/├), pass-through rails cross long connectors as ┼ — run on the fetch thread over `git::commit_graph` (git log --branches --tags HEAD --topo-order, 400 commits). Rows paint rails colour-cycled by lane, ref badges (HEAD bold accent, tags gold), subject, right-aligned age; click opens the commit's full patch (`git::show_commit`) in a read-only tab; refetches whenever the git worker sees head_oid move (commit/checkout/pull) with a triggered-while-inflight refresh queued to re-fire when the stale reply drains (so a Make Root racing a fetch never strands the panel on Loading), collapses from its header, keeps scroll across same-tip background refreshes
    ├── completion_popup.rs  LSP completion popup (anchored at the cursor, filterable; `area_for` clamps to the editor pane on all four edges — a popup wider than a narrow pane used to be pushed left past the pane's own edge and paint over the Explorer)
    ├── signature_help_popup.rs  LSP signature help / parameter hints: a one-line popup above the caret with the active parameter bolded, auto-triggered on `(`/`,` and dismissed on `)`/Esc (manager `RequestSignatureHelp` + `normalise_signature_help`)
    ├── connect_dialog.rs    remote SSH connect modal (host + auth prompt phases)
    ├── dependencies.rs  collapsible, language-aware DEPENDENCIES section: detects the workspace's package ecosystem(s) from manifest files at the root (Cargo.toml→Rust via `cargo metadata`, pyproject.toml/requirements.txt→Python, package.json→Node, go.mod→Go), resolves the packages off-thread, and labels the header for what it found ("RUST DEPENDENCIES" etc.). A ⋯-menu Explorer sub-view, display-only; gated on detection, so a folder with no manifest shows no dependency view and drops it from the ⋯ menu (App holds the detected ecosystems in dep_ecosystems, recomputed on every re-root)
    ├── diff.rs          side-by-side file diff renderer used by the explorer's Compare action; also derives hunk ranges from the row model and builds the single-hunk unified patches behind the diff pane's S / U / R stage / unstage / revert keys (gated to the Source Control HEAD diff via `left_is_git_head` — a Timeline snapshot diff never reaches the index; patches restore each line's CRLF bytes and git's no-newline marker; the action row follows the newest click or hunk jump, never a stale caret)
    ├── editor.rs        tree-sitter highlighted editor with full write path, mouse-drag selection, native-clipboard copy / cut, plus image / PDF / spreadsheet preview tabs (the CSV/diff canvases fill with `canvas_bg`: `Reset` on iTerm2 to inherit the SetColors session bg, the theme's `editor_bg` on every other host, where `Reset` would override the frame prefill and leave a host-black island; the image/PDF canvas uses `image_canvas_bg` instead — still `Reset` on Kitty hosts, because the preview sits at `KITTY_Z_BELOW_TEXT_AND_BG` and Kitty paints any cell with a non-default background over an image that deep, so an explicit fill hides the picture behind its own canvas — the themed look survives via the bake's theme-bg letterbox), the minimap rasterizer (`minimap_rgba`), indentation-based code folding (`fold_range` drives a gutter chevron; `is_line_hidden` binary-searches `hidden_ranges`, the merged spans rebuilt on every write to `folded` — it runs per rendered row per frame, so deriving it from the fold set there made Fold All on a large file cost millions of iterations a frame; the render's row builder skips hidden lines, cursor movement steps OVER a collapsed block, and `reveal_cursor_fold` guarantees the caret is never left on a hidden line — from `pin_on_edit` so no edit lands on one, and again at the top of the render, where every direct `cursor_row` setter converges (Go to Definition, search, Ctrl+G, a restored session) and where a caret with no painted row would otherwise leave nothing drawn at all; `open` drops fold state — line numbers into the old file — only when the incoming path DIFFERS, since `open` is also the same-path reload behind every FS-sync sweep and dropping it there popped the user's blocks open whenever anything rewrote the file), the testing play glyph (`locate::test_fn_on_line` marks `#[test]`-family fns and pytest `test_*` defs with a green ▷ in the sign margin — breakpoint dot and stop arrow outrank it — and `test_glyph_at` maps a click to the test's name, which the app runs through the test worker), the git gutter (`refresh_git_marks` diffs the buffer against the app-supplied HEAD baseline; `GitMark` bars paint in the gutter; the app fetches and invalidates those baselines across EVERY editor group, since inactive split panes render their editors too and a baseline left at the old HEAD keeps marking lines a commit already cleaned), bracket-match highlighting (`bracket_match_pair` tints the bracket beside the caret and its partner), LSP occurrence highlights (`apply_occurrences` converts documentHighlight's UTF-16 spans to char columns; the row loop tints reads with `occurrence_bg` and writes with the stronger `occurrence_write_bg`, cleared on every edit or caret move — VS Code's word highlight), multi-cursor editing (`carets`: `select_next_occurrence` for Cmd+D, `add_caret_at_screen` for Alt+click, `begin_box_select` / `box_select_to` for Shift+Alt column selection — ALT owns these because SGR mouse reports carry only shift/meta/ctrl and no super, so Cmd+click cannot be told from Option+click and Go to Definition rides CTRL instead, the modifier the terminal pane already uses for its file/URL clicks), LSP inlay hints (`apply_inlay_hints` decodes the seq-gated batches into per-line `inlay_spans`; the render splices each label into the row as dim italic virtual cells at its anchor, and every overlay painter, the caret (`cursor_screen_pos`), horizontal scroll (`ensure_cursor_col_visible`, `content_cols`), and mouse mapping (`buffer_pos_at`, hint cells snap to the anchor) translate buffer columns past them via `inlay_cells_before` — except carets (primary, secondary blocks, ghost carets), which use the strictly-before rule so a caret AT a hint's anchor sits left of the hint like VS Code; wrap mode suppresses hints; on by default, palette "Editor: Toggle Inlay Hints", persisted as `disable_inlay_hints`), and the breadcrumbs bar + sticky scroll rendered by `EditorTabs` (App pushes `breadcrumbs` and `sticky_lines` each frame from the outline scope chain; `breadcrumb_target_at` / `sticky_line_at` map clicks to jumps; crumbs are budgeted and advanced in display CELLS via `set_stringn`, so a CJK segment is neither overpainted by the next crumb nor mis-hit; the sticky band floats over content but stops above the caret's PAINTED row, read back out of the frame's own row layout so a collapsed fold or comment box between the top and the caret cannot make the band overshoot; a caret under the band cannot be painted at all, so `caret_floor_row` keeps the scroll from parking it there in the first place — dragging it to the first row the band does not cover instead of to `scroll`, which had suppressed the band for the whole of a wheel scroll)
    ├── editor_find.rs   VS Code-style inline Find bar (Cmd+F) with active-match orange highlight, Enter / Shift+Enter walk, case-sensitive / whole-word / regex toggles, and a Replace row (Cmd+Opt+F): Tab switches field, Enter replaces-and-advances, Cmd+Opt+Enter replaces all in one undo step; Replace All enumerates matches via the same `split_for_highlight` the count/paint/navigation use (never touching what the bar cannot show) and recounts afterwards; regex replacements expand `$n` captures plus VS Code's `\n`/`\t` escapes, a replacement newline splitting the line
    ├── extensions.rs    Extensions sidebar widget: projects the bundled + user extension manifests (lsp/manifest.rs summaries) into a theme-aware list — grouped under BUILT-IN/INSTALLED/AVAILABLE headers, each row a coloured language/file mark + name + blurb + a rounded pill toggle (Powerline caps + knob, brand-teal on / grey off), with a +Add affordance on AVAILABLE rows and a trash button (just left of the switch) on removable INSTALLED rows — plus a local filter box (narrows by name/blurb/id; no marketplace) with a clear (✕) and a refresh (⟳) affordance; reports row / switch / trash / clear / refresh clicks back to App (click_uninstall / click_action / click_clear / click_refresh / item_at), which owns the disabled-set prefs, the catalog install/uninstall, the remote-index refresh, and the per-control hover tooltips (fired only over a control, never the row body)
    ├── file_finder.rs   VS Code-style Quick Open (Cmd+P) fuzzy file picker with tiered match ranking (exact filename > prefix > substring > path > subsequence)
    ├── file_tree.rs     ignore::WalkBuilder backed tree, lazy children, fs-watcher refresh, multi-select, drag-drop, bulk trash, reveal-path on Cmd+P open
    ├── header_pill.rs   shared section-header pill button (chip-backed codicon affordance + theme colours) used by both the Remote Explorer (+ / refresh) and Source Control (refresh) headers
    ├── captures.rs      the panel group's CAPTURES tab (iTerm2's Capture Output): output lines collected by `capture` triggers (pane label, interpolated message, the whole escape-stripped line), newest selected; Enter / click has the App switch to TERMINAL, find the pane by shell pid, locate the newest grid row matching the captured text (prefix match, since long lines wrap), scroll it into view and select it. Pure widget, capped at 500 entries
    ├── history_popup.rs Ctrl+Shift+H command-history popup over command_history.rs: query line with caret, newest-first deduped results (green/red exit dot, duration + cwd + non-zero exit meta), Ctrl+R cycling the scope filter; pure widget, the App runs the search per edit and types the pick via paste_input
    ├── hover.rs         shared hover-feedback helpers (pointer hit-test + theme-aware row-hover background) used by the side panels and header pills
    ├── hover_popup.rs   anchored 300 ms-dwell popup: the LSP hover (wide), the tab-path tooltip, and `new_compact` button hints (shrink-to-fit) for chrome controls, all driven off one `ui_tooltip_at` dispatch in app/mod.rs
    ├── open_editors.rs  collapsible OPEN EDITORS section: the open editor tabs projected from EditorTabs each frame (dirty dot, active highlight), click-to-activate; one of the Explorer sub-views toggled by the ⋯ "Views and More Actions" menu on the EXPLORER title line
    ├── outline.rs       collapsible OUTLINE section under the file tree: the active editor's symbol tree, indented + kind-iconed, with follow-cursor highlight and click-to-jump; painted instantly from tree-sitter (see outline_syntax.rs) and refined by the LSP documentSymbol reply when it arrives (each request carries the edit seq, and `drain_lsp_document_symbols` forwards EVERY reply to `apply_outline_symbols`, which is the sole judge: it filters on the active path and on exact edit-seq equality, so a slow server can't flicker the breadcrumb's symbol crumb while typing. Deliberately no pre-selection in the drain — collapsing a tick's replies to whichever arrived last let a late reply for the file just left evict the active file's, and collapsing by highest seq is no better, since seq is a per-Editor counter that restarts at zero in a fresh editor group). One of the ⋯-menu Explorer sub-views (with Open Editors / Folders / Timeline / Dependencies); App::render_explorer_sections stacks the visible ones, the tree absorbing the leftover rows
    ├── osk.rs           on-screen keyboard for Termux (mouse tracking blocks the native soft keyboard): bottom-docked tappable band whose keys synthesize KeyEvents through handle_key; lower / shift / two symbol pages (Gboard `?123` digits+punctuation and a `=\<` more-symbols page of tilde/backtick/pipe, the bracket family, and math/typographic/currency glyphs, switched by the row-3 lead key where Shift sits on letters) plus caps lock (letters only), one-shot ctrl + alt latches on the bottom row next to space; physical-keyboard geometry (structural keys carry max cell widths, the left column staggers esc < tab < caps < shift like a MacBook, letters and space absorb wide-frame slack via water-filling, Enter grows into a two-row L on the right in both merged and split layouts (full-height even on one-row bands) and the collapse `⌄` key is about twice the `split` key); Gboard-style split layout for foldables (number/top rows split 5|5, the home and bottom rows one column earlier so `g` and `b` fall in the right thumb cluster, and the top-right cluster parks a `\` at the far edge (`y u i o p \`, qwerty letters keep their natural order); halves solved independently around a 2·width/9 center gap, space on both halves, merged again under 60 cols), toggled by the `split` key and persisted as `osk_split` in prefs; thumb-sized keys scale with frame height and the non-focused pane folds away while the band is up; key caps are drawn from the active theme's palette (brand-teal armed accent on Black, the historical navy on Dark); a tap-to-dictate mic key sits immediately right of the left alt (eating into the space bar, and the left space half when split) and drives `voice.rs`
    ├── output.rs        the panel group's OUTPUT tab: a read-only viewer over the `output.rs` bus with a channel dropdown, a minimum-level filter, an RPC trace toggle, and a clear action; renders the selected channel's level-coloured tail, auto-following new lines until the user scrolls up. The open dropdown windows its list when the channels outnumber the body rows (`dropdown_scroll`): it opens at the current selection, the wheel / PageUp/Down scroll the window instead of the log, and a one-column scrollbar (click-to-jump) marks the truncation — overflow channels used to be unreachable by any gesture
    ├── problems.rs      the panel group's PROBLEMS tab: aggregated workspace diagnostics projected from the App's per-file store, with a toolbar (severity filter cycling All / Errors / Errors & Warnings, and a group-by-file toggle between the collapsible per-file headers and a flat file-annotated list); click a diagnostic to jump, a header to collapse. The filter drops files with no matching diagnostic; the tab badge counts stay unfiltered
    ├── ports.rs         the panel group's PORTS tab: the registry of detected loopback ports (port / address / process / origin) fed by `port_detect.rs`, with the orange `⇄ host` marker for a forwarded remote port; pure widget (selection + click hit-testing), the App runs the open / forward / copy / stop actions. `reconcile_live`'s `live` set is EVERY loopback listener on the box (`port_detect::poll_all_listening`), never the pane-subtree scan that decides what to surface: a container's published port is nobody's descendant, and retiring it for missing from a snapshot that could never contain it dropped the row and `ssh -O cancel`ed a live tunnel seconds after the scrape found it. A failed probe reconciles nothing at all. `x` means two things and they are not the same: `stop_forwarding` tears the tunnel down and LEAVES the row, `remove` dismisses the row and suppresses re-detection for the session — routing the stop through `remove` blacklisted a still-listening port the user could never forward again. The body scrolls to keep the selection visible, since `f` and `x` act on it
    ├── process_picker.rs centered selectable list of attachable Python 3.14+ processes for "Debug: Attach to Python Process"; selecting one has the App spawn `pdb -p <pid>` in a PTY
    ├── remote.rs        Remote (SSH) sidebar widget with empty-state hero illustration
    ├── run_debug.rs     Run and Debug sidebar widget: empty-state Run [filename] button, and when a session is live the paused-state tree (call stack + expandable variables), a debug console of program output, and a `❯` REPL prompt; the App builds the rows and maps clicks back to frames / variables
    ├── testing.rs       Testing sidebar widget: the test suite tree (grouped by module / pytest file) with live pass/fail/skip status glyphs, a summary line reflecting the Activity (Discovering / Running / tally, with a leading `run failed` marker when the runner exited nonzero without streaming a Failed case — a compile error reports no cases, and a stale failure from an earlier run cannot mask the marker), and the failing-test count that feeds the beaker activity badge; a failure reported during a run is never downgraded by a later pass for the same name (the `Running` run-start mark is exempt, since `start_single` paints it through the same call and a fixed test must be able to go green on a re-run), because two harnesses in one `cargo test --no-fail-fast` can report the same test path and stdout carries no harness identity to separate them (cargo's "Running unittests …" banner is on stderr, read by another thread), so the row they share is honest only when it shows the worst outcome; a finished run rolls back marked cases it never reported (like a worker refusal) so a compile error cannot strand Running dots; run-at-cursor resolves a leaf unique in the tree to its full name for an exact run; rows clip by display width (`set_stringn`) so CJK names stop at the scrollbar lane; the view discovers on first open, Enter runs all tests, `r` re-discovers; each row's play/status glyph is the click-to-run button while a case's name reveals its source (`hit_at` maps the click)
    ├── scrollbar.rs     shared vertical- and horizontal-scrollbar geometry
    ├── search.rs        sidebar search panel (query/replace/include/exclude inputs) + .gitignore-aware walker, glob filtering, and replace
    ├── shortcuts.rs     F1 shortcuts modal: every binding grouped by pane, scrollable
    ├── branch_picker.rs Checkout / Create Branch quick-pick overlay: type to filter the repo's branches, Enter to switch or create-and-switch (also drives the Branch submenu's merge / rebase / delete / create-from via `branch_purpose`); pure widget fed by `git::list_branches`
    ├── input_prompt.rs  single-line text modal for SCM ops that need a typed value (clone URL, branch rename, remote name/URL, tag name), tagged by `InputPurpose`
    ├── list_picker.rs   generic single-choice picker for SCM ops that act on one of a git-owned list (apply/pop/drop a stash, delete a tag, remove/push-to a remote), tagged by `ListPurpose`
    ├── scm_menu.rs      the Source Control "⋯" title menu: a static tree of leaves + one-level fly-out submenus (Commit/Changes/Pull-Push/Branch/Remote/Stash/Tags); every leaf is an `ScmAction` dispatched in `App::dispatch_scm_action`
    ├── source_control.rs Source Control sidebar widget: branch summary (click to open the branch picker), commit input, change list, inline stage/unstage/discard row actions, commit split-button + actions menu (push/pull/sync/branch/stash/diffs), header refresh pill, no-repo hero
    ├── symbol_picker.rs VS Code "Go to Symbol in Editor" (Cmd/Ctrl+Shift+O): a fuzzy picker over the active file's outline symbols (kind-iconed, depth-indented); a `:` prefix switches to Go to Line; the App jumps via go_to_definition
    ├── workspace_symbols.rs VS Code "Go to Symbol in Workspace" (`#` in Quick Open): query box whose text fans out to every running server as `workspace/symbol` (debounced per keystroke burst, request-id keyed, stale replies dropped, selection restarts at the top per reply); rows show kind icon + name + workspace-relative path, Enter opens the file at the definition
    ├── terminal.rs      portable-pty + alacritty_terminal + ratatui integration with selection + scrollback; pane order lives in `App::terminals` and is drag-reorderable live (grab a pane's name pill side-by-side, or its rail row in maximize mode; `App::move_terminal` keeps the active pane pinned to its terminal, and re-seats each pane's `last_area` in SLOT order — the rect is a slot's geometry but lives on the terminal object, and the main loop drains the whole mouse burst before drawing, so without that the next motion report over the same cell resolves to the pane that just left it and swaps them back; in maximize mode neither positional rule holds — there is exactly ONE live rect, it belongs to whichever pane was active at the last PAINT (the press and the drag are drained together, so that is not the dragged terminal), and the drag leaves the dragged terminal active — so the live rect is found and seated on the pane the reorder leaves active; the session write is marked and flushed once per tick rather than run per motion report). `Drop` kills AND reaps the shell (portable-pty's SIGKILL escalation never waits, so a HUP-trapping shell left a zombie per closed pane), then wakes the reader through a shutdown pipe it polls beside the pty fd and joins it — EOF alone is not a reliable wake: on Linux a background job keeps the pty slave open after the shell dies, and a bare blocked `read` would hang the join (and the UI) for as long as the job runs. Mouse-wheel forwarding: `mouse_reporting()` reports whether the child enabled a tracking mode (`TermMode::MOUSE_MODE`); `report_mouse()` / the pure `encode_mouse_report()` emit an SGR (1006) or legacy X10 report. `App`'s wheel handler forwards the notch as a wheel report when the child tracks the mouse (so it scrolls its own buffer) unless `Shift` is held, which scrolls croft's scrollback; a child that doesn't track the mouse still gets the arrow-key fallback. Clicks/drags stay croft-local text selection (not forwarded); Shift+click extends the existing selection. Selection drift correction: selection/copy-cursor coordinates are down-anchored grid lines re-based every frame against a monotonic scroll clock — a one-cell tracer selection parked in alacritty's own (otherwise unused) `Term::selection` slot, which alacritty rotates on every scroll including ring rotation after scrollback saturates (where `history_size` freezes and can no longer serve as the clock); history growth is the fallback for the rare windows where a clear kills the tracer, and the alt screen freezes the clock. A selection made ON the alt screen instead carries an `AltSelAnchor` content fingerprint (the full text of its rows), because alt-screen apps (Claude Code) scroll by repainting: every rebase re-finds the rows via the exact-row count per candidate shift (>=2 exact rows when the block has two, >=1 non-blank, ties to the shift whose captured neighbour rows also match — a one-row selection on a repeated divider row follows its own copy, not the nearest lookalike — then to smallest movement — app chrome like Claude Code's input box or floating pills overdraws rows anywhere in the block as scrolling slides it underneath, so partial survival anchors by however many exact rows remain), paints only the surviving rows (`visible` per-row column clips: a row part-covered by a pill keeps BOTH intact ends via `partial_overlap_cols` (paint-only credit at the anchored shift: trailing-blank runs stripped, >=4 solid chars per end, no minimum share so a mid-row pill leaves under-half ends lit; overlapping ends — an animated counter mid-row — keep the row whole); drift is measured against `AltSelAnchor.top` (the anchor's OWN remembered position), never the selection's top, which mid-drag is the pointer and walked upward drags' anchors one row down per event) with copy served from the remembered extract whenever the block is not fully live; while a mouse drag is held (`drag_selecting`, ended by `end_drag` from the app's mouse-up) the selection never goes dormant and follows the pointer over whatever the grid shows — drags start on blank or animated rows whose anchors can't match — with the definitive anchor captured at release, goes dormant — hidden, coordinates frozen — when no run survives, revives when the content returns, and dies when the app leaves the alt screen. Edge-drag autoscroll on the alt screen forwards wheel reports to a mouse-tracking app (it scrolls; the anchor drags the selection; the head re-pins to the edge) instead of scrolling nonexistent scrollback. Find-in-terminal (`Cmd+F` everywhere, plus `Ctrl+F` off macOS only — on macOS Ctrl+F is a control byte the child owns and reaches it as 0x06, matching VS Code / iTerm2) reuses `editor_find`'s match helpers over `grid_lines_and_clock()` (the whole grid + scrollback as `Vec<String>` with the absolute `Line` of row 0 and the scroll-clock reading, one lock); `App::terminal_find` holds the query and is bound to the pane it opened on like quick-select and copy mode (`terminal_find_pane`, per-frame invariant + sibling-click close; closing clears every pane's highlight), `set_search`/`set_current_match` drive the render-loop highlight with the active match clock-stamped so it rides streaming output and navigation re-bases its anchor before walking, and `scroll_offset_for_line()` centers the active match in the viewport. Wide chars (CJK/emoji) occupy a `WIDE_CHAR` cell plus a spacer cell; `row_text_and_cols()` skips the spacers (returning a char-index → grid-column map) so copy/search read contiguous text while highlights still land on the right cells. `extract_selection_text` consults the WRAPLINE flag when joining rows: a soft-wrapped logical line copies (and is stored in the durable history, and pinned in the sticky header) as ONE line; only hard row breaks keep their newline. OSC 8 hyperlinks surface via `hyperlink_at`/`hyperlink_at_screen` (checked by the app's Cmd/Ctrl+click before the plain-text URL regex; only http/https URIs open — the cell can carry any scheme behind unrelated visible text, so `open_detected_url` refuses non-web links and surfaces the real destination in the status line); BEL latches into a flag the app drains per tick (`take_bell` → status bar). Command decorations: OSC 133 marks are anchored on the scroll clock like annotations/images ((line_rec, clock_rec) — stable past scrollback saturation; a destructive clear drops the marks whose content it erased, so no phantom dots resurface); `pair_decorations()` folds the mark stream into one `CommandDecoration` per finished command (prompt line, exit code, duration measured 133;C→133;D in the reader thread; a `CommandEnd` with no pending `CommandStart` is dropped, which filters a second integration layer's duplicate marks); the render loop paints each as a dot on the pane's left border (blue ok, red fail), `decoration_at_screen` hit-tests clicks (opening the decoration menu: Copy Output / Select Output / Re-run Command, headed by exit + `human_duration`; `⌘K ⇧C`/`⇧S`/`⇧R` apply the same to the last finished command), the record carries the `PromptEnd` cell and the `CommandStart`..`CommandEnd` span so `command_input_text`/`command_output_text`/`select_command_output` can extract or highlight exactly the typed command and its output, and `drain_finished_commands` feeds the app's long-command notification for unfocused panes. Quick-select (Ctrl+Shift+Space) pushes `HintSpan`s in via `set_hints`; the render loop paints match spans green and overlays black-on-gold label cells through the same colmap (see quick_select.rs). Trigger highlights ride the same per-row pass from the `set_triggers` Arc (see triggers.rs). Pane inline images: OscSniffer also captures iTerm2 OSC 1337 `File=…;inline=1` payloads (a dedicated multi-megabyte carry cap; alacritty drops the sequence, so the tee is the only survivor), anchored on the scroll clock like annotations ((line_rec, clock_rec), so the picture rides ring rotation past scrollback saturation); `pane_images()` surfaces them with their current grid line, a destructive clear drops them (the pane's Clear, and program-emitted wipes via WipeSniffer over the raw bytes — ED 2 erases on-screen anchors, ED 3 scrollback ones, RIS both; the sniffer tracks alt-screen transitions positionally within each chunk and ignores only wipes that land while the alternate screen is active), and the app's `update_terminal_image_overlay` bakes the active pane's newest one through the standard ImageOverlay pipeline (fit_image_auto → build_inline_image_z at KITTY_Z_BELOW_TEXT_AND_BG, unique KITTY_ID_TERMINAL slot, clear latch in consume_any_image_clear), reusing the baked payload on a pure anchor move (same seq/pane/cell size — no per-row re-decode), yielding to an open context menu on iTerm2/Sixel like the editor preview, and hiding it when the anchor scrolls off screen, in the alt screen, or when the panel is hidden. Named/Indexed 0-15 cell colors render through the theme's 16-color ANSI palette (`set_palette`, VS Code dark defaults, `ansi` array override in [[themes]] manifests). Shift+PageUp/PageDown/Home/End drive keyboard scrollback (all four fall through to an alt-screen program, End included); scrollback depth comes from `terminal_scrollback` in config.json at spawn. Broadcast input (Cmd+K I) lives in the app: `write_terminal_key`/`paste_terminal_input` mirror shell-bound input to every non-excluded pane, keystrokes encoded per pane because DECCKM is per-PTY state (a zsh pane gets SS3 arrows while a bash pane gets CSI) (the focused pane always receives its own input; `broadcast_excluded` is the per-pane opt-out, Cmd+K Shift+I), enabling routes through a red confirm modal, receiving panes wear a red ⇶ name pill, and closing down to one pane switches broadcast off. Selection carries a `block` flag (copy mode's Ctrl+V rectangle: `block_bounds` min/maxes rows and columns independently, `cell_in_block_selection` paints, `block_selection_text` extracts the same column slice per row); copy mode itself is app state (App::terminal_copy_mode, Ctrl+Shift+Y) driving `set_selection`/`set_copy_cursor` (a green modal block painted last in the cell loop) with vi motions over `row_text`/`grid_bounds`; each keypress first folds the scroll clock's movement since the last key into the stored coordinates, so motions continue from the re-anchored highlight instead of teleporting back to stale lines, and the mode is bound to the pane it opened on — activating a sibling pane closes it (tmux-style) rather than folding that pane's independent clock into the coordinates. `w`/`b`/`e` all wrap across rows like vim. At the 133;D mark the reader thread also extracts the typed command (`last_command_input_text` over the B→C span) and the OSC 7 cwd, sending a `FinishedCommand` down the drain — the durable command history's feed. OSC 7 paths are trusted for LOCAL filesystem use (split-in-cwd, session save) only via `local_shell_cwd()`, which requires the reporting host to be this machine (`command_history::is_local_host`: full-hostname match after one mDNS `.local` strip, or the bare short name — never first-label vs first-label) AND the claimed path to name the directory the kernel says the shell is in (`cwd_of_pid`, canonicalized so macOS's /tmp → /private/tmp symlink still matches — PTY bytes carry no author and a foreground job can print a claim and die before the bytes are parsed, so no tty-ownership sample establishes provenance; a forged claim equal to the kernel's truth grants nothing); the zsh/bash shims percent-escape `%` in `$PWD` (fish always escaped) because the sniffer percent-decodes every report, and the bash DEBUG-trap guard joins an ARRAY `PROMPT_COMMAND` with `;` (scoped IFS) so empty Enters never fabricate a command. Closing a pane parks it in App::closed_terminals for a 10s undo window (Cmd+K ⇧T restores process + scrollback; the tick reaps expired parks, whose Drop then kills the child); the panel layout persists across restarts via terminal_session.rs. OSC 9;4 progress renders as a gauge over the bottom border's glyphs (heavy strokes in the state's colour: blue/red/yellow, a wall-clock-phased sweeping segment for indeterminate; the name pill appends the percent when painted), held in a shared slot the reader thread writes and clears. Timestamps gutter: the reader thread stamps rows by content id keyed on the shared scroll clock (clock reading + cursor grid line — stable through scrollback saturation, frozen across alt-screen trips, never wiped by a cursor-up redraw) at chunk granularity into a bounded BTreeMap; the "Terminal: Toggle Timestamps" palette command paints each stamped row's HH:MM:SS (libc localtime) down the right edge, amber + warning mark when a row landed STALL_GAP_MS after its predecessor. Sticky command header: scrolled so the top row falls inside a command's output with its prompt above the view, the typed command (decoration span for finished ones, the newest CommandStart's B→C span for the running one) pins to the pane's top row with the scroll depth. Click-to-move prompt cursor: `prompt_click_arrows` maps a plain click on the cursor's own prompt row (newest mark = 133;B) to synthesized ←/→ sequences, clamped to the typed span; the app's mouse-up hook writes them pane-locally (never broadcast). Annotations (Cmd+K N on a selection): PaneAnnotation spans anchored on the scroll clock like selections ((line_rec, clock_rec) captured when the prompt OPENS so rows streaming while the note is typed don't shift the pin; GC'd off the scrollback floor), rendered amber + underlined under the cursor/selection/find layers; a plain click pops the note in a HoverPopup, Cmd+K N over a note edits, Cmd+K ⇧N deletes, all via PromptKind::AnnotateTerminal. Host accents: the app matches each pane's `shell_host()` against the compiled prefs rules per frame and sets `accent`/`accent_badge` — an accented pane's border wears the rule colour over the focus blue (gradient suppressed), the name pill goes black-on-accent with a warning mark, and the badge paints dim top-right. Cmd+K D dumps `grid_lines()` (blank tail trimmed) into an `open_text_buffer` scratch editor tab named after the pane
    ├── timeline.rs      collapsible TIMELINE section: the active file's git history (`git log --follow`) fetched off-thread, two rows per commit (summary + author/age), click-to-open the commit's diff; a ⋯-menu Explorer sub-view
    └── zoxide_jump.rs   Cmd+Z zoxide jump popup: fuzzy directory jumper that re-roots + cd's the terminal
tests/cli.rs             integration tests for the CLI surface
```