graff — a fast agentic coding harness in Zig: multi-provider, MCP, workflows, DGM evolution loop, TS/Python SDKs
Python
fix: harden markdown URL boundaries (#729)
yxlyxe7c2f8798d0f
diff --git a/TUI/markdown.zig b/TUI/markdown.zigindex 2ea3853f..d07ebe51 100644--- a/TUI/markdown.zig+++ b/TUI/markdown.zig@@ -307,12 +307,63 @@ fn appendBlock(out: *std.array_list.Managed(u8), line: []const u8, accent: []contry inlineSpans(out, line, accent, text);}-/// `code`, **bold** and `_italic_`, painted in place. Public for table.zig,-/// which renders a cell the same way prose is rendered rather than measuring-/// markers by hand — see the note at the head of that file.+const WrappedUrl = struct { url: []const u8, suffix: []const u8 };+const url_wrapper_pairs = [_]struct { open: []const u8, close: []const u8 }{+ .{ .open = "**", .close = "**" }, .{ .open = "__", .close = "__" },+ .{ .open = "~~", .close = "~~" }, .{ .open = "*", .close = "*" },+ .{ .open = "_", .close = "_" }, .{ .open = "`", .close = "`" },+};++fn unwrapUrlCore(core: []const u8, suffix: []const u8) ?WrappedUrl {+ var value = core;+ var removed = false;+ while (true) {+ var matched = false;+ for (url_wrapper_pairs) |pair| {+ if (value.len <= pair.open.len + pair.close.len or+ !std.mem.startsWith(u8, value, pair.open) or+ !std.mem.endsWith(u8, value, pair.close)) continue;+ value = value[pair.open.len .. value.len - pair.close.len];+ removed = true;+ matched = true;+ break;+ }+ if (!matched) break;+ }+ if (!removed or !(std.mem.startsWith(u8, value, "http://") or std.mem.startsWith(u8, value, "https://"))) return null;+ return .{ .url = value, .suffix = suffix };+}++fn unwrapUrlToken(token: []const u8) ?WrappedUrl {+ if (unwrapUrlCore(token, "")) |match| return match;+ var end = token.len;+ while (end > 0 and std.mem.indexOfScalar(u8, ".,;!?:", token[end - 1]) != null) {+ end -= 1;+ if (unwrapUrlCore(token[0..end], token[end..])) |match| return match;+ }+ return null;+}++/// Inline Markdown spans. URL tokens are settled first so wrapper delimiters+/// disappear while identical marker bytes inside an unwrapped URL stay opaque.pub fn inlineSpans(out: *std.array_list.Managed(u8), line: []const u8, accent: []const u8, text: []const u8) !void {var i: usize = 0;while (i < line.len) {+ if (line[i] == '*' or line[i] == '_' or line[i] == '~' or line[i] == '`' or line[i] == 'h') {+ var token_end = i;+ while (token_end < line.len and !std.ascii.isWhitespace(line[token_end])) token_end += 1;+ if (unwrapUrlToken(line[i..token_end])) |match| {+ try out.appendSlice(match.url);+ try out.appendSlice(match.suffix);+ i = token_end;+ continue;+ }+ if (std.mem.startsWith(u8, line[i..], "http://") or std.mem.startsWith(u8, line[i..], "https://")) {+ try out.appendSlice(line[i..token_end]);+ i = token_end;+ continue;+ }+ }if (line[i] == '`') {if (std.mem.indexOfScalarPos(u8, line, i + 1, '`')) |end| {try out.appendSlice(accent);diff --git a/TUI/markdown_tests.zig b/TUI/markdown_tests.zigindex 7afb0c60..3cd38b22 100644--- a/TUI/markdown_tests.zig+++ b/TUI/markdown_tests.zig@@ -100,6 +100,58 @@ test "render and renderThemed preserve an unwrapped URL ending in /**" {try std.testing.expectEqualStrings(url, themed_visible);}+fn expectVisible(out: []const u8, expected: []const u8) !void {+ const visible = try dump.visible(std.testing.allocator, out);+ defer std.testing.allocator.free(visible);+ try std.testing.expectEqualStrings(expected, visible);+}++test "render URL wrappers as clean visible text" {+ const url = "https://github.com/justrach/codegraff/issues/728";+ const cases = [_]struct { source: []const u8, expected: []const u8 }{+ .{ .source = "*" ++ url ++ "*", .expected = url },+ .{ .source = "**" ++ url ++ "**", .expected = url },+ .{ .source = "_" ++ url ++ "_", .expected = url },+ .{ .source = "__" ++ url ++ "__", .expected = url },+ .{ .source = "~~" ++ url ++ "~~", .expected = url },+ .{ .source = "`" ++ url ++ "`", .expected = url },+ // Independent spans are the mixed form supported by the TUI renderer.+ .{ .source = "**" ++ url ++ "** and _" ++ url ++ "_ and `" ++ url ++ "`", .expected = url ++ " and " ++ url ++ " and " ++ url },+ .{ .source = "See **" ++ url ++ "**, then continue.", .expected = "See " ++ url ++ ", then continue." },+ };++ for (cases) |case| {+ const plain = try render(std.testing.allocator, case.source, theme_mod.emerald);+ defer std.testing.allocator.free(plain);+ try expectVisible(plain, case.expected);++ const themed = try renderThemed(std.testing.allocator, case.source, theme_mod.of(.night), 120);+ defer std.testing.allocator.free(themed);+ try expectVisible(themed, case.expected);+ }+}++test "render and renderThemed preserve marker text in unwrapped URLs" {+ const cases = [_][]const u8{+ "See https://example.com/path/** followed by prose.",+ "https://example.com/path/__",+ "https://example.com/path/~~",+ "https://example.com/search?q=*",+ "https://docs.python.org/3/reference/datamodel.html#object.__init__",+ "https://example.com/path/a**b",+ };++ for (cases) |url| {+ const plain = try render(std.testing.allocator, url, theme_mod.emerald);+ defer std.testing.allocator.free(plain);+ try expectVisible(plain, url);++ const themed = try renderThemed(std.testing.allocator, url, theme_mod.of(.night), 120);+ defer std.testing.allocator.free(themed);+ try expectVisible(themed, url);+ }+}+test "the code band stays open to the row end and is released on the next line" {const th = theme_mod.of(.night);const code_bg = syntax.codeBg(false);diff --git a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsxindex 333abe89..607758f6 100644--- a/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx+++ b/gui/src/components/chat/markdown/MarkdownRenderer.test.tsx@@ -50,6 +50,41 @@ function renderedUrlButtons(html: string): Array<{ label: string; title: stringreturn buttons;}+const WRAPPED_URL = "https://example.com/docs";+const MARKDOWN_URL_WRAPPERS = ["*", "_", "__", "**", "~~"] as const;++test("linkifies URLs inside Markdown emphasis wrappers without delimiters", () => {+ const htmlByWrapper = MARKDOWN_URL_WRAPPERS.map((wrapper) =>+ renderToStaticMarkup(<MarkdownRenderer text={`${wrapper}${WRAPPED_URL}${wrapper}`} />),+ );++ expect(htmlByWrapper.flatMap(renderedUrlButtons)).toEqual(+ MARKDOWN_URL_WRAPPERS.map(() => ({ label: WRAPPED_URL, title: WRAPPED_URL })),+ );+ for (const [html, wrapper] of htmlByWrapper.map((html, index) => [+ html,+ MARKDOWN_URL_WRAPPERS[index],+ ] as const)) {+ expect(html).not.toContain(`${wrapper}${WRAPPED_URL}`);+ expect(html).not.toContain(`${WRAPPED_URL}${wrapper}`);+ }+});++test("keeps brackets and parentheses outside rendered URL targets", () => {+ const html = renderToStaticMarkup(+ <MarkdownRenderer text={`[${WRAPPED_URL}] (${WRAPPED_URL})`} />,+ );++ expect(renderedUrlButtons(html)).toEqual([+ { label: WRAPPED_URL, title: WRAPPED_URL },+ { label: WRAPPED_URL, title: WRAPPED_URL },+ ]);+ expect(html).toContain(`[<button`);+ expect(html).toContain(`</button>]`);+ expect(html).toContain(`(<button`);+ expect(html).toContain(`</button>)`);+});+test("a stray ** earlier in the line never lands in the link target", () => {for (const text of SHIFTED_PAIRING) {const html = renderToStaticMarkup(<MarkdownRenderer text={text} />);@@ -122,6 +157,7 @@ test("keeps an explicit labeled GitHub link href exact", () => {expect(html).toContain(`href="${GITHUB_ISSUE_URL}"`);expect(html).toContain(">issue 728</a>.");+ expect(linkTargets(html)).toEqual([GITHUB_ISSUE_URL]);expect(html).not.toContain(`${GITHUB_ISSUE_URL}**`);});diff --git a/gui/src/components/chat/markdown/MarkdownRenderer.tsx b/gui/src/components/chat/markdown/MarkdownRenderer.tsxindex 4d225941..99243613 100644--- a/gui/src/components/chat/markdown/MarkdownRenderer.tsx+++ b/gui/src/components/chat/markdown/MarkdownRenderer.tsx@@ -147,9 +147,21 @@ function renderInline(nodes: MdInline[], workspacePath?: string | null): ReactNo</span>);case "em":- return <em key={index}>{renderInline(node.children, workspacePath)}</em>;+ return (+ <em key={index}>+ <ChatInlineChildren workspacePath={workspacePath}>+ {renderInline(node.children, workspacePath)}+ </ChatInlineChildren>+ </em>+ );case "del":- return <del key={index}>{renderInline(node.children, workspacePath)}</del>;+ return (+ <del key={index}>+ <ChatInlineChildren workspacePath={workspacePath}>+ {renderInline(node.children, workspacePath)}+ </ChatInlineChildren>+ </del>+ );case "code":return <code key={index}>{node.value}</code>;case "math":diff --git a/gui/src/components/chat/utils/chatLinks.test.ts b/gui/src/components/chat/utils/chatLinks.test.tsindex f762562a..677cef39 100644--- a/gui/src/components/chat/utils/chatLinks.test.ts+++ b/gui/src/components/chat/utils/chatLinks.test.ts@@ -52,9 +52,20 @@ describe("getChatLinkMatches URL vs Markdown delimiters", () => {test("still trims a wrapping paren and trailing sentence punctuation", () => {expect(firstUrl("(https://example.com)")).toBe("https://example.com");+ expect(firstUrl("[https://example.com]")).toBe("https://example.com");expect(firstUrl("visit https://example.com.")).toBe("https://example.com");});+ test("preserves legal URL tails after an unrelated closed emphasis span", () => {+ const cases = [+ ["**done** https://example.com/glob/**", "https://example.com/glob/**"],+ ["__done__ https://example.com/path/__", "https://example.com/path/__"],+ ["~~done~~ https://example.com/path/~~", "https://example.com/path/~~"],+ ] as const;++ expect(cases.map(([text]) => firstUrl(text))).toEqual(cases.map(([, url]) => url));+ });+test("reports the correct span end after trimming the delimiters", () => {const [match] = getChatLinkMatches("**http://localhost:3003**");expect(match).toMatchObject({diff --git a/gui/src/components/chat/utils/chatLinks.ts b/gui/src/components/chat/utils/chatLinks.tsindex 04a147c4..6f64b172 100644--- a/gui/src/components/chat/utils/chatLinks.ts+++ b/gui/src/components/chat/utils/chatLinks.ts@@ -118,22 +118,27 @@ function markdownClosingDelimiterBefore(text: string, start: number): string | nreturn [...opening].reverse().join("");}-/**- * Does the text in front of the URL contain a run that could have *opened* this- * emphasis pair? A delimiter run only opens when a non-space follows it, so- * `**Note: see ` opens but `2 ** 3 ` does not.+/** Track whether this delimiter pair is still open at the URL boundary.+ * Closed earlier spans must not authorize trimming legal marker bytes from a+ * later URL (`**done** https://example.test/glob/**`).*/function hasEmphasisOpenerBefore(before: string, pair: string): boolean {+ let open = false;let index = before.indexOf(pair);while (index >= 0) {+ const previous = before[index - 1];const next = before[index + pair.length];- if (next != null && !/\s/u.test(next)) {- return true;+ const canOpen = next != null && !/\s/u.test(next);+ const canClose = previous != null && !/\s/u.test(previous);+ if (open && canClose) {+ open = false;+ } else if (!open && canOpen) {+ open = true;}- index = before.indexOf(pair, index + 1);+ index = before.indexOf(pair, index + pair.length);}- return false;+ return open;}/**diff --git a/scripts/test-pty-markdown.py b/scripts/test-pty-markdown.pyindex 1fa82369..b8feee83 100755--- a/scripts/test-pty-markdown.py+++ b/scripts/test-pty-markdown.py@@ -55,6 +55,11 @@ def main() -> None:"☑ Sanitize public errors."," ◦ Preserve private incident detail.","│ Public errors must never expose secrets.",+ "• Wrapped: https://example.test/a https://example.test/b",+ "• Wrapped: https://example.test/c https://example.test/d",+ "• Wrapped: https://example.test/e https://example.test/f",+ "• URL data: https://example.test/glob/** https://example.test/path/__",+ "• URL data: https://example.test/path/~~ https://example.test/a**b","• Link: https://github.com/justrach/codegraff/issues/728",)for mode, result in (("color", color_result), ("no-color", plain_result)):diff --git a/src/agent_render.zig b/src/agent_render.zigindex 669c0950..d293bc86 100644--- a/src/agent_render.zig+++ b/src/agent_render.zig@@ -15,6 +15,7 @@ const Agent = agent_mod.Agent;const ansi = @import("ansi.zig");const style = &ansi.style;+const markdown_url = @import("markdown_url.zig");const terminal = @import("term.zig");const termCols = terminal.termCols;@@ -248,7 +249,12 @@ pub fn mdStartProse(self: *Agent, w: *Io.Writer) void {pub fn mdSpanByte(self: *Agent, w: *Io.Writer, b: u8) void {switch (self.md_span) {.normal => switch (b) {- '*' => self.md_span = .star,+ '*' => {+ 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;@@ -321,14 +327,18 @@ pub fn mdStyle(self: *Agent, w: *Io.Writer, s: []const u8) void {pub fn mdFlushWord(self: *Agent, w: *Io.Writer) void {if (self.md_word.items.len == 0) return;- const vis = self.md_word_vis;+ const clean = markdown_url.unwrapToken(self.md_word.items);+ const vis = self.md_word_vis - if (clean) |match| match.removed else 0;const width = self.mdWidth();// Break before a word that would cross the edge — unless the line is// already fresh or the word can't fit any line (URLs: let the// terminal wrap it rather than shred it).if (self.md_col + vis > width and self.md_col > self.md_indent and self.md_indent + vis <= width)self.mdWrapBreak(w);- w.writeAll(self.md_word.items) catch {};+ if (clean) |match| {+ w.writeAll(match.url) catch {};+ w.writeAll(match.suffix) catch {};+ } else w.writeAll(self.md_word.items) catch {};self.md_col += vis;self.md_word.clearRetainingCapacity();self.md_word_vis = 0;@@ -348,10 +358,14 @@ 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 => w.writeByte('*') catch {},+ .star => unreachable,.bold_empty => {w.writeAll(style.reset) catch {};w.writeAll("**") catch {};@@ -411,40 +425,8 @@ pub fn countPrefix(s: []const u8, c: u8) usize {return i;}-/// Columns a cell occupies once rendered: matched **bold**/`code` markers-/// drop, and multi-byte UTF-8 sequences count as one column (wide CJK-/// glyphs are approximated as one).-pub fn inlineVisibleLen(s: []const u8) usize {- var i: usize = 0;- var n: usize = 0;- while (i < s.len) {- if (i + 1 < s.len and s[i] == '*' and s[i + 1] == '*') {- if (std.mem.indexOfPos(u8, s, i + 2, "**")) |end| {- n += codepointCount(s[i + 2 .. end]);- i = end + 2;- continue;- }- }- if (s[i] == '`') {- if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {- n += codepointCount(s[i + 1 .. end]);- i = end + 1;- continue;- }- }- if ((s[i] & 0xC0) != 0x80) n += 1;- i += 1;- }- return n;-}--pub fn codepointCount(s: []const u8) usize {- var n: usize = 0;- for (s) |b| {- if ((b & 0xC0) != 0x80) n += 1;- }- return n;-}+pub const inlineVisibleLen = markdown_url.inlineVisibleLen;+pub const codepointCount = markdown_url.codepointCount;/// Flush the trailing partial line at stream end (no forced newline — the/// caller adds the separating newline), and reset fence state.@@ -560,6 +542,21 @@ pub fn isRule(body: []const u8) bool {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 {};diff --git a/src/engine_sink_tests.zig b/src/engine_sink_tests.zigindex b69edee5..8f034a76 100644--- a/src/engine_sink_tests.zig+++ b/src/engine_sink_tests.zig@@ -314,37 +314,50 @@ test "TuiSink renders a plain text delta exactly as the no-color TTY did" {try std.testing.expectEqualStrings("plain\n\n", aw.writer.buffered());}-test "TuiSink excludes bold delimiters from no-color URL output (#729)" {- const saved_color = main_mod.use_color;- main_mod.use_color = false;- defer main_mod.use_color = saved_color;- const ansi = @import("ansi.zig");- const saved_style = ansi.style;- ansi.style = .{};- defer ansi.style = saved_style;+const UrlSettlement = enum { newline, stream_complete };+const UrlDeltaCase = struct {+ chunks: []const []const u8,+ want_line: []const u8,+};++const url_delta_cases = [_]UrlDeltaCase{+ // Direct wrappers: their punctuation remains visible but outside the URL.+ .{ .chunks = &.{ "*", "https://exam", "ple.com/a", "*." }, .want_line = "https://example.com/a.\n" },+ .{ .chunks = &.{ "*", "*https://example.com", "/b*", "*," }, .want_line = "https://example.com/b,\n" },+ .{ .chunks = &.{ "_https", "://example.com/c_", ";" }, .want_line = "https://example.com/c;\n" },+ .{ .chunks = &.{ "_", "_https://example.com/d", "_", "_:" }, .want_line = "https://example.com/d:\n" },+ .{ .chunks = &.{ "~", "~https://example.com/e~", "~!" }, .want_line = "https://example.com/e!\n" },+ .{ .chunks = &.{ "`https://", "example.com/f", "`?" }, .want_line = "https://example.com/f?\n" },++ // Without an opener, legal marker tails and interiors belong to the URL.+ .{ .chunks = &.{ "https://example.com/gl", "ob/**", " next" }, .want_line = "https://example.com/glob/** next\n" },+ .{ .chunks = &.{ "https://example.com/path/", "__" }, .want_line = "https://example.com/path/__\n" },+ .{ .chunks = &.{ "https://example.com/path/~", "~" }, .want_line = "https://example.com/path/~~\n" },+ .{ .chunks = &.{ "https://example.com/search?", "q=*" }, .want_line = "https://example.com/search?q=*\n" },+ .{ .chunks = &.{ "https://docs.python.org/3/reference/", "datamodel.html#object.__init__" }, .want_line = "https://docs.python.org/3/reference/datamodel.html#object.__init__\n" },+ .{ .chunks = &.{ "https://example.com/a*", "*b" }, .want_line = "https://example.com/a**b\n" },+};+fn expectUrlDeltaCase(settlement: UrlSettlement, c: UrlDeltaCase) !void {var aw: Io.Writer.Allocating = .init(std.testing.allocator);defer aw.deinit();var a = testAgent(&aw.writer);defer deinitMarkdown(&a);const s = tuiSink(&a);- s.emit(undefined, .{ .text_delta = .{ .text = "**https://github.com/justrach/codegraff/" } });- s.emit(undefined, .{ .text_delta = .{ .text = "issues/728**\n" } });- try std.testing.expectEqualStrings(- "https://github.com/justrach/codegraff/issues/728\n",- aw.writer.buffered(),- );-- aw.clearRetainingCapacity();- s.emit(undefined, .{ .text_delta = .{ .text = "Issue: **https://github.com/justrach/codegraff/issues/728**.\n" } });- try std.testing.expectEqualStrings(- "Issue: https://github.com/justrach/codegraff/issues/728.\n",- aw.writer.buffered(),- );+ for (c.chunks) |chunk| s.emit(undefined, .{ .text_delta = .{ .text = chunk } });+ switch (settlement) {+ .newline => s.emit(undefined, .{ .text_delta = .{ .text = "\n" } }),+ .stream_complete => s.emit(undefined, .{ .stream_complete = .{ .streamed_text = false } }),+ }+ const want = switch (settlement) {+ .newline => c.want_line,+ .stream_complete => c.want_line[0 .. c.want_line.len - 1],+ };+ try std.testing.expectEqualStrings(want, aw.writer.buffered());}-test "TuiSink preserves a no-color URL ending in a legal star pair (#729)" {+test "TuiSink settles no-color URL markers outside visible targets (#729)" {const saved_color = main_mod.use_color;main_mod.use_color = false;defer main_mod.use_color = saved_color;@@ -353,15 +366,10 @@ test "TuiSink preserves a no-color URL ending in a legal star pair (#729)" {ansi.style = .{};defer ansi.style = saved_style;- var aw: Io.Writer.Allocating = .init(std.testing.allocator);- defer aw.deinit();- var a = testAgent(&aw.writer);- defer deinitMarkdown(&a);- const s = tuiSink(&a);-- const url = "https://example.com/path/**";- s.emit(undefined, .{ .text_delta = .{ .text = url ++ "\n" } });- try std.testing.expectEqualStrings(url ++ "\n", aw.writer.buffered());+ for (url_delta_cases) |c| {+ try expectUrlDeltaCase(.newline, c);+ try expectUrlDeltaCase(.stream_complete, c);+ }}const swap: engine_events.ProviderFallback = .{diff --git a/src/markdown_url.zig b/src/markdown_url.zignew file mode 100644index 00000000..2252449a--- /dev/null+++ b/src/markdown_url.zig@@ -0,0 +1,115 @@+const std = @import("std");++pub const Unwrapped = struct {+ url: []const u8,+ suffix: []const u8,+ removed: usize,+};++const Pair = struct { open: []const u8, close: []const u8 };+const pairs = [_]Pair{+ .{ .open = "**", .close = "**" },+ .{ .open = "__", .close = "__" },+ .{ .open = "~~", .close = "~~" },+ .{ .open = "*", .close = "*" },+ .{ .open = "_", .close = "_" },+ .{ .open = "`", .close = "`" },+};++fn isSentencePunctuation(b: u8) bool {+ return std.mem.indexOfScalar(u8, ".,;!?:", b) != null;+}++fn unwrapCore(core: []const u8, suffix: []const u8) ?Unwrapped {+ var value = core;+ var removed: usize = 0;+ while (true) {+ var matched = false;+ for (pairs) |pair| {+ if (value.len <= pair.open.len + pair.close.len or+ !std.mem.startsWith(u8, value, pair.open) or+ !std.mem.endsWith(u8, value, pair.close)) continue;+ value = value[pair.open.len .. value.len - pair.close.len];+ removed += pair.open.len + pair.close.len;+ matched = true;+ break;+ }+ if (!matched) break;+ }+ if (removed == 0 or !(std.mem.startsWith(u8, value, "http://") or std.mem.startsWith(u8, value, "https://"))) return null;+ return .{ .url = value, .suffix = suffix, .removed = removed };+}++/// Remove balanced Markdown wrappers from a complete whitespace-delimited URL+/// token. The same marker bytes remain untouched when the token itself starts+/// with HTTP, so legal URL tails and interior marker runs are never guessed at.+pub fn unwrapToken(token: []const u8) ?Unwrapped {+ if (unwrapCore(token, "")) |match| return match;+ var core_end = token.len;+ while (core_end > 0 and isSentencePunctuation(token[core_end - 1])) {+ core_end -= 1;+ if (unwrapCore(token[0..core_end], token[core_end..])) |match| return match;+ }+ return null;+}++pub fn containsHttp(value: []const u8) bool {+ return std.mem.indexOf(u8, value, "http://") != null or std.mem.indexOf(u8, value, "https://") != null;+}++pub fn codepointCount(s: []const u8) usize {+ var count: usize = 0;+ for (s) |b| {+ if ((b & 0xC0) != 0x80) count += 1;+ }+ return count;+}++pub fn inlineVisibleLen(s: []const u8) usize {+ var i: usize = 0;+ var count: 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 (unwrapToken(s[i..token_end])) |match| {+ count += codepointCount(match.url) + codepointCount(match.suffix);+ i = token_end;+ continue;+ }+ if (std.mem.startsWith(u8, s[i..], "http://") or std.mem.startsWith(u8, s[i..], "https://")) {+ count += codepointCount(s[i..token_end]);+ 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| {+ count += codepointCount(s[i + 2 .. end]);+ i = end + 2;+ continue;+ }+ }+ if (s[i] == '`') {+ if (std.mem.indexOfScalarPos(u8, s, i + 1, '`')) |end| {+ count += codepointCount(s[i + 1 .. end]);+ i = end + 1;+ continue;+ }+ }+ if ((s[i] & 0xC0) != 0x80) count += 1;+ i += 1;+ }+ return count;+}++test "unwraps supported wrappers and preserves URL markers" {+ const url = "https://example.test/a";+ inline for (.{ "*", "**", "_", "__", "~~", "`" }) |pair| {+ const match = unwrapToken(pair ++ url ++ pair ++ ".").?;+ try std.testing.expectEqualStrings(url, match.url);+ try std.testing.expectEqualStrings(".", match.suffix);+ }+ try std.testing.expect(unwrapToken("https://example.test/glob/**") == null);+ try std.testing.expect(unwrapToken("https://example.test/a**b") == null);+}diff --git a/src/session_settings.zig b/src/session_settings.zigindex e82cb105..72b8e4aa 100644--- a/src/session_settings.zig+++ b/src/session_settings.zig@@ -312,6 +312,11 @@ pub fn setupSkillsAndTheme(io: Io, arena: Allocator, environ_map: anytype, out:\\- [x] Sanitize public errors.\\ - Preserve private incident detail.\\> Public errors must never expose secrets.+ \\- Wrapped: *https://example.test/a* **https://example.test/b**+ \\- Wrapped: _https://example.test/c_ __https://example.test/d__+ \\- Wrapped: ~~https://example.test/e~~ `https://example.test/f`+ \\- URL data: https://example.test/glob/** https://example.test/path/__+ \\- URL data: https://example.test/path/~~ https://example.test/a**b\\- Link: **https://github.com/justrach/codegraff/issues/728**);probe.flushStreamTail();