From 8fd3e8b85dbfac1d7e642e3751e1518aeeb1a109 Mon Sep 17 00:00:00 2001 From: Muspi Merol Date: Fri, 27 Nov 2026 02:32:54 +0800 Subject: [PATCH 01/10] Fold each injected record under its activity line --- scripts/events.test.ts | 34 ++++++++++++++++++++++++++++------ scripts/injected-log.jq | 27 +++++++++++++++++++++++++-- scripts/injected-log.test.ts | 6 ++++-- 3 files changed, 57 insertions(+), 10 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 50414c7..e7c6267 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -55,7 +55,9 @@ function runLoggedHook(log: string, overrides = {}) { const activities = injected.split("\n").filter(Boolean).map(line => JSON.parse(line)); const contexts = JSON.parse(hook.output).reason.split("\n").slice(1, -1).map((line: string) => JSON.parse(line)); expect(contexts).toEqual(activities.map(({ workflow, ...context }) => context)); - return { ...hook, contexts, activities, text: formatted.stdout.toString().replace(/\u001b\[[0-9;]*m/g, "") }; + // Each activity is a group whose body is the delivered record; assertions read the headers. + const text = formatted.stdout.toString().split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length)).join("\n").replace(/\u001b\[[0-9;]*m/g, ""); + return { ...hook, contexts, activities, text }; } type CIResponse = { pages?: object[]; error?: string }; @@ -1557,12 +1559,30 @@ test("injected GitHub activity is logged with a colour per meaning", () => { JSON.stringify({ event: "check_run", check_run: { name: "CI ##[error]synthetic", details_url: "https://example.test/r/4" } }), ].join("\n") + "\n"); expect(crafted).not.toContain("::stop-commands::"); - expect(crafted).not.toMatch(/^ *::/m); + // Only the folding markers themselves may start a workflow command; nothing from a payload can. + for (const line of crafted.split("\n").filter(line => line.startsWith("::"))) { + expect(line === "::endgroup::" || line.startsWith("::group::")).toBe(true); + } expect(crafted).not.toContain("##["); expect(crafted).toContain(":​:error:​:forged"); expect(crafted).toContain("#​#[error]synthetic"); }); +test("an injected event folds the record the model received", () => { + const input = JSON.stringify({ event: "issue_comment", action: "created", sender: { login: "alice", type: "User" }, issue: { number: 7 }, + comment: { id: 4, body: "hi ##[error]x", html_url: "/pull/7#issuecomment-4" }, workflow: "CI" }); + const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(input + "\n") }); + expect(result.exitCode).toBe(0); + const output = result.stdout.toString(); + // The header is what the live view reads; the record folds under it so the payload can be checked in place. + expect(output.startsWith("::group::\u001b[96missue_comment/created\u001b[0m alice /pull/7#issuecomment-4\n{\n")).toBe(true); + expect(output).toContain(' \u001b[36m"comment"\u001b[0m: {\n \u001b[36m"id"\u001b[0m: \u001b[33m4\u001b[0m,'); + expect(output).toContain('\u001b[32m"hi #\u200b#[error]x"\u001b[0m'); + // `workflow` is display-only correlation the model never received. + expect(output).not.toContain('"workflow"'); + expect(output.endsWith("\n::endgroup::\n\n")).toBe(true); +}); + test("hook deliveries are published for the live log", () => { const { dir, output } = runHook(frame("issue_comment", { sender: human, issue: { number: 7, pull_request: {} }, comment: { id: 1, body: "hi", html_url: "https://example.test/c/1" } }, "writer", true)); expect(JSON.parse(output).decision).toBe("block"); @@ -1808,7 +1828,9 @@ test("injected command markers stay escaped when concurrent output splits a line const { dir } = runHook(frame("check_run", { action: "completed", sender: bot, check_run: check({ name: `${"x".repeat(4096)}::error::forged\n:::error title=forged:::payload` }) })); const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(readFileSync(join(dir, "injected.log"))) }); expect(result.exitCode).toBe(0); - expect(result.stdout.toString()).not.toContain("::"); + for (const line of result.stdout.toString().split("\n").filter(line => line.startsWith("::"))) { + expect(line === "::endgroup::" || line.startsWith("::group::")).toBe(true); + } }); test("injected command escaping covers the runner's leading whitespace", () => { @@ -1818,8 +1840,8 @@ test("injected command escaping covers the runner's leading whitespace", () => { const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(readFileSync(join(dir, "injected.log"))) }); expect(result.exitCode).toBe(0); // Include U+0085 explicitly because JavaScript trimStart does not include it, whereas .NET does. - const lines = result.stdout.toString().split("\n").map((line) => line.replace(/^[\s\u0085]+/, "")); - expect(lines.some((line) => line.startsWith("::"))).toBe(false); + const lines = result.stdout.toString().split("\n").map((line) => line.replace(/^[\s\u0085]+/, "")).filter((line) => line.startsWith("::")); + expect(lines.every((line) => line === "::endgroup::" || line.startsWith("::group::"))).toBe(true); } }); @@ -2067,7 +2089,7 @@ test("injected changes link to the received commit in its PR when available", () for (const pr of ["7", ""]) { const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(input), env: { ...process.env, PR_NUMBER: pr } }); expect(result.exitCode).toBe(0); - const lines = result.stdout.toString().split("\n").filter(Boolean); + const lines = result.stdout.toString().split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length)); const path = pr ? `/pull/${pr}/commits/${head}` : `/commit/${head}`; for (const line of lines.slice(0, 2)) expect(line).toEndWith(path); for (const line of lines.slice(2, 4)) expect(line).not.toContain("/commit"); diff --git a/scripts/injected-log.jq b/scripts/injected-log.jq index 2dec30e..3f36730 100644 --- a/scripts/injected-log.jq +++ b/scripts/injected-log.jq @@ -33,12 +33,35 @@ def event_line: "\u001b[\(event_color)m\(.event)\(if .action then "/" + .action + (event_subject | if . == "" then "" else " " + . end) + (verdict | if . then ":" + . else "" end) + (target_url | if . then " " + . else "" end); +# The folded body is the record the model received, so colour it the way jq colours a terminal: keys, strings, numbers and literals each get a colour. +def hkey: tojson | "\u001b[36m\(.)\u001b[0m"; +def scalar: if type == "string" then tojson | "\u001b[32m\(.)\u001b[0m" + elif type == "number" then "\u001b[33m\(tostring)\u001b[0m" + elif type == "boolean" then "\u001b[35m\(tostring)\u001b[0m" + else "\u001b[90mnull\u001b[0m" end; +def pretty($depth): + (reduce range(0; $depth) as $i (""; . + " ")) as $pad + | if type == "object" then + if length == 0 then "{}" else + "{\n" + (to_entries | map($pad + " " + (.key | hkey) + ": " + (.value | pretty($depth + 1))) | join(",\n")) + "\n" + $pad + "}" + end + elif type == "array" then + if length == 0 then "[]" else + "[\n" + (map($pad + " " + pretty($depth + 1)) | join(",\n")) + "\n" + $pad + "]" + end + else scalar end; # Event text comes from GitHub payloads, and the runner parses a workflow command in any line of stdout: `::` after leading whitespace, and legacy `##[` anywhere. # Break every marker, including overlapping colons: concurrent tool output can insert a newline inside a long event record. # A zero-width space keeps the log readable without sharing the tool logger's suppression token. def escape_commands: gsub("\r"; "") | gsub("##\\["; "#​#[") | gsub(":(?=:)"; ":​"); (fromjson? // null) as $event -| (if $event == null then . else ($event | event_line) end) -| escape_commands +# The line stays the summary the live view reads; the record itself folds under it so a reviewer can check what the model was told. +# Only the record is escaped: the group markers are ours and the runner has to read them. +| (if $event == null then . | escape_commands else + # A group title is one line: a payload newline inside a name would end the fold at the runner. + "::group::" + ($event | event_line | escape_commands | gsub("\n"; " ")) + + "\n" + ($event | del(.workflow) | pretty(0) | escape_commands) + + "\n::endgroup::" + end) # The live log view paints a band behind lines that carry only whitespace, and copied logs keep it; emit no trailing spaces. | gsub("(?m)[ \t]+$"; "") | rtrimstr("\n") + "\n" diff --git a/scripts/injected-log.test.ts b/scripts/injected-log.test.ts index c76dc2b..d397512 100644 --- a/scripts/injected-log.test.ts +++ b/scripts/injected-log.test.ts @@ -110,7 +110,7 @@ test.each([ log.append(...records); await until(() => log.output().includes("subscription_recovery")); await log.finish(); - expect(log.output().trim().split("\n").filter(Boolean)).toEqual([ + expect(log.output().split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length))).toEqual([ "check_run/completed CI / dependabot job:success /actions/runs/90/job/1", "check_run/completed CI / human job:success /actions/runs/90/job/2", "check_run/completed blacksmith.sh / Proof:skipped https://blacksmith.sh/check/3", @@ -150,7 +150,9 @@ test("CI log uses the hosted credential and escapes API-supplied names", async ( await until(() => log.output().includes("check (windows, 3.12):success")); await log.finish(); expect(log.calls()[0]).toMatchObject({ token: "", config: log.env.GH_CONFIG_DIR }); - expect(log.output()).not.toContain("::"); + for (const line of log.output().split("\n").filter(line => line.startsWith("::"))) { + expect(line === "::endgroup::" || line.startsWith("::group::")).toBe(true); + } expect(log.output()).not.toContain("##["); }); From 048711e309ac94609edacffbabb22c538928da76 Mon Sep 17 00:00:00 2001 From: "muspi-merol-review[bot]" <349105566+muspi-merol-review[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:40:16 +0000 Subject: [PATCH 02/10] Preserve activity titles and check the full worker output --- scripts/events.test.ts | 25 +++++++++++++++++++------ scripts/injected-log.jq | 7 +++++-- scripts/injected-log.test.ts | 8 ++++++-- 3 files changed, 30 insertions(+), 10 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index e7c6267..de132d5 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -57,7 +57,7 @@ function runLoggedHook(log: string, overrides = {}) { expect(contexts).toEqual(activities.map(({ workflow, ...context }) => context)); // Each activity is a group whose body is the delivered record; assertions read the headers. const text = formatted.stdout.toString().split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length)).join("\n").replace(/\u001b\[[0-9;]*m/g, ""); - return { ...hook, contexts, activities, text }; + return { ...hook, contexts, activities, text, formatted: formatted.stdout }; } type CIResponse = { pages?: object[]; error?: string }; @@ -1583,6 +1583,20 @@ test("an injected event folds the record the model received", () => { expect(output.endsWith("\n::endgroup::\n\n")).toBe(true); }); +test("the Actions runner decodes the group title without changing percent-encoded text", () => { + const name = "build%0Apreview\nreport", url = "https://example.test/?discount=5%25"; + const input = JSON.stringify({ event: "status", context: name, target_url: url }); + for (const hosted of ["", "true"]) { + const result = Bun.spawnSync(["jq", "-Rr", "-f", join(scripts, "injected-log.jq")], { + stdin: Buffer.from(input), env: { ...process.env, REVIEW_HOSTED: hosted }, + }); + expect(result.exitCode).toBe(0); + const [header] = result.stdout.toString().split("\n"); + const title = hosted ? header : header.replaceAll("%0D", "\r").replaceAll("%0A", "\n").replaceAll("%25", "%"); + expect(title).toEndWith("build%0Apreview report " + url); + } +}); + test("hook deliveries are published for the live log", () => { const { dir, output } = runHook(frame("issue_comment", { sender: human, issue: { number: 7, pull_request: {} }, comment: { id: 1, body: "hi", html_url: "https://example.test/c/1" } }, "writer", true)); expect(JSON.parse(output).decision).toBe("block"); @@ -1624,7 +1638,7 @@ test.each([ { event: "subscription_recovery", body: { reason: "connection_failed", status: "0" }, expected: { reason: "connection_failed", status: "0" } }, ]; const events = cases.map(({ event, body }) => frame(event, body)); - const { dir, run, contexts, text, env: hookEnv } = runLoggedHook(events.join("") + events.join(""), env); + const { dir, run, contexts, text, formatted, env: hookEnv } = runLoggedHook(events.join("") + events.join(""), env); expect(contexts).toHaveLength(cases.length); for (const [index, { event, body, expected }] of cases.entries()) { const context = contexts[index]; @@ -1656,7 +1670,7 @@ test.each([ const worker = Bun.spawnSync(["bash", join(scripts, "injected-log.sh"), path], { env: { ...hookEnv, ...env }, timeout: 3000 }); expect(worker.exitCode).toBe(0); expect(worker.stderr.toString()).toBe(""); - expect(worker.stdout.toString().replace(/\u001b\[[0-9;]*m/g, "")).toBe(text); + expect(worker.stdout).toEqual(formatted); }); test("branch commit comments retain their commit, file, line and original sender", () => { @@ -1828,9 +1842,8 @@ test("injected command markers stay escaped when concurrent output splits a line const { dir } = runHook(frame("check_run", { action: "completed", sender: bot, check_run: check({ name: `${"x".repeat(4096)}::error::forged\n:::error title=forged:::payload` }) })); const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(readFileSync(join(dir, "injected.log"))) }); expect(result.exitCode).toBe(0); - for (const line of result.stdout.toString().split("\n").filter(line => line.startsWith("::"))) { - expect(line === "::endgroup::" || line.startsWith("::group::")).toBe(true); - } + const payload = result.stdout.toString().replace(/^::group::/, "").replace(/\n::endgroup::\n\n$/, ""); + expect(payload).not.toContain("::"); }); test("injected command escaping covers the runner's leading whitespace", () => { diff --git a/scripts/injected-log.jq b/scripts/injected-log.jq index 3f36730..81f6b94 100644 --- a/scripts/injected-log.jq +++ b/scripts/injected-log.jq @@ -54,14 +54,17 @@ def pretty($depth): # Break every marker, including overlapping colons: concurrent tool output can insert a newline inside a long event record. # A zero-width space keeps the log readable without sharing the tool logger's suppression token. def escape_commands: gsub("\r"; "") | gsub("##\\["; "#​#[") | gsub(":(?=:)"; ":​"); +# The Actions runner decodes percent escapes in a group title. The hosted log reads it directly. +def group_title: event_line | escape_commands | gsub("\n"; " ") | if env.REVIEW_HOSTED == "true" then . else gsub("%"; "%25") end; (fromjson? // null) as $event # The line stays the summary the live view reads; the record itself folds under it so a reviewer can check what the model was told. # Only the record is escaped: the group markers are ours and the runner has to read them. | (if $event == null then . | escape_commands else # A group title is one line: a payload newline inside a name would end the fold at the runner. - "::group::" + ($event | event_line | escape_commands | gsub("\n"; " ")) + "::group::" + ($event | group_title) + "\n" + ($event | del(.workflow) | pretty(0) | escape_commands) + "\n::endgroup::" end) # The live log view paints a band behind lines that carry only whitespace, and copied logs keep it; emit no trailing spaces. -| gsub("(?m)[ \t]+$"; "") | rtrimstr("\n") + "\n" +# Start only at the first space in a run so a long stretch inside a comment takes one pass. +| gsub("(?m)(? boolean, timeout = 2000) { } } +function groupTitles(output: string) { + return output.split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length)); +} + function start(responses: Record = {}, env = {}) { const setup = fixture(responses, env); const process = Bun.spawn(["bash", join(import.meta.dir, "injected-log.sh"), join(setup.dir, "injected.log")], { env: setup.env, stdout: "pipe", stderr: "pipe" }); @@ -83,7 +87,7 @@ test("CI log resolves and caches the exact suite using only the Actions credenti await until(() => log.output().includes("CI / check (windows, 3.13):success")); await log.finish(); expect(log.output()).toContain("CI / check (windows, 3.12):success"); - expect(log.output()).not.toContain("dependabot"); + expect(groupTitles(log.output()).join("\n")).not.toContain("dependabot"); expect(log.calls()).toEqual([{ argv: ["api", "repos/owner/repo/actions/runs?check_suite_id=100&per_page=1"], token: "job-token", config: log.env.GH_CONFIG_DIR, stdin: "" }]); }); @@ -110,7 +114,7 @@ test.each([ log.append(...records); await until(() => log.output().includes("subscription_recovery")); await log.finish(); - expect(log.output().split("\n").filter(line => line.startsWith("::group::")).map(line => line.slice("::group::".length))).toEqual([ + expect(groupTitles(log.output())).toEqual([ "check_run/completed CI / dependabot job:success /actions/runs/90/job/1", "check_run/completed CI / human job:success /actions/runs/90/job/2", "check_run/completed blacksmith.sh / Proof:skipped https://blacksmith.sh/check/3", From 5e5ba11d03208ca8c45c4a6cffb3fe1acc8d91c6 Mon Sep 17 00:00:00 2001 From: Muspi Merol Date: Fri, 27 Nov 2026 02:49:57 +0800 Subject: [PATCH 03/10] Start each folded record on its own line --- scripts/events.test.ts | 2 +- scripts/injected-log.jq | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index de132d5..83fd6b9 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1575,7 +1575,7 @@ test("an injected event folds the record the model received", () => { expect(result.exitCode).toBe(0); const output = result.stdout.toString(); // The header is what the live view reads; the record folds under it so the payload can be checked in place. - expect(output.startsWith("::group::\u001b[96missue_comment/created\u001b[0m alice /pull/7#issuecomment-4\n{\n")).toBe(true); + expect(output.startsWith("\n::group::\u001b[96missue_comment/created\u001b[0m alice /pull/7#issuecomment-4\n{\n")).toBe(true); expect(output).toContain(' \u001b[36m"comment"\u001b[0m: {\n \u001b[36m"id"\u001b[0m: \u001b[33m4\u001b[0m,'); expect(output).toContain('\u001b[32m"hi #\u200b#[error]x"\u001b[0m'); // `workflow` is display-only correlation the model never received. diff --git a/scripts/injected-log.jq b/scripts/injected-log.jq index 81f6b94..1b3ec3b 100644 --- a/scripts/injected-log.jq +++ b/scripts/injected-log.jq @@ -61,7 +61,8 @@ def group_title: event_line | escape_commands | gsub("\n"; " ") | if env.REVIEW_ # Only the record is escaped: the group markers are ours and the runner has to read them. | (if $event == null then . | escape_commands else # A group title is one line: a payload newline inside a name would end the fold at the runner. - "::group::" + ($event | group_title) + # A newline first: the tool log writer shares stdout and can be mid-line, and a header it swallows would leave our close marker to end its group. + "\n::group::" + ($event | group_title) + "\n" + ($event | del(.workflow) | pretty(0) | escape_commands) + "\n::endgroup::" end) From 6f8d1e80c1507467179bf49afbcb46eaf8e54aac Mon Sep 17 00:00:00 2001 From: "muspi-merol-review[bot]" <349105566+muspi-merol-review[bot]@users.noreply.github.com> Date: Thu, 26 Nov 2026 18:52:08 +0000 Subject: [PATCH 04/10] Account for the leading newline in activity log tests --- scripts/events.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 83fd6b9..39752e1 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1591,7 +1591,7 @@ test("the Actions runner decodes the group title without changing percent-encode stdin: Buffer.from(input), env: { ...process.env, REVIEW_HOSTED: hosted }, }); expect(result.exitCode).toBe(0); - const [header] = result.stdout.toString().split("\n"); + const [, header] = result.stdout.toString().split("\n"); const title = hosted ? header : header.replaceAll("%0D", "\r").replaceAll("%0A", "\n").replaceAll("%25", "%"); expect(title).toEndWith("build%0Apreview report " + url); } @@ -1842,7 +1842,7 @@ test("injected command markers stay escaped when concurrent output splits a line const { dir } = runHook(frame("check_run", { action: "completed", sender: bot, check_run: check({ name: `${"x".repeat(4096)}::error::forged\n:::error title=forged:::payload` }) })); const result = Bun.spawnSync(["jq", "-Rr", "-f", join(root, "scripts/injected-log.jq")], { stdin: Buffer.from(readFileSync(join(dir, "injected.log"))) }); expect(result.exitCode).toBe(0); - const payload = result.stdout.toString().replace(/^::group::/, "").replace(/\n::endgroup::\n\n$/, ""); + const payload = result.stdout.toString().replace(/^\n::group::/, "").replace(/\n::endgroup::\n\n$/, ""); expect(payload).not.toContain("::"); }); From b1cbf42127aebfd1f7ae00ee6db82f2d96acb93c Mon Sep 17 00:00:00 2001 From: Muspi Merol Date: Sat, 28 Nov 2026 01:26:06 +0800 Subject: [PATCH 05/10] Let one process own the review's stdout --- scripts/events.test.ts | 13 +++++++++++ scripts/injected-log.sh | 7 +++++- scripts/log-mux.mjs | 50 +++++++++++++++++++++++++++++++++++++++++ scripts/run-review.sh | 7 +++++- 4 files changed, 75 insertions(+), 2 deletions(-) create mode 100644 scripts/log-mux.mjs diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 39752e1..8f3c635 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1568,6 +1568,19 @@ test("injected GitHub activity is logged with a colour per meaning", () => { expect(crafted).toContain("#​#[error]synthetic"); }); +test("one writer prints activity only between whole tool records", () => { + const dir = mkdtempSync(join(tmpdir(), "review-mux-")); + homes.push(dir); + writeFileSync(join(dir, "injected.rendered"), "\n::group::activity\n{}\n::endgroup::\n"); + const toolLog = "::group::$\nsleep 1\n::endgroup::\nplain line\n"; + const result = Bun.spawnSync(["bash", join(scripts, "review-bun.sh"), join(root, "scripts/log-mux.mjs")], { + env: { ...process.env, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root }, stdin: Buffer.from(toolLog), timeout: 8000, + }); + expect(result.exitCode).toBe(0); + // The activity block is whole and lands outside the tool group, whatever the tool writer was doing. + expect(result.stdout.toString()).toBe("\n::group::activity\n{}\n::endgroup::\n" + toolLog); +}); + test("an injected event folds the record the model received", () => { const input = JSON.stringify({ event: "issue_comment", action: "created", sender: { login: "alice", type: "User" }, issue: { number: 7 }, comment: { id: 4, body: "hi ##[error]x", html_url: "/pull/7#issuecomment-4" }, workflow: "CI" }); diff --git a/scripts/injected-log.sh b/scripts/injected-log.sh index 46470ed..0619d95 100644 --- a/scripts/injected-log.sh +++ b/scripts/injected-log.sh @@ -35,5 +35,10 @@ while IFS= read -r line <&3; do enriched=$(jq -c --arg workflow "${workflows[$key]}" '. + {workflow: $workflow}' <<< "$line" 2>/dev/null) && line=$enriched fi fi - printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" + # The action routes this through the log multiplexer, which is the only writer on stdout; anywhere else prints. + if [ -n "${LOG_RENDERED:-}" ]; then + printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" >> "$LOG_RENDERED" + else + printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" + fi done diff --git a/scripts/log-mux.mjs b/scripts/log-mux.mjs new file mode 100644 index 0000000..c0a6d7b --- /dev/null +++ b/scripts/log-mux.mjs @@ -0,0 +1,50 @@ +// The only process that writes the review's stdout: it prints the tool log and, between whole records, whatever the +// activity worker rendered in the meantime. Two writers interleaved a fold marker with tool output, which the runner +// then paired with the wrong group. +import { readFileSync, writeFileSync, writeSync } from "node:fs"; +import { join } from "node:path"; + +const rendered = join(process.env.RUNNER_TEMP, "injected.rendered"); +const cursor = join(process.env.RUNNER_TEMP, "injected.offset"); +// The worker can outlive the tool stream, so the offset is handed to a final drain. +let offset = 0; +try { + offset = Number(readFileSync(cursor, "utf8").trim() || 0); +} catch {} +const drain = () => { + let content; + try { + content = readFileSync(rendered); + } catch { + return; // The worker creates it; nothing to drain before that. + } + if (content.length <= offset) return; + writeSync(1, content.subarray(offset)); + offset = content.length; + writeFileSync(cursor, String(offset)); +}; + +if (process.argv.includes("--drain")) { + drain(); + process.exit(0); +} + +let pending = "", inGroup = false; +const decoder = new TextDecoder(); +// A record is one line, or a whole fold from its header to its end marker; the worker's output waits for the boundary. +for await (const chunk of Bun.stdin.stream()) { + pending += decoder.decode(chunk, { stream: true }); + for (let end; (end = pending.indexOf("\n")) !== -1;) { + const line = pending.slice(0, end + 1); + pending = pending.slice(end + 1); + if (!inGroup) drain(); + writeSync(1, line); + if (line.startsWith("::group::")) inGroup = true; + else if (line.startsWith("::endgroup::")) inGroup = false; + } +} +if (pending) { + if (!inGroup) drain(); + writeSync(1, pending); +} +if (!inGroup) drain(); diff --git a/scripts/run-review.sh b/scripts/run-review.sh index a2043cb..9526474 100644 --- a/scripts/run-review.sh +++ b/scripts/run-review.sh @@ -83,7 +83,10 @@ fresh() { "$OPEN" } codex_patches() { "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/codex-patches.mjs" "$@"; } -log() { codex_patches "${1:-}" | jq --unbuffered -rR --arg stop "$(openssl rand -hex 16)" -f "$GITHUB_ACTION_PATH/scripts/codex-log.jq"; } +# One process owns stdout: the activity worker renders into a file and this multiplexer prints it between records. +export LOG_RENDERED="$RUNNER_TEMP/injected.rendered" +: > "$LOG_RENDERED" +log() { codex_patches "${1:-}" | jq --unbuffered -rR --arg stop "$(openssl rand -hex 16)" -f "$GITHUB_ACTION_PATH/scripts/codex-log.jq" | bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs"; } # Hook deliveries never reach the exec stream, so the hook writes them aside and this tail shows them as they land. # This writer escapes command syntax instead of stopping commands, since the tool log above holds the runner's one suppression token. : > "$RUNNER_TEMP/injected.log" @@ -98,6 +101,8 @@ finish_injected() { kill "$INJECTED_TAIL" 2>/dev/null || true fi wait "$INJECTED_TAIL" 2>/dev/null || true + # The worker can finish after the tool stream; print what it rendered in the meantime. + bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs" --drain || true # The hosted parent flushes during cleanup. Actions runs this script directly. if [ "${REVIEW_HOSTED:-}" != true ] && [ -n "${REVIEW_TRACE_RELAY_URL:-}" ]; then "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/review-trace.mjs" --flush || true From 911051ab7fd88e4ea8521f5ba4129996fd2118f6 Mon Sep 17 00:00:00 2001 From: "muspi-merol-review[bot]" <349105566+muspi-merol-review[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:33:50 +0000 Subject: [PATCH 06/10] Read only new activity bytes and reset the cursor for each review --- scripts/events.test.ts | 26 ++++++++++++++++++-------- scripts/hosted-review.test.ts | 6 ++++-- scripts/injected-log.test.ts | 4 ++++ scripts/log-mux.mjs | 20 +++++++++++++------- scripts/run-review.sh | 7 +++---- 5 files changed, 42 insertions(+), 21 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 8f3c635..6ab3f09 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1568,17 +1568,27 @@ test("injected GitHub activity is logged with a colour per meaning", () => { expect(crafted).toContain("#​#[error]synthetic"); }); -test("one writer prints activity only between whole tool records", () => { +test("one writer prints activity only between whole tool records", async () => { const dir = mkdtempSync(join(tmpdir(), "review-mux-")); homes.push(dir); - writeFileSync(join(dir, "injected.rendered"), "\n::group::activity\n{}\n::endgroup::\n"); - const toolLog = "::group::$\nsleep 1\n::endgroup::\nplain line\n"; - const result = Bun.spawnSync(["bash", join(scripts, "review-bun.sh"), join(root, "scripts/log-mux.mjs")], { - env: { ...process.env, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root }, stdin: Buffer.from(toolLog), timeout: 8000, + const activity = "\n::group::activity\n{}\n::endgroup::\n"; + const header = "::group::$\n", body = "sleep 1\n::endgroup::\n"; + const child = Bun.spawn(["bash", join(scripts, "review-bun.sh"), join(root, "scripts/log-mux.mjs")], { + env: { ...process.env, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root }, stdin: "pipe", stdout: "pipe", timeout: 3000, }); - expect(result.exitCode).toBe(0); - // The activity block is whole and lands outside the tool group, whatever the tool writer was doing. - expect(result.stdout.toString()).toBe("\n::group::activity\n{}\n::endgroup::\n" + toolLog); + child.stdin.write(header); + child.stdin.flush(); + const reader = child.stdout.getReader(); + const { value } = await reader.read(); + reader.releaseLock(); + // Append only after the mux starts printing the tool group. + writeFileSync(join(dir, "injected.rendered"), activity); + child.stdin.write(body + "plain line\n"); + child.stdin.end(); + let output = new TextDecoder().decode(value); + for await (const chunk of child.stdout) output += new TextDecoder().decode(chunk); + expect(await child.exited).toBe(0); + expect(output).toBe(header + body + activity + "plain line\n"); }); test("an injected event folds the record the model received", () => { diff --git a/scripts/hosted-review.test.ts b/scripts/hosted-review.test.ts index 52c3fe5..b9439d4 100644 --- a/scripts/hosted-review.test.ts +++ b/scripts/hosted-review.test.ts @@ -283,9 +283,11 @@ exec '${process.execPath}' --config="$RUNNER_TEMP/mock-bun.toml" "$RUNNER_TEMP/d const launch = launcher === "npm" ? [codex] : []; const args = (entrypoint: string) => [setup.checkout, `--config=${join(actionPath, "scripts", "review-bun.toml")}`, entrypoint]; const patches = join(actionPath, "scripts", "codex-patches.mjs"); - // The two sides of the review pipeline can start in either order. + const mux = join(actionPath, "scripts", "log-mux.mjs"); + // Pipeline stages start concurrently. The mux runs once more for the final drain. expect(calls.filter(call => call[2] === patches)).toEqual([args(patches)]); - expect(calls.filter(call => call[2] !== patches)).toEqual([ + expect(calls.filter(call => call[2] === mux)).toEqual([args(mux), args(mux)]); + expect(calls.filter(call => call[2] !== patches && call[2] !== mux)).toEqual([ ...launch, join(actionPath, "scripts", "doc-fallbacks.ts"), "-e", ...(entry === "hosted" ? ["-e"] : []), ...launch, ].map(args)); }); diff --git a/scripts/injected-log.test.ts b/scripts/injected-log.test.ts index 743981c..f6381e6 100644 --- a/scripts/injected-log.test.ts +++ b/scripts/injected-log.test.ts @@ -225,10 +225,14 @@ test.each([0, 7])("review log cleanup preserves exit code %i and drains its fina const { dir, env } = fixture(); const source = readFileSync(join(import.meta.dir, "run-review.sh"), "utf8"); const region = source.slice(source.indexOf(': > "$RUNNER_TEMP/injected.log"'), source.indexOf("trap finish_injected EXIT") + "trap finish_injected EXIT".length); + // A reused runner can retain the previous review's spool and cursor. + writeFileSync(join(dir, "injected.rendered"), "old activity\n".repeat(200)); + writeFileSync(join(dir, "injected.offset"), String(readFileSync(join(dir, "injected.rendered")).length)); writeFileSync(join(dir, "records"), JSON.stringify(event(100, "last job", { workflow: "CI" })) + "\n"); const result = Bun.spawnSync(["bash", "-eo", "pipefail", "-c", `${region}\ncat "$RUNNER_TEMP/records" >> "$RUNNER_TEMP/injected.log"\nexit ${code}`], { env, timeout: 3000 }); expect(result.exitCode).toBe(code); expect(result.stdout.toString()).toContain("CI / last job:success"); + expect(result.stdout.toString()).not.toContain("old activity"); expect(result.stdout.toString()).not.toContain("review_log_end"); expect(() => process.kill(Number(readFileSync(join(dir, "tail.pid"), "utf8")), 0)).toThrow(); }); diff --git a/scripts/log-mux.mjs b/scripts/log-mux.mjs index c0a6d7b..f7b02b9 100644 --- a/scripts/log-mux.mjs +++ b/scripts/log-mux.mjs @@ -1,7 +1,7 @@ // The only process that writes the review's stdout: it prints the tool log and, between whole records, whatever the // activity worker rendered in the meantime. Two writers interleaved a fold marker with tool output, which the runner // then paired with the wrong group. -import { readFileSync, writeFileSync, writeSync } from "node:fs"; +import { fstatSync, openSync, readFileSync, readSync, writeFileSync, writeSync } from "node:fs"; import { join } from "node:path"; const rendered = join(process.env.RUNNER_TEMP, "injected.rendered"); @@ -11,16 +11,22 @@ let offset = 0; try { offset = Number(readFileSync(cursor, "utf8").trim() || 0); } catch {} +const activityBuffer = Buffer.allocUnsafe(64 * 1024); +let renderedFd; const drain = () => { - let content; try { - content = readFileSync(rendered); + renderedFd ??= openSync(rendered, "r"); } catch { - return; // The worker creates it; nothing to drain before that. + return; // The optional activity log may be unavailable. + } + const end = fstatSync(renderedFd).size; + if (end <= offset) return; + while (offset < end) { + const size = readSync(renderedFd, activityBuffer, 0, Math.min(end - offset, activityBuffer.length), offset); + if (!size) break; + for (let written = 0; written < size;) written += writeSync(1, activityBuffer, written, size - written); + offset += size; } - if (content.length <= offset) return; - writeSync(1, content.subarray(offset)); - offset = content.length; writeFileSync(cursor, String(offset)); }; diff --git a/scripts/run-review.sh b/scripts/run-review.sh index 9526474..a7b9765 100644 --- a/scripts/run-review.sh +++ b/scripts/run-review.sh @@ -84,14 +84,13 @@ fresh() { } codex_patches() { "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/codex-patches.mjs" "$@"; } # One process owns stdout: the activity worker renders into a file and this multiplexer prints it between records. -export LOG_RENDERED="$RUNNER_TEMP/injected.rendered" -: > "$LOG_RENDERED" log() { codex_patches "${1:-}" | jq --unbuffered -rR --arg stop "$(openssl rand -hex 16)" -f "$GITHUB_ACTION_PATH/scripts/codex-log.jq" | bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs"; } # Hook deliveries never reach the exec stream, so the hook writes them aside and this tail shows them as they land. # This writer escapes command syntax instead of stopping commands, since the tool log above holds the runner's one suppression token. : > "$RUNNER_TEMP/injected.log" -rm -f "$RUNNER_TEMP/injected.done" -REVIEW_ACTIONS_TOKEN="${REVIEW_ACTIONS_TOKEN:-}" bash "$GITHUB_ACTION_PATH/scripts/injected-log.sh" "$RUNNER_TEMP/injected.log" & +: > "$RUNNER_TEMP/injected.rendered" +rm -f "$RUNNER_TEMP/injected.done" "$RUNNER_TEMP/injected.offset" +LOG_RENDERED="$RUNNER_TEMP/injected.rendered" REVIEW_ACTIONS_TOKEN="${REVIEW_ACTIONS_TOKEN:-}" bash "$GITHUB_ACTION_PATH/scripts/injected-log.sh" "$RUNNER_TEMP/injected.log" & INJECTED_TAIL=$! # Only the background log worker needs the GitHub Actions lookup credential. unset REVIEW_ACTIONS_TOKEN From 6957dce4b9ce4700ff485542106f5b7c638b5b4a Mon Sep 17 00:00:00 2001 From: "muspi-merol-review[bot]" <349105566+muspi-merol-review[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 17:38:37 +0000 Subject: [PATCH 07/10] Keep worker test output out of the parent review log --- scripts/events.test.ts | 2 +- scripts/injected-log.test.ts | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 6ab3f09..ba305af 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1690,7 +1690,7 @@ test.each([ // Run the same records through the actual shared worker used by both entry points. const path = join(dir, "injected.log"); writeFileSync(path, readFileSync(path, "utf8") + '{"review_log_end":true}\n'); - const worker = Bun.spawnSync(["bash", join(scripts, "injected-log.sh"), path], { env: { ...hookEnv, ...env }, timeout: 3000 }); + const worker = Bun.spawnSync(["bash", join(scripts, "injected-log.sh"), path], { env: { ...hookEnv, ...env, LOG_RENDERED: "" }, timeout: 3000 }); expect(worker.exitCode).toBe(0); expect(worker.stderr.toString()).toBe(""); expect(worker.stdout).toEqual(formatted); diff --git a/scripts/injected-log.test.ts b/scripts/injected-log.test.ts index f6381e6..e1e8c38 100644 --- a/scripts/injected-log.test.ts +++ b/scripts/injected-log.test.ts @@ -35,7 +35,7 @@ if (response.fail) { console.error("HTTP 403"); process.exit(1); } console.log(JSON.stringify(response.body || {})); `); for (const name of ["gh", "tail"]) chmodSync(join(dir, name), 0o755); - return { setup, dir, env: { ...process.env, PATH: `${dir}:${process.env.PATH}`, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root, GITHUB_REPOSITORY: "owner/repo", GH_CONFIG_DIR: join(dir, "gh-config"), REVIEW_ACTIONS_TOKEN: "job-token", GH_TOKEN: "app-token", GITHUB_TOKEN: "", ...env } }; + return { setup, dir, env: { ...process.env, PATH: `${dir}:${process.env.PATH}`, RUNNER_TEMP: dir, LOG_RENDERED: "", GITHUB_ACTION_PATH: root, GITHUB_REPOSITORY: "owner/repo", GH_CONFIG_DIR: join(dir, "gh-config"), REVIEW_ACTIONS_TOKEN: "job-token", GH_TOKEN: "app-token", GITHUB_TOKEN: "", ...env } }; } async function until(predicate: () => boolean, timeout = 2000) { From f20de30de61342ca7d7c16c027f1bb7be882ae48 Mon Sep 17 00:00:00 2001 From: Muspi Merol Date: Sat, 28 Nov 2026 07:14:54 +0800 Subject: [PATCH 08/10] Serialize complete live log records across review attempts --- scripts/codex-log.jq | 2 +- scripts/codex-patches.mjs | 3 +- scripts/events.test.ts | 39 ++--- scripts/injected-log.jq | 10 +- scripts/injected-log.sh | 6 +- scripts/injected-log.test.ts | 152 ++++++++++++++++++++ scripts/log-mux.mjs | 113 +++++++++------ scripts/log-mux.test.ts | 267 +++++++++++++++++++++++++++++++++++ scripts/run-review.sh | 10 +- 9 files changed, 521 insertions(+), 81 deletions(-) create mode 100644 scripts/log-mux.test.ts diff --git a/scripts/codex-log.jq b/scripts/codex-log.jq index b0f0c50..d96de0d 100644 --- a/scripts/codex-log.jq +++ b/scripts/codex-log.jq @@ -61,7 +61,7 @@ def prose: gsub("\r"; "") | gsub("(?m)[ \t]+$"; "") | if . == "" then "" else split("\n") | map(if . == "" then . else "\u001b[1;34m\(.)\u001b[0m" end) | join("\n") end; # The settled verdict is one JSON record, marked by its conclusion so it does not read as more prose. def verdict: (. | fromjson? // null) as $v | if ($v | type) == "object" and $v.conclusion then "\u001b[1;\(if $v.conclusion == "failure" then 31 else 32 end)m\(if $v.conclusion == "failure" then "✗" else "✓" end)\u001b[0m \($v | json)" else prose end; -fromjson? // {type: "error", message: .} +if type == "string" then fromjson? // {type: "error", message: .} else . end | if .type == "error" then .message elif .type == "turn.failed" then .error.message elif .type == "item.completed" and .item.type == "agent_message" then (.item.text // "" | verdict) diff --git a/scripts/codex-patches.mjs b/scripts/codex-patches.mjs index a813358..751811e 100644 --- a/scripts/codex-patches.mjs +++ b/scripts/codex-patches.mjs @@ -92,6 +92,7 @@ if (process.argv[2] === "--baseline") { if (paired) { console.log(JSON.stringify(event)); continue; } } catch { paired = false; } } - console.log(line); + // Keep stderr readable while feeding JSON to jq: its older raw-input reader corrupts split UTF-8 characters. + console.log(event === undefined ? JSON.stringify({ type: "error", message: line }) : line); } } diff --git a/scripts/events.test.ts b/scripts/events.test.ts index 64f298f..6f8493e 100644 --- a/scripts/events.test.ts +++ b/scripts/events.test.ts @@ -1567,29 +1567,6 @@ test("injected GitHub activity is logged with a colour per meaning", () => { expect(crafted).toContain("#​#[error]synthetic"); }); -test("one writer prints activity only between whole tool records", async () => { - const dir = mkdtempSync(join(tmpdir(), "review-mux-")); - homes.push(dir); - const activity = "\n::group::activity\n{}\n::endgroup::\n"; - const header = "::group::$\n", body = "sleep 1\n::endgroup::\n"; - const child = Bun.spawn(["bash", join(scripts, "review-bun.sh"), join(root, "scripts/log-mux.mjs")], { - env: { ...process.env, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root }, stdin: "pipe", stdout: "pipe", timeout: 3000, - }); - child.stdin.write(header); - child.stdin.flush(); - const reader = child.stdout.getReader(); - const { value } = await reader.read(); - reader.releaseLock(); - // Append only after the mux starts printing the tool group. - writeFileSync(join(dir, "injected.rendered"), activity); - child.stdin.write(body + "plain line\n"); - child.stdin.end(); - let output = new TextDecoder().decode(value); - for await (const chunk of child.stdout) output += new TextDecoder().decode(chunk); - expect(await child.exited).toBe(0); - expect(output).toBe(header + body + activity + "plain line\n"); -}); - test("an injected event folds the record the model received", () => { const input = JSON.stringify({ event: "issue_comment", action: "created", sender: { login: "alice", type: "User" }, issue: { number: 7 }, comment: { id: 4, body: "hi ##[error]x", html_url: "/pull/7#issuecomment-4" }, workflow: "CI" }); @@ -1599,12 +1576,26 @@ test("an injected event folds the record the model received", () => { // The header is what the live view reads; the record folds under it so the payload can be checked in place. expect(output.startsWith("\n::group::\u001b[96missue_comment/created\u001b[0m alice /pull/7#issuecomment-4\n{\n")).toBe(true); expect(output).toContain(' \u001b[36m"comment"\u001b[0m: {\n \u001b[36m"id"\u001b[0m: \u001b[33m4\u001b[0m,'); - expect(output).toContain('\u001b[32m"hi #\u200b#[error]x"\u001b[0m'); + expect(output).toContain('\u001b[32m"hi #\\u0023[error]x"\u001b[0m'); // `workflow` is display-only correlation the model never received. expect(output).not.toContain('"workflow"'); expect(output.endsWith("\n::endgroup::\n\n")).toBe(true); }); +test("folded activity JSON preserves command-like data, backslashes and zero-width spaces", () => { + const record = { event: "issue_comment", sender: { login: "alice" }, comment: { + body: "::error::forged\n##[error]forged\n:::warning:::overlap\n\\:: \\u003a \u0000 original:\u200b: #\u200b#[", + "::group::": "##[error]", + } }; + const result = Bun.spawnSync(["jq", "-Rr", "-f", join(scripts, "injected-log.jq")], { stdin: Buffer.from(JSON.stringify(record) + "\n") }); + expect(result.exitCode).toBe(0); + const output = result.stdout.toString().replace(/\x1b\[[0-9;]*m/g, ""); + const body = output.slice(output.indexOf("\n{\n") + 1, output.lastIndexOf("\n::endgroup::")); + expect(body).not.toContain("::"); + expect(body).not.toContain("##["); + expect(JSON.parse(body)).toEqual(record); +}); + test("the Actions runner decodes the group title without changing percent-encoded text", () => { const name = "build%0Apreview\nreport", url = "https://example.test/?discount=5%25"; const input = JSON.stringify({ event: "status", context: name, target_url: url }); diff --git a/scripts/injected-log.jq b/scripts/injected-log.jq index 1b3ec3b..8d65d76 100644 --- a/scripts/injected-log.jq +++ b/scripts/injected-log.jq @@ -51,19 +51,19 @@ def pretty($depth): end else scalar end; # Event text comes from GitHub payloads, and the runner parses a workflow command in any line of stdout: `::` after leading whitespace, and legacy `##[` anywhere. -# Break every marker, including overlapping colons: concurrent tool output can insert a newline inside a long event record. -# A zero-width space keeps the log readable without sharing the tool logger's suppression token. +# Break every marker, including overlapping colons, without sharing the tool logger's suppression token. def escape_commands: gsub("\r"; "") | gsub("##\\["; "#​#[") | gsub(":(?=:)"; ":​"); +# JSON escapes keep the folded record parseable back to the exact payload, including command-like strings. +def escape_json_commands: gsub("##\\["; "#\\u0023[") | gsub(":(?=:)"; "\\u003a"); # The Actions runner decodes percent escapes in a group title. The hosted log reads it directly. def group_title: event_line | escape_commands | gsub("\n"; " ") | if env.REVIEW_HOSTED == "true" then . else gsub("%"; "%25") end; -(fromjson? // null) as $event +(if type == "string" then fromjson? // null else . end) as $event # The line stays the summary the live view reads; the record itself folds under it so a reviewer can check what the model was told. # Only the record is escaped: the group markers are ours and the runner has to read them. | (if $event == null then . | escape_commands else # A group title is one line: a payload newline inside a name would end the fold at the runner. - # A newline first: the tool log writer shares stdout and can be mid-line, and a header it swallows would leave our close marker to end its group. "\n::group::" + ($event | group_title) - + "\n" + ($event | del(.workflow) | pretty(0) | escape_commands) + + "\n" + ($event | del(.workflow) | pretty(0) | escape_json_commands) + "\n::endgroup::" end) # The live log view paints a band behind lines that carry only whitespace, and copied logs keep it; emit no trailing spaces. diff --git a/scripts/injected-log.sh b/scripts/injected-log.sh index 0619d95..e19a2ed 100644 --- a/scripts/injected-log.sh +++ b/scripts/injected-log.sh @@ -35,10 +35,10 @@ while IFS= read -r line <&3; do enriched=$(jq -c --arg workflow "${workflows[$key]}" '. + {workflow: $workflow}' <<< "$line" 2>/dev/null) && line=$enriched fi fi - # The action routes this through the log multiplexer, which is the only writer on stdout; anywhere else prints. + # JSON-string framing publishes a complete record only after its final newline, even across multiple jq writes. if [ -n "${LOG_RENDERED:-}" ]; then - printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" >> "$LOG_RENDERED" + printf '%s\n' "$line" | jq --unbuffered -c -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" >> "$LOG_RENDERED" else - printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" + printf '%s\n' "$line" | jq --unbuffered -r -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" fi done diff --git a/scripts/injected-log.test.ts b/scripts/injected-log.test.ts index e1e8c38..f2fe2ae 100644 --- a/scripts/injected-log.test.ts +++ b/scripts/injected-log.test.ts @@ -221,6 +221,156 @@ console.log(JSON.stringify({ type: "thread.started", thread_id: "fixture" })); expect(result.stdout.toString()).toContain("CI / check (windows, 3.12):success"); }, 7000); +test.each(["rejected resume", "missing verdict"])("the live log survives %s and drains activity after the final attempt", async mode => { + const { setup, dir, env } = fixture({ 100: { wait: true, body: run() } }); + const comment = (id: number) => ({ event: "issue_comment", action: "created", sender: { login: "alice" }, + comment: { id, body: `${id}: ${"边界🙂".repeat(4096)}`, html_url: `/pull/7#issuecomment-${id}` } }); + const records = [comment(1), event(100, "between attempts", { id: 2 }), comment(3), comment(4)]; + writeFileSync(join(dir, "records.json"), JSON.stringify(records)); + writeFileSync(join(dir, "last-record"), JSON.stringify(records[3]) + "\n"); + writeFileSync(join(dir, "event.json"), JSON.stringify({ action: "opened", sender: { login: "alice" }, issue: { number: 7 } })); + if (mode === "rejected resume") writeFileSync(join(dir, "last-thread-id"), "previous-thread\n"); + // Pricing runs after the last log() pipeline. Its final delivery can only be printed by the EXIT drain. + writeFileSync(join(dir, "bun"), `#!/usr/bin/env bash +if [[ $1 == --config=* ]]; then exec '${process.execPath}' "$@"; fi +if [[ $1 == -e ]]; then cat "$RUNNER_TEMP/last-record" >> "$RUNNER_TEMP/injected.log"; fi +`); + writeFileSync(join(dir, "codex"), `#!${process.execPath} +import { appendFileSync, existsSync, readFileSync, writeFileSync } from "node:fs"; +const dir = process.env.RUNNER_TEMP; +const attempts = dir + "/attempts.jsonl"; +const attempt = existsSync(attempts) ? readFileSync(attempts, "utf8").trim().split("\\n").length + 1 : 1; +appendFileSync(attempts, JSON.stringify({ attempt, resume: process.argv[3] === "resume" }) + "\\n"); +const records = JSON.parse(readFileSync(dir + "/records.json", "utf8")); +const append = index => appendFileSync(dir + "/injected.log", JSON.stringify(records[index]) + "\\n"); +const waitFor = async predicate => { + const deadline = Date.now() + 5000; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("Fixture gate was not released"); + await Bun.sleep(10); + } +}; +console.log(JSON.stringify({ type: "thread.started", thread_id: "fixture-thread" })); +console.log(JSON.stringify({ type: "item.completed", item: { type: "command_execution", command: "bash -lc 'attempt-" + attempt + "'", + aggregated_output: "tool-" + attempt + "\\n" + "完整 output 🙂".repeat(8192) + "\\nend-" + attempt + "\\n" } })); +if (attempt === 1) { + await waitFor(() => existsSync(dir + "/deliver-first")); + append(0); + // The parent waits for the actual visible activity while this Codex stdout stays open and idle. + await waitFor(() => existsSync(dir + "/release-first")); + append(1); + // Keep this record's real activity formatter behind an in-flight metadata lookup across log() attempts. + await waitFor(() => existsSync(dir + "/calls") && readFileSync(dir + "/calls", "utf8").includes("check_suite_id=100")); + if (process.env.RETRY_MODE === "rejected resume") { + console.log(JSON.stringify({ type: "error", message: "modelProviderMismatch" })); + process.exit(1); + } +} else { + await waitFor(() => existsSync(dir + "/deliver-second")); + append(2); + await waitFor(() => existsSync(dir + "/release-second")); + const output = process.argv[process.argv.indexOf("--output-last-message") + 1]; + writeFileSync(output, JSON.stringify({ conclusion: "success", summary: "complete", commits: [{ sha: process.env.HEAD_SHA, conclusion: "success" }] })); +} +`); + for (const name of ["bun", "codex"]) chmodSync(join(dir, name), 0o755); + const child = Bun.spawn(["bash", join(import.meta.dir, "run-review.sh")], { + env: { ...env, RETRY_MODE: mode, AGENT: String(mode === "rejected resume"), PR_NUMBER: "", CHECK_ID: "1", ISSUE_NUMBER: "7", + BASE: "main", HEAD_BRANCH: "fixture", FORK_KEY: "", HEAD_SHA: head, BEFORE: "", DISPATCHED_SHA: head, DISPATCHED_BASE: "main", + CODEX_HOME: dir, CODEX_BIN: join(dir, "codex"), CODEX_RUNTIME: "", REVIEW_HOSTED: "", REVIEW_TRACE_RELAY_URL: "", + GITHUB_EVENT_NAME: "issues", GITHUB_EVENT_PATH: join(dir, "event.json"), GITHUB_STEP_SUMMARY: join(dir, "summary.md") }, + stdout: "pipe", stderr: "pipe", timeout: 10000, + }); + setup.process = child; + let output = ""; + const decoder = new TextDecoder(); + const stdout = (async () => { + for await (const chunk of child.stdout) output += decoder.decode(chunk, { stream: true }); + output += decoder.decode(); + })(); + const stderr = new Response(child.stderr).text(); + try { + await until(() => output.includes("end-1\u001b[0m\n::endgroup::"), 5000); + writeFileSync(join(dir, "deliver-first"), ""); + await until(() => output.includes("/pull/7#issuecomment-1") && existsSync(join(dir, "injected.offset")), 5000); + expect(child.exitCode).toBeNull(); + const firstOffset = Number(readFileSync(join(dir, "injected.offset"), "utf8")); + expect(firstOffset).toBeGreaterThan(0); + writeFileSync(join(dir, "release-first"), ""); + await until(() => readFileSync(join(dir, "attempts.jsonl"), "utf8").trim().split("\n").length === 2, 5000); + await until(() => output.includes("end-2\u001b[0m\n::endgroup::"), 5000); + writeFileSync(join(dir, "release"), ""); + writeFileSync(join(dir, "deliver-second"), ""); + await until(() => output.includes("/pull/7#issuecomment-3"), 5000); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBeGreaterThan(firstOffset); + writeFileSync(join(dir, "release-second"), ""); + expect(await child.exited).toBe(0); + await stdout; + expect(await stderr).toBe(""); + } finally { + for (const name of ["release", "deliver-first", "deliver-second", "release-first", "release-second"]) writeFileSync(join(dir, name), ""); + } + const visible = output.replace(/\x1b\[[0-9;]*m/g, ""); + const groups = [...visible.matchAll(/^::group::([^\n]*)\n([\s\S]*?)^::endgroup::$/gm)]; + const activities = groups.filter(([, title]) => !title.startsWith("$ ")).map(([, , body]) => JSON.parse(body)); + expect(activities).toEqual(records); + expect(groups.filter(([, title]) => title.startsWith("$ ")).map(([, title, body]) => [title, body])).toEqual([1, 2].map(attempt => [ + `$ attempt-${attempt}`, `tool-${attempt}\n${"完整 output 🙂".repeat(8192)}\nend-${attempt}\n`, + ])); + expect(visible.indexOf("/pull/7#issuecomment-4")).toBeGreaterThan(visible.indexOf("::notice::")); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(readFileSync(join(dir, "injected.rendered")).length); + expect(readFileSync(join(dir, "attempts.jsonl"), "utf8").trim().split("\n").map(line => JSON.parse(line).resume)) + .toEqual(mode === "rejected resume" ? [true, false] : [false, true]); + expect(() => process.kill(Number(readFileSync(join(dir, "tail.pid"), "utf8")), 0)).toThrow(); +}, 15000); + +test("activity remains live during the capacity cooldown and is not replayed by the next mux", async () => { + const { setup, dir, env } = fixture(); + const source = readFileSync(join(import.meta.dir, "run-review.sh"), "utf8"); + const region = source.slice(source.indexOf(': > "$RUNNER_TEMP/injected.log"'), source.indexOf("trap finish_injected EXIT") + "trap finish_injected EXIT".length); + const cooldown = source.match(/ if grep -Eq 'capacity\|overloaded\|too many requests'[\s\S]*?\n fi/)?.[0]; + expect(cooldown).toBeDefined(); + writeFileSync(join(dir, "codex.jsonl"), "capacity\n"); + writeFileSync(join(dir, "sleep"), `#!${process.execPath} +import { existsSync, writeFileSync } from "node:fs"; +if (process.argv[2] !== "30") throw new Error("Expected the production cooldown"); +writeFileSync(process.env.RUNNER_TEMP + "/sleeping", ""); +while (!existsSync(process.env.RUNNER_TEMP + "/release-sleep")) await Bun.sleep(10); +`); + chmodSync(join(dir, "sleep"), 0o755); + const child = Bun.spawn(["bash", "-eo", "pipefail", "-c", `${region}\n${cooldown}\nbash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs" { + for await (const chunk of child.stdout) output += decoder.decode(chunk, { stream: true }); + output += decoder.decode(); + })(); + const stderr = new Response(child.stderr).text(); + const record = { event: "issue_comment", sender: { login: "alice" }, comment: { id: 1, body: "during cooldown 边界🙂\n".repeat(512) } }; + let offset = 0; + try { + await until(() => existsSync(join(dir, "sleeping"))); + appendFileSync(join(dir, "injected.log"), JSON.stringify(record) + "\n"); + await until(() => output.includes("::endgroup::") && existsSync(join(dir, "injected.offset"))); + expect(child.exitCode).toBeNull(); + const body = output.replace(/\x1b\[[0-9;]*m/g, "").match(/^::group::[^\n]*\n([\s\S]*?)^::endgroup::$/m)![1]; + expect(JSON.parse(body)).toEqual(record); + offset = Number(readFileSync(join(dir, "injected.offset"), "utf8")); + expect(offset).toBeGreaterThan(0); + } finally { + writeFileSync(join(dir, "release-sleep"), ""); + } + expect(await child.exited).toBe(0); + await stdout; + expect(await stderr).toBe(""); + expect(groupTitles(output)).toHaveLength(1); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(offset); + expect(offset).toBe(readFileSync(join(dir, "injected.rendered")).length); +}); + test.each([0, 7])("review log cleanup preserves exit code %i and drains its final row", code => { const { dir, env } = fixture(); const source = readFileSync(join(import.meta.dir, "run-review.sh"), "utf8"); @@ -234,6 +384,8 @@ test.each([0, 7])("review log cleanup preserves exit code %i and drains its fina expect(result.stdout.toString()).toContain("CI / last job:success"); expect(result.stdout.toString()).not.toContain("old activity"); expect(result.stdout.toString()).not.toContain("review_log_end"); + expect(groupTitles(result.stdout.toString())).toHaveLength(1); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(readFileSync(join(dir, "injected.rendered")).length); expect(() => process.kill(Number(readFileSync(join(dir, "tail.pid"), "utf8")), 0)).toThrow(); }); diff --git a/scripts/log-mux.mjs b/scripts/log-mux.mjs index f7b02b9..757c614 100644 --- a/scripts/log-mux.mjs +++ b/scripts/log-mux.mjs @@ -1,56 +1,83 @@ -// The only process that writes the review's stdout: it prints the tool log and, between whole records, whatever the -// activity worker rendered in the meantime. Two writers interleaved a fold marker with tool output, which the runner -// then paired with the wrong group. -import { fstatSync, openSync, readFileSync, readSync, writeFileSync, writeSync } from "node:fs"; +// jq encodes each complete formatted record as one JSON string. Only this process writes the two streams to stdout. +import { closeSync, fstatSync, openSync, readFileSync, readSync, writeFileSync, writeSync } from "node:fs"; import { join } from "node:path"; const rendered = join(process.env.RUNNER_TEMP, "injected.rendered"); const cursor = join(process.env.RUNNER_TEMP, "injected.offset"); -// The worker can outlive the tool stream, so the offset is handed to a final drain. +// Each retry starts another mux; only fully printed activity may be skipped by it or by the final drain. let offset = 0; -try { - offset = Number(readFileSync(cursor, "utf8").trim() || 0); -} catch {} -const activityBuffer = Buffer.allocUnsafe(64 * 1024); -let renderedFd; -const drain = () => { - try { - renderedFd ??= openSync(rendered, "r"); - } catch { - return; // The optional activity log may be unavailable. +try { offset = Number(readFileSync(cursor, "utf8")); } +catch (error) { if (error.code !== "ENOENT") throw error; } +if (!Number.isSafeInteger(offset) || offset < 0) throw new Error("Invalid activity log cursor"); + +function writeRecord(frame) { + const record = JSON.parse(frame.toString("utf8")); + if (typeof record !== "string") throw new Error("Expected a formatted log string"); + // Preserve jq -r's trailing newline. A pipe may accept only part of a large UTF-8 record at a time. + const bytes = Buffer.from(record + "\n"); + for (let written = 0; written < bytes.length;) written += writeSync(1, bytes, written, bytes.length - written); +} + +function frames(emit) { + let parts = []; + return { + push(chunk) { + let start = 0; + for (let end; (end = chunk.indexOf(10, start)) !== -1; start = end + 1) { + const tail = chunk.subarray(start, end); + const frame = parts.length ? Buffer.concat([...parts, tail]) : tail; + parts = []; + emit(frame); + } + // Own the unfinished bytes: the file reader reuses its fixed-size buffer on the next read. + if (start < chunk.length) parts.push(Buffer.from(chunk.subarray(start))); + }, + get pending() { return parts.length > 0; }, + }; +} + +const activity = frames(frame => { + writeRecord(frame); + offset += frame.length + 1; + writeFileSync(cursor, String(offset)); +}); +const buffer = Buffer.allocUnsafe(64 * 1024); +let renderedFd, readOffset = offset; +function drain() { + try { renderedFd ??= openSync(rendered, "r"); } + catch (error) { + if (error.code === "ENOENT") return; + throw error; } + // Snapshot the available bytes so a busy worker cannot keep this drain open indefinitely. const end = fstatSync(renderedFd).size; - if (end <= offset) return; - while (offset < end) { - const size = readSync(renderedFd, activityBuffer, 0, Math.min(end - offset, activityBuffer.length), offset); + while (readOffset < end) { + const size = readSync(renderedFd, buffer, 0, Math.min(end - readOffset, buffer.length), readOffset); if (!size) break; - for (let written = 0; written < size;) written += writeSync(1, activityBuffer, written, size - written); - offset += size; + readOffset += size; + activity.push(buffer.subarray(0, size)); } - writeFileSync(cursor, String(offset)); -}; - -if (process.argv.includes("--drain")) { - drain(); - process.exit(0); } -let pending = "", inGroup = false; -const decoder = new TextDecoder(); -// A record is one line, or a whole fold from its header to its end marker; the worker's output waits for the boundary. -for await (const chunk of Bun.stdin.stream()) { - pending += decoder.decode(chunk, { stream: true }); - for (let end; (end = pending.indexOf("\n")) !== -1;) { - const line = pending.slice(0, end + 1); - pending = pending.slice(end + 1); - if (!inGroup) drain(); - writeSync(1, line); - if (line.startsWith("::group::")) inGroup = true; - else if (line.startsWith("::endgroup::")) inGroup = false; +let timer; +try { + drain(); + if (process.argv.includes("--drain")) { + // run-review.sh waits for the worker first, so a remaining fragment is a failed record, not an in-flight write. + if (activity.pending) throw new Error("Incomplete activity log record"); + } else { + // Codex may reason or wait on a command without emitting any tool records for minutes. + timer = setInterval(() => { + try { drain(); } + // Bun reports timer exceptions without stopping the loop; never consume more bytes after a failed frame. + catch (error) { console.error(error); process.exit(1); } + }, 50); + const tools = frames(frame => { drain(); writeRecord(frame); }); + for await (const chunk of Bun.stdin.stream()) tools.push(Buffer.from(chunk)); + if (tools.pending) throw new Error("Incomplete tool log record"); + drain(); } +} finally { + clearInterval(timer); + if (renderedFd !== undefined) closeSync(renderedFd); } -if (pending) { - if (!inGroup) drain(); - writeSync(1, pending); -} -if (!inGroup) drain(); diff --git a/scripts/log-mux.test.ts b/scripts/log-mux.test.ts new file mode 100644 index 0000000..26ba36b --- /dev/null +++ b/scripts/log-mux.test.ts @@ -0,0 +1,267 @@ +import { afterEach, expect, test } from "bun:test"; +import { appendFileSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; + +const scripts = import.meta.dir, root = resolve(scripts, ".."); +const dirs: string[] = [], children: ReturnType[] = []; +const stop = "test-log-command-token"; +const stripColors = (text: string) => text.replace(/\x1b\[[0-9;]*m/g, ""); +const input = (records: object[]) => Buffer.from(records.map(record => JSON.stringify(record)).join("\n") + "\n"); + +afterEach(async () => { + for (const child of children.splice(0)) { + if (child.exitCode === null) { child.kill(); await child.exited; } + } + for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function fixture() { + const dir = mkdtempSync(join(tmpdir(), "review-log-mux-")); + dirs.push(dir); + writeFileSync(join(dir, "injected.rendered"), ""); + return dir; +} + +function formatter(name: "codex" | "injected", framed = true) { + return ["jq", "--unbuffered", framed ? "-c" : "-r", "--arg", "stop", stop, "-f", join(scripts, `${name}-log.jq`)]; +} + +function render(name: "codex" | "injected", records: object[], framed = false, hosted = "") { + const result = Bun.spawnSync(formatter(name, framed), { + env: { ...process.env, REVIEW_HOSTED: hosted }, stdin: input(records), + }); + expect(result.exitCode).toBe(0); + expect(result.stderr.toString()).toBe(""); + return result.stdout; +} + +function mux(dir: string, drain = false) { + const child = Bun.spawn([process.execPath, `--config=${join(scripts, "review-bun.toml")}`, join(scripts, "log-mux.mjs"), ...(drain ? ["--drain"] : [])], { + env: { ...process.env, RUNNER_TEMP: dir, GITHUB_ACTION_PATH: root }, + stdin: "pipe", stdout: "pipe", stderr: "pipe", timeout: 8000, + }); + children.push(child); + let output = ""; + const stdout = (async () => { + const decoder = new TextDecoder(); + for await (const chunk of child.stdout) output += decoder.decode(chunk, { stream: true }); + output += decoder.decode(); + })(); + const stderr = new Response(child.stderr).text(); + return { + child, output: () => output, + finish: async (success = true) => { + child.stdin.end(); + const code = await child.exited; + await stdout; + if (success) { + expect(code).toBe(0); + expect(await stderr).toBe(""); + } else { + expect(code).not.toBe(0); + expect((await stderr).length).toBeGreaterThan(0); + } + return output; + }, + }; +} + +async function until(predicate: () => boolean) { + const deadline = Date.now() + 3000; + while (!predicate()) { + if (Date.now() >= deadline) throw new Error("Timed out waiting for the live log"); + await Bun.sleep(10); + } +} + +const activity = (id: number, size = 0) => ({ + event: "issue_comment", action: "created", sender: { login: "alice%0A\n::error::title", type: "User" }, + comment: { id, body: `activity-${id}: literal:\u200b: \\:: \\u003a ${"字🙂x".repeat(size)}\n\u0000 ::error::forged\n##[error]forged\n::group::forged\n::endgroup::`, html_url: `/pull/7#issuecomment-${id}` }, + workflow: "display-only workflow", +}); +const tool = (id: number, size = 0) => ({ type: "item.completed", item: { + type: "command_execution", command: `bash -lc 'tool-${id}'`, + aggregated_output: `tool-${id}-begin\n${"字🙂x".repeat(size)}\u0000\n::error::forged-${id}\n##[error]forged-${id}\n::group::forged-${id}\n::endgroup::\ntool-${id}-end\n`, +} }); + +// Model the runner's command state, so a payload's fake group markers do not hide a lost +// stop/resume token or make an activity group appear nested inside a tool's output. +function groups(output: string) { + const result: { title: string; body: string[] }[] = []; + let current: typeof result[number] | undefined, token: string | undefined; + for (const line of stripColors(output).split("\n")) { + if (token) { + if (line === `::${token}::`) token = undefined; + else current?.body.push(line); + } else if (line.startsWith("::group::")) { + expect(current === undefined).toBe(true); + current = { title: line.slice("::group::".length), body: [] }; + } else if (line.startsWith("::stop-commands::")) { + expect(current !== undefined).toBe(true); + token = line.slice("::stop-commands::".length); + } else if (line === "::endgroup::") { + expect(current !== undefined).toBe(true); + result.push(current!); + current = undefined; + } else { + expect(/^\s*::|##\[/.test(line)).toBe(false); + if (current) current.body.push(line); + else expect(line).toBe(""); + } + } + expect(current === undefined && token === undefined).toBe(true); + return result; +} + +test.each(["", "true"])("concurrent production formatters preserve large records and runner commands (hosted=%j)", async hosted => { + const dir = fixture(), log = mux(dir); + // Each record is much larger than PIPE_BUF; both streams contain multibyte text, + // newlines, NUL and command-looking data. They must survive byte-chunk boundaries. + const activities = [activity(1, 1024), activity(2, 2560), activity(3, 1024), activity(4, 2560)]; + const tools = [tool(1, 24000), tool(2, 24000), tool(3, 24000), tool(4, 24000)]; + const producer = (name: "codex" | "injected", records: object[]) => { + const child = Bun.spawn(formatter(name), { + env: { ...process.env, REVIEW_HOSTED: hosted }, stdin: input(records), stdout: "pipe", stderr: "pipe", + }); + children.push(child); + return child; + }; + const toolWriter = producer("codex", tools), activityWriter = producer("injected", activities); + const pump = async (child: typeof toolWriter, write: (bytes: Uint8Array) => void | Promise) => { + const stderr = new Response(child.stderr).text(); + for await (const chunk of child.stdout) { + for (let position = 0; position < chunk.length; position += 1019) { + await write(chunk.subarray(position, position + 1019)); + await Bun.sleep(1); + } + } + expect(await child.exited).toBe(0); + expect(await stderr).toBe(""); + }; + await Promise.all([ + pump(toolWriter, async bytes => { log.child.stdin.write(bytes); await log.child.stdin.flush(); }), + pump(activityWriter, bytes => appendFileSync(join(dir, "injected.rendered"), bytes)), + ]); + const output = await log.finish(); + // Comparing with raw production formatter output also detects changes to whitespace, + // Unicode, escaping and command tokens; removing each once proves no extra output. + let remainder = output; + for (const [name, records] of [["codex", tools], ["injected", activities]] as const) { + for (const record of records) { + const rendered = render(name, [record], false, hosted).toString(); + const position = remainder.indexOf(rendered); + expect(position).toBeGreaterThanOrEqual(0); + remainder = remainder.slice(0, position) + remainder.slice(position + rendered.length); + } + } + expect(remainder.length).toBe(0); + const blocks = groups(output); + expect(blocks).toHaveLength(tools.length + activities.length); + const activityGroups = blocks.filter(block => block.title.startsWith("issue_comment/created")); + expect(activityGroups.map(block => JSON.parse(block.body.join("\n")).comment.id)).toEqual([1, 2, 3, 4]); + activityGroups.forEach((block, index) => { + const { workflow, ...expected } = activities[index]; + expect(JSON.parse(block.body.join("\n"))).toEqual(expected); + expect(block.title).toContain(hosted ? "alice%0A " : "alice%250A "); + }); + const toolGroups = blocks.filter(block => block.title.startsWith("$ tool-")); + expect(toolGroups.map(block => block.title)).toEqual(["$ tool-1", "$ tool-2", "$ tool-3", "$ tool-4"]); + toolGroups.forEach((block, index) => expect(block.body.join("\n") === tools[index].item.aggregated_output.replace(/\n$/, "")).toBe(true)); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(readFileSync(join(dir, "injected.rendered")).length); +}, 15000); + +test("only complete activity records appear while a tool record is unfinished and stdin is idle", async () => { + const dir = fixture(), log = mux(dir); + const event = activity(10, 5000), command = tool(10, 24000); + const eventBytes = render("injected", [event], true), toolBytes = render("codex", [command], true); + // Split inside a UTF-8 character rather than only on ASCII/JSON boundaries. + const split = eventBytes.indexOf(Buffer.from("🙂")) + 1; + expect(split).toBeGreaterThan(1); + appendFileSync(join(dir, "injected.rendered"), eventBytes.subarray(0, split)); + log.child.stdin.write(toolBytes.subarray(0, 4097)); + await log.child.stdin.flush(); + await Bun.sleep(150); + expect(log.output()).toBe(""); + appendFileSync(join(dir, "injected.rendered"), eventBytes.subarray(split, -1)); + await Bun.sleep(150); + expect(log.output()).toBe(""); + // A final newline commits the frame; no tool write or EOF wakes the reader. + appendFileSync(join(dir, "injected.rendered"), eventBytes.subarray(-1)); + const expectedEvent = render("injected", [event]).toString(); + await until(() => log.output() === expectedEvent); + expect(log.child.exitCode).toBeNull(); + log.child.stdin.write(toolBytes.subarray(4097)); + const output = await log.finish(); + expect(output === expectedEvent + render("codex", [command]).toString()).toBe(true); +}); + +test("retry, resume and the final drain share a byte cursor through complete records only", async () => { + const dir = fixture(), path = join(dir, "injected.rendered"); + const events = [activity(21, 2048), activity(22, 5000), activity(23, 2048)]; + const bytes = events.map(event => render("injected", [event], true)); + const expected = events.map(event => render("injected", [event]).toString()); + const cursor = () => existsSync(join(dir, "injected.offset")) ? Number(readFileSync(join(dir, "injected.offset"), "utf8")) : 0; + appendFileSync(path, Buffer.concat([bytes[0], bytes[1].subarray(0, 4097)])); + const first = mux(dir); + expect(await first.finish() === expected[0]).toBe(true); + expect(cursor()).toBe(bytes[0].length); + appendFileSync(path, bytes[1].subarray(4097)); + const resumed = mux(dir); + await until(() => resumed.output() === expected[1]); + appendFileSync(path, bytes[2].subarray(0, 4097)); + expect(await resumed.finish() === expected[1]).toBe(true); + expect(cursor()).toBe(bytes[0].length + bytes[1].length); + // The worker completes this last record only after the last tool pipeline exits. + appendFileSync(path, bytes[2].subarray(4097)); + expect(await mux(dir, true).finish() === expected[2]).toBe(true); + expect(cursor()).toBe(bytes.reduce((total, record) => total + record.length, 0)); + expect(await mux(dir, true).finish()).toBe(""); +}); + +test("a truncated final activity is reported without emitting or consuming it", async () => { + const dir = fixture(), path = join(dir, "injected.rendered"); + const first = activity(31), last = activity(32, 20000); + const firstBytes = render("injected", [first], true), lastBytes = render("injected", [last], true); + appendFileSync(path, Buffer.concat([firstBytes, lastBytes.subarray(0, -1)])); + expect(await mux(dir, true).finish(false) === render("injected", [first]).toString()).toBe(true); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(firstBytes.length); + appendFileSync(path, lastBytes.subarray(-1)); + expect(await mux(dir, true).finish() === render("injected", [last]).toString()).toBe(true); +}); + +test.each(["{broken}\n", "123\n", JSON.stringify("unfinished tool record\n")])("invalid or unfinished tool framing cannot leak into the visible log (%j)", async frame => { + const log = mux(fixture()); + log.child.stdin.write(frame); + expect(await log.finish(false)).toBe(""); +}); + +test("a malformed activity during tool idle exits without consuming later records", async () => { + const dir = fixture(), log = mux(dir), path = join(dir, "injected.rendered"); + const first = activity(41), later = activity(42); + const firstBytes = render("injected", [first], true), expected = render("injected", [first]).toString(); + appendFileSync(path, firstBytes); + await until(() => log.output() === expected); + appendFileSync(path, Buffer.concat([Buffer.from("{broken}\n"), render("injected", [later], true)])); + // Keep tool stdin open: the independent activity timer must report this failure. + await until(() => log.child.exitCode !== null); + expect(log.child.exitCode).toBe(1); + expect(await log.finish(false) === expected).toBe(true); + expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(firstBytes.length); +}); + +test("the production patch bridge preserves long Unicode stderr through JSON formatting", async () => { + const stderr = "raw stderr: " + "字🙂x".repeat(24000) + "\u0000 end"; + const bridge = Bun.spawnSync([process.execPath, `--config=${join(scripts, "review-bun.toml")}`, join(scripts, "codex-patches.mjs")], { + stdin: Buffer.from(stderr + "\n"), env: { ...process.env, CODEX_HOME: "" }, + }); + expect(bridge.exitCode).toBe(0); + const record = JSON.parse(bridge.stdout.toString()); + expect(record.type).toBe("error"); + expect(record.message === stderr).toBe(true); + const formatted = Bun.spawnSync(formatter("codex"), { stdin: bridge.stdout }); + expect(formatted.exitCode).toBe(0); + const log = mux(fixture()); + log.child.stdin.write(formatted.stdout); + expect(await log.finish() === stderr + "\n\n").toBe(true); +}); diff --git a/scripts/run-review.sh b/scripts/run-review.sh index a7b9765..0c4cc1b 100644 --- a/scripts/run-review.sh +++ b/scripts/run-review.sh @@ -84,9 +84,9 @@ fresh() { } codex_patches() { "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/codex-patches.mjs" "$@"; } # One process owns stdout: the activity worker renders into a file and this multiplexer prints it between records. -log() { codex_patches "${1:-}" | jq --unbuffered -rR --arg stop "$(openssl rand -hex 16)" -f "$GITHUB_ACTION_PATH/scripts/codex-log.jq" | bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs"; } +log() { codex_patches "${1:-}" | jq --unbuffered -c --arg stop "$(openssl rand -hex 16)" -f "$GITHUB_ACTION_PATH/scripts/codex-log.jq" | bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs"; } # Hook deliveries never reach the exec stream, so the hook writes them aside and this tail shows them as they land. -# This writer escapes command syntax instead of stopping commands, since the tool log above holds the runner's one suppression token. +# The worker frames each formatted record for the same writer as the tool log, including while Codex is quiet. : > "$RUNNER_TEMP/injected.log" : > "$RUNNER_TEMP/injected.rendered" rm -f "$RUNNER_TEMP/injected.done" "$RUNNER_TEMP/injected.offset" @@ -101,7 +101,7 @@ finish_injected() { fi wait "$INJECTED_TAIL" 2>/dev/null || true # The worker can finish after the tool stream; print what it rendered in the meantime. - bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs" --drain || true + bash "$GITHUB_ACTION_PATH/scripts/review-bun.sh" "$GITHUB_ACTION_PATH/scripts/log-mux.mjs" --drain Date: Fri, 27 Nov 2026 23:17:51 +0000 Subject: [PATCH 09/10] Preserve JSON values printed as plain Codex stderr --- scripts/codex-patches.mjs | 3 ++- scripts/log-mux.test.ts | 13 +++++++------ 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/scripts/codex-patches.mjs b/scripts/codex-patches.mjs index 751811e..b75fdab 100644 --- a/scripts/codex-patches.mjs +++ b/scripts/codex-patches.mjs @@ -93,6 +93,7 @@ if (process.argv[2] === "--baseline") { } catch { paired = false; } } // Keep stderr readable while feeding JSON to jq: its older raw-input reader corrupts split UTF-8 characters. - console.log(event === undefined ? JSON.stringify({ type: "error", message: line }) : line); + if (event !== null && typeof event === "object" && !Array.isArray(event)) console.log(line); + else console.log(JSON.stringify({ type: "error", message: line })); } } diff --git a/scripts/log-mux.test.ts b/scripts/log-mux.test.ts index 26ba36b..5289e53 100644 --- a/scripts/log-mux.test.ts +++ b/scripts/log-mux.test.ts @@ -250,18 +250,19 @@ test("a malformed activity during tool idle exits without consuming later record expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBe(firstBytes.length); }); -test("the production patch bridge preserves long Unicode stderr through JSON formatting", async () => { +test("the production patch bridge preserves Unicode and JSON-valued stderr through formatting", async () => { const stderr = "raw stderr: " + "字🙂x".repeat(24000) + "\u0000 end"; + const lines = [stderr, "false", "null", "42", '"quoted"', "[1,2]"]; const bridge = Bun.spawnSync([process.execPath, `--config=${join(scripts, "review-bun.toml")}`, join(scripts, "codex-patches.mjs")], { - stdin: Buffer.from(stderr + "\n"), env: { ...process.env, CODEX_HOME: "" }, + stdin: Buffer.from(lines.join("\n") + "\n"), env: { ...process.env, CODEX_HOME: "" }, }); expect(bridge.exitCode).toBe(0); - const record = JSON.parse(bridge.stdout.toString()); - expect(record.type).toBe("error"); - expect(record.message === stderr).toBe(true); + const records = bridge.stdout.toString().trimEnd().split("\n").map(line => JSON.parse(line)); + expect(records.every(record => record.type === "error")).toBe(true); + expect(records.map(record => record.message)).toEqual(lines); const formatted = Bun.spawnSync(formatter("codex"), { stdin: bridge.stdout }); expect(formatted.exitCode).toBe(0); const log = mux(fixture()); log.child.stdin.write(formatted.stdout); - expect(await log.finish() === stderr + "\n\n").toBe(true); + expect(await log.finish() === lines.join("\n\n") + "\n\n").toBe(true); }); From fe521ccfd352545ce9f7eb0e3738128f895bac34 Mon Sep 17 00:00:00 2001 From: Muspi Merol Date: Sat, 28 Nov 2026 07:26:19 +0800 Subject: [PATCH 10/10] Wait for committed activity cursors in lifecycle tests --- scripts/injected-log.test.ts | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/injected-log.test.ts b/scripts/injected-log.test.ts index f2fe2ae..6b5ab66 100644 --- a/scripts/injected-log.test.ts +++ b/scripts/injected-log.test.ts @@ -292,9 +292,12 @@ if (attempt === 1) { try { await until(() => output.includes("end-1\u001b[0m\n::endgroup::"), 5000); writeFileSync(join(dir, "deliver-first"), ""); - await until(() => output.includes("/pull/7#issuecomment-1") && existsSync(join(dir, "injected.offset")), 5000); + await until(() => output.includes("/pull/7#issuecomment-1"), 5000); + // The gate holds the worker at this complete frame; stdout can arrive before its cursor write finishes. + const firstOffset = readFileSync(join(dir, "injected.rendered")).lastIndexOf(10) + 1; + await until(() => firstOffset > 0 && existsSync(join(dir, "injected.offset")) + && Number(readFileSync(join(dir, "injected.offset"), "utf8")) === firstOffset, 5000); expect(child.exitCode).toBeNull(); - const firstOffset = Number(readFileSync(join(dir, "injected.offset"), "utf8")); expect(firstOffset).toBeGreaterThan(0); writeFileSync(join(dir, "release-first"), ""); await until(() => readFileSync(join(dir, "attempts.jsonl"), "utf8").trim().split("\n").length === 2, 5000); @@ -302,6 +305,9 @@ if (attempt === 1) { writeFileSync(join(dir, "release"), ""); writeFileSync(join(dir, "deliver-second"), ""); await until(() => output.includes("/pull/7#issuecomment-3"), 5000); + const secondOffset = readFileSync(join(dir, "injected.rendered")).lastIndexOf(10) + 1; + await until(() => secondOffset > firstOffset + && Number(readFileSync(join(dir, "injected.offset"), "utf8")) === secondOffset, 5000); expect(Number(readFileSync(join(dir, "injected.offset"), "utf8"))).toBeGreaterThan(firstOffset); writeFileSync(join(dir, "release-second"), ""); expect(await child.exited).toBe(0); @@ -354,11 +360,13 @@ while (!existsSync(process.env.RUNNER_TEMP + "/release-sleep")) await Bun.sleep( try { await until(() => existsSync(join(dir, "sleeping"))); appendFileSync(join(dir, "injected.log"), JSON.stringify(record) + "\n"); - await until(() => output.includes("::endgroup::") && existsSync(join(dir, "injected.offset"))); + await until(() => output.includes("::endgroup::")); + offset = readFileSync(join(dir, "injected.rendered")).lastIndexOf(10) + 1; + await until(() => offset > 0 && existsSync(join(dir, "injected.offset")) + && Number(readFileSync(join(dir, "injected.offset"), "utf8")) === offset); expect(child.exitCode).toBeNull(); const body = output.replace(/\x1b\[[0-9;]*m/g, "").match(/^::group::[^\n]*\n([\s\S]*?)^::endgroup::$/m)![1]; expect(JSON.parse(body)).toEqual(record); - offset = Number(readFileSync(join(dir, "injected.offset"), "utf8")); expect(offset).toBeGreaterThan(0); } finally { writeFileSync(join(dir, "release-sleep"), "");