Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/codex-log.jq
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
4 changes: 3 additions & 1 deletion scripts/codex-patches.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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 }));
}
}
67 changes: 58 additions & 9 deletions scripts/events.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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, "");
Comment thread
muspi-merol-review[bot] marked this conversation as resolved.
Resolved
return { ...hook, contexts, activities, text, formatted: formatted.stdout };
}

type CIResponse = { pages?: object[]; error?: string };
Expand Down Expand Up @@ -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");
Expand Down Expand Up @@ -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];
Expand Down Expand Up @@ -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", () => {
Expand Down Expand Up @@ -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", () => {
Expand All @@ -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);
}
});

Expand Down Expand Up @@ -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");
Expand Down
6 changes: 4 additions & 2 deletions scripts/hosted-review.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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));
});
Expand Down
39 changes: 33 additions & 6 deletions scripts/injected-log.jq
Original file line number Diff line number Diff line change
Expand Up @@ -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)(?<![ \t])[ \t]+$"; "") | rtrimstr("\n") + "\n"
7 changes: 6 additions & 1 deletion scripts/injected-log.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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"
# 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
Loading
Loading