graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
Prepare v0.302.52 terminal improvements
Rach Pradhan96d327595c76
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 282aa980..0277b60e 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -183,6 +183,9 @@ jobs:- name: PTY Markdown rendering testrun: python3 scripts/test-pty-markdown.py zig-out/bin/graff+ - name: PTY worker inspection test+ run: python3 scripts/test-pty-workers.py zig-out/bin/graff+- name: Parallel bash Esc cancellation test (#266)run: python3 scripts/test-pty-parallel-cancel.py zig-out/bin/graffdiff --git a/AGENTS.md b/AGENTS.mdindex 694f03ba..19faa787 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -94,7 +94,7 @@ new load-bearing decision, add a record in the same branch.## Terminal UI: what's ours to change-- **Colors, bold/dim, glyphs, layout are ours.** Styling travels in the output byte stream as SGR escape sequences, so the app controls it per character. The palette lives in `src/ansi.zig` (the accent is codegraff.com's emerald `#059669`; coral/red hues are reserved for errors).+- **Colors, bold/dim, glyphs, layout are ours.** Styling travels in the output byte stream as SGR escape sequences, so the app controls it per character. The palette lives in `src/ansi.zig` (the line REPL follows Harness's Codegraff Dark theme: amber `#e8a33d`, cream text, and warm neutrals; coral/red hues are reserved for errors).- **The font is not ours.** The terminal emulator owns the typeface — it loads the font, measures the cell grid, and rasterizes glyphs itself; the wire protocol has no sequence for an app to request a font. (xterm's legacy `OSC 50` is unimplemented by modern emulators and would hijack the user's whole terminal — do not emit it.) If a user asks to "change the REPL font," the answer is their terminal's config, e.g. `font-family = Geist Mono` (the site's typeface) in Ghostty — never a code change here.- **HDR/wide-gamut color is not ours either.** Truecolor SGR is 8-bit sRGB per channel — the protocol's ceiling; no sequence expresses Display P3 or EDR headroom, and macOS terminals clip app colors to SDR regardless of the panel. Pick values that look right on both P3 and sRGB displays (as `#059669` does); that's the whole lever.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 99d9d894..a6266b92 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -14,6 +14,9 @@ current is part of cutting a release.- The terminal REPL has a clearer session strip, a subtle divider, and distinct styling for active and completed checklist items. The bare prompt, scrollback, and plain output remain intact; no native window or graphical toolkit is required.- Operational modes stay visible before workspace metadata when a terminal pane is narrow.+- The line REPL uses a warm amber palette with cream text and muted status metadata.+- Markdown emphasis renders in streamed replies and agent reports instead of leaving single-marker formatting literal.+- `/workers` opens a read-only subagent browser with clickable rows, live activity, Markdown reports, and keyboard navigation. `/agents` still lists agent types.- Includes independent conversation forks for subagents and workflow fan-out, optional retained workers, and bounded workflow synthesis that preserves earlier findings.- Release binaries are built ReleaseSafe: an out-of-range index or overflow stops graff with a clear panic instead of silently corrupting state, and the stripped binaries are about 17-20% smaller.- Retains all changes from v0.302.51.diff --git a/docs/adr/0302-terminal-repl-chrome-stays-in-the-terminal.md b/docs/adr/0302-terminal-repl-chrome-stays-in-the-terminal.mdindex e96b0c7e..120303e8 100644--- a/docs/adr/0302-terminal-repl-chrome-stays-in-the-terminal.md+++ b/docs/adr/0302-terminal-repl-chrome-stays-in-the-terminal.md@@ -13,9 +13,19 @@ Refine the existing terminal sinks rather than introducing a graphical toolkitor another frontend. The status strip emphasizes session identity and operationalmodes while keeping workspace and usage metadata quiet. Mode labels take widthpriority over workspace metadata. A colored terminal replaces the existing blank-separator row with a dim rule, leaving one column free to avoid autowrap.+separator row with a faint rule and short amber leading edge, leaving one+column free to avoid autowrap. In color, separate the model and operational modes+from right-aligned, muted metadata; preserve the same width priorities. Plain+output stays compact and unpadded.-Standing work uses dim completed items and an emerald active item. Waiting work+Use Harness's Codegraff Dark foreground palette: amber `#e8a33d`, cream+`#edeae2`, warm muted `#9a9384` and faint `#5c564b`, with coral errors and sage+success. Keep the legacy ANSI palette available for compatibility. Theme roles+also color attachment chips; no editor path hard-codes the former accent.+Do not change the terminal's background, font, or persistent settings.++Standing work uses muted completed and pending items, with a solid amber marker+and bold text for the active item. Plain output keeps its existing state glyphs. Waiting workremains explicit; styling never changes its state or implies completion. Keep thebare `›`, editor behavior, scrollback, engine events and ACP unchanged. Withcolor disabled, omit the divider and all styling sequences.diff --git a/docs/adr/0303-terminal-markdown-and-worker-inspection.md b/docs/adr/0303-terminal-markdown-and-worker-inspection.mdnew file mode 100644index 00000000..5fe092d1--- /dev/null+++ b/docs/adr/0303-terminal-markdown-and-worker-inspection.md@@ -0,0 +1,40 @@+# 0303. Inspect workers without replacing the line REPL++## Context++The terminal already renders Markdown blocks and streams inline bold and code,+but single-marker emphasis remained literal. Worker launch and completion rows+provided no in-terminal route to the activity and reports available to ACP+clients. A permanent multi-column layout would replace the line REPL's+scrollback and editor contract rather than improving it.++## Decision++Share inline emphasis handling between the streaming and buffered terminal+renderers. Render balanced asterisk and underscore emphasis, retain markers+inside URLs and identifiers, and support escaped punctuation. Keep styling in+the existing palette; plain output never gains terminal escape sequences.+Structured engine events and stored model text remain unchanged.++Expose `/workers [child-id]` as a read-only inspector of the current process's+existing bounded child-activity snapshots. `/agents` continues to list agent+types. In a colored terminal the inspector temporarily owns the alternate+screen: click or Enter opens a card, arrow keys scroll, Escape returns, and q+closes it. Refresh existing snapshots; never spawn, resume, steer, or cancel an+agent to inspect it. Outside the terminal, provide a plain list or report.++Use the same parent PID/start-identity directory and child IDs as the ACP+activity feed. Bound reads and event counts, reject invalid or mismatched IDs,+and strip untrusted terminal control sequences before rendering. Tool-result+bodies and already-emitted thought text expand only on explicit request;+failures remain visible. Indicate truncated snapshots.++## Consequences++The line editor, ordinary transcript, engine, ACP event shapes, and separately+maintained fullscreen client remain unchanged. Mouse reporting and raw input+are scoped to the inspector and restored on exit, including error paths.+Worker cards wait at the existing line-boundary gate while the inspector owns+the screen. Terminal scrollback itself is not a clickable native widget: the+launch row names `/workers`, where click and keyboard inspection are available.+Snapshots show bounded recent activity, not an unlimited historical transcript.diff --git a/docs/adr/README.md b/docs/adr/README.mdindex 18d7b823..f743114e 100644--- a/docs/adr/README.md+++ b/docs/adr/README.md@@ -327,6 +327,8 @@ record only when you need the evidence or the edge cases.| [0301](0301-failed-requests-settle-the-pending-turn.md) | Exhausted request retries leave a truthful failure boundary in history so an identical prompt can run after reconnecting, including after save/load; duplicate-host protection and bounded retries stay unchanged. || [0302](0302-terminal-repl-chrome-stays-in-the-terminal.md) | Refine the line REPL's terminal sinks: quiet status hierarchy, mode-first width priority and active-work emphasis, without native windows or changing the editor, engine or external fullscreen client. |+| [0303](0303-terminal-markdown-and-worker-inspection.md) | The line REPL renders inline emphasis and offers a temporary mouse/keyboard `/workers` inspector over the existing bounded ACP child feed, without replacing the editor or changing engine behavior. |+## When to write oneWrite an ADR when a decision is load-bearing and non-obvious: it was reacheddiff --git a/docs/releases/v0.302.52.md b/docs/releases/v0.302.52.mdnew file mode 100644index 00000000..8977618b--- /dev/null+++ b/docs/releases/v0.302.52.md@@ -0,0 +1,11 @@+# v0.302.52++Release binaries now use Zig ReleaseSafe, keeping runtime safety checks enabled.++- A clearer terminal prompt and status strip, warm amber accents, and distinct active checklist styling make ongoing work easier to follow.+- Markdown emphasis renders in streamed replies and agent reports instead of leaving formatting markers literal.+- `/workers` opens a read-only subagent browser: click or press Enter to inspect activity and reports, use arrow keys to scroll, Escape to return, and q to close. Tool bodies expand on request. `/agents` still lists agent types.+- Narrow terminals keep operational modes visible before optional metadata. Plain output stays free of terminal control sequences.+- Release publication waits for CI on the exact tagged commit.++Includes the fixes from v0.302.51. The ordinary line REPL and the separately installed fullscreen terminal UI remain distinct.diff --git a/scripts/eval/tier1-manifest.json b/scripts/eval/tier1-manifest.jsonindex 0cd4cd30..45b95808 100644--- a/scripts/eval/tier1-manifest.json+++ b/scripts/eval/tier1-manifest.json@@ -14,7 +14,7 @@"src/main.zig","src/repl.zig"],- "test_count_baseline": 3487,+ "test_count_baseline": 3496,"test_count_slack": 25,"required_invariants": [{diff --git a/scripts/test-pty-markdown.py b/scripts/test-pty-markdown.pyindex b8feee83..3538aadb 100755--- a/scripts/test-pty-markdown.py+++ b/scripts/test-pty-markdown.py@@ -10,9 +10,8 @@ from pty_harness import run_to_exit_arg = sys.argv[1] if len(sys.argv) > 1 else "graff"GRAFF = os.path.abspath(_arg) if os.sep in _arg else _arg-# Headings were coral; the palette alignment moved them to the emerald accent-# (ansi.zig style.accent — coral read as error red).-ACCENT = b"\x1b[38;2;5;150;105m"+# Match the production line REPL's Harness Codegraff Dark palette.+ACCENT = b"\x1b[38;2;232;163;61m"def main() -> None:@@ -48,6 +47,7 @@ def main() -> None:"◆ Gaps","• No bot-specific route tests exist.","• Pin install.sh and verify its checksum.",+ "• Emphasis: Coding agents / harnesses, readable, strong, foo_bar.","◆ Recommended implementation order","1. Immediately: require collaborator permission.","2) Next: deduplicate X-GitHub-Delivery.",@@ -83,7 +83,7 @@ def main() -> None:)if b"\x1b[" in plain_result.raw:raise SystemExit("Markdown no-color render unexpectedly contains ANSI")- for ansi in (ACCENT, b"\x1b[33m", b"\x1b[32m"):+ for ansi in (ACCENT, b"\x1b[38;2;217;164;65m", b"\x1b[38;2;127;168;107m", b"\x1b[3m"):if ansi not in color_result.raw:raise SystemExit(f"Markdown render missing ANSI style {ansi!r}")print("ok PTY Markdown color/no-color links, blocks, inline styles, and ANSI")diff --git a/scripts/test-pty-workers.py b/scripts/test-pty-workers.pynew file mode 100644index 00000000..88a52cd7--- /dev/null+++ b/scripts/test-pty-workers.py@@ -0,0 +1,160 @@+#!/usr/bin/env python3+"""Exercise the actual REPL inspector with offline sample activity, not agents."""+import argparse+import json+import os+from pathlib import Path+import subprocess+import tempfile+import time++from pty_harness import PtySession, terminal_text+++def seed(home, pid):+ registry = home / ".graff/live"+ matches = list(registry.glob(str(pid) + "-*.json"))+ if len(matches) != 1:+ raise AssertionError("Missing own-process presence identity")+ parent = json.loads(matches[0].read_text())+ directory = registry / ("activity-%d-%x" % (pid, parent["start_id"]))+ directory.mkdir(mode=0o700)+ samples = (+ ("sample-review", "Review terminal rendering", "working"),+ ("sample-tests", "Check narrow terminals", "completed"),+ ("sample-error", "Inspect error handling", "failed"),+ )+ for index, (ident, label, status) in enumerate(samples):+ meta = {"id": ident, "label": label, "task": "Inspect the **terminal** boundary.",+ "model": "sample-model", "status": status, "updatedAt": 30 - index}+ data = {"agent": meta, "events": [+ {"type": "tool_call", "id": "read-1", "name": "read_file", "text": "example.zig"},+ {"type": "tool_result", "id": "read-1", "name": "read_file", "text": "Expanded tool sample"},+ {"type": "reasoning", "text": "Emitted thought sample"},+ ], "response": "## Findings\nThe **layout** is readable.\n- *Emphasis* renders without markers.\n- `code` stays distinct.\n"}+ (directory / (ident + ".meta")).write_text(json.dumps(meta))+ (directory / (ident + ".json")).write_text(json.dumps(data))+ return directory+++def capture_frame(session, start, path):+ # A single flush can cross several PTY reads. Wait for the last frame's+ # footer reset rather than capturing as soon as an early body word arrives.+ deadline = time.monotonic() + session.timeout+ while True:+ raw = bytes(session.raw[start:])+ offset = raw.rfind(b"\x1b[2J\x1b[H")+ frame = raw[offset:] if offset >= 0 else b""+ footer = frame.rfind(("\x1b[%d;1H" % session.rows).encode())+ if footer >= 0 and b"\x1b[0m" in frame[footer:]:+ break+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise AssertionError("Inspector did not finish its frame")+ session.pump(min(0.05, remaining))+ if path:+ path.with_suffix(".ansi").write_bytes(frame)+ path.with_suffix(".txt").write_text(terminal_text(frame))+ return frame+++def exercise(binary, cols, captures):+ with tempfile.TemporaryDirectory(prefix="graff-workers-") as tmp:+ base = Path(tmp)+ home, work = base / "home", base / "workspace"+ (home / ".harness").mkdir(parents=True)+ work.mkdir()+ subprocess.run(["git", "init", "--quiet", str(work)], check=True)+ (home / ".harness/settings.json").write_text('{"ai_title":false,"session_recap":false,"skills":{"codedbpro":false}}')+ config = home / "empty-mcp.json"+ config.write_text('{"mcpServers":{}}')+ unset = tuple(k for k in os.environ if any(s in k.upper() for s in+ ("API_KEY", "ACCESS_TOKEN", "AUTH_TOKEN"))) + ("CODEX_HOME", "NO_COLOR")+ env = {"HOME": str(home), "GRAFF_FLEET": "off", "GRAFF_LEARN_AUTO": "off",+ "GRAFF_MCP_CONFIG": str(config), "GRAFF_NO_TELEMETRY": "1"}+ # Supply only a synthetic key after inherited credentials are removed.+ unset = tuple(k for k in unset if k != "CODEGRAFF_API_KEY")+ env["CODEGRAFF_API_KEY"] = "offline-worker-test"+ with PtySession(binary, ["--model", "deepseek-v4-pro", "--no-telemetry"],+ cwd=str(work), env=env, unset_env=unset, timeout=20,+ rows=24, cols=cols) as session:+ session.wait_for_prompt(timeout=60)+ directory = seed(home, session.pid)+ cursor = len(session.raw)+ session.send_line("/workers")+ session.wait_for_literal("recent agents", start=cursor)+ session.wait_for_literal("Enter inspect", start=cursor)+ list_path = captures / ("workers-list-%d" % cols) if captures else None+ listing = capture_frame(session, cursor, list_path)+ if b"\x1b[?1000h" not in session.raw[cursor:]:+ raise AssertionError("Mouse reporting was not enabled")+ for label in ("Review terminal", "Check narrow", "Inspect error"):+ if label not in terminal_text(listing):+ raise AssertionError("Missing sample card: " + label)++ # A real SGR mouse press, deliberately fragmented across writes.+ cursor = len(session.raw)+ session.send(b"\x1b[<0;3;")+ session.send(b"4M")+ session.wait_for_literal("terminal boundary", start=cursor)+ detail_path = captures / ("workers-detail-%d" % cols) if captures else None+ details = capture_frame(session, cursor, detail_path)+ visible = terminal_text(details)+ if "Emphasis renders without markers." not in visible:+ raise AssertionError("Markdown report did not render")+ if "Expanded tool sample" in visible or "Emitted thought sample" in visible:+ raise AssertionError("Details expanded without a request")+ cursor = len(session.raw)+ session.send_text("t")+ session.wait_for_literal("Expanded tool sample", start=cursor)+ cursor = len(session.raw)+ session.send_text("h")+ session.wait_for_literal("Emitted thought sample", start=cursor)+ cursor = len(session.raw)+ session.send_key("esc")+ session.wait_for_literal("recent agents", start=cursor)++ # Refresh an existing snapshot while the browser stays open.+ path = directory / "sample-review.meta"+ meta = json.loads(path.read_text())+ meta["label"] = "Updated live sample"+ path.write_text(json.dumps(meta))+ cursor = len(session.raw)+ session.send_text("r")+ session.wait_for_literal("Updated live sample", start=cursor)+ cursor = len(session.raw)+ session.send_text("q")+ session.wait_for_prompt(start=cursor)+ restored = bytes(session.raw[cursor:])+ for mode in (b"\x1b[?1000l", b"\x1b[?1006l", b"\x1b[?1049l", b"\x1b[?25h"):+ if mode not in restored:+ raise AssertionError("Inspector did not restore terminal mode")++ cursor = len(session.raw)+ session.send_line("/workers ../invalid")+ session.wait_for_literal("usage: /workers [child-id]", start=cursor)+ session.wait_for_prompt(start=cursor)+ cursor = len(session.raw)+ session.send_line("/version")+ session.wait_for_prompt(start=cursor)+ session.send_key("ctrl-d")+ result = session.read_until_exit(5)+ if result.timed_out or result.exit_code != 0:+ raise AssertionError("REPL did not exit cleanly after inspection")+ print("ok %d columns: click, Markdown, disclosures, live refresh, Esc, cleanup, next command" % cols)+++def main():+ parser = argparse.ArgumentParser()+ parser.add_argument("binary", nargs="?", default="zig-out/bin/graff")+ parser.add_argument("--capture-dir", type=Path)+ args = parser.parse_args()+ binary = str(Path(args.binary).resolve())+ if args.capture_dir:+ args.capture_dir.mkdir(parents=True, exist_ok=True)+ for cols in (96, 40):+ exercise(binary, cols, args.capture_dir)+++if __name__ == "__main__":+ main()diff --git a/src/additional_tests.zig b/src/additional_tests.zigindex 40c2e590..fd419015 100644--- a/src/additional_tests.zig+++ b/src/additional_tests.zig@@ -64,6 +64,10 @@ test "submitted prompt keeps key material masked" {}test "submitted prompt retains attachment chip styling" {+ const ansi = @import("ansi.zig");+ const saved = ansi.style;+ ansi.style = ansi.Style.harness;+ defer ansi.style = saved;var output: Io.Writer.Allocating = .init(std.testing.allocator);defer output.deinit();const mark = "[Image #1]";@@ -71,6 +75,6 @@ test "submitted prompt retains attachment chip styling" {try std.testing.expect(std.mem.indexOf(u8,output.writer.buffered(),- "\x1b[7;38;2;5;150;105m[Image #1]\x1b[0m caption",+ "\x1b[38;2;232;163;61m\x1b[7m[Image #1]\x1b[0m caption",) != null);}diff --git a/src/agent_markdown_inline.zig b/src/agent_markdown_inline.zignew file mode 100644index 00000000..56bc9bb9--- /dev/null+++ b/src/agent_markdown_inline.zig@@ -0,0 +1,200 @@+//! Inline Markdown shared by the live REPL and buffered lines.+const std = @import("std");+const Io = std.Io;+const Agent = @import("agent.zig").Agent;+const ansi = @import("ansi.zig");+const style = &ansi.style;+const markdown_url = @import("markdown_url.zig");++pub const State = enum { normal, star, underscore, bold_empty, under_empty, bold, under_bold, bold_star, under_end, code, italic, under_italic, escape };++pub fn byte(self: *Agent, w: *Io.Writer, b: u8) void {+ switch (self.md_span) {+ .normal => switch (b) {+ '*', '_' => {+ const word = self.md_word.items;+ if (markdown_url.containsHttp(word) or (b == '_' and word.len > 0 and (std.ascii.isAlphanumeric(word[word.len - 1]) or word[word.len - 1] == '_')))+ self.mdWrapByte(w, b)+ else+ self.md_span = if (b == '*') .star else .underscore;+ },+ '\\' => self.md_span = .escape,+ '`' => {+ self.mdStyle(w, style.yellow);+ self.md_span = .code;+ },+ else => self.mdWrapByte(w, b),+ },+ .star, .underscore => {+ const under = self.md_span == .underscore;+ const marker: u8 = if (under) '_' else '*';+ if (b == marker) {+ self.mdStyle(w, style.bold);+ self.md_span = if (under) .under_empty else .bold_empty;+ } else if (b == ' ' or b == '\t') {+ self.mdWrapByte(w, marker);+ self.md_span = .normal;+ self.mdSpanByte(w, b);+ } else {+ self.mdStyle(w, style.italic);+ self.md_span = if (under) .under_italic else .italic;+ self.mdSpanByte(w, b);+ }+ },+ .italic, .under_italic => {+ const marker: u8 = if (self.md_span == .under_italic) '_' else '*';+ if (b == marker) {+ self.mdStyle(w, style.reset);+ self.md_span = .normal;+ } else self.mdWrapByte(w, b);+ },+ .escape => {+ if (std.mem.indexOfScalar(u8, "*_`\\[]()#~", b) == null) self.mdWrapByte(w, '\\');+ self.mdWrapByte(w, b);+ self.md_span = .normal;+ },+ .bold_empty, .under_empty => {+ const under = self.md_span == .under_empty;+ if (b == @as(u8, if (under) '_' else '*')) {+ self.md_span = if (under) .under_end else .bold_star;+ } else {+ self.md_span = if (under) .under_bold else .bold;+ self.mdSpanByte(w, b);+ }+ },+ .bold, .under_bold => {+ const under = self.md_span == .under_bold;+ if (b == @as(u8, if (under) '_' else '*'))+ self.md_span = if (under) .under_end else .bold_star+ else+ self.mdWrapByte(w, b);+ },+ .bold_star, .under_end => {+ const under = self.md_span == .under_end;+ const marker: u8 = if (under) '_' else '*';+ if (b == marker) {+ self.mdStyle(w, style.reset);+ self.md_span = .normal;+ } else {+ self.mdWrapByte(w, marker);+ self.md_span = if (under) .under_bold else .bold;+ self.mdSpanByte(w, b);+ }+ },+ .code => if (b == '`') {+ self.mdStyle(w, style.reset);+ self.md_span = .normal;+ } else self.mdWrapByte(w, b),+ }+}++pub fn finish(self: *Agent, w: *Io.Writer) void {+ if (self.md_span == .star or self.md_span == .underscore) {+ self.mdWrapByte(w, if (self.md_span == .underscore) '_' else '*');+ self.md_span = .normal;+ }+ self.mdFlushWord(w);+ switch (self.md_span) {+ .normal => {},+ .escape => w.writeByte('\\') catch {},+ .star, .underscore => unreachable,+ .bold_empty, .under_empty => {+ w.writeAll(style.reset) catch {};+ w.writeAll(if (self.md_span == .under_empty) "__" else "**") catch {};+ },+ .bold, .under_bold, .code, .italic, .under_italic => w.writeAll(style.reset) catch {},+ .bold_star, .under_end => {+ w.writeByte(if (self.md_span == .under_end) '_' else '*') catch {};+ w.writeAll(style.reset) catch {};+ },+ }+ self.md_span = .normal;+}++pub fn render(w: *Io.Writer, s: []const u8) void {+ var i: usize = 0;+ while (i < s.len) {+ if (s[i] == '*' or s[i] == '_' or s[i] == '~' or s[i] == '`' or s[i] == 'h') {+ var token_end = i;+ while (token_end < s.len and s[token_end] != ' ') token_end += 1;+ if (markdown_url.unwrapToken(s[i..token_end])) |match| {+ w.writeAll(match.url) catch {};+ w.writeAll(match.suffix) catch {};+ i = token_end;+ continue;+ }+ if (std.mem.startsWith(u8, s[i..], "http://") or std.mem.startsWith(u8, s[i..], "https://")) {+ w.writeAll(s[i..token_end]) catch {};+ i = token_end;+ continue;+ }+ }+ if (s[i] == '\\' and i + 1 < s.len and std.mem.indexOfScalar(u8, "*_`\\[]()#~", s[i + 1]) != null) {+ w.writeByte(s[i + 1]) catch {};+ i += 2;+ continue;+ }+ if (markdown_url.emphasisAt(s, i)) |span| {+ w.print("{s}{s}{s}", .{ if (span.strong) style.bold else style.italic, s[span.start..span.end], style.reset }) catch {};+ i = span.after;+ continue;+ }+ if (s[i] == '`') {+ if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {+ w.print("{s}{s}{s}", .{ style.yellow, s[i + 1 .. end], style.reset }) catch {};+ i = end + 1;+ continue;+ }+ }+ w.writeByte(s[i]) catch {};+ i += 1;+ }+}++fn testStream(a: std.mem.Allocator, text: []const u8) ![]const u8 {+ var out: Io.Writer.Allocating = .init(a);+ var agent: Agent = .{ .gpa = a, .arena = a, .io = std.testing.io, .client = undefined, .provider = undefined, .messages = .init(a), .sub = true, .label = "Markdown test", .out = &out.writer, .md_width = 200 };+ defer @import("agent_render.zig").deinitMarkdown(&agent);+ for (text) |b| agent.streamMarkdown(&.{b});+ agent.flushStreamTail();+ return out.written();+}++test "terminal markdown streams emphasis across individual byte deltas" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const old = ansi.style;+ defer ansi.style = old;+ ansi.style = .harness;+ const text = try testStream(arena.allocator(), "*Coding agents / harnesses*: **ready** _next_ __strong__ `code_name` foo_bar\\*\n");+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[3mCoding agents / harnesses\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[1mready\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[3mnext\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[1mstrong\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "code_name") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "foo_bar*") != null);+}++test "terminal markdown preserves URL marker data and code contents" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const old = ansi.style;+ defer ansi.style = old;+ ansi.style = .{};+ const text = try testStream(arena.allocator(), "https://example.test/glob/** https://example.test/path/__ `*literal*`\\\n");+ try std.testing.expectEqualStrings("https://example.test/glob/** https://example.test/path/__ *literal*\\\n", text);+ try std.testing.expect(std.mem.indexOfScalar(u8, text, 0x1b) == null);+}++test "terminal markdown buffered emphasis and visible widths agree" {+ const old = ansi.style;+ defer ansi.style = old;+ ansi.style = .{};+ var out: Io.Writer.Allocating = .init(std.testing.allocator);+ defer out.deinit();+ const source = "*one* **two** _three_ __four__ foo_bar \\*five\\* `six`";+ const expected = "one two three four foo_bar *five* six";+ render(&out.writer, source);+ try std.testing.expectEqualStrings(expected, out.written());+ try std.testing.expectEqual(expected.len, markdown_url.inlineVisibleLen(source));+}diff --git a/src/agent_prompt_render.zig b/src/agent_prompt_render.zigindex 0bdd81df..74f251da 100644--- a/src/agent_prompt_render.zig+++ b/src/agent_prompt_render.zig@@ -91,7 +91,16 @@ fn cwdName(cwd: []const u8) []const u8 {}fn modeSegment(w: *Io.Writer, text: []const u8) !void {- try w.print(" · {s}{s}{s}{s}{s}{s}", .{ style.reset, style.accent, style.bold, text, style.reset, style.dim });+ try w.print(" · {s}{s}{s}{s}{s}{s}", .{ style.reset, style.accent, style.bold, text, style.reset, style.muted });+}++fn metadataPrefix(w: *Io.Writer, first: *bool, gap: usize) !void {+ if (first.* and gap > 0) {+ for (0..gap) |_| try w.writeByte(' ');+ } else {+ try w.writeAll(" · ");+ }+ first.* = false;}fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {@@ -99,8 +108,11 @@ fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {// Reuse the blank separator row, not another panel or an editor border.// Leave a column free so the rule never triggers terminal autowrap.if (style.accent.len > 0 and cols > 1) {- try w.writeAll(style.dim);- for (0..cols - 1) |_| try w.writeAll("─");+ const lead = @min(@as(usize, 3), cols - 1);+ try w.writeAll(style.accent);+ for (0..lead) |_| try w.writeAll("─");+ try w.print("{s}{s}", .{ style.reset, style.faint });+ for (lead..cols - 1) |_| try w.writeAll("─");try w.writeAll(style.reset);}try w.writeByte('\n');@@ -148,6 +160,7 @@ fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {const show_plan = st.plan and fitsSegment(&used, avail, 3 + "Plan".len);const show_strict = st.strict and fitsSegment(&used, avail, 3 + "Strict".len);const show_ultra = st.ultracode and fitsSegment(&used, avail, 3 + "Ultracode".len);+ const identity_width = used;const show_cwd = folder.len > 0 and fitsSegment(&used, avail, 3 + 2 + folder.len);const show_ctx = ctx.len > 0 and fitsSegment(&used, avail, 3 + ctx.len);const show_cache = show_ctx and cache.len > 0 and fitsSegment(&used, avail, 3 + cache.len);@@ -157,20 +170,39 @@ fn line(w: *Io.Writer, st: PromptStatus, cols: usize) !void {const show_session = st.standing.session.len > 0 andfitsSegment(&used, avail, 3 + st.standing.session.len);- try w.print("{s}{s}{s}{s}{s}", .{ style.bold, style.accent, st.model, style.reset, style.dim });+ try w.print("{s}{s}{s}{s}{s}", .{ style.bold, style.accent, st.model, style.reset, style.muted });if (show_fast) try modeSegment(w, "Fast");if (show_effort) try w.print(" · {s}", .{reasoningLabel(st.effort.?)});if (show_fallback) try modeSegment(w, "Fallback");if (show_plan) try modeSegment(w, "Plan");if (show_strict) try modeSegment(w, "Strict");if (show_ultra) try modeSegment(w, "Ultracode");- if (show_cwd) try w.print(" · ~/{s}", .{folder});- if (show_ctx) try w.print(" · {s}", .{ctx});- if (show_cache) try w.print(" · {s}", .{cache});- if (show_cost) try w.print(" · {s}", .{cost});- if (show_resume) try w.print(" · {s}", .{resume_hint});- if (show_image) try w.print(" · image", .{});- if (show_session) try w.print(" · {s}", .{st.standing.session});+ // Keep the active seat on the left and quiet metadata on the right.+ // The first metadata separator becomes whitespace, not another badge.+ // Byte-based budgets remain conservative for non-ASCII labels; plain+ // terminals retain their exact compact, unpadded transcript.+ const gap = if (style.accent.len > 0 and used > identity_width)+ avail -| (used - 3)+ else+ 0;+ var first_metadata = true;+ if (show_cwd) {+ try metadataPrefix(w, &first_metadata, gap);+ try w.print("~/{s}", .{folder});+ }+ const Metadata = struct { show: bool, text: []const u8 };+ for ([_]Metadata{+ .{ .show = show_ctx, .text = ctx },+ .{ .show = show_cache, .text = cache },+ .{ .show = show_cost, .text = cost },+ .{ .show = show_resume, .text = resume_hint },+ .{ .show = show_image, .text = "image" },+ .{ .show = show_session, .text = st.standing.session },+ }) |segment| {+ if (!segment.show) continue;+ try metadataPrefix(w, &first_metadata, gap);+ try w.writeAll(segment.text);+ }try w.print("{s}\n{s}{s}›{s} ", .{ style.reset, style.bold, style.accent, style.reset });try w.flush();}@@ -460,6 +492,9 @@ test "terminal chrome bounds its divider and separates identity from metadata" {const text = aw.written();const end = std.mem.indexOfScalar(u8, text, '\n').?;try std.testing.expectEqual(cols - 1, std.mem.count(u8, text[0..end], "─"));+ if (cols >= 4) try std.testing.expect(std.mem.startsWith(u8, text, "\x1b[38;2;5;150;105m───\x1b[0m\x1b[2m"));+ try std.testing.expect(std.mem.indexOf(u8, text, " · ~/w") == null);+ if (cols == 18) try std.testing.expect(std.mem.indexOf(u8, text, " ~/w\x1b[0m\n") != null);try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[1m\x1b[38;2;5;150;105mm\x1b[0m\x1b[2m") != null);try std.testing.expect(std.mem.endsWith(u8, text, "\n\x1b[1m\x1b[38;2;5;150;105m›\x1b[0m "));}diff --git a/src/agent_render.zig b/src/agent_render.zigindex 7bf79740..237dbded 100644--- a/src/agent_render.zig+++ b/src/agent_render.zig@@ -69,7 +69,7 @@ pub fn atLineStart(self: *const Agent) bool {pub const MdKind = enum { classify, hold, prose, header, fenced, pre };-pub const MdSpan = enum { normal, star, bold_empty, bold, bold_star, code };+pub const MdSpan = @import("agent_markdown_inline.zig").State;const TaskItem = struct { checked: bool, text: []const u8 };@@ -252,53 +252,7 @@ pub fn mdStartProse(self: *Agent, w: *Io.Writer) void {/// styling on as soon as it's seen instead of waiting for the closer./// Literal bytes route through mdWrapByte (terminal-width word wrap);/// style sequences through mdStyle (zero-width, ordered with the word).-pub fn mdSpanByte(self: *Agent, w: *Io.Writer, b: u8) void {- switch (self.md_span) {- .normal => switch (b) {- '*' => {- if (markdown_url.containsHttp(self.md_word.items))- self.mdWrapByte(w, b)- else- self.md_span = .star;- },- '`' => {- self.mdStyle(w, style.yellow);- self.md_span = .code;- },- else => self.mdWrapByte(w, b),- },- .star => if (b == '*') {- self.mdStyle(w, style.bold);- self.md_span = .bold_empty;- } else {- self.mdWrapByte(w, '*'); // lone star is literal- self.md_span = .normal;- self.mdSpanByte(w, b);- },- .bold_empty => if (b == '*') {- self.md_span = .bold_star;- } else {- self.md_span = .bold;- self.mdSpanByte(w, b);- },- .bold => switch (b) {- '*' => self.md_span = .bold_star,- else => self.mdWrapByte(w, b),- },- .bold_star => if (b == '*') {- self.mdStyle(w, style.reset);- self.md_span = .normal;- } else {- self.mdWrapByte(w, '*');- self.md_span = .bold;- self.mdSpanByte(w, b);- },- .code => if (b == '`') {- self.mdStyle(w, style.reset);- self.md_span = .normal;- } else self.mdWrapByte(w, b),- }-}+pub const mdSpanByte = @import("agent_markdown_inline.zig").byte;/// Terminal-width word wrap for streamed prose. Literal bytes buffer/// into the current word; a space flushes it — and a word that would@@ -363,27 +317,7 @@ pub fn mdWidth(self: *Agent) usize {/// Settle the span machine at line end: pending markers print literally,/// open spans close their styling.-pub fn mdSpanEnd(self: *Agent, w: *Io.Writer) void {- if (self.md_span == .star) {- self.mdWrapByte(w, '*');- self.md_span = .normal;- }- self.mdFlushWord(w);- switch (self.md_span) {- .normal => {},- .star => unreachable,- .bold_empty => {- w.writeAll(style.reset) catch {};- w.writeAll("**") catch {};- },- .bold, .code => w.writeAll(style.reset) catch {},- .bold_star => {- w.writeByte('*') catch {};- w.writeAll(style.reset) catch {};- },- }- self.md_span = .normal;-}+pub const mdSpanEnd = @import("agent_markdown_inline.zig").finish;/// End of line (newline or stream end): render anything still held,/// settle styling, and reset the per-line state. Returns false when the@@ -447,8 +381,8 @@ pub fn flushStreamTail(self: *Agent) void {/// Render one markdown line to ANSI (portable SGR only — bold/color, no/// italic, so iTerm/Ghostty/Terminal/Windows-Terminal all agree): code-/// fences + fenced bodies dimmed, ATX headers bold-emerald, `-`/`*`/`+`-/// bullets → emerald •, and inline `**bold**` / `` `code` `` spans.+/// fences + fenced bodies dimmed, ATX headers accented, `-`/`*`/`+`+/// bullets → accented •, with inline emphasis, bold and code spans.pub fn renderMdLine(self: *Agent, w: *Io.Writer, line: []const u8) void {var lead: usize = 0;while (lead < line.len and line[lead] == ' ') lead += 1;@@ -546,42 +480,7 @@ pub fn isRule(body: []const u8) bool {/// Emit a line with inline `**bold**` and `` `code` `` spans styled; the/// markers themselves are dropped. Unmatched markers print literally.-pub fn renderInline(w: *Io.Writer, s: []const u8) void {- var i: usize = 0;- while (i < s.len) {- if (s[i] == '*' or s[i] == '_' or s[i] == '~' or s[i] == '`' or s[i] == 'h') {- var token_end = i;- while (token_end < s.len and s[token_end] != ' ') token_end += 1;- if (markdown_url.unwrapToken(s[i..token_end])) |match| {- w.writeAll(match.url) catch {};- w.writeAll(match.suffix) catch {};- i = token_end;- continue;- }- if (std.mem.startsWith(u8, s[i..], "http://") or std.mem.startsWith(u8, s[i..], "https://")) {- w.writeAll(s[i..token_end]) catch {};- i = token_end;- continue;- }- }- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {- w.print("{s}{s}{s}", .{ style.bold, s[i + 2 .. end], style.reset }) catch {};- i = end + 2;- continue;- }- }- if (s[i] == '`') {- if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {- w.print("{s}{s}{s}", .{ style.yellow, s[i + 1 .. end], style.reset }) catch {};- i = end + 1;- continue;- }- }- w.writeByte(s[i]) catch {};- i += 1;- }-}+pub const renderInline = @import("agent_markdown_inline.zig").render;test "codepointCount: counts UTF-8 codepoints, not bytes" {try std.testing.expectEqual(@as(usize, 5), codepointCount("hello"));diff --git a/src/agent_working.zig b/src/agent_working.zigindex a1a2e702..e51d02b9 100644--- a/src/agent_working.zig+++ b/src/agent_working.zig@@ -33,17 +33,20 @@ pub fn write(w: *Io.Writer, title: []const u8, items: []const Item) void {for (items) |it| {if (it.done) done += 1;}- w.print("{s}WORKING{s} {s}{s}{s}", .{ style.dim, style.reset, style.bold, shown, style.reset }) catch return;- if (items.len > 0) w.print(" {s}{d}/{d}{s}", .{ style.dim, done, items.len, style.reset }) catch return;+ w.print("{s}WORKING{s} {s}{s}{s}{s}", .{ style.muted, style.reset, style.bold, style.text, shown, style.reset }) catch return;+ if (items.len > 0) w.print(" {s}{d}/{d}{s}", .{ style.muted, done, items.len, style.reset }) catch return;w.writeByte('\n') catch return;const n = @min(items.len, max_items);for (items[0..n], 0..) |it, i| {const branch: []const u8 = if (i + 1 == n) "└ " else "├ ";- const mark: []const u8 = if (it.done) "✓" else if (it.active) "◌" else "○";- const color = if (it.done) style.dim else if (it.active) style.accent else "";+ const mark: []const u8 = if (it.done) "✓" else if (it.active)+ (if (style.accent.len > 0) "●" else "◌")+ else+ "○";+ const color = if (it.active and !it.done) style.accent else style.muted;const weight = if (it.active and !it.done) style.bold else "";w.print("{s}{s}{s}{s}{s}{s} {s}{s}\n", .{- style.dim, branch, style.reset, color, weight, mark, clip(it.content, item_clip), style.reset,+ style.faint, branch, style.reset, color, weight, mark, clip(it.content, item_clip), style.reset,}) catch return;}}@@ -67,7 +70,7 @@ pub fn writeFromStanding(w: *Io.Writer, st: engine_events.StandingWork) void {fn writeWaiting(w: *Io.Writer, waiting: []const u8) void {if (waiting.len == 0) return;w.print("{s}↻{s}{s} waiting on {s} — graff continues when it finishes{s}\n", .{- style.accent, style.reset, style.dim, waiting, style.reset,+ style.accent, style.reset, style.muted, waiting, style.reset,}) catch return;}@@ -118,7 +121,7 @@ test "completed checklist stays out of idle prompt redraws" {test "terminal working block highlights active work without hiding waiting" {const saved = style.*;- style.* = @import("ansi.zig").Style.ansi;+ style.* = @import("ansi.zig").Style.harness;defer style.* = saved;var aw: Io.Writer.Allocating = .init(std.testing.allocator);defer aw.deinit();@@ -129,9 +132,9 @@ test "terminal working block highlights active work without hiding waiting" {};writeFromStanding(&aw.writer, .{ .goal = "ship it", .todos = &items, .todos_done = 1, .todos_total = 3, .waiting = "agent 4" });const text = aw.written();- try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[2m✓ finished\x1b[0m") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[38;2;5;150;105m\x1b[1m◌ current\x1b[0m") != null);- try std.testing.expect(std.mem.indexOf(u8, text, "○ next") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[38;2;154;147;132m✓ finished\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[38;2;232;163;61m\x1b[1m● current\x1b[0m") != null);+ try std.testing.expect(std.mem.indexOf(u8, text, "\x1b[38;2;154;147;132m○ next\x1b[0m") != null);try std.testing.expect(std.mem.indexOf(u8, text, "waiting on agent 4 — graff continues when it finishes") != null);}diff --git a/src/ansi.zig b/src/ansi.zigindex 087742f6..352be875 100644--- a/src/ansi.zig+++ b/src/ansi.zig@@ -3,7 +3,7 @@//! on std only, so any UI module can import it without pulling in main.zig.//!//! `style` starts blank (every field an empty string, so styled writes emit no-//! bytes) and main flips it to `Style.ansi` once it confirms stdout is a TTY+//! bytes) and main selects a palette once it confirms stdout is a TTY//! with color enabled. First of the shared leaves split out of main.zig (#123).const std = @import("std");@@ -12,10 +12,11 @@ pub const Style = struct {reset: []const u8 = "",dim: []const u8 = "",bold: []const u8 = "",- /// Codegraff's identity color: the emerald accent from codegraff.com- /// (--accent: #059669). Keep this separate from status colors so the- /// accent always means "active/selected/Codegraff", never implicitly- /// success or error.+ italic: []const u8 = "",+ text: []const u8 = "",+ muted: []const u8 = "",+ faint: []const u8 = "",+ /// Identity/selection color, separate from success and error colors.accent: []const u8 = "",red: []const u8 = "",green: []const u8 = "",@@ -27,6 +28,9 @@ pub const Style = struct {.reset = "\x1b[0m",.dim = "\x1b[2m",.bold = "\x1b[1m",+ .italic = "\x1b[3m",+ .muted = "\x1b[2m",+ .faint = "\x1b[2m",// #059669 is the site's --accent token: 5.6:1 on pure-black and 3.8:1// on pure-white terminal backgrounds, and it no longer reads as the// error red users mistook the old coral for.@@ -37,10 +41,27 @@ pub const Style = struct {.magenta = "\x1b[35m",.cyan = "\x1b[36m",};++ /// Harness Codegraff Dark foreground tokens; never changes the background.+ pub const harness: Style = .{+ .reset = "\x1b[0m",+ .dim = "\x1b[2m",+ .bold = "\x1b[1m",+ .italic = "\x1b[3m",+ .text = "\x1b[38;2;237;234;226m", // #edeae2+ .muted = "\x1b[38;2;154;147;132m", // #9a9384+ .faint = "\x1b[38;2;92;86;75m", // #5c564b+ .accent = "\x1b[38;2;232;163;61m", // #e8a33d+ .red = "\x1b[38;2;210;103;79m", // #d2674f+ .green = "\x1b[38;2;127;168;107m", // #7fa86b+ .yellow = "\x1b[38;2;217;164;65m", // #d9a441+ .magenta = "\x1b[38;2;189;128;228m", // #bd80e4+ .cyan = "\x1b[38;2;127;168;107m", // #7fa86b+ };};/// The active palette. Blank by default (color off); main sets it to-/// `Style.ansi` at startup when the terminal supports color. Modules read it+/// a color palette at startup when the terminal supports color. Modules read it/// via a `const style = &term.style;` alias so field access auto-derefs.pub var style: Style = .{};@@ -49,6 +70,9 @@ test "Style: blank by default, ansi has escape codes" {try std.testing.expectEqualStrings("", blank.reset);try std.testing.expectEqualStrings("", blank.bold);try std.testing.expectEqualStrings("", blank.accent);+ try std.testing.expectEqualStrings("", blank.text);+ try std.testing.expectEqualStrings("", blank.muted);+ try std.testing.expectEqualStrings("", blank.faint);try std.testing.expectEqualStrings("\x1b[0m", Style.ansi.reset);try std.testing.expectEqualStrings("\x1b[1m", Style.ansi.bold);try std.testing.expectEqualStrings("\x1b[38;2;5;150;105m", Style.ansi.accent);@@ -56,6 +80,32 @@ test "Style: blank by default, ansi has escape codes" {try std.testing.expectEqualStrings("\x1b[36m", Style.ansi.cyan);}+test "terminal chrome uses the Harness Codegraff Dark palette" {+ const blank = Style{};+ for ([_][]const u8{+ blank.reset, blank.dim, blank.bold, blank.text, blank.muted, blank.faint,+ blank.accent, blank.red, blank.green, blank.yellow, blank.magenta, blank.cyan,+ }) |sequence| try std.testing.expectEqualStrings("", sequence);+ try std.testing.expectEqualStrings("", blank.italic);+ const palette = Style.harness;+ try std.testing.expectEqualStrings("\x1b[3m", palette.italic);+ try std.testing.expectEqualStrings("\x1b[0m", palette.reset);+ try std.testing.expectEqualStrings("\x1b[1m", palette.bold);+ try std.testing.expectEqualStrings("\x1b[2m", palette.dim);+ try std.testing.expectEqualStrings("\x1b[38;2;237;234;226m", palette.text);+ try std.testing.expectEqualStrings("\x1b[38;2;154;147;132m", palette.muted);+ try std.testing.expectEqualStrings("\x1b[38;2;92;86;75m", palette.faint);+ try std.testing.expectEqualStrings("\x1b[38;2;232;163;61m", palette.accent);+ try std.testing.expectEqualStrings("\x1b[38;2;210;103;79m", palette.red);+ try std.testing.expectEqualStrings("\x1b[38;2;127;168;107m", palette.green);+ try std.testing.expectEqualStrings("\x1b[38;2;217;164;65m", palette.yellow);+ try std.testing.expectEqualStrings("\x1b[38;2;189;128;228m", palette.magenta);+ try std.testing.expectEqualStrings("\x1b[38;2;127;168;107m", palette.cyan);+ try std.testing.expectEqualStrings("", Style.ansi.text);+ try std.testing.expectEqualStrings(Style.ansi.dim, Style.ansi.muted);+ try std.testing.expectEqualStrings(Style.ansi.dim, Style.ansi.faint);+}+test "style global starts blank so styled writes emit nothing until enabled" {// Fresh-process default: no color. (Other tests may flip it; assert fields// are well-formed rather than a specific value to stay order-independent.)diff --git a/src/cards.zig b/src/cards.zigindex dd4a0a3f..83c1352a 100644--- a/src/cards.zig+++ b/src/cards.zig@@ -1,4 +1,4 @@-//! Subagent cards (#51): launch/done one-liners (`↯ scout` / `✓ scout`) and+//! Subagent cards (#51): launch/done one-liners (`● Agent` / `✓ Agent`) and//! the inspect-report writer (`.graff/subagents/<id>.md`). The sa- id is not//! foreground UI (ADR 0021). Split out of main.zig (600-line goal).@@ -60,7 +60,7 @@ pub fn subagentId(buf: []u8, ordinal: u32, label: []const u8, prompt: []const u8return std.fmt.bufPrint(buf, "sa-{d:0>3}-{s}", .{ ordinal, hex }) catch buf[0..0];}-/// One-line launch: `↯ scout {label}`. The sa- id and the boxed prompt are+/// One-line launch: `● Agent {label} /workers`. The sa- id and prompt are/// not foreground UI (ADR 0021); `/debug` still names the id.pub fn subagentLaunchCard(arena: Allocator, id: []const u8, sprite: []const u8, label: []const u8, kind: []const u8, activity: []const u8) void {_ = sprite;@@ -69,16 +69,16 @@ pub fn subagentLaunchCard(arena: Allocator, id: []const u8, sprite: []const u8,if (root.json_mode) return;var aw: Io.Writer.Allocating = .init(arena);const w = &aw.writer;- const shown = collapseWs(label);+ const shown = collapseWs(@import("line_repl_disclosure.zig").sanitized(arena, label) catch "Agent");if (@import("repl.zig").g_debug) {- w.print(" {s}↯ scout{s} {s}{s}{s} [{s}]\n", .{ style.dim, style.reset, style.bold, shown, style.reset, id }) catch return;+ w.print(" {s}● Agent{s} {s}{s}{s} [{s}]\n", .{ style.accent, style.reset, style.bold, shown, style.reset, id }) catch return;} else {- w.print(" {s}↯ scout{s} {s}{s}{s}\n", .{ style.dim, style.reset, style.bold, shown, style.reset }) catch return;+ w.print(" {s}● Agent{s} {s}{s}{s} {s}/workers{s}\n", .{ style.accent, style.reset, style.bold, shown, style.reset, style.muted, style.reset }) catch return;}tick_gate.workerLine(aw.writer.buffered());}-/// One-line settle: `✓ scout {label}` (or ✗). Cache hit rides when the+/// One-line settle: `✓ Agent {label}` (or ✗). Cache hit rides when the/// worker reported usage (ADR 0018 for scouts). Elapsed/tools/inspect path/// stay in `.graff/subagents/<id>.md`.pub fn subagentDoneCard(@@ -100,10 +100,10 @@ pub fn subagentDoneCard(if (root.json_mode) return;var aw: Io.Writer.Allocating = .init(arena);const w = &aw.writer;- const shown = collapseWs(label);+ const shown = collapseWs(@import("line_repl_disclosure.zig").sanitized(arena, label) catch "Agent");const mark: []const u8 = if (ok) "✓" else "✗";const mc: []const u8 = if (ok) style.green else style.red;- w.print(" {s}{s} scout{s} {s}", .{ mc, mark, style.reset, shown }) catch return;+ w.print(" {s}{s} Agent{s} {s}", .{ mc, mark, style.reset, shown }) catch return;if (context_tokens > 0) {const pct = @min((cache_read *| 100) / context_tokens, 100);w.print(" {s}cache {d}%{s}", .{ style.dim, pct, style.reset }) catch return;diff --git a/src/command_catalog.zig b/src/command_catalog.zigindex f5c106d7..19a28742 100644--- a/src/command_catalog.zig+++ b/src/command_catalog.zig@@ -94,6 +94,7 @@ pub const commands = [_]Item{.{ .name = "/trajectory", .desc = "show this session's agent tree — turns + spawned subagents" },.{ .name = "/issue", .usage = "/issue <what went wrong>", .desc = "file one sanitized public tracker issue from this session" },.{ .name = "/agents", .desc = "list agent types — builtin personas + .harness/agents" },+ .{ .name = "/workers", .usage = "/workers [child-id]", .desc = "inspect this session's subagents: click/Enter for live activity and reports, Esc to return" },.{ .name = "/skills", .usage = "/skills [add|remove <name>]", .desc = "list SKILL.md playbooks + companion tools; add/remove enables or disables one" },.{ .name = "/plugins", .usage = "/plugins [list|load <name>]", .desc = "list Claude/Cursor/Grok/Codex plugin trees graff is reading in place; load names one" },.{ .name = "/hooks", .desc = "list lifecycle hooks and the built-in codedb guard" },diff --git a/src/commands_misc.zig b/src/commands_misc.zigindex 09e0ff6d..846099b4 100644--- a/src/commands_misc.zig+++ b/src/commands_misc.zig@@ -162,6 +162,7 @@ fn ownedSessionName(arena: Allocator, arg: []const u8, fallback: []const u8) Allpub fn tryHandle(root: *Agent, keys: *Keys, arena: Allocator, line: []const u8, out: *Io.Writer) !bool {if (try @import("adopt.zig").trySlash(root.io, arena, root.home, line, out)) return true;if (try commands_privacy.tryHandle(root, line, out)) return true;+ if (try @import("terminal_workers.zig").tryHandle(root, line, out)) return true;if (try playbook_glue.command(root, arena, line, out)) return true; // #381 /never | /constraintif (std.mem.startsWith(u8, line, "/schedule") and (line.len == 9 or line[9] == ' ' or line[9] == '\t')) return @import("schedule.zig").slashCommand(root, arena, line, out);if (std.mem.startsWith(u8, line, "/adapter") and (line.len == 8 or line[8] == ' ' or line[8] == '\t')) return @import("channel_worker.zig").slashCommand(root, arena, line, out);diff --git a/src/input_util.zig b/src/input_util.zigindex d812912e..50201e37 100644--- a/src/input_util.zig+++ b/src/input_util.zig@@ -371,7 +371,8 @@ pub fn redraw(o: *Io.Writer, items: []const u8, c: usize, marks: []const []consto.writeAll("\x1b[0m") catch {};shine_active = false;}- o.writeAll(if (main_mod.use_color) "\x1b[7;38;2;5;150;105m" else "\x1b[7m") catch {};+ if (main_mod.use_color) o.writeAll(@import("ansi.zig").style.accent) catch {};+ o.writeAll("\x1b[7m") catch {};mark_end = best_end;mark_open = true;}diff --git a/src/line_repl_disclosure.zig b/src/line_repl_disclosure.zigindex ffaae368..3dd48522 100644--- a/src/line_repl_disclosure.zig+++ b/src/line_repl_disclosure.zig@@ -95,7 +95,7 @@ fn skipEscape(text: []const u8, start: usize) usize {/// Raw means uninterpreted, not unsafe: terminal controls and invalid UTF-8/// never get a chance to repaint the user's terminal.-fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {+pub fn sanitized(alloc: std.mem.Allocator, text: []const u8) ![]u8 {var out = std.array_list.Managed(u8).init(alloc);errdefer out.deinit();var i: usize = 0;diff --git a/src/main.zig b/src/main.zigindex 736edcda..64eac159 100644--- a/src/main.zig+++ b/src/main.zig@@ -57,7 +57,7 @@ test {_ = @import("codex_node_repl.zig");_ = pricing;_ = models_cache;- _ = ansi;+ _ = .{ ansi, @import("agent_markdown_inline.zig"), @import("terminal_workers_tests.zig") };_ = serve;_ = .{ @import("json_inbox.zig"), @import("acp_inbox.zig"), @import("cite_markup.zig"), @import("server_diagnostics.zig"), @import("server_discovery.zig"), @import("job_browser_guard.zig"), @import("preview_consumers.zig"), @import("plan_usage.zig"), @import("server_port.zig"), @import("job_registry_stop_tests.zig") };_ = util;diff --git a/src/markdown_url.zig b/src/markdown_url.zigindex 2252449a..5fddabe9 100644--- a/src/markdown_url.zig+++ b/src/markdown_url.zig@@ -57,6 +57,27 @@ pub fn containsHttp(value: []const u8) bool {return std.mem.indexOf(u8, value, "http://") != null or std.mem.indexOf(u8, value, "https://") != null;}+pub const Emphasis = struct { start: usize, end: usize, after: usize, strong: bool };++/// Balanced inline emphasis; underscores inside identifiers stay literal.+pub fn emphasisAt(s: []const u8, i: usize) ?Emphasis {+ if (i >= s.len or (s[i] != '*' and s[i] != '_')) return null;+ if (s[i] == '_' and i > 0 and (std.ascii.isAlphanumeric(s[i - 1]) or s[i - 1] == '_')) return null;+ const n: usize = if (i + 1 < s.len and s[i + 1] == s[i]) 2 else 1;+ const start = i + n;+ if (start >= s.len or std.ascii.isWhitespace(s[start])) return null;+ var pos = start;+ while (std.mem.indexOfPos(u8, s, pos, s[i..start])) |end| {+ if (end > start and s[end - 1] != '\\' and !std.ascii.isWhitespace(s[end - 1])) {+ const after = end + n;+ if (s[i] != '_' or after == s.len or !std.ascii.isAlphanumeric(s[after]))+ return .{ .start = start, .end = end, .after = after, .strong = n == 2 };+ }+ pos = end + n;+ }+ return null;+}+pub fn codepointCount(s: []const u8) usize {var count: usize = 0;for (s) |b| {@@ -83,12 +104,15 @@ pub fn inlineVisibleLen(s: []const u8) usize {continue;}}- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {- count += codepointCount(s[i + 2 .. end]);- i = end + 2;- continue;- }+ if (s[i] == '\\' and i + 1 < s.len and std.mem.indexOfScalar(u8, "*_`\\[]()#~", s[i + 1]) != null) {+ count += 1;+ i += 2;+ continue;+ }+ if (emphasisAt(s, i)) |span| {+ count += codepointCount(s[span.start..span.end]);+ i = span.after;+ continue;}if (s[i] == '`') {if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {diff --git a/src/readline_commit.zig b/src/readline_commit.zigindex d277b2b0..95e49c72 100644--- a/src/readline_commit.zig+++ b/src/readline_commit.zig@@ -42,7 +42,8 @@ pub fn commit(out: *Io.Writer, items: []const u8, marks: []const []const u8, pasif (store.highlightEndAt(items, i)) |end| best_end = @max(best_end, end);}if (best_end > i) {- out.writeAll(if (use_color) "\x1b[7;38;2;5;150;105m" else "\x1b[7m") catch {};+ if (use_color) out.writeAll(@import("ansi.zig").style.accent) catch {};+ out.writeAll("\x1b[7m") catch {};mark_end = best_end;mark_open = true;}diff --git a/src/repl_markdown.zig b/src/repl_markdown.zigindex e9cf1ad8..aeb61eb8 100644--- a/src/repl_markdown.zig+++ b/src/repl_markdown.zig@@ -150,7 +150,7 @@ fn plainInline(a: std.mem.Allocator, line: []const u8) ![]const u8 {/// covers the ranges that misalign TUI table borders (CJK, Hangul, kana,/// fullwidth forms, common emoji planes). Emoji-presentation via a VS16 (U+FE0F)/// on a text-default base is not width-promoted. ASCII/Latin-1 skip the table.-fn codepointWidth(cp: u21) usize {+pub fn codepointWidth(cp: u21) usize {if (cp < 0x300) return 1; // ASCII + Latin-1 (control bytes stay 1, as before)if ((cp >= 0x300 and cp <= 0x36F) or // combining diacritical marks(cp >= 0x200B and cp <= 0x200F) or // ZWSP..RLMdiff --git a/src/session_render.zig b/src/session_render.zigindex d47ec938..38475e23 100644--- a/src/session_render.zig+++ b/src/session_render.zig@@ -35,7 +35,7 @@ const autocommit_suffix = " · auto-committing each turn (`graff worktree merge`/// state, so the engine says only that color exists and this decides what it/// looks like. Reached through engine_sink.enableColor.pub fn enableColor() void {- ansi.style = ansi.Style.ansi;+ ansi.style = ansi.Style.harness;}/// Draw one lifecycle event, or nothing when the moment belongs to anotherdiff --git a/src/session_settings.zig b/src/session_settings.zigindex 6f18a064..530b881a 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -363,6 +363,7 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:\\## Gaps\\- No bot-specific route tests exist.\\- Pin `install.sh` and verify its checksum.+ \\- Emphasis: *Coding agents / harnesses*, _readable_, __strong__, foo_bar.\\\\## Recommended implementation order\\1. **Immediately:** require collaborator permission.diff --git a/src/term.zig b/src/term.zigindex a32e2062..d1ae32dd 100644--- a/src/term.zig+++ b/src/term.zig@@ -261,6 +261,11 @@ pub const tty = struct {return n > 0;}+ /// Picker/inspector readiness includes bytes already queued by the editor.+ pub fn pollPrompt(in: *std.Io.Reader, timeout_ms: i32) bool {+ return queued_pos < queued_len or in.buffered().len > 0 or poll(timeout_ms);+ }+/// Non-blocking read of pending raw stdin bytes (terminal already in raw/// mode); returns the byte count. On Windows it drains queued console/// records and emits the ASCII byte of each key-down (Esc->0x1b,diff --git a/src/terminal_workers.zig b/src/terminal_workers.zignew file mode 100644index 00000000..f8de9353--- /dev/null+++ b/src/terminal_workers.zig@@ -0,0 +1,371 @@+//! Read-only, mouse-enabled inspection of this process's existing child feed.+const std = @import("std");+const Io = std.Io;+const A = std.mem.Allocator;+const Agent = @import("agent.zig").Agent;+const activity = @import("subagent_activity.zig");+const ansi = @import("ansi.zig");+const style = &ansi.style;+const term = @import("term.zig");+const safe = @import("line_repl_disclosure.zig").sanitized;+const cellWidth = @import("repl_markdown.zig").codepointWidth;++pub const Point = struct { x: usize, y: usize };+pub const Action = union(enum) { none, up, down, select, back, quit, tools, thoughts, refresh, click: Point };++pub const Keys = struct {+ bytes: [64]u8 = undefined,+ len: usize = 0,+ pub fn feed(self: *Keys, b: u8) Action {+ if (self.len == 0) {+ return switch (b) {+ 0x1b => blk: {+ self.bytes[0] = b;+ self.len = 1;+ break :blk .none;+ },+ '\r', '\n' => .select,+ 0x03, 'q' => .quit,+ 0x7f, 0x08 => .back,+ 'k' => .up,+ 'j' => .down,+ 't' => .tools,+ 'h' => .thoughts,+ 'r' => .refresh,+ else => .none,+ };+ }+ if (self.len == self.bytes.len) {+ self.len = 0;+ return .none;+ }+ self.bytes[self.len] = b;+ self.len += 1;+ if (self.len == 2) {+ if (b != '[') {+ self.len = 0;+ return .back;+ }+ return .none;+ }+ if (b < 0x40 or b > 0x7e) return .none;+ const packet = self.bytes[0..self.len];+ self.len = 0;+ if (std.mem.eql(u8, packet, "\x1b[A")) return .up;+ if (std.mem.eql(u8, packet, "\x1b[B")) return .down;+ if (std.mem.startsWith(u8, packet, "\x1b[<") and (b == 'M' or b == 'm')) {+ var parts = std.mem.splitScalar(u8, packet[3 .. packet.len - 1], ';');+ const button = std.fmt.parseInt(u16, parts.next() orelse "", 10) catch return .none;+ const x = std.fmt.parseInt(u16, parts.next() orelse "", 10) catch return .none;+ const y = std.fmt.parseInt(u16, parts.next() orelse "", 10) catch return .none;+ if (parts.next() != null or x == 0 or y == 0 or b == 'm') return .none;+ if (button == 64) return .up;+ if (button == 65) return .down;+ if (button & 3 == 0 and button & 64 == 0) return .{ .click = .{ .x = x, .y = y } };+ }+ if (b == 'u') {+ const end = std.mem.indexOfScalar(u8, packet, ';') orelse packet.len - 1;+ const code = std.fmt.parseInt(u32, packet[2..end], 10) catch return .none;+ return switch (code) {+ 13 => .select,+ 27 => .back,+ 113 => .quit,+ else => .none,+ };+ }+ return .none;+ }+ pub fn expire(self: *Keys) Action {+ const escape = self.len == 1;+ self.len = 0;+ return if (escape) .back else .none;+ }+};++pub fn snapshot(a: A, io: Io, dir: Io.Dir, id: []const u8) !activity.Snapshot {+ if (!activity.validId(id)) return error.InvalidChildId;+ const name = try std.fmt.allocPrint(a, "{s}.json", .{id});+ const bytes = try dir.readFileAlloc(io, name, a, .limited(activity.file_limit));+ const result = try std.json.parseFromSliceLeaky(activity.Snapshot, a, bytes, .{ .ignore_unknown_fields = true });+ if (!std.mem.eql(u8, result.agent.id, id) or result.events.len > activity.max_events) return error.InvalidChildSnapshot;+ return result;+}++fn oneLine(a: A, text: []const u8) ![]const u8 {+ const cleaned = try safe(a, text);+ for (cleaned) |*b| if (b.* == '\n' or b.* == '\t') {+ b.* = ' ';+ };+ return cleaned;+}++fn statusColor(status: []const u8) []const u8 {+ if (std.mem.eql(u8, status, "failed")) return style.red;+ if (std.mem.eql(u8, status, "completed")) return style.green;+ return style.accent;+}+fn mark(status: []const u8) []const u8 {+ if (std.mem.eql(u8, status, "failed")) return "✗";+ if (std.mem.eql(u8, status, "completed")) return "✓";+ return "●";+}++/// Styled bytes are ours; untrusted snapshot strings are sanitized first.+fn advance(text: []const u8, i: usize) usize {+ if (text[i] == 0x1b and i + 1 < text.len and text[i + 1] == '[') {+ var end = i + 2;+ while (end < text.len) : (end += 1) if (text[end] >= 0x40 and text[end] <= 0x7e) return end + 1;+ return text.len;+ }+ return @min(text.len, i + (std.unicode.utf8ByteSequenceLength(text[i]) catch 1));+}+fn width(text: []const u8, i: usize, end: usize) usize {+ if (text[i] == 0x1b) return 0;+ return cellWidth(std.unicode.utf8Decode(text[i..end]) catch '?');+}+fn clipped(out: *Io.Writer, text: []const u8, cols: usize) !void {+ var i: usize = 0;+ var used: usize = 0;+ while (i < text.len) {+ const end = advance(text, i);+ const n = width(text, i, end);+ if (used + n > cols) break;+ try out.writeAll(text[i..end]);+ used += n;+ i = end;+ }+ try out.writeAll(style.reset);+}++pub fn wrap(a: A, text: []const u8, cols: usize) ![][]const u8 {+ var result: std.ArrayList([]const u8) = .empty;+ var lines = std.mem.splitScalar(u8, text, '\n');+ while (lines.next()) |line| {+ var start: usize = 0;+ var i: usize = 0;+ var used: usize = 0;+ var space: ?usize = null;+ while (i < line.len) {+ const end = advance(line, i);+ const n = width(line, i, end);+ if (used + n > @max(cols, 2) and i > start) {+ const cut = if (line[i] == ' ') i else if (space) |s| (if (s > start) s else i) else i;+ try result.append(a, line[start..cut]);+ start = if (cut < line.len and line[cut] == ' ') cut + 1 else cut;+ i = start;+ used = 0;+ space = null;+ continue;+ }+ if (line[i] == ' ') space = i;+ used += n;+ i = end;+ }+ try result.append(a, line[start..]);+ }+ return result.items;+}++fn markdown(root: *Agent, a: A, out: *Io.Writer, text: []const u8) !void {+ const cleaned = try safe(a, text);+ var view = root.*;+ view.md_fence = false;+ var lines = std.mem.splitScalar(u8, cleaned, '\n');+ while (lines.next()) |line| {+ view.renderMdLine(out, line);+ try out.writeByte('\n');+ }+}++pub fn detail(root: *Agent, a: A, child: activity.Snapshot, tools: bool, thoughts: bool) ![]const u8 {+ var buffer: Io.Writer.Allocating = .init(a);+ const out = &buffer.writer;+ try out.print("{s}Task{s}\n", .{ style.bold, style.reset });+ try markdown(root, a, out, child.agent.task);+ try out.print("\n{s}Activity{s}\n", .{ style.bold, style.reset });+ for (child.events) |event| {+ if (std.mem.eql(u8, event.type, "tool_call")) {+ try out.print("{s}↳ {s}{s} {s}\n", .{ style.accent, try safe(a, event.name), style.reset, try safe(a, event.text) });+ } else if (std.mem.eql(u8, event.type, "tool_result")) {+ try out.print("{s}{s} {s}{s}\n", .{ if (event.is_error) style.red else style.muted, if (event.is_error) "✗" else "✓", try safe(a, event.name), style.reset });+ if (tools or event.is_error) try markdown(root, a, out, event.text);+ } else if (std.mem.eql(u8, event.type, "reasoning")) {+ if (thoughts) try markdown(root, a, out, event.text);+ } else if (std.mem.eql(u8, event.type, "text") and child.response.len == 0) {+ try markdown(root, a, out, event.text);+ }+ }+ if (child.response.len > 0) {+ try out.print("\n{s}Report{s}\n", .{ style.bold, style.reset });+ try markdown(root, a, out, child.response);+ }+ if (child.agent.truncated) try out.print("\n{s}Earlier activity omitted (bounded snapshot).{s}\n", .{ style.muted, style.reset });+ return buffer.written();+}++pub fn drawList(a: A, out: *Io.Writer, rows: []const activity.Meta, selected: usize, cols: usize, height: usize) !usize {+ try clipped(out, try std.fmt.allocPrint(a, "{s}{s}Workers{s} {d} recent agents", .{ style.bold, style.accent, style.reset, rows.len }), cols -| 1);+ try out.print("\n{s}", .{style.muted});+ try clipped(out, "Click an agent to inspect its activity", cols -| 1);+ try out.writeAll("\n\n");+ const visible = @max(@as(usize, 1), (height -| 5) / 3);+ const chosen = @min(selected, rows.len -| 1);+ const off = if (chosen >= visible) chosen - visible + 1 else 0;+ for (rows[off..@min(rows.len, off + visible)], off..) |row, index| {+ const title = try std.fmt.allocPrint(a, "{s}{s} {s}{s} {s}{s}{s}", .{ statusColor(row.status), mark(row.status), if (index == selected) style.bold else style.text, try oneLine(a, row.label), style.reset, style.muted, try oneLine(a, row.status) });+ try out.writeAll(if (index == selected) "› " else " ");+ try clipped(out, title, cols -| 3);+ try out.writeAll("\n ");+ const seat = if (row.model.len == 0) "starting" else try oneLine(a, row.model);+ try out.writeAll(style.muted);+ try clipped(out, seat, cols -| 5);+ try out.writeAll("\n\n");+ }+ if (rows.len == 0) try clipped(out, "No subagents yet.", cols -| 1);+ return off;+}++pub fn clickedRow(point: Point, off: usize, total: usize, cols: usize, height: usize) ?usize {+ const visible = @max(@as(usize, 1), (height -| 5) / 3);+ if (point.x == 0 or point.x >= cols or point.y < 4 or point.y >= 4 + visible * 3) return null;+ const index = off + (point.y - 4) / 3;+ return if (index < total) index else null;+}++fn browse(root: *Agent, out: *Io.Writer, dir: Io.Dir, initial: []const u8) !void {+ const input = root.in orelse return;+ const raw = term.tty.enterRaw(true) orelse return;+ defer term.tty.restore(raw);+ const gate = @import("tick_gate.zig");+ gate.hold();+ defer {+ out.writeAll("\x1b[0m\x1b[?1000l\x1b[?1006l\x1b[?25h\x1b[?1049l") catch {};+ out.flush() catch {};+ _ = gate.setLineStart(true);+ }+ try out.writeAll("\x1b[?1049h\x1b[?1000h\x1b[?1006h\x1b[?25l");+ var selected: usize = 0;+ var id_buf: [64]u8 = undefined;+ var id: []const u8 = "";+ if (initial.len > 0) {+ @memcpy(id_buf[0..initial.len], initial);+ id = id_buf[0..initial.len];+ }+ var scroll: usize = 0;+ var tools = false;+ var thoughts = false;+ var keys: Keys = .{};+ var arena = std.heap.ArenaAllocator.init(root.gpa);+ defer arena.deinit();+ while (term.tty.isForeground()) {+ _ = arena.reset(.retain_capacity);+ const a = arena.allocator();+ const cols = term.termCols();+ const height = term.termRows();+ const rows = try @import("acp_agent_activity.zig").list(a, root.io, dir);+ selected = @min(selected, rows.len -| 1);+ try out.writeAll("\x1b[2J\x1b[H");+ var off: usize = 0;+ if (id.len == 0) {+ off = try drawList(a, out, rows, selected, cols, height);+ } else if (snapshot(a, root.io, dir, id)) |child| {+ const title = try std.fmt.allocPrint(a, "← Workers / {s}{s}{s}", .{ style.bold, try oneLine(a, child.agent.label), style.reset });+ try clipped(out, title, cols -| 1);+ try out.writeByte('\n');+ try out.writeAll(statusColor(child.agent.status));+ try clipped(out, try std.fmt.allocPrint(a, "{s} · {s}", .{ try oneLine(a, child.agent.status), try oneLine(a, child.agent.model) }), cols -| 1);+ try out.writeAll("\n\n");+ const lines = try wrap(a, try detail(root, a, child, tools, thoughts), cols -| 3);+ const room = height -| 5;+ scroll = @min(scroll, lines.len -| room);+ for (lines[scroll..@min(lines.len, scroll + room)]) |line| {+ try out.writeAll(style.text);+ try clipped(out, line, cols -| 1);+ try out.writeByte('\n');+ }+ } else |_| {+ try clipped(out, "Activity unavailable. Esc goes back.", cols -| 1);+ }+ try out.print("\x1b[{d};1H{s}", .{ height, style.muted });+ try clipped(out, if (id.len == 0) "↑/↓ move · click/Enter inspect · Esc/q close" else "↑/↓ scroll · Esc back · t tools · h thoughts · q close", cols -| 1);+ try out.flush();+ const action: Action = if (term.tty.pollPrompt(input, 500))+ keys.feed(@import("input_util.zig").editByte(input) orelse return)+ else+ keys.expire();+ switch (action) {+ .quit => return,+ .back => if (id.len > 0) {+ id = "";+ scroll = 0;+ } else return,+ .up => if (id.len > 0) {+ scroll -|= 1;+ } else {+ selected -|= 1;+ },+ .down => if (id.len > 0) {+ scroll +|= 1;+ } else {+ selected = @min(selected + 1, rows.len -| 1);+ },+ .tools => tools = !tools,+ .thoughts => thoughts = !thoughts,+ .select, .click => {+ if (id.len > 0) {+ if (action == .click and action.click.y <= 2) {+ id = "";+ scroll = 0;+ }+ } else {+ const index = if (action == .click) clickedRow(action.click, off, rows.len, cols, height) orelse continue else selected;+ if (index < rows.len) {+ const chosen = rows[index].id;+ @memcpy(id_buf[0..chosen.len], chosen);+ id = id_buf[0..chosen.len];+ scroll = 0;+ }+ }+ },+ .none, .refresh => {},+ }+ }+}++pub fn tryHandle(root: *Agent, line: []const u8, out: *Io.Writer) !bool {+ if (!std.mem.eql(u8, line, "/workers") and !std.mem.startsWith(u8, line, "/workers ")) return false;+ const id = std.mem.trim(u8, line["/workers".len..], " \t");+ if (id.len > 0 and !activity.validId(id)) {+ try out.writeAll("usage: /workers [child-id]\n");+ return true;+ }+ const self = @import("proc_identity.zig").selfRecord(root.io);+ var buf: [80]u8 = undefined;+ const path = try std.fmt.allocPrint(root.gpa, "{s}/{s}/{s}", .{ root.home, @import("presence.zig").registry_subdir, try activity.directory(&buf, self.pid, self.start_id) });+ defer root.gpa.free(path);+ var dir = Io.Dir.cwd().openDir(root.io, path, .{ .iterate = true }) catch {+ try out.writeAll("No subagents yet. Workers appear here when they start.\n");+ return true;+ };+ defer dir.close(root.io);+ if (root.in != null and @import("main.zig").use_color and term.termCols() >= 20 and term.termRows() >= 10) {+ try browse(root, out, dir, id);+ } else {+ var arena = std.heap.ArenaAllocator.init(root.gpa);+ defer arena.deinit();+ const a = arena.allocator();+ if (id.len > 0) {+ const child = snapshot(a, root.io, dir, id) catch {+ try out.writeAll("Subagent activity is unavailable.\n");+ return true;+ };+ try out.writeAll(try detail(root, a, child, false, false));+ } else {+ const rows = try @import("acp_agent_activity.zig").list(a, root.io, dir);+ for (rows) |row| try out.print("{s} {s} {s}\n", .{ row.id, try oneLine(a, row.status), try oneLine(a, row.label) });+ if (rows.len == 0) try out.writeAll("No subagents yet.\n");+ }+ }+ try out.flush();+ return true;+}diff --git a/src/terminal_workers_tests.zig b/src/terminal_workers_tests.zignew file mode 100644index 00000000..e8f5ff1d--- /dev/null+++ b/src/terminal_workers_tests.zig@@ -0,0 +1,118 @@+const std = @import("std");+const Io = std.Io;+const workers = @import("terminal_workers.zig");+const activity = @import("subagent_activity.zig");+const ansi = @import("ansi.zig");++fn packet(keys: *workers.Keys, bytes: []const u8) workers.Action {+ var action: workers.Action = .none;+ for (bytes) |b| action = keys.feed(b);+ return action;+}++test "terminal workers parses fragmented mouse keyboard and escape input" {+ var keys: workers.Keys = .{};+ try std.testing.expect(packet(&keys, "\x1b[<0;7;") == .none);+ const click = packet(&keys, "4M");+ try std.testing.expectEqual(workers.Point{ .x = 7, .y = 4 }, click.click);+ try std.testing.expect(packet(&keys, "\x1b[<0;7;4m") == .none);+ try std.testing.expect(packet(&keys, "\x1b[<35;7;4M") == .none);+ try std.testing.expect(packet(&keys, "\x1b[<64;7;4M") == .up);+ try std.testing.expect(packet(&keys, "\x1b[<65;7;4M") == .down);+ try std.testing.expect(packet(&keys, "\x1b[A") == .up);+ try std.testing.expect(packet(&keys, "\x1b[B") == .down);+ try std.testing.expect(packet(&keys, "\x1b[13u") == .select);+ try std.testing.expect(packet(&keys, "\x1b") == .none);+ try std.testing.expect(keys.expire() == .back);+ try std.testing.expect(packet(&keys, "\x03") == .quit);+ try std.testing.expect(packet(&keys, "t") == .tools);+ try std.testing.expect(packet(&keys, "h") == .thoughts);+ try std.testing.expect(packet(&keys, "\x1b[<0;0;4M") == .none);+}++test "terminal workers list keeps narrow cards and hit targets aligned" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const old = ansi.style;+ defer ansi.style = old;+ ansi.style = .{};+ var rows: [8]activity.Meta = undefined;+ for (&rows) |*row| row.* = .{ .id = "child-a", .label = "Long\nlabel\twith\x1b[2Jcontrols", .task = "Inspect", .model = "example-model" };+ var out: Io.Writer.Allocating = .init(a);+ const off = try workers.drawList(a, &out.writer, &rows, 7, 20, 10);+ try std.testing.expectEqual(@as(usize, 7), off);+ try std.testing.expectEqual(@as(?usize, 7), workers.clickedRow(.{ .x = 3, .y = 4 }, off, rows.len, 20, 10));+ try std.testing.expect(workers.clickedRow(.{ .x = 3, .y = 3 }, off, rows.len, 20, 10) == null);+ try std.testing.expect(workers.clickedRow(.{ .x = 20, .y = 4 }, off, rows.len, 20, 10) == null);+ try std.testing.expect(workers.clickedRow(.{ .x = 3, .y = 7 }, off, rows.len, 20, 10) == null);+ try std.testing.expect(std.mem.indexOfScalar(u8, out.written(), 0x1b) == null);+ var lines = std.mem.splitScalar(u8, out.written(), '\n');+ var row: usize = 0;+ while (lines.next()) |line| : (row += 1) {+ try std.testing.expect(@import("markdown_url.zig").codepointCount(line) < 20);+ if (row == 3) try std.testing.expect(std.mem.startsWith(u8, line, "› ● "));+ }+ _ = try workers.drawList(a, &out.writer, &.{}, 999, 20, 10);+}++test "terminal workers wraps UTF8 and ANSI without splitting either" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const lines = try workers.wrap(arena.allocator(), "\x1b[1ma界bc\x1b[0m", 3);+ try std.testing.expectEqual(@as(usize, 2), lines.len);+ try std.testing.expectEqualStrings("\x1b[1ma界", lines[0]);+ try std.testing.expectEqualStrings("bc\x1b[0m", lines[1]);+ const words = try workers.wrap(arena.allocator(), "one two three", 7);+ try std.testing.expectEqualStrings("one two", words[0]);+ try std.testing.expectEqualStrings("three", words[1]);+}++test "terminal workers snapshots reject traversal and mismatched identities" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ var tmp = std.testing.tmpDir(.{});+ defer tmp.cleanup();+ const io = std.testing.io;+ try std.testing.expectError(error.InvalidChildId, workers.snapshot(a, io, tmp.dir, "../child-a"));+ const child: activity.Snapshot = .{ .agent = .{ .id = "child-a", .label = "Review", .task = "Inspect" }, .events = &.{}, .response = "Done" };+ try tmp.dir.writeFile(io, .{ .sub_path = "child-a.json", .data = try std.json.Stringify.valueAlloc(a, child, .{}) });+ const read = try workers.snapshot(a, io, tmp.dir, "child-a");+ try std.testing.expectEqualStrings("Done", read.response);+ try tmp.dir.writeFile(io, .{ .sub_path = "child-b.json", .data = try std.json.Stringify.valueAlloc(a, child, .{}) });+ try std.testing.expectError(error.InvalidChildSnapshot, workers.snapshot(a, io, tmp.dir, "child-b"));+ var events: [activity.max_events + 1]activity.Event = @splat(.{ .type = "text" });+ var excess = child;+ excess.events = &events;+ try tmp.dir.writeFile(io, .{ .sub_path = "child-a.json", .data = try std.json.Stringify.valueAlloc(a, excess, .{}) });+ try std.testing.expectError(error.InvalidChildSnapshot, workers.snapshot(a, io, tmp.dir, "child-a"));+}++test "terminal workers details are sanitized and disclosures stay opt in" {+ var arena = std.heap.ArenaAllocator.init(std.testing.allocator);+ defer arena.deinit();+ const a = arena.allocator();+ const old = ansi.style;+ defer ansi.style = old;+ ansi.style = .{};+ var root: @import("agent.zig").Agent = .{ .gpa = a, .arena = a, .io = std.testing.io, .client = undefined, .provider = undefined, .messages = .init(a), .sub = false, .label = "Test", .out = null, .md_fence = true };+ const child: activity.Snapshot = .{ .agent = .{ .id = "child-a", .label = "Review", .task = "Inspect the **boundary**", .truncated = true }, .events = &.{+ .{ .type = "tool_call", .id = "tool-a", .name = "read_file", .text = "example.zig" },+ .{ .type = "tool_result", .id = "tool-a", .name = "read_file", .text = "hidden tool body" },+ .{ .type = "reasoning", .text = "emitted thought text" },+ .{ .type = "tool_result", .is_error = true, .text = "visible failure" },+ }, .response = "## Report\n*Ready*\x1b[2J\x1b]52;c;bad\x07" };+ const quiet = try workers.detail(&root, a, child, false, false);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "Inspect the boundary") != null);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "Ready") != null);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "visible failure") != null);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "hidden tool body") == null);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "emitted thought text") == null);+ try std.testing.expect(std.mem.indexOf(u8, quiet, "bounded snapshot") != null);+ try std.testing.expect(std.mem.indexOfScalar(u8, quiet, 0x1b) == null);+ const expanded = try workers.detail(&root, a, child, true, true);+ try std.testing.expect(std.mem.indexOf(u8, expanded, "hidden tool body") != null);+ try std.testing.expect(std.mem.indexOf(u8, expanded, "emitted thought text") != null);+ try std.testing.expect(root.md_fence);+}