Two purposes: orient coding agents in the tuicr codebase, and explain how to read tuicr's review export (last section).
tuicr is a Rust TUI and library for code review. src/ layout is self-describing (ls src/); src/lib.rs is the public crate surface (ReviewStore, session/comment types). Notes below are only what the code does not say.
e2e/: tmux-driven end-to-end suite that runs the real binary against fake forges (e2e/fakeforge/); see e2e/README.md, coverage map in e2e/COVERAGE.md.
Repository-managed agent integration: skills/tuicr/ (shared skill bundle that launches tuicr in a cmux, Rex, tmux, Zellij, or Herdr split pane).
- Every user-visible bug fix or behaviour change adds or updates an e2e scenario
e2e/scenarios/<area>/<behaviour>.py, named after the behaviour, with the PR/issue in its header comment. It must FAIL on the parent commit and PASS with the change. Unit tests are still required. - Run:
cargo build --release && TUICR_BIN=target/release/tuicr uv run --python 3.12 e2e/run.py [<area>/<behaviour>…](needs tmux and uv for Python 3.11+; hg/jj scenarios SKIP without them). CI jobe2eruns it on ubuntu and macOS. Authoring guide:e2e/README.md. - Before committing Python changes run
uvx ruff@0.15.16 format --check,uvx ruff@0.15.16 checkanduvx ty@0.0.44 checkwithe2e/pyproject.toml(exact commands and pinned versions as in CI:CONTRIBUTING.md#python-checks). - Scenarios are Python on the stdlib library
e2e/lib/e2e/(from e2e import scenario); all scenarios are.py, never add a.sh. A known failure declares a module-levelQUARANTINE = "<reason>". Harness self-test:uv run --python 3.12 e2e/selftest/run.py. - Forges are always faked (
e2e/fakeforge/,e2e/bin/{gh,glab,tea,bkt}, fake Gerrit). Never call a real forge, network or credentials from a scenario. - Adding a scenario: update
e2e/COVERAGE.md.
App (src/app/mod.rs, src/app/): central state (vcs, vcs_info, session, diff_files, input_mode, scroll/cursor). PR mode adds pr_info. Comment navigation uses CommentNavigatorState/CommentNavigatorItem derived from line_annotations, so local comments and visible remote threads jump to the annotations the diff renders (move_cursor_to_annotation).
VcsBackend (src/vcs/traits.rs): GitBackend (libgit2 by default; Git CLI for sparse checkouts, which also emits a startup warning, or backend = "cli"), HgBackend, JjBackend, all always compiled. detect_vcs() tries jj, then git, then hg. supports_sparse_checkout() is a capability hook. remote_url(name) must be implemented by every adapter and wired into the Git-only discovery call in main.rs; forge parsing stays in forge::resolve_remote_repository, never in the VCS adapter.
FileTreeFilter (src/app/mod.rs, src/app/file_filter.rs): i/e regex include/exclude, / path search, and show_reviewed (:set reviewed!, config show_reviewed).
show_reviewedis command-only: the project reserves single-stroke keys for vim motions, so never add a key for it.- A filter is a view over
diff_files, never a mutation:file_idxstays absolute.App::file_passes_filter()is the single on-screen predicate, consulted bybuild_visible_items,rebuild_annotations,file_render_height/effective_file_height(0 lines when hidden),hunk_positions, and both diff renderers. Gate any new loop overdiff_files. - Two predicates on purpose:
file_matches_patterns()(i/eonly: the review population, used byfile_count(),reviewed_count(),/search) vsfile_passes_filter()(that plusshow_reviewed). Counting visible rows would render the progress fraction as0/nwhen reviewed files are hidden. Only the file-levelreviewedflag hides; a file with individuallyR-marked hunks stays visible (andis_hunk_reviewedhashes every hunk, so do not call it speculatively). FileTreeFilterhas a hand-writtenDefaultbecauseshow_revieweddefaults to true.- Marking a file reviewed while hiding deletes the cursor's row, so
toggle_reviewed_for_file_idxcallsadvance_past_hidden_file()(next visible file, wrapping, parking at the overview when empty) regardless ofadjust_cursor. file_filter.draftmakes the tree a text-input sub-state ofInputMode::Normal(same shape aspr_filter_draft);main.rsroutes tomap_file_tree_prompt_modewhile it isSome. An open prompt owns input whatever panel has focus (a click can move focus to the diff):handler::handle_normal_actionchecks it beforefocused_panel, andhandler::handle_pasteis the one paste table (prompts and picker filters accept paste; other Normal-mode paste is dropped on purpose). A diff drag is ignored while it is open (noVisualSelect).main.rsroutes keys throughhandler::map_normal_path_keyandhandler::dispatch_action, so tests drive the real path. Keys are focus-scoped viamap_file_tree_mode: the tree claimsi/e/I/E//; the diff keepsi= edit comment,/= search diff.- Filters are session-local, never persisted, and apply at render/measure time, unlike
.tuicrignore, which drops files at load time.
InputMode (src/app/mod.rs): Normal, Command, Comment (Ctrl-S saves, Ctrl-C cancels), Search, Help, MessageDetails, Summary, Confirm, CommitSelect, VisualSelect, ThemePicker, FilePicker.
Summary(:summary) replaces the diff, keeps the file sidebar, lists everylocal_draftcomment, selects the first on open.Enterjumps to the comment in the continuous diff (leaving single-file view; a reviewed file/hunk is revealed without clearing its persisted state);Escreturns without jumping.ThemePicker(src/app/theme_picker.rs):j/klive-previews by reassigningApp::theme(renderers read&app.themeper frame, so no invalidation)./opens a filter draft committed onEnter, discarded onEsc.Enterkeeps the preview for the session and never writesconfig.toml;Escreverts to aThemesnapshot taken on entry (Themehas a manualClonebecause itsOnceLockhighlighter cache is notClone).:theme <name>applies directly.FilePicker(src/app/file_picker.rs,<leader>p): built likeThemePicker, but the list narrows while the filter draft is typed andEnterjumps straight to the selection (jump_to_file). Candidates are captured on open from files passingfile_passes_filter; a background reload can replacediff_filesmeanwhile, soEnterre-resolves by display path and re-checks the filter.
ReviewSession (src/model/review.rs): persisted state, files: HashMap<PathBuf, FileReview> (reviewed, reviewed_hunks, file_comments, line_comments: HashMap<u32, Vec<Comment>>). PR sessions add pr_description_reviewed (r on the PR description): when set, ui::pr_info_panel::pr_info_display_lines yields only the title row, and every PR-info row counter (annotations, heights, search) must go through it to match the renderer. It returns rows cached on App::pr_info_rows_cache (keyed on width and PR metadata); swap themes through App::set_theme to drop the cache, and both diff renderers sync the inner width before building these rows. It merges three-way like a file's reviewed and carries over unconditionally to a new PR head.
ReviewStore (src/review_store.rs): library facade (list_sessions_for_repo, get_review, add_comment, save_review, delete_review). add_comment_to_session() is shared with App::save_comment().
PR mode and the local backend: PR mode swaps vcs/vcs_info for PrNoopVcs and a forge: root; the checkout's backend is parked in App::parked_vcs (or reopened with detect_vcs after tuicr pr). Anything that lists or loads a local target (selector, session resume) must run inside with_local_vcs, which swaps it in and then either restores the PR backend or, if a local review replaced the PR, drops the PR state. Scope local sessions by local_repo_root, never vcs_info.root_path.
Action (src/input/keybindings.rs): map_key_to_action(key, mode). map_global_key covers keys identical in every mode (Ctrl-l → Redraw); main.rs checks it via handler::handle_global_key before the pending-prefix, vim-editor and per-mode maps, so they never reach a text buffer. Redraw and Event::Resize call App::request_full_redraw; the main loop then calls TerminalSession::repaint_from_scratch inside the synchronized update. Never use ratatui's Terminal::clear there: it queries the cursor position, which times out under --stdout.
- Startup: invalid
--themeexits non-zero; precedence--theme> config > dark. Theme lookup: bundled, then$XDG_CONFIG_HOME/tuicr/themes/(%APPDATA%on Windows); local themes may reference a.tmTheme, andsrc/syntax/mod.rstranslates the ANSI-slot placeholders some bat-compatible Base16 files use.syntax::load_user_syntaxesadds siblingsyntaxes/*.sublime-syntaxonce, before the firstSyntaxHighlighterexists (absent/empty dir skips the ~200ms relink; a bad grammar is a startup warning). Unknown config keys warn and are ignored.tuicr updateexits before TUI setup (flow insrc/update/). --line N(needs--file/--path, rejected withpr):App::pending_start_lineis applied byapply_pending_start_lineafter the firstterminal.draw, because centering needs the viewport height render measures; it waits while a modal/selector is open or no rows exist.main.rsrepaints in the same synchronized update so the unpositioned frame never shows.- Sidebar position: with
file_list_position = "right",App::focus_pane_left/focus_pane_rightmirror the<leader>h/<leader>lwalk; mouse hit-testing reads the renderedfile_list_area/diff_arearects, so it needs no change. - Selection colors: local-theme
selection_markerdrives cursor indicators and commit-range bars independently ofborder_focused; missing values keep each indicator's legacy foreground; row backgrounds still usebg_highlight/cursor_line_bg, PR numbers/hashescursor_color. - Diff watch:
diff_watch_interval_msreload also refreshes the inline commit pane and the staged/unstaged rows; aDiffSource::CommitRangepane is left alone;StagedUnstagedAndCommits(-r -w) keeps its range and refreshes only the two working-tree rows. Ignored for PR and--all-files. Reloads of a-rrange (watch ticks,:e) diff from the base resolved at startup (App::revision_range, used only while the fetched commit list matches), soA...Bkeeps its merge base. - Render: all files become one
Vec<Line>sliced byscroll_offset. Syntax coloring happens at render, not parse: backends leavehighlighted_spansasNone; the diff view callsApp::color_visible_hunks(src/app/coloring.rs) for hunks in the viewport ±1 screen (colored_hunksrecords visited hunks; rebuilding annotations clears it). Container grammars (needs_full_file_highlight: Vue, Svelte, PHP, ...) are colored from whole-file content at parse time (enhance_with_full_file_highlight); if that cannot run (file >1 MB, no content) they stay uncolored. Diff search highlighting patchestheme.search_match_bgviaui::text_utils::apply_search_highlight_*. The comment navigator hides when no comment rows exist. - Persistence: sessions live in
~/.local/share/tuicr/reviews/; PR session files and manifest buckets are host-aware for new sessions, while legacy hostless files stay readable in place (resolve_pr_target,docs/FORGES.mdG13);active_sessions.jsonbesideindex.jsonrecords open TUIs (pid, slug, path, last-seen).update_session_in_dir(tuicr review add|delete|clear) writes a local session back to the exact file it loaded (never a re-derived slug path) and indexes it by path only when it lives underreviews/; a corruptindex.jsonis moved toindex.json.corruptand rebuilt fromsessions/, as is a missingindex.jsonbeside existing sessions (manifest_for_update/read_manifest); the active-session registry replaces only the current pid's entry; session paths serialize throughpath_codec(non-UTF-8 Unix paths as a NUL-tagged hex string). Saves use a storage lock plus temp-file rename with stale sidecar lock recovery. The TUI keeps a persisted-session snapshot so polling (review_watch_interval_ms),:eand autosave merge external comment adds/edits/deletes (tuicr review ...) without overwriting local edits. The session file exists as soon as a session is active; TUI-created empty ones are deleted on exit.tuicr review delete|clearc|cleardelete a session they empty unlessactive_sessions.jsonlists a live owner.ReviewStore::delete_open_review(Sessions tabdd) ignores only this process's own registry entry, so the review the TUI itself loaded is deletable;App::forget_deleted_sessiondrops that in-memory copy, or autosave and diff reconciliation would write the deleted comments back. Local reloads re-run VCS diff loading and.tuicrignorefiltering; full reloads persist file hashes and invalidated review markers without saving unrelated dirty state; strict commit subsets stay live-only; manual:ealso reloads persisted comments before applying the diff. Successful comment submits autosave with a locked atomic write that merges external comments first. Switching local targets (confirm_commit_selection,sessions_tab_select) saves the outgoing session viaApp::save_outgoing_sessionin the loaders only, after the diff fetched (not on NoChanges/failed resumes), aborting on save failure;sessions_tab_selectre-reads the selected JSON after the loader, since the row may be the open session.clear_commit_paneandinstall_review_commitsmove focus off a hidden commit pane. - Review CLI (
src/review_cli.rs, JSON only):--repois a selector: a checkout path (local sessions plus PR sessions of itsorigin) or a forge coordinate (owner/repo, repo URL; matches by slug). A PR session resolves by its self-contained slug (gh:owner/repo/pr/N), no--reponeeded.review listshowsactiveandkind. - Comments:
App::save_comment()builds anAddCommentRequestforadd_comment_to_session();:clip/:export→export_to_clipboard()(stdout with--stdout). - PR review-requested toggle (
ron the Pull Requests tab,ForgeKind::pr_list_scopes): cycles all open → requesting me → (GitHub only)PersonallyRequested, i.e.user-review-requested:@me, excluding team requests. Bitbucket'sstate="OPEN"must live insideq(Cloud ignores a standalonestateonceqexists). Gerrit diverges: seedocs/FORGES.mdG4.
Everything under src/forge/ (GitHub gh, GitLab glab, Gitea tea, Bitbucket bkt, Azure DevOps, Gerrit). Read docs/FORGES.md before touching src/forge/, PR mode, session keys/lifecycle, PR submit, or any code that assigns diff_files in PR mode (commit-message pseudo-file, file registration, base/merge-base SHA, batched line counts, e in PR mode). It holds detection order, ForgeBackend contracts, async/session/submit rules and gotchas F1-F10, G1-G12.
Numbered once. Forge/PR-mode gotchas (F*, G*) live in docs/FORGES.md.
-
Patch display headers are never authoritative metadata. Paths/statuses come from Git
--raw -z, jj templates, Mercurialstatus -0, or forge JSON.diff_parseronly consumes@@hunks, using their declared old/new counts as the grammar. Add no quoting or path-header heuristics. -
Anchor restore must scroll: setting
diff_state.cursor_linewithoutmove_cursor_to_annotationleaves the viewport at the top. -
Comment's line anchor lives in theHashMapkey, notComment.line_context(Comment::newleaves it unset). The submit mapper takes an explicitCommentAnchor; never infer "file-level" fromline_context.is_none(). -
Comments are commit-scoped via
Comment::commit_id. With exactly one commit shown,App::save_commentstamps its SHA.Some(sha)comments are hidden when a different commit (or subset withoutsha) is selected;None(legacy, review-level, cumulative-diff) is always visible.App::comment_visible(&Comment)is the single predicate, applied inrebuild_annotations, both diff renderers, the navigator, and submit preflight.AnnotatedLine::LineComment/FileCommentcomment_idxis the absolute index into the stored value;delete_comment_at_cursorandenter_edit_modemust look it up directly, not re-count by side. -
Register diff files before
r,R, or a comment can land on them. All three look the file up inReviewSession.filesby display path (toggles return silently;add_comment_to_sessionerrorssession does not contain file). Any code assigningself.diff_filesmust callApp::register_diff_files(narrowing the inline commit pane once skipped this). -
The
[TYPE]prefix uses the config-resolvedlabel, not theCommentTypeid (CommentTypehas no label;as_str()is the uppercased id).app::resolve_comment_type_labelis the single resolver;App::comment_type_label(TUI), the markdown export andSubmitContext::type_label(src/forge/submit.rs) delegate to it, anddescribe_row(src/ui/submit_modals.rs, which previews what gets posted) callsApp::comment_type_label. Hence submit takes aSubmitContext, not a bare&ForgeConfig. -
Gates must run from the worktree:
cdinto it beforecargo(it resolvesCargo.tomlfrompwd; the wrong tree is exercised silently). -
TestBackend modal sizing: 60%×40% on 120×24 is 72×9 (7 content rows). The submit confirmation modal needs 70% height, the submit-action picker 50% (footer line).
-
GNU Linux release binaries stay dynamically linked (static glibc can crash loading a host NSS module such as Fedora's
libnss_myhostname); musl artifacts are the static builds. Direct updates must keep the running binary's GNU/musl target when choosing an asset. -
PR editor snapshots live in a private per-user cache dir keyed by the full revision SHA.
editor_target::snapshot_root(host, PR, the SHA actually fetched) sits underProjectDirscachesnapshots/(0700, owner-checked);materializecreates directories without following symlinks and links an exclusively created temp file into place, so never write snapshots withfs::writeor under the shared temp dir.TUICR_GLAB_DEBUGlogs toglab-debug.login the same cache dir (0600,O_NOFOLLOW). The directory name is a truncated readable slug plus a hash of host/repo/PR/SHA, so it stays under NAME_MAX for any namespace. The debug log refuses to append to an existing file that is not an owner-only regular file. -
Local slugs and
forge:paths readoriginand owners faithfully. Gerrit'sremote_for_repositoryreads remotes throughforge::remotes(libgit2, thengit remote get-url) so reftable/SHA-256 checkouts work.resolve_owner_repo(local slugs) still uses libgit2 only; changing it re-slugs existing reviews and must land with the storage identity change.RepoCoordinate::parsetriesforge:<host>/<owner…>/<repo>(parse_forge_path) before the hostname parsers, which would strip Gerrit'sa/and drop multi-segment owners.
When adding user-facing features, update the relevant documentation:
Document every configuration option in docs/CONFIG.md. Only critical
configuration options should also appear in README.md; document all other
configuration options in docs/CONFIG.md only.
| Document | Update when adding/changing... |
|---|---|
README.md |
Keybindings, commands (:*), CLI flags, features list, installation methods, agent integration setup, forge limitations |
src/ui/help_popup.rs |
Keybindings or commands (update the help_text vector) |
src/ui/status_bar.rs |
Keybindings worth advertising in the per-pane hint line |
docs/CLI.md |
Any clap flag, subcommand, env var, stderr marker, or exit code: add a row to the matching table |
docs/KEYBINDINGS.md |
Any keybinding or : command: add a row to the pane's key table and the : command table, plus prose for new behavior |
AGENTS.md |
Key types, invariants, non-obvious behavior, general gotchas, repo-managed agent integrations (forge detail goes in docs/FORGES.md) |
docs/FORGES.md |
Forge backend contracts, detection, session/submit rules, F*/G* gotchas (new forge-specific gotchas go here) |
e2e/COVERAGE.md |
Adding, renaming or removing an e2e scenario, or closing a listed gap (authoring rules stay in e2e/README.md) |
docs/CONFIG.md |
Any config.toml key: add a row to the Options table and a line to the Full example block |
When a user reviews your changes with tuicr, they will provide you with a structured Markdown document optimized for agent consumption.
I reviewed your code and have the following comments. Please address them.
Reviewing unstaged changes
Comment types: ISSUE (problems to fix), SUGGESTION (improvements), NOTE (observations), PRAISE (positive feedback)
Summary: {optional overall notes}
## Local tuicr Comments
1. **[ISSUE]** `src/auth.rs:42` - Magic number should be a named constant
2. **[SUGGESTION]** `src/api.rs` - Consider adding unit tests
3. **[NOTE]** `src/utils.rs:15` - Why was this approach chosen?That is the default layout, not a fixed contract. The [export] section of config.toml lets a user reword or drop the intro line, the Reviewing … line, the comment-type legend, and either section heading. Parse the numbered comment list as the only part guaranteed to be present. See docs/CONFIG.md for the keys.
In pull request mode the header block also includes URL: and Head: lines identifying the pull request and the commit reviewed, and unresolved upstream threads follow under their own heading.
| Type | Meaning | Action Required |
|---|---|---|
| [ISSUE] | Problem that must be fixed | Yes - address before proceeding |
| [SUGGESTION] | Improvement recommendation | Consider implementing |
| [NOTE] | Observation or question | Respond or acknowledge |
| [PRAISE] | Positive feedback | No action needed |
Each comment is numbered and self-contained:
{n}. **[TYPE]** \{file}:{line}` - {content}` (line comment){n}. **[TYPE]** \{file}` - {content}` (file comment)
You can reference comments by number (e.g., "Regarding comment #2...").
[ISSUE] comments are blocking and must be fixed:
## Issues Addressed
- #1 `src/auth.rs:42` - Extracted magic number to `TOKEN_EXPIRY_SECONDS` constant[SUGGESTION] comments are non-blocking but should be considered. Either implement or explain why not.
[NOTE] comments often contain questions. Provide brief explanations.
## Changes Made
### Issues Addressed
- #1 - Extracted magic number to `TOKEN_EXPIRY_SECONDS` constant
### Suggestions Implemented
- #2 - Added unit tests for API module
### Suggestions Declined
- #5 - Kept current approach because [reason]
### Notes Addressed
- #3 - This approach was chosen for performance reasons- Read the full review before making changes
- Prioritize [ISSUE] items - these are blocking
- Reference comments by number when responding
- Preserve reviewer intent - don't over-engineer solutions
- Be concise in your response
- If unclear, ask for clarification rather than guessing