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..b75fdab 100644 --- a/scripts/codex-patches.mjs +++ b/scripts/codex-patches.mjs @@ -92,6 +92,8 @@ 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. + 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/events.test.ts b/scripts/events.test.ts index 987af5a..6f8493e 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, formatted: formatted.stdout }; } type CIResponse = { pages?: object[]; error?: string }; @@ -1556,12 +1558,58 @@ 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("\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 #\\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 }); + 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"); @@ -1603,7 +1651,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]; @@ -1632,10 +1680,10 @@ 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.toString().replace(/\u001b\[[0-9;]*m/g, "")).toBe(text); + expect(worker.stdout).toEqual(formatted); }); test("an edited pull request says what changed, including a new base", () => { @@ -1833,7 +1881,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); - expect(result.stdout.toString()).not.toContain("::"); + const payload = result.stdout.toString().replace(/^\n::group::/, "").replace(/\n::endgroup::\n\n$/, ""); + expect(payload).not.toContain("::"); }); test("injected command escaping covers the runner's leading whitespace", () => { @@ -1843,8 +1892,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); } }); @@ -2092,7 +2141,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/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.jq b/scripts/injected-log.jq index 2dec30e..8d65d76 100644 --- a/scripts/injected-log.jq +++ b/scripts/injected-log.jq @@ -33,12 +33,39 @@ 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. +# Break every marker, including overlapping colons, 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 +# 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; +(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. + "\n::group::" + ($event | group_title) + + "\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. -| 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)(?/dev/null) && line=$enriched fi fi - printf '%s\n' "$line" | jq --unbuffered -rR -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" + # 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 -c -f "$GITHUB_ACTION_PATH/scripts/injected-log.jq" >> "$LOG_RENDERED" + else + 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 c76dc2b..6b5ab66 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) { @@ -46,6 +46,10 @@ async function until(predicate: () => 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().trim().split("\n").filter(Boolean)).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", @@ -150,7 +154,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("##["); }); @@ -215,15 +221,179 @@ 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"), 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(); + 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); + 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); + 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::")); + 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); + 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"); 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(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 new file mode 100644 index 0000000..757c614 --- /dev/null +++ b/scripts/log-mux.mjs @@ -0,0 +1,83 @@ +// 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"); +// 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")); } +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; + while (readOffset < end) { + const size = readSync(renderedFd, buffer, 0, Math.min(end - readOffset, buffer.length), readOffset); + if (!size) break; + readOffset += size; + activity.push(buffer.subarray(0, size)); + } +} + +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); +} diff --git a/scripts/log-mux.test.ts b/scripts/log-mux.test.ts new file mode 100644 index 0000000..5289e53 --- /dev/null +++ b/scripts/log-mux.test.ts @@ -0,0 +1,268 @@ +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 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(lines.join("\n") + "\n"), env: { ...process.env, CODEX_HOME: "" }, + }); + expect(bridge.exitCode).toBe(0); + 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() === lines.join("\n\n") + "\n\n").toBe(true); +}); diff --git a/scripts/run-review.sh b/scripts/run-review.sh index a2043cb..0c4cc1b 100644 --- a/scripts/run-review.sh +++ b/scripts/run-review.sh @@ -83,12 +83,14 @@ 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. +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" -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 @@ -98,6 +100,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