Skip to content

core(fix[pre-0.1]): Pre-0.1 protocol, sync, PTY, and CI hardening - #33

Merged
tony merged 8 commits into
masterfrom
feat/pre-0.1-hardening
Nov 25, 2026
Merged

tony merged 8 commits into
masterfrom
feat/pre-0.1-hardening

Conversation

@tony

@tony tony commented Nov 23, 2026 •

Copy link
Copy Markdown
Member

Summary

Pre-0.1 protocol, synchronization, PTY, documentation, and cross-platform CI hardening slices on top of v0.0.1a0 (#3, #13, #17, #18, #21, #22, #23, #24, #25, #26).

Deliverables

  • #21 (904ff6d): DECSTBM SIXEL mask preservation before abs_row shifts, graphics retention and bounds clipping across resize(), O(1)-per-row streaming primary reflow for unwrapped scrollback rows (used <= new_cols), PromptZone and Kitty (abs_row, col) pin remapping, monotonic scrolled_total continuity, and docs/_static/css/libvt.css .sd doctest override (git-pull/gp-sphinx#85).
  • #22 (d230e13): Per-Terminal row-generation counter (_RowGenCounter), opaque non-instantiable SyncToken, structural _Row write-barrier generation stamps, and DCH DECLRMM wrapped preservation when c_col < left.
  • #23 (8146de2): Bounded ASCII integer parsers (0x30..0x39: <= 65535 OSC codes, uint32 Kitty IDs, signed 32-bit OSC 133;D exit codes, non-raising feed() on malformed OSC 7/9;9/10/11), and UTF-8 _event_byte_cost() accounting across every Event variant.
  • #18 (d3dc45e): Scoped CSI 5:3 m overline decoding strictly to decode_tmux_capture(), plus chained single-invocation TmuxCaptureCommand (build_tmux_capture_command) bracketing capture-pane -S - -E - -e -p -N -T -F (-N -T + -J on 3.4–3.7, -N + -J on 3.3a) with display-message headers/footers.
  • #24 (599b2dc): Synchronous PtySession.send() / paste() + query replies on a single bounded FIFO drained via loop.add_writer and await drain(), committed_generation-driven wait_for() wakeups, PtySession.resize() ?2048 reply flush, non-awaiting finally master_fd close, and unconditional ?2026 hold expiry on EOF / aclose().
  • #25, #17 (625401a): Strip OSC 8 hyperlinks from BCE, primary SU scrollback history, 0x7F DEL UTF-8 flush, non-m colon CSI drop + well-formed 4/38/48/58 colon SGR validation, DECSLRM interior wide preservation, Formatter(OutputFormat.VT) mode/cursor/wrapped-row round-tripping, and DEFAULT_PROFILE / XTERM_PROFILE vs TMUX_PROFILE (?69 off, DECSTR no-op, CSI 5;10 s save, top > 0 history, isolated DECSC vs ?1049h) split.
  • #26 (20a4726): Zero-list-allocation OSC 4/104 256-palette and semicolon-chained OSC 10–12/110–112 dynamic color queries (Profile.cursor_rgb), < DEC_PRIVATE_MASK-bounded all-mode DECRQM, per-Screen XTMODKEYS (CSI > 4 ; pv m, CSI ? 4 m, levels 1/2 ASCII-safe key encoding), default-enabled ?1007 (Mode.ALTERNATE_SCROLL), cell-calibrated ?1016 MouseEvent pixels + ?2048/TIOCSWINSZ pixel geometry, error XTSMGRAPHICS (?Pi;3S), silent OSC 9/99/777, global private-members: False autodoc hygiene, and single-thread Terminal ownership docs.
  • #3, #13 (318dc31): test-macos (macos-latest Python 3.14 full POSIX PTY suite + ty) and test-windows (windows-latest Python 3.14 portable core/stream + ty) CI jobs in .github/workflows/tests.yml, --paths "/*" CloudFront invalidation in .github/workflows/docs.yml, Operating System :: Microsoft :: Windows classifier, wheel/sdist test guards, and isolated read-only libtmux + libvt wheel smoke verification.

Closes #3, closes #13, closes #17, closes #18, closes #21, closes #22, closes #23, closes #24, closes #25, closes #26.

Test plan

  • uv run ruff format --check . & uv run ruff check .
  • uv run ty check (Linux, darwin, and win32 targets)
  • uv run pytest -m "" (100 passed, including doctests across README.md and docs/)
  • just -f docs/justfile sphinxopts="-W --keep-going" html (zero warnings, zero private/raw TypeAliasType leaks)
  • GitHub Actions matrix green across ubuntu-latest (3.12–3.15), macos-latest (3.14), windows-latest (3.14), and docs (3.14)
  • Isolated /tmp libvt + libtmux wheel consumer smoke test (live tmux pane capture + deliberate assert_screen_box mismatch check)

why: DECSTBM top-zero margins corrupted SIXEL visibility masks when
advancing scrollback, while resize() discarded stored graphics and
thawed unwrapped history rows unnecessarily. Also keep triple-quoted
doctest strings (.sd) upright and scoped out of dark mode.

what:
- Preserve scrollback-bound placements and SIXEL masks in
  GraphicsTracker.on_region_scroll and ED 3 clear_history
- Retain and clip placements across reflow and non-reflow resizes,
  resolving Kitty relative parent chains in O(P)
- Stream unwrapped scrollback FrozenRow lines with used <= cols through
  Screen._reflow_primary in O(1) per row and remap PromptZone and
  root placement (abs_row, col) pins
- Unify Snapshot.at_abs and _HistoryView width semantics across resizes
- Add docs/_static/css/libvt.css override for .highlight .sd italics
why: SyncToken exposed 15 internal watermark fields coupled to a
process-global row counter, while direct _Row, Screen, and ModeState
mutations could bypass row generation stamps or tear ?2026 frame holds,
and ICH/DCH outside DECLRMM cleared soft-wrap flags.

what:
- Move SyncToken state onto private _SyncState with fork-safe per-PID
  terminal IDs, compact repr(), and copy/pickle support
- Replace global row generation with per-ScreenSet _RowGenCounter and
  private _Row write barriers across all cell, wrap, and resize edits
- Wire ModeState, Screen, and ScreenSet mutation hooks into Terminal to
  preserve ?2026 holds and invalidate cached snapshots
- Guard ICH/DCH behind DECLRMM bounds and heal DECSLRM wide/spacer splits
- Document SyncToken migration in CHANGES and MIGRATION
why: int() and str.isdigit() accepted non-ASCII digits and raised
ValueError on >4300-digit numbers or malformed OSC 7 URIs, while
_event_byte_cost() charged a flat 64 bytes on string-bearing events.

what:
- Add bounded ASCII 0-9 integer parsers in parser.py (<=65535 OSC codes,
  uint32 Kitty IDs across multi-chunk uploads, signed int32 OSC 133;D)
- Replace str.isdigit()/int() in status.py, terminal.py, tmux.py, aio.py,
  and graphics.py, and parse OSC 10/11 hex strictly from ASCII 0-9A-Fa-f
- Catch ValueError on malformed OSC 7 / OSC 9;9 URIs in _update_cwd()
- Charge UTF-8 payload bytes across all 15 Event variants with
  assert_never exhaustiveness and skip eviction when cost > max_bytes
why: tmux grid_string_cells_code formats SGR 53 overline as CSI 5:3 m
by accident while live tmux and Ghostty ignore 5:3 on input, and
separate display-message + capture-pane -N calls cannot disambiguate
wide-wrap spacers from literal trailing spaces or prevent TOCTOU drift.

what:
- Ignore CSI 5:3 m in global parse_sgr() and rewrite top-level 5:3 SGR
  groups to 53 strictly inside decode_tmux_capture()'s _CaptureRowSink,
  filtering non-SGR/OSC-8 sequences on the scratch decoder.
- Add trim_trailing (-T) support to decode_tmux_capture() and
  Terminal/Snapshot.from_tmux_capture(), preserving explicit trailing
  spaces, wide-wrap SPACER_HEAD cells, and primary scrollback across
  alternate-screen (?1049h) captures.
- Add build_tmux_capture_command() and TmuxCaptureCommand chaining
  display-message and capture-pane -S - -E - -e -p -N -T -F (-N -T + -J
  on 3.4-3.7, -N + -J on 3.3a) with WINDOW_MAXIMUM bounds.
why: Direct non-blocking os.write() calls on PtySession._master_fd hit
kernel TTYHOG limits on multi-KiB pastes and could interleave synchronous
query replies inside PasteEvent frames, while AsyncTerminalStream and
PtySession omitted ?2026 expiry on EOF/aclose(), missed mid-chunk
?2026l...?2026h commits, and dropped ?2048 resize replies.

what:
- Queue synchronous PtySession.send(), send_event(), send_key(), paste(),
  and auto-replies onto one bounded slab-coalesced FIFO deque drained via
  loop.add_writer with await session.drain() high-water backpressure.
- Add Terminal.committed_generation (and ModeState on_set_mode routing)
  plus loop.call_later sync-timeout timers so wait_for() wakes on
  mid-chunk committed frames without leaking torn ?2026 snapshots.
- Expire ?2026 holds unconditionally on EOF and aclose(), flush ?2048
  replies in PtySession.resize(), guard master_fd/reader/writer cleanup
  inside non-awaiting finally blocks, and guard POSIX signal APIs for
  Windows portability.
why: BCE erases leaked active OSC 8 hyperlinks onto blank cells, SU
discarded scrolled-off lines instead of pushing to primary scrollback,
0x7F DEL failed to flush incomplete multi-byte UTF-8 sequences, non-m
CSI sequences with colon subparameters executed instead of dropping,
DECSLRM partial scrolls clobbered wide glyphs wholly inside margins,
Formatter(OutputFormat.VT) emitted layout modes before cells and skipped
wrapped-row padding, and DECSTR / ?69 / DECSC / DECSTBM top > 0 behavior
diverged between Ghostty/xterm and tmux (#25, #17).

what:
- Strip OSC 8 hyperlinks in Terminal._bce_pair(), save primary SU lines
  to scrollback with region-height clamping, and flush incomplete UTF-8
  on 0x7F DEL in Parser.feed_to.
- Drop non-m CSI sequences carrying colon subparameters (including past
  max_csi_params) and restrict parse_sgr colon groups to well-formed
  4/38/48/58 attributes.
- Heal DECSLRM / clear_range / write_ascii_slice wide boundaries only on
  straddling SPACER_TAIL / WIDE edges and clear bottom-row SPACER_HEAD
  on full-width scroll_down.
- Emit ?2027l before cells and IRM/DECOM/DECLRMM/?7l/?25l/DECSCUSR after
  cells in Formatter(OutputFormat.VT) while padding wrapped rows.
- Split DEFAULT_PROFILE / XTERM_PROFILE (VT510 DECSTR mode set, shared
  primary DECSC/?1049h save slot with isolated alt slot, SS2/SS3 save)
  from TMUX_PROFILE (declrmm_enabled=False, top_margin_scrolls_to_history,
  and separate_alt_save_cursor=True with ?1048 disabled).
why: Real-world TUIs probe OSC 4/104 and semicolon-chained OSC 10-12
color queries, XTMODKEYS key-modifier levels, ?1007 alternate scroll,
cell-calibrated ?1016/?2048/TIOCSWINSZ pixel dimensions, and
XTSMGRAPHICS sentinels, while desktop notifications (OSC 9/99/777) and
>=32768 mode queries should not misfire or alias DEC private modes.

what:
- Add zero-list-allocation OSC 4/104 256-palette overrides/queries and
  semicolon-chained OSC 10-12/110-112 foreground, background, and
  Profile.cursor_rgb cursor color handling, plus silent OSC 99/777.
- Bound ANSI/DEC mode codes below DEC_PRIVATE_MASK across DECRQM,
  SM/RM, and tmux capture decoding, and answer XTSMGRAPHICS with
  ?Pi;3S.
- Track per-Screen XTMODKEYS modify_other_keys (0..2) with ?4m queries
  and ASCII-safe Shift/Ctrl/Alt encoding, default-enable ?1007
  Mode.ALTERNATE_SCROLL, derive/clamp ?1016 MouseEvent pixels, and
  report pixel dimensions in ?2048 and TIOCSWINSZ.
- Document single-thread Terminal ownership, hide private autodoc
  members globally in docs/conf.py, and link APIs across docs/topics.
why: Darwin pty.openpty()/TIOCSCTTY/TTYHOG and Windows portable sans-I/O
execution were unverified in GitHub Actions, and sdist/wheel test runs
and CloudFront cache invalidation had partial path coverage.

what:
- Add test-macos (macos-latest, Python 3.14 full PTY suite + ty) and
  test-windows (windows-latest, Python 3.14 portable core/stream + ty)
  jobs in .github/workflows/tests.yml, and widen CloudFront invalidation
  in .github/workflows/docs.yml to --paths '/*'.
- Add Operating System :: Microsoft :: Windows classifier, UTF-8 MyST
  include encodings in docs/{history,migration}.md, wheel/sdist guards
  in tests/test_{libvt,benchmark}.py, and fast-exiting child drain plus
  win32 open_pty NotImplementedError coverage in tests/test_aio.py.
@tony
tony merged commit aef11f2 into master Nov 25, 2026
8 checks passed

This branch was successfully deployed

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