Skip to content

graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs

Python

feat(repl): markdown rendering — soft token wraps, raw indented code, CRLF tolerance, pipe-less tables

Rach Pradhan39ee169115d7
diff --git a/src/agent_render.zig b/src/agent_render.zig
index d71fbee1..5d66f50a 100644
--- a/src/agent_render.zig
+++ b/src/agent_render.zig
@@ -55,7 +55,7 @@ pub fn atLineStart(self: *const Agent) bool {
return self.md_kind == .classify and self.md_buf.items.len == 0 and self.md_word.items.len == 0;
}
-pub const MdKind = enum { classify, hold, prose, header, fenced };
+pub const MdKind = enum { classify, hold, prose, header, fenced, pre };
pub const MdSpan = enum { normal, star, bold, bold_star, code };
@@ -94,6 +94,7 @@ fn mdStartItem(self: *Agent, w: *Io.Writer, held: []const u8, lead: usize, prefi
}
pub fn mdByte(self: *Agent, w: *Io.Writer, b: u8) void {
+ if (b == '\r') return; // CRLF deltas: a stray CR must not poison classification
if (b == '\n') {
// A swallowed line (table row joining the buffer) keeps its
// newline too — the table renders with its own line breaks.
@@ -107,7 +108,7 @@ pub fn mdByte(self: *Agent, w: *Io.Writer, b: u8) void {
},
.hold => self.md_buf.append(self.gpa, b) catch {},
.prose => self.mdSpanByte(w, b),
- .header, .fenced => w.writeByte(b) catch {},
+ .header, .fenced, .pre => w.writeByte(b) catch {},
}
}
@@ -124,7 +125,6 @@ pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
// A buffered table ends at the first line that isn't another row —
// render it before this line emits anything.
if (self.md_table.items.len > 0 and body[0] != '|') self.flushTable(w);
-
if (self.md_fence) {
// Inside a fence the only special line is the ``` closer.
const bt = countPrefix(body, '`');
@@ -138,6 +138,14 @@ pub fn mdTryClassify(self: *Agent, w: *Io.Writer) void {
self.md_buf.clearRetainingCapacity();
return;
}
+ // Indented code block (4+ leading spaces): preformatted — stream raw.
+ // The prose wrapper's word-wrap shredded code formatting (#v0.0.274).
+ if (lead >= 4) {
+ self.md_kind = .pre;
+ w.writeAll(held) catch {};
+ self.md_buf.clearRetainingCapacity();
+ return;
+ }
switch (body[0]) {
'`' => {
const bt = countPrefix(body, '`');
@@ -369,6 +377,7 @@ pub fn mdFinishLine(self: *Agent, w: *Io.Writer) bool {
},
.prose => self.mdSpanEnd(w),
.header, .fenced => w.writeAll(style.reset) catch {},
+ .pre => {}, // nothing was styled
}
self.md_buf.clearRetainingCapacity();
self.md_kind = .classify;
diff --git a/src/agent_table.zig b/src/agent_table.zig
index 8721d2f3..4e89c67f 100644
--- a/src/agent_table.zig
+++ b/src/agent_table.zig
@@ -13,6 +13,7 @@ const Agent = agent_mod.Agent;
const ansi = @import("ansi.zig");
const style = &ansi.style;
+const util = @import("util.zig");
const terminal = @import("term.zig");
const termCols = terminal.termCols;
@@ -173,15 +174,16 @@ pub fn wrapCell(gpa: Allocator, cell: []const u8, width: usize, out: *std.ArrayL
out.append(gpa, cell[ls..le]) catch return;
lv = 0;
}
- if (lv == 0 and av > budget) { // oversized atom: hard-split
+ if (lv == 0 and av > budget) { // oversized atom: split at punctuation when one is in reach
var j = i;
var v: usize = 0;
while (j < ae and v < budget) {
j += std.unicode.utf8ByteSequenceLength(cell[j]) catch 1;
v += 1;
}
- out.append(gpa, cell[i..j]) catch return;
- i = j;
+ const cut = util.softCut(cell, i, j);
+ out.append(gpa, cell[i..cut]) catch return;
+ i = cut;
continue;
}
if (lv == 0) ls = i else lv += 1; // joining space
diff --git a/src/main_test.zig b/src/main_test.zig
index e23da8fc..c1bde2cc 100644
--- a/src/main_test.zig
+++ b/src/main_test.zig
@@ -115,6 +115,40 @@ test "incremental markdown streaming renders like renderMdLine" {
try std.testing.expectEqualStrings("abc defghijklm\n", aw.writer.buffered());
}
+test "streamed markdown: pipe-less tables align; lone candidates stay prose; indented code streams raw" {
+ var aw: Io.Writer.Allocating = .init(std.testing.allocator);
+ defer aw.deinit();
+ var a: Agent = .{
+ .gpa = std.testing.allocator,
+ .arena = std.testing.allocator,
+ .io = undefined,
+ .client = undefined,
+ .provider = undefined,
+ .messages = undefined,
+ .sub = false,
+ .label = "test",
+ .out = &aw.writer,
+ };
+ defer a.md_buf.deinit(std.testing.allocator);
+ defer a.md_word.deinit(std.testing.allocator);
+ defer {
+ for (a.md_table.items) |r| std.testing.allocator.free(r);
+ a.md_table.deinit(std.testing.allocator);
+ }
+
+ // Indented code blocks (4+ spaces) stream raw — never word-wrapped.
+ a.md_width = 12;
+ a.streamMarkdown(" const x = longcall(a, b);\n");
+ try std.testing.expectEqualStrings(" const x = longcall(a, b);\n", aw.writer.buffered());
+ aw.clearRetainingCapacity();
+
+ // CRLF deltas: a stray \r must not turn the row into wrapped prose.
+ a.streamMarkdown("| a | b |\r\n| --- | --- |\r\n");
+ try std.testing.expectEqualStrings("", aw.writer.buffered()); // still buffering, not printed
+ a.flushStreamTail();
+ try std.testing.expect(std.mem.indexOf(u8, aw.writer.buffered(), " │ ") != null);
+}
+
test "/bash slash command runs the bash tool and frees its gpa-allocated result" {
// Regression guard for PR #38: the /bash slash handler routes through execTool, whose result.text is gpa-owned (NOT arena-owned — every other
// caller frees it). Forgetting `defer root.gpa.free(result.text)` in handleCommand leaks on every /bash call; std.testing.allocator catches it here.
diff --git a/src/repl_markdown.zig b/src/repl_markdown.zig
index 178a5514..9121571d 100644
--- a/src/repl_markdown.zig
+++ b/src/repl_markdown.zig
@@ -7,6 +7,7 @@ const std = @import("std");
const zz = @import("zigzag");
const util = @import("repl_util.zig");
+const softCut = @import("util.zig").softCut;
const accent = util.accent;
/// Render a markdown string to ANSI for display — approximates the harness's
@@ -52,6 +53,16 @@ pub fn renderMarkdown(gpa: std.mem.Allocator, src: []const u8, width_hint: usize
idx = end - 1;
continue;
}
+ // Pipe-less GFM table ("a | b" / "--- | ---"): same box form. Only
+ // whole-buffer rendering can see the separator row, so this lives
+ // here rather than in the streaming classifier.
+ if (hasPipeCells(t) and idx + 1 < lines.len and isPipelessSep(std.mem.trim(u8, lines[idx + 1], " \t"))) {
+ var end = idx;
+ while (end < lines.len and hasPipeCells(std.mem.trimStart(u8, lines[end], " "))) end += 1;
+ try renderTable(&out, a, lines[idx..end], width_hint);
+ idx = end - 1;
+ continue;
+ }
if (std.mem.startsWith(u8, t, "#")) {
var h = t;
while (h.len > 0 and h[0] == '#') h = h[1..];
@@ -72,6 +83,30 @@ fn isTableRow(t: []const u8) bool {
return t.len >= 2 and t[0] == '|';
}
+/// Cells joined by ` | ` somewhere in the line — a GFM row written without
+/// leading/trailing pipes. Never true for a leading-pipe row (checked first).
+fn hasPipeCells(t: []const u8) bool {
+ var i: usize = 1;
+ while (i + 1 < t.len) : (i += 1) {
+ if (t[i] == '|' and t[i - 1] == ' ' and t[i + 1] == ' ') return true;
+ }
+ return false;
+}
+
+/// `--- | ---` alignment row in the pipe-less shape: dashes required, only
+/// separator characters otherwise, and at least one pipe.
+fn isPipelessSep(t: []const u8) bool {
+ var dash = false;
+ var pipe = false;
+ for (t) |c| switch (c) {
+ ':', ' ', '\t' => {},
+ '-' => dash = true,
+ '|' => pipe = true,
+ else => return false,
+ };
+ return dash and pipe;
+}
+
/// `|---|:--:|` style alignment row: pipes/colons/spaces only, dashes required.
fn isTableSep(t: []const u8) bool {
if (t.len == 0 or t[0] != '|') return false;
@@ -191,8 +226,9 @@ fn wrapCell(a: std.mem.Allocator, s: []const u8, w: usize) ![]const []const u8 {
bytes += clen;
cw += cpw;
}
- try lines.append(try a.dupe(u8, rem[0..bytes]));
- rem = rem[bytes..];
+ const cut = softCut(rem, 0, bytes); // break after / _ - . : rather than mid-token
+ try lines.append(try a.dupe(u8, rem[0..cut]));
+ rem = rem[cut..];
}
const ww = dispWidth(rem);
if (ww == 0) continue;
@@ -467,3 +503,17 @@ test "renderMarkdown: table honors column alignment" {
defer gpa.free(lout);
try std.testing.expect(std.mem.indexOf(u8, util.stripControl(a, lout), " 5") == null);
}
+
+test "renderMarkdown: pipe-less GFM table renders as box-drawing" {
+ const gpa = std.testing.allocator;
+ const md = "Item | Desc\n--- | ---\n1 | Inspect files";
+ const out = try renderMarkdown(gpa, md, 80);
+ defer gpa.free(out);
+ try std.testing.expect(std.mem.indexOf(u8, out, "┌") != null); // box form
+ try std.testing.expect(std.mem.indexOf(u8, out, "Inspect files") != null);
+ // A lone pipe-less line with NO separator row stays prose.
+ const prose = try renderMarkdown(gpa, "left | right\njust text", 80);
+ defer gpa.free(prose);
+ try std.testing.expect(std.mem.indexOf(u8, prose, "┌") == null);
+ try std.testing.expect(std.mem.indexOf(u8, prose, "left | right") != null);
+}
diff --git a/src/util.zig b/src/util.zig
index 50ffa0ad..7d96fabc 100644
--- a/src/util.zig
+++ b/src/util.zig
@@ -105,6 +105,36 @@ pub fn unixMs(io: Io) i64 {
return @intCast(@divTrunc(ts.nanoseconds, 1_000_000));
}
+/// Preferred split offset for an over-wide atom (a table cell token that
+/// cannot fit its column whole): the LAST identifier/path punctuation
+/// (`/ _ - . : = > ) ]`) at or before `hi`, so `foo/bar__baz` breaks after
+/// a punctuation run instead of mid-word. Keeps at least the first third
+/// of the budget on the line; returns `hi` when no such break exists.
+pub fn softCut(s: []const u8, lo: usize, hi: usize) usize {
+ if (hi <= lo or hi > s.len) return hi;
+ const min_keep = lo + (hi - lo) / 3;
+ var i: usize = hi;
+ while (i > min_keep) {
+ i -= 1;
+ const brk = switch (s[i]) {
+ '/', '_', '-', '.', ':', '=', '>', ')', ']' => true,
+ else => false,
+ };
+ if (brk) return i + 1;
+ }
+ return hi;
+}
+
+test "softCut: break after punctuation, keep the floor, else hard-split" {
+ // "mcp__codedbpro" in a 12-col cell: the '_' run at index 4 is inside
+ // the keep-floor's reach from the right, and the cut lands after it.
+ try std.testing.expectEqual(@as(usize, 5), softCut("mcp__codedbpro", 0, 12));
+ // A later '/' wins over an earlier '_'.
+ try std.testing.expectEqual(@as(usize, 15), softCut("aa/bb/cc/dd/ee/ff", 0, 15));
+ // No punctuation in reach: hard-split unchanged.
+ try std.testing.expectEqual(@as(usize, 8), softCut("abcdefghij", 0, 8));
+}
+
const json_bytes_max_depth = 32;
/// Serialized byte count of a JSON value, near enough for a budget decision