Skip to content

Core(feat[vt]): Add sans-I/O VT engine, RLE grid, OSC 7501, input, and ADRs - #2

Merged
tony merged 29 commits into
masterfrom
feat/v2-architecture
Nov 23, 2026
Merged

tony merged 29 commits into
masterfrom
feat/v2-architecture

Conversation

@tony

@tony tony commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

Summary

Adds the libvt sans-I/O virtual terminal engine, two-tier run-length-encoded scrollback grid, SHA-256-pinned Unicode 17.0.0 grapheme clustering tables, Rex OSC 7501 Program Status store, mode-aware outbound input encoders, asyncio stream and controlling-TTY POSIX PTY adapters, pytest11 fixtures, and Architecture Decision Records 0001–0010.

Architecture Decision Records

  • ADR 0001 (docs/project/adr/0001-clean-room-provenance-and-license-firewall.md): Clean-room MIT provenance, libvt distribution naming, Python >= 3.12 floor, and instance-owned caches safe for PYTHON_GIL=0 free-threading and PEP 734 subinterpreters.
  • ADR 0002 (docs/project/adr/0002-sans-io-layers-profiles-and-closed-events.md): Four-layer sans-I/O boundary, progressive-disclosure render / strip / explain entry points, Profile / Policy / Limits split, private _TerminalSink callback path, and closed Event union.
  • ADR 0003 (docs/project/adr/0003-two-tier-packed-viewport-and-rle-scrollback.md): Lazy 64-bit inline array('Q') viewport rows paired with run-length-encoded FrozenRow scrollback, scroll row recycling, and RowRun span iteration.
  • ADR 0004 (docs/project/adr/0004-zero-based-row-col-coordinates-and-sync-stepping.md): Keyword-only (*, rows=24, cols=80) geometry, zero-based (row, col) indexing, TMUX_PROFILE vs XTERM_PROFILE pending_wrap rules, lazy copy-on-write ?2026 holds, feed_until stepping, generation-tagged expire_synchronized_output, and primary-screen soft-wrap resize reflow.
  • ADR 0005 (docs/project/adr/0005-utf8-c1-isolation-and-unicode-17-grapheme-width.md): ParserState.STRING_ESC 7-bit string termination, separated encoding="utf-8" | "latin-1" wire modes, C0 incomplete-UTF-8 flush ordering, cluster-anchor invalidation, 32-codepoint grapheme caps, and SHA-256-pinned two-stage Unicode 17.0.0 width and UAX Support XTSAVE (CSI ? Pm s) and XTRESTORE (CSI ? Pm r) private mode save/restore #29 clustering tables.
  • ADR 0006 (docs/project/adr/0006-charset-designations-and-single-truth-mode-reconciliation.md): G0–G3 DEC Special Graphics designations (ESC ( 0, SO/SI, SS2/SS3), CBT/CHT, DECSCA/DECSED/DECSEL, CSI 22 J scroll-clear, and single-truth ?47/?1047/?1049 DECRQM reporting.
  • ADR 0007 (docs/project/adr/0007-rex-osc-7501-program-status-and-semantic-prompts.md): Rex OSC 7501 colon grammar, hierarchical task inheritance, urgency ordering, profile- and policy-gated OSC 7501 ; ? capability replies, OSC 9;4 fallback, OSC 133 monotonic abs_row prompt zones, OSC 7 (cwd_uri + Policy.osc7_hosts), OSC 52, DECRQSS, XTGETTCAP, ?2031/?996n, ESC k tmux window renames (WindowRenamed), OSC 10/11 and 110/111 colors, and DCS tmux; Passthrough events with persistent inner replay.
  • ADR 0008 (docs/project/adr/0008-mode-aware-input-encoding-and-paste-safety.md): Outbound KeyEvent, MouseEvent, FocusEvent, and PasteEvent encoding, per-screen KittyKeyboardStack (>u, <u, =u, ?u), and fail-closed UnsafePasteError bracketed paste checks.
  • ADR 0009 (docs/project/adr/0009-declarative-sequence-codec-and-stream-explainer.md): Cold-path explain / format_explain VT sequence disassembler and python -m libvt (explain, render, strip) CLI.
  • ADR 0010 (docs/project/adr/0010-transport-only-asyncio-and-diagnostic-pytest-plugin.md): Zero asyncio/pty/pytest import overhead on import libvt, AsyncTerminalStream, controlling-TTY POSIX open_pty (TIOCSCTTY, pre-exec handoff marker, SIGPIPE/SIGXFSZ reset, killpg teardown, tty_mode), protocol-typed vt_* fixtures, literal assert_screen, column-exact assert_screen_box, and FlightRecorder failure dumps.

Subsystems

  • Parser and Unicode (src/libvt/parser.py, src/libvt/_ucd.py, scripts/generate_ucd.py): VT500 streaming parser with colon/semicolon CsiParams bitmasks, parse_sgr (4:3, 38:2::R:G:B, 58:5:idx), STRING_ESC string termination preserving DCS header intermediates, DCS tmux; ESC ESC collapsing, encoding="utf-8" | "latin-1", and SHA-256-pinned Unicode 17.0.0 East Asian width and UAX Support XTSAVE (CSI ? Pm s) and XTRESTORE (CSI ? Pm r) private mode save/restore #29 ?2027 grapheme clustering.
  • Grid, Screen, and Terminal (src/libvt/_grid.py, src/libvt/screen.py, src/libvt/terminal.py): Lazy 64-bit packed viewport rows with two-sided wide-spacer and cross-row SPACER_HEAD boundary healing across horizontal edits and DECLRMM sub-rectangle scrolling; RLE FrozenRow scrollback; primary soft-wrap resize reflow; ?2026 copy-on-write committed snapshots and feed_until; and Formatter (PLAIN, VT, HTML with URI scheme allowlisting).
  • Protocols, Input, and Transport (src/libvt/status.py, src/libvt/events.py, src/libvt/input.py, src/libvt/codec.py, src/libvt/aio.py, src/libvt/testing.py, src/libvt/pytest_plugin.py): ProgramStatusStore, KeyEvent/MouseEvent/FocusEvent/PasteEvent encoders, explain disassembler, AsyncTerminalStream, controlling-TTY POSIX open_pty (tty_mode="cooked" | "cbreak" | "raw"), literal assert_screen and boxed assert_screen_box (with BiDi/C0 escaping and │W soft-wrap markers), and vt_* fixtures.

Verification

  • uv run ruff format --check .
  • uv run ruff check .
  • uv run ty check
  • uv run pytest (unit, CLI, 766 Unicode 17.0.0 GraphemeBreakTest.txt vectors, Python 3.15 unicodedata parity, live POSIX controlling-PTY subprocess, 400-trial seeded property fuzzing, and README.md / docs/ doctests)
  • just -f docs/justfile sphinxopts="-W --keep-going" html

tony added 3 commits November 21, 2026 14:41
why: Record clean-room MIT boundaries, two-tier storage, Unicode 17
clustering, Rex OSC 7501, input encoding, and safety contracts before
implementing the v0.1 engine.

what:
- Add ADRs 0001-0010 covering provenance, Profile/Policy/Limits,
  packed viewport + FrozenRow RLE scrollback, (row, col) coordinates
  and reflow, UTF-8/C1 isolation + Unicode 17 block table, G0-G3
  charsets + single-truth DECRQM, Rex OSC 7501 + semantic prompts,
  mode-aware input encoding + fail-closed paste, sequence explain
  codec, and asyncio/PTY/pytest diagnostics
- Register ADRs 0001-0010 in docs/project/adr/index.md
why: Downstream TUI and libtmux test harnesses require a clean-room MIT,
zero-dependency virtual terminal with compact scrollback, Unicode 17
grapheme clustering, bidirectional query replies, mode-aware input
encoding, and Rex OSC 7501 program status support.

what:
- Add streaming VT500 parser with 7-bit string isolation, colon SGR
  subparameters, DCS intermediate preservation, and tmux passthrough
  ESC-ESC collapsing
- Add two-tier grid with lazy 64-bit inline attributes, wide-spacer
  boundary healing, RLE FrozenRow scrollback, and primary resize reflow
- Add Unicode 17.0.0 two-stage width and UAX #29 clustering tables
- Add Terminal, Profile/Policy/Limits, ?2026 CoW stepping, Rex OSC 7501
  store, OSC 133/7/52, DECRQM/DECRQSS/XTGETTCAP, and Formatter
- Add mode-aware input encoders, KittyKeyboardStack, and fail-closed
  bracketed paste validation
- Add codec explainer, CLI, AsyncTerminalStream, POSIX open_pty,
  protocol-typed pytest fixtures, and 400-trial property fuzz tests
why: Callers need executable documentation covering the sans-I/O
terminal API, two-tier RLE grid, synchronized-output stepping, Rex OSC
7501 status tracking, mode-aware input encoding, and public modules.

what:
- Expand README.md, docs/index.md, and docs/quickstart.md with doctested
  usage examples
- Add topic guides for architecture, ?2026 sync/asyncio, protocols/input,
  and pyte migration
- Add Sphinx API reference pages across all public libvt modules
- Update AGENTS.md module map and record 0.1.x deliverables in CHANGES
tony added 3 commits November 21, 2026 17:07
why: Align Unicode 17 clustering, string-escape framing, passthrough
policy, cross-row wide healing, and OSC 7 host checks with standards.

what:
- Compile SHA-256-pinned Unicode 17.0.0 UCD and Emoji tables and verify
  all 766 GraphemeBreakTest vectors
- Add ParserState.STRING_ESC, encoding="utf-8"|"latin-1", Passthrough
  event, and default-deny Policy.allow_passthrough
- Heal cross-row SPACER_HEAD cells across horizontal and margin edits
- Replace os.uname() in Terminal OSC 7 handling with Policy.osc7_hosts
  and Terminal.cwd_uri
why: Establish a real controlling terminal without preexec_fn and stop
assert_screen() from stripping literal TUI box-drawing borders.

what:
- Acquire TIOCSCTTY, reset SIGPIPE, and propagate execvp OSError via an
  isolated -I -S child trampoline in open_pty()
- Add tty_mode ("cooked"|"cbreak"|"raw") to open_pty() and vt_pty
- Keep assert_screen() strictly literal and add assert_screen_box()
why: Keep ADR specifications, topic guides, and CHANGES aligned with the
shipped public API and security policy defaults.

what:
- Update ADRs 0002, 0005, 0007, and 0010 for STRING_ESC, Passthrough,
  pinned Unicode 17.0.0 UCD, OSC 7 hosts, TIOCSCTTY, and boxed asserts
- Update architecture, asyncio, and CHANGES entries
tony added 2 commits November 21, 2026 20:00
Widen ?2027 Indic conjunct and Mc spacing-mark clusters to 2 columns while giving conjoining Hangul V/T and Cf Prepend standalone width 0, validate VS15/VS16 against immediate predecessors, and pass Profile rules into display_width().

Repair cross-row SPACER_HEAD cells and clear predecessor wrapped flags before mutating continuation cells, separate _Row.text_used from BCE background fills, and anchor live RowView instances to Screen row coordinates across scroll recycling.

Persist inner passthrough parser state across split DCS tmux; envelopes, raise max_dcs_bytes above max_apc_bytes, bound unread event bytes via max_event_bytes, emit UnhandledSequence on string overflow, consume ESC k window renames on TMUX_PROFILE, add OSC 10/11 and 110/111 dynamic color handling plus newline_mode, decouple OSC 7501;? replies from event recording, enforce RFC 8089 on OSC 7 cwd paths, and harden open_pty() with a pre-exec marker, strict TIOCSCTTY, python_executable, and killpg SIGHUP teardown.
Document profile- and policy-gated OSC 7501;? replies, updated Limits defaults, TMUX_CAPTURE_POLICY, WindowRenamed, and hardened open_pty() process-group teardown across ADRs 0002, 0007, and 0010, protocols docs, and CHANGES.
why: Unconditionally clearing pending_wrap on resize caused same-size
resizes to overwrite the last column, widening with reflow to drop the
right-margin advance, and dummy cursor cells to inject phantom blank
rows on exact-fit shrinks.

what:
- Add reflow_on_resize to Profile (False on XTERM_PROFILE) and default
  Terminal.resize and PtySession.resize reflow=None to the profile
- Return early from Screen.resize when dimensions do not change
- Track logical eff_cur_col and cur_after_extra in _reflow_primary
  without dummy trailing cells
- Preserve pending_wrap on non-reflow resizes when old_cur_col < cols
  and synchronize _saved_primary cursor state when resizing on ?1049h
tony added 2 commits November 22, 2026 08:45
why: Updating _generation only at the end of feed() allowed a cached
pre-feed snapshot to leak into _held_snapshot when bytes preceded BSU in
the same chunk, and scalar cursor, mode, and OSC mutations bypassed
_before_mutate().

what:
- Invalidate _cached_snapshot inside _before_mutate() and build held
  snapshots with TRANSIENT_SNAPSHOT_MODES excluded
- Call _before_mutate() across cursor, DECTCEM/DECSCUSR, mode, title,
  cwd, prompt-zone, and program-status mutators
- Emit RenderHoldChanged(active=False) after reset() updates generation
why: Sharing the ED 2 branch with ED 3 erased all visible viewport
cells, cleared pending_wrap, and emitted ScreenErased on scrollback-only
CSI 3 J clears.

what:
- Separate mode == 3 and not selective from ED 2 so CSI 3 J clears
  scrollback without mutating visible rows or pending_wrap
- Add Profile.ed3_clears_scrollback_on_alt (True on XTERM_PROFILE and
  TMUX_PROFILE, False on DEFAULT_PROFILE)
- Ignore unrecognized ED/EL parameters and DECSED 3 without clearing
  pending_wrap
why: Review-round grab-bag files obscured module ownership, and full
1.1M-codepoint loops, per-step grid scans, and extra subprocess spawns
slowed local test runs.

what:
- Replace review-round and multi-module grab-bag test files with 1:1
  per-module test files (test_aio, test_codec, test_exc, test_graphics,
  test_input, test_parser, test_screen, test_status, test_terminal,
  test_testing, test_tmux, test_ucd)
- Migrate multi-case loops to typed NamedTuple @pytest.mark.parametrize
  tables with explicit test_id identifiers and strict ty annotations
- Verify Unicode 17 parity across distinct stage-2 blocks and stage-1
  boundaries, scan SAFE_NARROW_BMP_RE in C, test CLI stdin in-process,
  and consolidate POSIX PTY assertions into one child session
why: GitHub Actions ubuntu-latest ships tmux < 3.8 without capture-pane
-F, and TMUX_METADATA_FORMAT queried synchronize-panes instead of DEC
?2026 synchronized_output_flag.

what:
- Query #{synchronized_output_flag} in TMUX_METADATA_FORMAT
- Fall back from capture-pane -F to -e -p -N plus -p -J in the live tmux
  integration test when running against tmux < 3.8
why: Skipping OSError.__init__ on empty or falsy os_args leaves C
OSError slots uninitialized on subclasses overriding __init__, while
unconditional __dict__.clear() and __dict__.update() in __setstate__
wiped state on None or invalid inputs and bypassed C descriptors.

what:
- Call OSError.__init__(obj, *os_args) unconditionally in
  _reconstruct_timeout_error and preserve non-errno multi-element args
  and mutated OSError descriptors
- Validate str-keyed dict state upfront in __setstate__ and restore
  entries via setattr while keeping None as a no-op
- Preserve unmangled double-underscore slots on all-underscore classes
  and test all 6 subclass, copy, pickle, and ExceptionGroup shapes
why:
- Widening a narrow cell via VS16 or spacing continuation stamped the
  active stream pen onto SPACER_TAIL, dropping base SGR, hyperlinks,
  and DECSCA protection when attributes changed mid-cluster.
- Stage-1 boundary checks in test_ucd skipped non-17.0 stdlib runtimes
  and left interior block-index aliasing unchecked on Python 3.12-3.14.

what:
- Inherit base_pen and base_ext from target onto SPACER_TAIL on
  width_override == 2 and clear vacated VS15 cells with BCE background
  only via _PEN_BG_MASK.
- Emit EXPANDED_UCD_SHA256 from scripts/generate_ucd.py and verify all
  4,352 expanded stage-1 UCD blocks via SHA-256 in tests/test_ucd.py.
why:
- Signed row fields on PromptZone and ImagePlacement turned negative
  once scrolled into history, causing snap[z.row] to index from the
  bottom of the active viewport instead of scrollback.
- Allocating new PromptZone and ImagePlacement tuples on every snapshot
  to recompute viewport-relative row coordinates went stale after the
  next scroll linefeed.

what:
- Store monotonic abs_row and col on PromptZone and ImagePlacement and
  replace occupies_cell with ImagePlacement.occupies_abs.
- Add Snapshot.at_abs, Snapshot.viewport_row, Snapshot.scrolled_total,
  and Snapshot.evicted_total, preserving scrolled_total == evicted_total
  + len(history) across scrollback=0, ED 3, bulk scrolls, and reflow.
- Crop top-clipped SIXEL and Kitty placements in abs_row space and
  include scrolled_total and evicted_total in Snapshot.to_dict.
why:
- _Row.freeze omitted per-column cell tuples whenever combining marks
  and wide SPACER_TAIL empty strings cancelled out to len(text) ==
  text_used, dropping wide glyphs in FrozenRow.char_at and RowView.runs,
  while FrozenRow.used truncated trailing BCE spans when cells existed.
- Materializing tuple(RowView(fr) ...) on every snapshot() and history
  access scaled as O(scrollback).

what:
- Populate FrozenRow.cells whenever "" is in chars[:text_used] or
  len(text) != text_used, include run_end and ext_end in FrozenRow.used,
  cache clean _frozen rows on _Row, binary-search FrozenRow.attr_at and
  ext_at via bisect_right, and coalesce FrozenRow runs in O(R + E).
- Store primary scrollback in 256-row CoW blocks (_HistoryBuffer /
  _FrozenHistory) exposed as Sequence[RowView] via _HistoryView, and add
  value-based RowView.__eq__.
@tony
tony merged commit 0c7ee41 into master Nov 23, 2026
6 checks passed

This branch was successfully deployed

1 active deployment
docs — d9a07745 Deployed Nov 23, 2026 by tony via build (3.14) #27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant