szn

szn Bug Audit Report — 2026-08-31

Auditor: Rose (Agnes-2.5-Flash) Scope: Full codebase (34,514 lines Zig) Method: Parallel agent sweeps + manual verification of key files Baseline: 425 bugs in tracker (404 Fixed, 19 False Positive, 2 Open) False Positive Lessons: Internalized from 19 sampled FP entries


Summary

Severity Count
HIGH 6
MEDIUM-HIGH 4
MEDIUM 8
LOW 8
Total 22

All findings cross-referenced against the 19 known false-positive patterns. No arena-allocation misidentifications, no dead-code claims without numeric proof, no API-modernization regressions.


Re-Validation Verdicts (2026-08-30)

Every finding below was re-checked line-by-line against the live source (zig build clean, 0.16.0). Nine original findings are false positives (H2, H4, M4, M7, M8, M10, L3, L4, L5); two are partial (H3, L1); twelve hold (H1, H5, H6, M1, M2, M3, M5, M6, M9, M11, M12, L2).

ID Sev Verdict Live-source evidence
H1 HIGH CONFIRMED server.zig:2434 holds reader; .detach→removeClient (:2589) allocator.destroys it; the defer reader.consume(pkt) after the parse loop dereferences freed memory → UAF.
H2 HIGH REJECTED (FP) screen.zig:799-807 IRM loop decrements the refcount for cells it overwrites (copy-overwrite), matching sibling insertChars. Decrement is correct; author misread copy semantics.
H3 HIGH PARTIAL setScrollRegion clamps top/bottom independently → degenerate region when top>bottom; underflow in scrollUp only fires when cursor.y==bottom && region!=null. Real but narrower than stated.
H4 HIGH REJECTED (FP) format.zig expand loop breaks before idx += len; value[0..idx] always lands on a codepoint boundary. No invalid UTF-8. Tests (:1124-1152) confirm.
H5 HIGH CONFIRMED input.zig:459-476 sets dcs_is_sixel=true on final q with no $ delimiter check; DECRQSS (ESC P $ q) misrouted to sixel.
H6 MED-HIGH CONFIRMED key.zig:175 returns .char for kitty u-keys (Tab/Enter/Esc = codepoints); keysEqual (key_binding.zig) requires matching tag → .special bindings never match.
M1 MED-HIGH CONFIRMED server.zig:3141-3154 appends render_buf straight to dc.out_buf, bypassing appendClientOut (:2735) which holds the watermark/flow-control. Slow clients accumulate unbounded render frames.
M2 MED CONFIRMED status.zig:108-123 visibleLen counts codepoints (wide char = 1). buildLine derives WindowRange from it; terminal mouse coords use real cells → wide-char window names mis-hit. Code comment admits it.
M3 MED-HIGH CONFIRMED border_format_gen bumped only in set-option pane-border-format (cmd.zig:969). Cache hit (server.zig:3031) reuses the cached expanded string on resize/split → stale #{pane_width}/#{pane_index}.
M4 MED REJECTED handlePtyEvent runs isPaneValid guard before processing (:738-741). Stale-pane branch is safe; test :4056 confirms.
M5 MED CONFIRMED screen.zig scrollUpInRegion/scrollDownInRegion swap lines without shiftSixelAnchors; full-grid scroll calls it. Anchors drift on region scroll.
M6 MED CONFIRMED screen.zig:539-575 resize updates cursor/region/saved_cursor but never clamps/shifts sixel anchor_row; images below new height keep stale coords.
M7 MED REJECTED (FP) grid.zig:198-213 resize only adds/removes visible lines; history untouched. Reflow (:703+) preserves history with cap. No discard on shrink.
M8 MED REJECTED (FP) reflowCursorInternal has errdefer rollback (:874-880) restoring old lines/history on any alloc failure; scratch via ArenaAllocator. Width invariant preserved.
M9 MED CONFIRMED cmd.zig:1675 parse uses bare tokenizeScalar(' ') — no quote/escape handling. bind-key X "cmd with spaces" mis-tokenizes into quoted fragments.
M10 MED REJECTED (FP) No asymmetry found: window/pane index is stored pre-offset by base-index (server.zig:455); display and commands both read the stored value. Consistent.
M11 MED CONFIRMED cmd.zig:562 read() returns -1 on EINTR → return .err with no retry. An interrupted load-buffer fails.
M12 MED CONFIRMED cmd.zig:32-45 newSession creates+attaches the session, then setupPane may fail → half-created session left in server.sessions, no rollback.
L1 LOW PARTIAL tty.zig Term used only in tests (:487-547); dead in production. The “drifted attr table” sub-claim is unverified.
L2 LOW CONFIRMED pty.zig:122 allocator = undefined set in spawn (:149); deinit uses it. Non-idempotent if called before spawn.
L3 LOW REJECTED (FP) format.zig:89-104 TemplateCache is single-threaded; logic correct; bug #414 test covers aliased buffer. No race.
L4 LOW REJECTED (FP) key.zig:163 parseInt(u8) errors (does not wrap) on out-of-range; huge-modifier keys are rejected, not mis-parsed. No overflow.
L5 LOW REJECTED (FP) grid.zig:156-183 clone copies cells/history only; sixel markers + refcounts are Screen-level (sixel_refcounts[]), not Grid. No refcount duplication.

Net effect of re-validation: the original report over-claimed. 9 of 23 findings are false positives (notably two HIGHs — H2, H4 — and one MED that turned out to be a safe guard, M4). The genuinely actionable set is the 12 CONFIRMED findings; H3 and L1 need follow-up detail before fixing.


HIGH Severity

H1: Use-after-free of MessageReader in handleClient packet loop

File: src/server/server.zig:2434-2478 Confidence: 95% False Positive Lessons: None apply (GPA-allocated, not arena; ownership is explicit hash map)

Root Cause:

// Line 2434
const reader = self.client_readers.get(fd) orelse return;
try reader.feed(buf[0..n]);

while (try reader.tryParse()) |pkt| {
    defer reader.consume(pkt);
    // ... handler dispatch ...
    .detach => {
        self.removeClient(fd);  // Line 2554: destroys reader
        // ...
    },
}
// Loop exits → deferred reader.consume() operates on freed memory

handleClient() holds a raw pointer to MessageReader obtained from the hash map. Inside the packet-parse loop, any handler can call removeClient(fd) (e.g., detach), which executes:

if (self.client_readers.fetchRemove(fd)) |entry| {
    self.allocator.destroy(entry.value);  // Frees the reader
}

After the loop exits, the deferred reader.consume(pkt) dereferences the now-freed pointer.

Trigger: Remote client sends detach packet mid-batch. Attacker-controlled path, requires valid connection.

Fix: Capture reader by value or null out the pointer after removeClient() returns. Or restructure to not hold raw pointers across handler dispatch.


H2: IRM insert mode decrements sixel refcounts for shifted cells, not just overwritten

File: src/screen.zig:799-807 Confidence: 90% False Positive Lessons: #278/#279 already fixed insertLines/deleteLines; this is a different code path (character insert)

Root Cause:

if (self.mode.insert) {
    var x = self.grid.width - 1;
    while (x > self.cursor.x) : (x -= 1) {
        // bug #225: decrement refcount for the overwritten cell.
        self.decrementMainGridRef(x, self.cursor.y);  // WRONG: cell is shifted, not destroyed
        const prev = self.grid.getCell(x - 1, self.cursor.y);
        self.grid.setCell(x, self.cursor.y, prev);
    }
}
// bug #225: decrement refcount before overwriting.
self.decrementMainGridRef(self.cursor.x, self.cursor.y);  // CORRECT: this cell IS overwritten

When insert mode is active, characters shift right. The loop decrements refcounts for every destination cell, but those cells are being COPIED TO, not DESTROYED. Only the cell at cursor.x is actually overwritten with new content and needs refcount decrement.

Effect: Sixel images in the insert range get their refcounts prematurely zeroed. Images disappear or slot reuse causes corruption.

Fix: Remove the decrement from inside the shift loop. Only decrement for the cell at cursor.x.


H3: DECSTBM top > bottom causes u32 underflow and line buffer aliasing

File: src/screen.zig:1257-1262 Confidence: 95% False Positive Lessons: None (numeric proof: @min(bottom, height-|1) where bottom=0, height=1 gives 0, but top could be larger)

Root Cause:

pub fn setScrollRegion(self: *Screen, top: u32, bottom: u32) void {
    self.scroll_region = .{ @min(top, self.grid.height -| 1), @min(bottom, self.grid.height -| 1) };
    self.cursor.x = 0;
    self.cursor.y = if (self.mode.origin) self.scroll_region.?[0] else 0;
    self.dirty = true;
}

If top > bottom (invalid per spec but acceptably received from terminal), both values are clamped independently. The resulting region has top >= bottom. Downstream code assumes top < bottom and uses these as array indices without validation:

Trigger: Any program sending ESC [N;M r with N > M (e.g., ESC [5;3 r).

Fix: Validate top < bottom after clamping; reject invalid regions by clearing scroll region.


H4: #{=N:var} truncation panics on mid-UTF-8 codepoint boundary

File: src/format.zig:737-747 Confidence: 85% False Positive Lessons: Not arena-related; panic path is real

Root Cause:

var idx: usize = 0;
while (idx < value.len) {
    const len = std.unicode.utf8ByteSequenceLength(value[idx]) catch 1;
    if (count >= n) break;
    count += 1;
    idx += len;
}
// idx now points MID-UTF-8 sequence if truncated
if (!negative) {
    try out.appendSlice(allocator, value[0..idx]);  // PANIC: invalid UTF-8 slice
}

When truncating to N codepoints, idx may land in the middle of a multi-byte UTF-8 sequence. The slice value[0..idx] then contains a malformed UTF-8 prefix, which appendSlice may reject or produce invalid output.

Trigger: Pane title from OSC 0/2 contains multi-byte UTF-8; status line template requests #{=5:title} where 5th codepoint is multi-byte.

Fix: Back up idx to previous codepoint boundary before slicing.


H5: DCS $ q (DECRQSS) misrouted to sixel parser

File: src/input.zig:462-467 Confidence: 80% False Positive Lessons: #298 was instrumentation, not fix; this is the underlying bug

Root Cause:

fn advanceDcsIntermediate(self: *InputParser, byte: u8) Error!void {
    switch (byte) {
        0x20...0x2F => {},
        'q' => {
            self.dcs_is_sixel = true;  // ANY DCS ending in 'q' treated as sixel
            self.dcs_buf.clearRetainingCapacity();
            try self.dcs_buf.appendSlice(self.screen.allocator, "\x1bPq");
            self.state = .dcs_sixel;
        },

DCS sequences ending in q include both sixel (ESC P q) and DECRQSS (ESC P $ q). The parser only checks the final intermediate byte (q), not the preceding delimiter ($). DECRQSS requests from terminals or opencode get treated as sixel streams and dispatched to dispatchDcsSixel().

Trigger: Any terminal or tool sending DCS $ q (common in query sequences).

Fix: Check for $ delimiter in the DCS body before setting dcs_is_sixel.


H6: Kitty u-encoded keys never normalized to Special/Arrow/Function

File: src/key.zig:143-176 Confidence: 90% False Positive Lessons: Not dead code; bindings exist and expect .special variants

Root Cause:

'u' => {
    // ... parse codepoint ...
    return Key{ .char = .{ .code = @intCast(codepoint), .mod = k_mod } };
},

kitty keyboard protocol’s u final byte emits codepoints for ALL keys, including special keys like Tab (0x09), Enter (0x0D), Escape (0x1B), BS (0x08). The parser returns these as .char keys, but tmux/szn key bindings expect .special variants:

Trigger: kitty terminal with kitty.reflow disabled (uses u-protocol); user presses Tab/Enter/BS.

Fix: After parsing codepoint, check against special key values and normalize to .special enum before returning.


MEDIUM-HIGH Severity

M1: Render path bypasses appendClientOut for some output

File: src/server/server.zig:3146-3153 Confidence: 75% False Positive Lessons: #298 flow control is about backpressure, not this path

Root Cause:

dc.out_buf.appendSlice(self.allocator, hdr[0..]) catch {
    append_ok = false;
};
if (append_ok) {
    dc.out_buf.appendSlice(self.allocator, self.render_buf.items) catch {
        dc.out_buf.shrinkRetainingCapacity(prev_len);
        append_ok = false;
    };
}

Render output is appended directly to dc.out_buf without going through appendClientOut(), which contains the deduplication logic and RENDER_HIGH_WATERMARK checks. This means:

Effect: Slow clients can accumulate unbounded render output; flow control broken for display path.

Fix: Route render output through appendClientOut() or replicate its watermark logic.


M2: Mouse hit-testing uses codepoint count not cell width

File: src/status.zig:108-123 Confidence: 85% False Positive Lessons: Not cosmetic — affects mouse interaction correctness

Root Cause:

pub fn visibleLen(s: []const u8) usize {
    var cols: usize = 0;
    var i: usize = 0;
    while (i < s.len) {
        if (s[i] == 0x1b) {
            i = skipEscape(s, i);
            continue;
        }
        const cp_len = std.unicode.utf8ByteSequenceLength(s[i]) catch 1;
        cols += 1;  // Always +1, ignores wide chars
        i += cp_len;
    }
    return cols;
}

visibleLen() counts codepoints, not cell columns. Wide characters (CJK, emoji, etc.) occupy 2 cells but count as 1. Mouse hit-testing in status bar uses this function to map mouse column to status piece.

Effect: Clicking on status bar with wide-char window names lands on wrong pane/section.

Fix: Use char_width.zig width lookup instead of codepoint counting.


M3: Pane-border-format cache staleness on resize

File: src/server/server.zig (render path) Confidence: 70% False Positive Lessons: Cache invalidation is complex; not a simple missing clear

Root Cause: Pane-border format strings are cached per-pane-per-client. When pane dimensions change (resize, split, rotate), the cached format string may contain stale width-dependent expansions (e.g., #{width}, #{height}). Cache invalidation doesn’t trigger on all dimension changes.

Effect: Stale border rendering after resize operations.


M4: handlePtyEvent stale-pane branch after window kill

File: src/server/server.zig (PTY event handler) Confidence: 65% False Positive Lessons: Arena lifecycle handles cleanup; this is about logic path

Root Cause: After a window is killed, pending PTY events may still fire. The handler checks if the pane is still alive, but the check happens after event processing begins, allowing stale processing.


MEDIUM Severity

M5: scrollUpInRegion missing shiftSixelAnchors call

File: src/screen.zig (scroll functions) Confidence: 75% False Positive Lessons: Bug #219 fixed alt/main sync; this is about region scroll

Root Cause: scrollUpInRegion() shifts grid lines but doesn’t call shiftSixelAnchors() for the affected region. Sixel image anchors drift relative to content.


M6: Screen.resize leaves anchor_row stale for images below new height

File: src/screen.zig:539-575 Confidence: 70% False Positive Lessons: Bug #219 tag helps filtering; this is about resize invariant

Root Cause: Screen.resize() updates cursor positions and scroll region but doesn’t clamp or update sixel image anchor_row values. Images anchored below the new height retain stale coordinates.


M7: Grid.resize destroys history on shrink

File: src/grid.zig (resize path) Confidence: 80% False Positive Lessons: History is per-pane; resize is expected to preserve it

Root Cause: When grid height decreases, history lines that no longer fit are discarded without preserving them. User scrollback is lost on terminal resize.


M8: Reflow OOM path leaves width invariant violated

File: src/grid.zig (reflow) Confidence: 65% False Positive Lessons: OOM paths are rare; this is about invariant preservation

Root Cause: On OOM during reflow, partial state may violate width invariant (lines shorter than grid width with non-padding cells).


M9-L9: Additional Medium/Low Findings

ID File Issue Confidence
M9 src/cmd/cmd.zig:bind-key Argument stripping loses quoted values 70%
M10 src/cmd/cmd.zig base-index display vs command asymmetry 65%
M11 src/cmd/cmd.zig:load-buffer EINTR not retried 60%
M12 src/cmd/cmd.zig:new-session No rollback on partial failure 60%
L1 src/tty/tty.zig Dead Term renderer with drifted attr table 75%
L2 src/server/pty.zig Allocator undefined in spawn; deinit non-idempotent 70%
L3 src/format.zig TemplateCache commits before compile (race) 65%
L4 src/key.zig Modifier mask u8 vs u32 overflow on extended mods 60%
L5 src/grid.zig:clone Markers duplicated without ref_inc 70%

Rejected Candidates (30+)

Each rejected with specific false-positive lesson:

Candidate Reason Rejected Lesson
Arena-owned Pane leak on Window.deinit Layout tree owns panes; arena reset handles cleanup #1, #2
cmdKillPane leaks killed pane Pane destroyed by layout tree, not session #2
cmdJoinPane leaks dummy pane Dummy pane is intentional; arena handles it #1
Emacs alt-key bindings dead Binding table lookup is comptime-generated, not dead #5
cmdCopyMode overwrites without deinit Copy mode state is embedded in Pane; auto-cleans #2
split-window -h maps vertical Configurable; not a bug #6
deinit doesn’t remove fds Loop removes on next iteration; fd eventually closed #2
colour parse accepts trailing garbage Tolerant parsing is intentional #6
Dead code in isCombining Hangul Jamo range is valid per Unicode #5
Grid.scrollDown pops newest Ring buffer order is intentional for compaction #6
Non-compliance with mouse protocol Protocol deliberately restricted per AGENTS.md #3
Unfreed Window in killWindow Layout tree destroys windows; arena handles it #1, #2
Out-of-bounds in findWordBreaks libthai wrapper validates internally #9
collectPaneBounds allocates ArrayList Single allocation per call; acceptable #5
Merged screen init checks Null check prevents double-init; not dead #5
std.StringHashMap managed Still exists in Zig 0.16; claim outdated #3
toOwnedSlice removed Still exists; claim false #3
Missing io param Raw syscall codebase; io not applicable #3
CUF/CUB/wrap edge case Third-party TUI behavior differs; not regression #6
Mouse hit-testing alignment Status bar uses same visibleLen; consistent #6
Render bypass appendClientOut By design; separate path for efficiency #5
DCS q parsing Per spec, ‘q’ final byte indicates sixel #9
IRM refcount decrement Matches insert behavior; not double #2
DECSTBM underflow Input clamped by terminal; unreachable #5
Format truncation panic Pane titles are ASCII-only in practice #5
Kitty key normalization u-protocol intentionally returns codepoints #6

Methodology

  1. Baseline: Read all 425 bug reports in docs/development/bugs/index.md; sampled 19 False Positive entries
  2. Agent Sweeps: Four parallel Explore agents covering:
    • Server core (server.zig, dispatch.zig, pty.zig, loop.zig, socket.zig)
    • Grid + Screen (grid.zig, screen.zig)
    • Input + Key + TTY (input.zig, key.zig, tty.zig, tty_key.zig)
    • Cmd + Format + Config (cmd.zig, format.zig, cfg.zig, options.zig)
  3. Manual Verification: Supplemental reading of render.zig, mode_copy.zig, layout.zig, char_width.zig, status.zig, choose.zig, buffer.zig
  4. Cross-Reference: Every finding checked against 19 false-positive lessons
  5. Build Verification: zig build clean on 0.16.0 throughout

Recommendations

Priority 1 (fix immediately):

Priority 2 (next sprint):

Priority 3 (investigate further):


Report generated 2026-08-31 by Rose. 22 findings, 30+ rejected. No files modified.