From 9ef726a475de37da7bf0a3d43ea0dee32dc1aa4c Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 15:47:52 -0700 Subject: [PATCH 1/7] workflows(pr-review): one review comment per PR, edited in place on each wake MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The GitHub step is now a small Node script (fetch built in) instead of shell-parsed JSON: it walks the PR's comments for the bot's marker comment, skips when it already carries this head SHA, PATCHes it with the new verdict otherwise, and POSTs only when none exists. Exercised against a real PR: post → skip (same SHA) → update (new SHA) left one comment. Co-Authored-By: Claude Opus 5 (1M context) --- workflows/README.md | 2 +- workflows/pr-review.flow.ts | 58 +++++++++++++++++++++++++------------ 2 files changed, 41 insertions(+), 19 deletions(-) diff --git a/workflows/README.md b/workflows/README.md index a6196f9a0..f69d958ff 100644 --- a/workflows/README.md +++ b/workflows/README.md @@ -7,7 +7,7 @@ not accepted by `flows`. Changing the launch location does not translate it. | Workflow | Engine | Placement and external dependencies | | --- | --- | --- | -| `pr-review.flow.ts` | `flows` v2 / Cloud listener | This repository's own pull-request reviewer. Deployed to Agent Relay Cloud as a `pull_request` listener on `AgentWorkforce/flows` (`flows deploy workflows/pr-review.flow.ts --repo AgentWorkforce/flows --on github:events=pull_request --approver --name flows-pr-review`). Cloud checks out the PR head and passes `input.pullRequest`; the diff is written to `review/diff.patch`, four lens agents (kernel, sdk, docs, repo; `cli: "claude"` pinned in the file, so no `flows.json`) run in parallel gated on their findings files, a consensus agent reconciles disagreement, and the verdict is posted as one PR comment through the GitHub REST API with the sandbox.s `GH_TOKEN` (idempotent per head SHA). A draft is reviewed at its next push or reopen after being marked ready; a wake caused by a submitted review is declined (no re-review); every other wake posts a fresh comment. Runs locally with `--local-agent` and `--input '{"diffRange":"origin/main...HEAD"}'` (comment step skipped). Redeploy after changing the file: Cloud runs the stored copy, not the branch. | +| `pr-review.flow.ts` | `flows` v2 / Cloud listener | This repository's own pull-request reviewer. Deployed to Agent Relay Cloud as a `pull_request` listener on `AgentWorkforce/flows` (`flows deploy workflows/pr-review.flow.ts --repo AgentWorkforce/flows --on github:events=pull_request --approver --name flows-pr-review`). Cloud checks out the PR head and passes `input.pullRequest`; the diff is written to `review/diff.patch`, four lens agents (kernel, sdk, docs, repo; `cli: "claude"` pinned in the file, so no `flows.json`) run in parallel gated on their findings files, a consensus agent reconciles disagreement, and the verdict is one PR comment through the GitHub REST API with the sandbox's `GH_TOKEN`, edited in place on each wake (idempotent per head SHA). A draft is reviewed at its next push or reopen after being marked ready; a wake caused by a submitted review is declined (no re-review); every other wake updates that one comment. Runs locally with `--local-agent` and `--input '{"diffRange":"origin/main...HEAD"}'` (comment step skipped). Redeploy after changing the file: Cloud runs the stored copy, not the branch. | | `drive-local.yaml` | `flows` / local kernel | Local, deterministic F8b work package from `ops/BACKLOG.md`. Requires built SDK, local kernel, Node/npm and a work branch. Runtime has no Cloud, Daytona, Relaycast, GitHub or model call. Installation needs package registries. | | `preswarm-check.yaml` | `flows` / local kernel | Local review of a committed diff against `main` (or `BASE_REF`). Invokes installed/authenticated Claude, Codex and OpenCode CLIs; those use their model services. No Cloud admission or Daytona. Passing `flows check` proves only that `sh` resolves, not the nested reviewers' auth. | | `drive.yaml` | Previous `relayflows` engine | Written for either an existing checkout or a cloud snapshot. Local operation requires that engine plus Claude/Codex and toolchains; PR delivery needs GitHub access. Cloud snapshot delivery uses the Cloud proxy or external recovery. Its sync step resets/checks out branches: do not run it over an active worktree. | diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index 95c6e904c..36107b74f 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -182,26 +182,48 @@ export default flow( // The comment goes through the REST API with the repository token Cloud puts // in the sandbox as GH_TOKEN (the same credential git uses there). The // relayfile GitHub mount behind `f.github.*` is not attached to authored -// runs on Cloud — its first live run failed with -// helper_provider.mount_required at exactly this step. A deterministic step -// is not exactly-once, so the post is idempotent: the marker carries the -// head SHA and an existing comment for it means a re-dispatched step skips. -// The body is bounded from the front (f.run returns a 64 KiB stdout *tail*, -// which would drop the verdict) under GitHub's 65,536-char comment limit. -const shellNum = (n: number): string => String(n); +// runs on Cloud (cloud #3812) — its first live run failed with +// helper_provider.mount_required at exactly this step. +// +// One review comment per PR, edited in place: the marker names the head SHA +// reviewed; an existing marker comment is PATCHed (skipped when it already +// carries this SHA, so a re-dispatched step never double-posts), else one is +// POSTed. The body is bounded from the front (f.run returns a 64 KiB stdout +// *tail*, which would drop the verdict) under GitHub's 65,536-char limit. +const POST_SCRIPT = String.raw` +const [owner, repo, number, headSha, bodyPath] = process.argv.slice(2); +const token = process.env.GH_TOKEN; +if (!token) { console.error("GH_TOKEN is not set; cannot post the review"); process.exit(1); } +const fs = require("fs"); +const MARK = ""; +const api = "https://api.github.com/repos/" + owner + "/" + repo; +const headers = { Authorization: "Bearer " + token, Accept: "application/vnd.github+json", "Content-Type": "application/json", "User-Agent": "flows-pr-review" }; +async function gh(method, url, body) { + const res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }); + if (!res.ok) { console.error(method + " " + url + " -> " + res.status + " " + (await res.text()).slice(0, 300)); process.exit(1); } + return res.json(); +} +(async () => { + let existing; + for (let page = 1; page <= 50; page += 1) { + const list = await gh("GET", api + "/issues/" + number + "/comments?per_page=100&page=" + page); + existing = list.find((c) => typeof c.body === "string" && c.body.startsWith(MARK)); + if (existing || list.length < 100) break; + if (page === 50) { console.error("more than 5000 comments; refusing to post without a complete scan"); process.exit(1); } + } + if (existing && existing.body.startsWith(marker)) { console.log("already posted for " + headSha); return; } + let text = fs.readFileSync(bodyPath, "utf8"); + if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; + const body = marker + "\n" + text; + if (existing) { await gh("PATCH", api + "/issues/comments/" + existing.id, { body }); console.log("updated comment " + existing.id + " for " + headSha); } + else { const c = await gh("POST", api + "/issues/" + number + "/comments", { body }); console.log("posted comment " + c.id + " for " + headSha); } +})(); +`; async function postComment(f: Ctx, pr: Pr): Promise { - const api = `https://api.github.com/repos/${REPO.owner}/${REPO.repo}/issues/${shellNum(pr.number)}/comments`; - const marker = ``; + await f.run("cat > review/post.cjs <<'EOF'\n" + POST_SCRIPT + "\nEOF\n"); await f.run( - `[ -n "$GH_TOKEN" ] || { echo "GH_TOKEN is not set; cannot post the review" >&2; exit 1; }; ` - // Walk every page of comments (busy PRs exceed one page) before posting. - + `page=1; while :; do out=$(curl -sf -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" ${shellWord(`${api}?per_page=100&page=`)}"$page") || exit 1; ` - + `if printf '%s' "$out" | grep -qF ${shellWord(marker)}; then echo "already posted for ${pr.headSha}"; exit 0; fi; ` - // The page is one JSON line: count occurrences, not lines. - + `[ "$(printf '%s' "$out" | grep -o '"node_id"' | wc -l)" -ge 100 ] || break; page=$((page+1)); [ "$page" -le 50 ] || { echo "more than 5000 comments; refusing to post without a complete marker scan" >&2; exit 1; }; done; ` - + `{ printf '%s\n' ${shellWord(marker)}; if [ "$(wc -c < ${CONSENSUS})" -gt 60000 ]; then head -c 60000 ${CONSENSUS}; printf '\n\n_…truncated; the full review is in the run artifacts (${CONSENSUS})._\n'; else cat ${CONSENSUS}; fi; } > review/comment.md && ` - + `node -e 'const fs=require("fs");process.stdout.write(JSON.stringify({body:fs.readFileSync("review/comment.md","utf8")}))' > review/comment.json && ` - + `curl -sf -X POST -H "Authorization: Bearer $GH_TOKEN" -H "Accept: application/vnd.github+json" ${shellWord(api)} --data-binary @review/comment.json > /dev/null`, + `node review/post.cjs ${shellWord(REPO.owner)} ${shellWord(REPO.repo)} ${shellWord(String(pr.number))} ${shellWord(pr.headSha)} ${shellWord(CONSENSUS)}`, { timeout: "2m" }, ); } From d32f37b890186c7d1a77bd2df210d5e9c2f66c13 Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 16:07:05 -0700 Subject: [PATCH 2/7] workflows(pr-review): never let an older wake overwrite a newer verdict; delete legacy duplicates MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Before writing, re-read the marker comment and ask GitHub's compare API whether the commit it carries is ahead of ours; if so the newer wake owns the comment. Legacy duplicate marker comments are deleted so one remains. Exercised against a real PR: newer → written, older → refused, even newer → written, duplicates removed, one comment throughout. Co-Authored-By: Claude Opus 5 (1M context) --- workflows/pr-review.flow.ts | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index 36107b74f..da5406aa1 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -202,22 +202,39 @@ const headers = { Authorization: "Bearer " + token, Accept: "application/vnd.git async function gh(method, url, body) { const res = await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) }); if (!res.ok) { console.error(method + " " + url + " -> " + res.status + " " + (await res.text()).slice(0, 300)); process.exit(1); } - return res.json(); + const text = await res.text(); + return text ? JSON.parse(text) : null; } (async () => { - let existing; + // Collect every marker comment (legacy runs left one per wake). + const found = []; for (let page = 1; page <= 50; page += 1) { const list = await gh("GET", api + "/issues/" + number + "/comments?per_page=100&page=" + page); - existing = list.find((c) => typeof c.body === "string" && c.body.startsWith(MARK)); - if (existing || list.length < 100) break; + for (const c of list) if (typeof c.body === "string" && c.body.startsWith(MARK)) found.push(c); + if (list.length < 100) break; if (page === 50) { console.error("more than 5000 comments; refusing to post without a complete scan"); process.exit(1); } } - if (existing && existing.body.startsWith(marker)) { console.log("already posted for " + headSha); return; } + const existing = found[0]; + for (const dup of found.slice(1)) { await gh("DELETE", api + "/issues/comments/" + dup.id); console.log("deleted duplicate comment " + dup.id); } + const shaOf = (c) => ((c.body.match(/^/) || [])[1]); + if (existing && shaOf(existing) === headSha) { console.log("already posted for " + headSha); return; } let text = fs.readFileSync(bodyPath, "utf8"); if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; const body = marker + "\n" + text; - if (existing) { await gh("PATCH", api + "/issues/comments/" + existing.id, { body }); console.log("updated comment " + existing.id + " for " + headSha); } - else { const c = await gh("POST", api + "/issues/" + number + "/comments", { body }); console.log("posted comment " + c.id + " for " + headSha); } + if (!existing) { const c = await gh("POST", api + "/issues/" + number + "/comments", { body }); console.log("posted comment " + c.id + " for " + headSha); return; } + // Overlapping wakes: a run for an older head must never overwrite a newer + // verdict. Re-read right before writing; if the comment carries a commit + // that is *ahead* of ours (GitHub's compare, so it works without local + // history), the newer wake owns the comment and we leave it. + const fresh = await gh("GET", api + "/issues/comments/" + existing.id); + const current = shaOf(fresh) || ""; + if (current === headSha) { console.log("already posted for " + headSha); return; } + if (current) { + const cmp = await gh("GET", api + "/compare/" + headSha + "..." + current); + if (cmp && cmp.status === "ahead") { console.log("comment already carries newer " + current + "; not overwriting with " + headSha); return; } + } + await gh("PATCH", api + "/issues/comments/" + existing.id, { body }); + console.log("updated comment " + existing.id + " for " + headSha); })(); `; async function postComment(f: Ctx, pr: Pr): Promise { From 872c8f6f3be801124cd446de65c58b7d674f088c Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 16:38:30 -0700 Subject: [PATCH 3/7] retrigger the reviewer after the relayauth 500 From 858e5a5e8db6beb1a869e0f83088d2c004e14f26 Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 16:50:49 -0700 Subject: [PATCH 4/7] workflows(pr-review): own the comment by identity; converge races; keep the newest on cleanup; handle rebases MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Marker carries the posting login; a comment is ours only when its author is that login (a human cannot post as the bot), so a spoofed marker can neither suppress a review nor redirect the PATCH. - Two wakes that both scan-then-create converge: after posting, re-list and keep the lowest id. - Duplicate cleanup keeps the comment for our SHA, else the most recently updated one — never an older verdict over a newer. - Rebase/force-push (compare status diverged): the more recently committed head owns the comment; ahead/identical skip, behind overwrites. Co-Authored-By: Claude Opus 5 (1M context) --- workflows/pr-review.flow.ts | 65 +++++++++++++++++++++++++------------ 1 file changed, 44 insertions(+), 21 deletions(-) diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index da5406aa1..c837390aa 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -196,7 +196,6 @@ const token = process.env.GH_TOKEN; if (!token) { console.error("GH_TOKEN is not set; cannot post the review"); process.exit(1); } const fs = require("fs"); const MARK = ""; const api = "https://api.github.com/repos/" + owner + "/" + repo; const headers = { Authorization: "Bearer " + token, Accept: "application/vnd.github+json", "Content-Type": "application/json", "User-Agent": "flows-pr-review" }; async function gh(method, url, body) { @@ -205,36 +204,60 @@ async function gh(method, url, body) { const text = await res.text(); return text ? JSON.parse(text) : null; } -(async () => { - // Collect every marker comment (legacy runs left one per wake). +// Marker: "". A comment is ours only +// when its author IS the login its own marker names: anyone can type the +// marker text, nobody else can post as our identity. +const parseMark = (c) => { const m = typeof c.body === "string" && c.body.match(/^/); return m && c.user && c.user.login === m[2] ? { sha: m[1], login: m[2] } : null; }; +const markerFor = (login) => MARK + " " + headSha + " by:" + login + " -->"; +async function ours() { const found = []; for (let page = 1; page <= 50; page += 1) { const list = await gh("GET", api + "/issues/" + number + "/comments?per_page=100&page=" + page); - for (const c of list) if (typeof c.body === "string" && c.body.startsWith(MARK)) found.push(c); + for (const c of list) { const m = parseMark(c); if (m) found.push({ c, m }); } if (list.length < 100) break; if (page === 50) { console.error("more than 5000 comments; refusing to post without a complete scan"); process.exit(1); } } + return found; +} +async function committerDate(sha) { const c = await gh("GET", api + "/commits/" + sha); return Date.parse(c.commit.committer.date); } +// true when the comment's commit should keep the comment (it is not older than ours). +async function theirsWins(theirSha) { + if (theirSha === headSha) return true; + const cmp = await gh("GET", api + "/compare/" + headSha + "..." + theirSha); + if (!cmp) return true; + if (cmp.status === "ahead" || cmp.status === "identical") return true; + if (cmp.status === "behind") return false; + // diverged (rebase / force-push): the more recently committed head owns the comment. + return (await committerDate(theirSha)) >= (await committerDate(headSha)); +} +(async () => { + let found = await ours(); + // Converge legacy duplicates to one comment without discarding a newer + // verdict: keep the one for our SHA, else the most recently updated. + if (found.length > 1) { + found.sort((x, y) => (x.m.sha === headSha ? -1 : y.m.sha === headSha ? 1 : Date.parse(y.c.updated_at) - Date.parse(x.c.updated_at))); + for (const dup of found.slice(1)) { await gh("DELETE", api + "/issues/comments/" + dup.c.id); console.log("deleted duplicate comment " + dup.c.id); } + found = [found[0]]; + } const existing = found[0]; - for (const dup of found.slice(1)) { await gh("DELETE", api + "/issues/comments/" + dup.id); console.log("deleted duplicate comment " + dup.id); } - const shaOf = (c) => ((c.body.match(/^/) || [])[1]); - if (existing && shaOf(existing) === headSha) { console.log("already posted for " + headSha); return; } let text = fs.readFileSync(bodyPath, "utf8"); if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; - const body = marker + "\n" + text; - if (!existing) { const c = await gh("POST", api + "/issues/" + number + "/comments", { body }); console.log("posted comment " + c.id + " for " + headSha); return; } - // Overlapping wakes: a run for an older head must never overwrite a newer - // verdict. Re-read right before writing; if the comment carries a commit - // that is *ahead* of ours (GitHub's compare, so it works without local - // history), the newer wake owns the comment and we leave it. - const fresh = await gh("GET", api + "/issues/comments/" + existing.id); - const current = shaOf(fresh) || ""; - if (current === headSha) { console.log("already posted for " + headSha); return; } - if (current) { - const cmp = await gh("GET", api + "/compare/" + headSha + "..." + current); - if (cmp && cmp.status === "ahead") { console.log("comment already carries newer " + current + "; not overwriting with " + headSha); return; } + if (!existing) { + const posted = await gh("POST", api + "/issues/" + number + "/comments", { body: MARK + " " + headSha + " by:pending -->\n" + text }); + // Stamp our real login into the marker now that we know it. + await gh("PATCH", api + "/issues/comments/" + posted.id, { body: markerFor(posted.user.login) + "\n" + text }); + // Two wakes can both scan-then-create; converge to the lowest id. + const again = await ours(); + const lowest = again.reduce((a, b) => (a && a.c.id < b.c.id ? a : b), null); + if (lowest && lowest.c.id !== posted.id) { await gh("DELETE", api + "/issues/comments/" + posted.id); console.log("raced: kept " + lowest.c.id + ", deleted ours " + posted.id); return; } + console.log("posted comment " + posted.id + " for " + headSha); return; } - await gh("PATCH", api + "/issues/comments/" + existing.id, { body }); - console.log("updated comment " + existing.id + " for " + headSha); + // Re-read right before writing; never overwrite a verdict for a newer head. + const fresh = await gh("GET", api + "/issues/comments/" + existing.c.id); + const cur = parseMark(fresh); + if (cur && (await theirsWins(cur.sha))) { console.log("comment already carries " + cur.sha + "; not overwriting with " + headSha); return; } + await gh("PATCH", api + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login) + "\n" + text }); + console.log("updated comment " + existing.c.id + " for " + headSha); })(); `; async function postComment(f: Ctx, pr: Pr): Promise { From dd786b14a9e99a60a9e3321217292e6c56529a0d Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 18:11:43 -0700 Subject: [PATCH 5/7] workflows(pr-review): the publisher is a real file with a test suite; identity-first; soft-fail cleanup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Applies the reviewer's own live review of this PR (run on flows-pr-review, comment 5737789796). The GitHub publisher moves to workflows/pr-review- post.cjs, embedded verbatim in the flow; packages/sdk/tests/pr-review- post.test.ts pins the two together and drives every branch against a fake GitHub API (14 cases): identity via /user or a pending→stamped marker, same/older/newer/diverged/unresolvable heads, spoofed markers ignored, legacy markers adopted and converged to the newest, vanished comment re-posted, best-effort DELETE/compare/re-read failures never block the verdict, post-race convergence keeps the winning head. review/ is gitignored; header and README wording corrected. Co-Authored-By: Claude Opus 5 (1M context) --- .gitignore | 3 + packages/sdk/tests/pr-review-post.test.ts | 192 ++++++++++++++++++++++ workflows/README.md | 2 +- workflows/pr-review-post.cjs | 135 +++++++++++++++ workflows/pr-review.flow.ts | 162 ++++++++++++------ 5 files changed, 447 insertions(+), 47 deletions(-) create mode 100644 packages/sdk/tests/pr-review-post.test.ts create mode 100644 workflows/pr-review-post.cjs diff --git a/.gitignore b/.gitignore index 95c9bf17c..2ad26b6af 100644 --- a/.gitignore +++ b/.gitignore @@ -21,3 +21,6 @@ dist/ # Legacy drive-local snapshots; the preparing launcher no longer executes them. .drive-gate/ .flows/build.key + +# workflows/pr-review.flow.ts scratch dir (findings, diff, publisher script) +review/ diff --git a/packages/sdk/tests/pr-review-post.test.ts b/packages/sdk/tests/pr-review-post.test.ts new file mode 100644 index 000000000..4d8859021 --- /dev/null +++ b/packages/sdk/tests/pr-review-post.test.ts @@ -0,0 +1,192 @@ +// Exercises workflows/pr-review-post.cjs (this repo's own PR reviewer's +// publisher) against a fake GitHub API, one branch per case, and pins the +// copy embedded in workflows/pr-review.flow.ts to the file. +import { createServer, type IncomingMessage, type Server } from 'node:http'; +import { execFile } from 'node:child_process'; +import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +const ROOT = resolve(__dirname, '../../..'); +const SCRIPT = join(ROOT, 'workflows/pr-review-post.cjs'); +const SHA_A = 'a'.repeat(40); +const SHA_B = 'b'.repeat(40); +const SHA_C = 'c'.repeat(40); + +interface Comment { id: number; body: string; user: { login: string; type: string }; updated_at: string } +interface Fake { + comments: Comment[]; + user: { login: string } | null; + compare: Record; + dates: Record; + log: string[]; + nextId: number; +} + +let server: Server; let base: string; let fake: Fake; let dir: string; + +function body(req: IncomingMessage): Promise { + return new Promise((res) => { let s = ''; req.on('data', (d) => { s += d; }); req.on('end', () => res(s)); }); +} +beforeEach(async () => { + fake = { comments: [], user: null, compare: {}, dates: {}, log: [], nextId: 100 }; + dir = mkdtempSync(join(tmpdir(), 'pr-review-post-')); + writeFileSync(join(dir, 'body.md'), 'verdict body\n'); + server = createServer(async (req, res) => { + const url = new URL(req.url ?? '/', 'http://x'); + const path = url.pathname; const method = req.method ?? 'GET'; + fake.log.push(`${method} ${path}`); + const json = (code: number, value: unknown) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(value === null ? '' : JSON.stringify(value)); }; + if (method === 'GET' && path === '/user') return fake.user ? json(200, fake.user) : json(403, { message: 'Resource not accessible by integration' }); + if (method === 'GET' && path === '/repos/o/r/issues/7/comments') { + const page = Number(url.searchParams.get('page') ?? '1'); const per = Number(url.searchParams.get('per_page') ?? '100'); + return json(200, fake.comments.slice((page - 1) * per, page * per)); + } + if (method === 'POST' && path === '/repos/o/r/issues/7/comments') { + const { body: b } = JSON.parse(await body(req)) as { body: string }; + const c: Comment = { id: fake.nextId++, body: b, user: { login: 'relay[bot]', type: 'Bot' }, updated_at: new Date().toISOString() }; + fake.comments.push(c); return json(201, c); + } + const one = path.match(/^\/repos\/o\/r\/issues\/comments\/(\d+)$/); + if (one) { + const c = fake.comments.find((x) => x.id === Number(one[1])); + if (!c) return json(404, { message: 'Not Found' }); + if (method === 'GET') return json(200, c); + if (method === 'PATCH') { c.body = (JSON.parse(await body(req)) as { body: string }).body; c.updated_at = new Date().toISOString(); return json(200, c); } + if (method === 'DELETE') { fake.comments = fake.comments.filter((x) => x.id !== c.id); return json(204, null); } + } + const cmp = path.match(/^\/repos\/o\/r\/compare\/([0-9a-f]{40})\.\.\.([0-9a-f]{40})$/); + if (cmp) { const st = fake.compare[`${cmp[1]}...${cmp[2]}`]; return st === undefined || st === 404 ? json(404, { message: 'Not Found' }) : json(200, { status: st }); } + const commit = path.match(/^\/repos\/o\/r\/commits\/([0-9a-f]{40})$/); + if (commit) { const d = fake.dates[commit[1]]; return d ? json(200, { commit: { committer: { date: d } } }) : json(404, { message: 'Not Found' }); } + return json(500, { message: `unhandled ${method} ${path}` }); + }); + await new Promise((r) => server.listen(0, '127.0.0.1', r)); + const addr = server.address(); base = `http://127.0.0.1:${typeof addr === 'object' && addr ? addr.port : 0}`; +}); +afterEach(() => { server.close(); }); + +// Async on purpose: a sync spawn would block the loop that serves the fake API. +function run(headSha: string, opts: { token?: string } = {}): Promise<{ code: number; out: string; err: string }> { + return new Promise((done) => { + execFile(process.execPath, [SCRIPT, 'o', 'r', '7', headSha, join(dir, 'body.md')], { + env: { ...process.env, GITHUB_API: base, GH_TOKEN: opts.token ?? 't' }, encoding: 'utf8', timeout: 10_000, + }, (error, out, err) => done({ code: error && typeof (error as { code?: unknown }).code === 'number' ? (error as { code: number }).code : (error ? -1 : 0), out, err })); + }); +} +const mark = (sha: string, login?: string) => ``; +const seed = (sha: string, opts: { login?: string | null; author?: string; text?: string; updated?: string } = {}): Comment => { + const c: Comment = { id: fake.nextId++, body: `${mark(sha, opts.login === null ? undefined : (opts.login ?? 'relay[bot]'))}\n${opts.text ?? 'old'}`, user: { login: opts.author ?? 'relay[bot]', type: 'Bot' }, updated_at: opts.updated ?? '2026-01-01T00:00:00Z' }; + fake.comments.push(c); return c; +}; +const ours = () => fake.comments.filter((c) => c.body.startsWith('" is ours only +// when the comment's author IS that login — anyone can type the marker, +// nobody else can post as our identity. Legacy markers without "by:" (from +// the previously deployed copy) are adopted when authored by the same login +// as a comment we own, or by the login we just posted as. +// +// Ordering: a verdict for an older head never overwrites a newer one. GitHub's +// compare API decides (ahead/identical → theirs stays; behind → ours wins; +// diverged, i.e. rebase → the more recently committed head wins). A head the +// repo can no longer resolve loses. +// +// Delivery: only the POST/PATCH that carries the verdict is fatal. Cleanup, +// compare and re-read calls are best-effort and log instead of failing. + +const [owner, repo, number, headSha, bodyPath] = process.argv.slice(2); +const token = process.env.GH_TOKEN; +if (!owner || !repo || !number || !headSha || !bodyPath) { console.error("usage: pr-review-post.cjs "); process.exit(2); } +if (!token) { console.error("GH_TOKEN is not set; cannot post the review"); process.exit(1); } +const fs = require("fs"); +const API = (process.env.GITHUB_API || "https://api.github.com") + "/repos/" + owner + "/" + repo; +const MARK = ""; +/** {sha, login|null} for any marker line (new or legacy form), else null. */ +function readMark(c) { + if (!c || typeof c.body !== "string" || !c.user) return null; + const m = c.body.match(/^/); + return m ? { sha: m[1], login: m[2] || null } : null; +} +/** Marker comments that are provably ours; `knownLogins` adopts legacy/pending markers by author. */ +async function ours(knownLogins) { + const all = []; + for (let page = 1; page <= 50; page += 1) { + const list = await gh("GET", API + "/issues/" + number + "/comments?per_page=100&page=" + page); + for (const c of list) { const m = readMark(c); if (m) all.push({ c, m }); } + if (list.length < 100) break; + if (page === 50) { console.error("more than 5000 comments; refusing to post without a complete scan"); process.exit(1); } + } + const logins = new Set(knownLogins || []); + for (const x of all) if (x.m.login && x.m.login !== "pending" && x.c.user.login === x.m.login) logins.add(x.m.login); + return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); +} +async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } +/** Should the comment carrying `theirSha` stay as it is (i.e. is it not older than ours)? */ +async function theirsWins(theirSha) { + if (theirSha === headSha) return true; + const cmp = await gh("GET", API + "/compare/" + headSha + "..." + theirSha, undefined, { soft: true }); + if (!cmp) return false; // a head the repo cannot resolve is not a newer head + if (cmp.status === "ahead" || cmp.status === "identical") return true; + if (cmp.status === "behind") return false; + const [theirs, mine] = [await committerDate(theirSha), await committerDate(headSha)]; + if (theirs === null || mine === null) return false; + return theirs >= mine; +} +const byPreference = (a, b) => (a.m.sha === headSha ? -1 : b.m.sha === headSha ? 1 : Date.parse(b.c.updated_at) - Date.parse(a.c.updated_at)); +async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + id, undefined, { soft: true }); console.log("deleted duplicate comment " + id); } + +(async () => { + let text = fs.readFileSync(bodyPath, "utf8"); + if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; + + // Identity first when the token allows (a user token does; an installation + // token may 403): it lets legacy markers be adopted on the first scan and + // makes the create path a single write. + const me = await gh("GET", (process.env.GITHUB_API || "https://api.github.com") + "/user", undefined, { soft: true }); + let found = await ours(me && me.login ? [me.login] : []); + if (found.length > 1) { + // Converge legacy duplicates to one comment without discarding a newer + // verdict: keep the one for our SHA, else the most recently updated. + found.sort(byPreference); + for (const dup of found.slice(1)) await softDelete(dup.c.id); + found = [found[0]]; + } + const existing = found[0]; + + if (!existing) { + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(me && me.login ? me.login : "pending") + "\n" + text }); + const login = posted.user.login; + if (!(me && me.login)) await gh("PATCH", API + "/issues/comments/" + posted.id, { body: markerFor(login) + "\n" + text }, { soft: true }); + // Two wakes can both scan-then-create. Re-scan (adopting any by:pending + // orphans this login left) and converge on the comment whose head wins. + const again = (await ours([login])).filter((x) => x.c.user.login === login); + if (again.length > 1) { + let keep = again.find((x) => x.c.id === posted.id) || again[0]; + for (const other of again) { + if (other.c.id === keep.c.id) continue; + if (other.m.sha === headSha) { if (other.c.id < keep.c.id) keep = other; } // same head: lowest id wins + else if (await theirsWins(other.m.sha)) keep = other; // a newer head owns the comment + } + for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); + if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } + } + console.log("posted comment " + posted.id + " for " + headSha); return; + } + + // Re-read right before writing; a vanished comment means "none exists". + const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); + if (fresh === null) { + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; + } + const cur = readMark(fresh); + if (cur && (await theirsWins(cur.sha))) { console.log("comment already carries " + cur.sha + "; not overwriting with " + headSha); return; } + await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + console.log("updated comment " + existing.c.id + " for " + headSha); +})(); diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index c837390aa..fc907c230 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -6,8 +6,9 @@ // the same diff through lenses that match this codebase — the Rust kernel, // the TypeScript SDK/surface, and the examples + docs that make claims about // them — each gated on writing findings. A reconciliation step then looks for -// places two lenses disagree and posts the reconciled verdict as one PR -// comment, so the review is on the PR, not only in run artifacts. +// places two lenses disagree and publishes the reconciled verdict as the +// PR's single review comment (created once, edited in place on later wakes; +// see workflows/pr-review-post.cjs), so the review is on the PR itself. // // Local: flows run workflows/pr-review.flow.ts --local-agent \ // --input '{"diffRange":"origin/main...HEAD"}' @@ -115,11 +116,11 @@ export default flow( range = `FETCH_HEAD...${pr.headSha}`; } - // `review/` is not a dot-directory on purpose: the worker journals the - // artifacts it finds by scanning the tree, and that scan skips dot - // entries. It is recreated per run because `artifact_exists` records - // presence on content change, so a re-run writing the same "No findings" - // text into a leftover file would fail its gate. + // `review/` (gitignored) is not a dot-directory on purpose: the worker + // journals the artifacts it finds by scanning the tree, and that scan + // skips dot entries. It is recreated per run because `artifact_exists` + // records presence on content change, so a re-run writing the same "No + // findings" text into a leftover file would fail its gate. await f.run("rm -rf review && mkdir -p review"); // The diff goes through a file, not through f.run's return value: that // value is the kernel's stdout tail (64 KiB) and a task string is one @@ -190,78 +191,147 @@ export default flow( // carries this SHA, so a re-dispatched step never double-posts), else one is // POSTed. The body is bounded from the front (f.run returns a 64 KiB stdout // *tail*, which would drop the verdict) under GitHub's 65,536-char limit. -const POST_SCRIPT = String.raw` +// Embedded verbatim from workflows/pr-review-post.cjs — packages/sdk/tests/pr-review-post.test.ts +// fails if the two drift. The file is the source of truth; edit it, not this. +const POST_SCRIPT = ` +#!/usr/bin/env node +// pr-review-post — publish flows-pr-review's verdict as ONE comment per PR. +// +// Used by workflows/pr-review.flow.ts (which embeds this file verbatim and +// writes it into the run's scratch dir; packages/sdk/tests/pr-review-post.test.ts +// keeps the two in sync and exercises every branch against a fake GitHub). +// +// node pr-review-post.cjs +// env: GH_TOKEN (required), GITHUB_API (default https://api.github.com) +// +// Ownership: a marker "" is ours only +// when the comment's author IS that login — anyone can type the marker, +// nobody else can post as our identity. Legacy markers without "by:" (from +// the previously deployed copy) are adopted when authored by the same login +// as a comment we own, or by the login we just posted as. +// +// Ordering: a verdict for an older head never overwrites a newer one. GitHub's +// compare API decides (ahead/identical → theirs stays; behind → ours wins; +// diverged, i.e. rebase → the more recently committed head wins). A head the +// repo can no longer resolve loses. +// +// Delivery: only the POST/PATCH that carries the verdict is fatal. Cleanup, +// compare and re-read calls are best-effort and log instead of failing. + const [owner, repo, number, headSha, bodyPath] = process.argv.slice(2); const token = process.env.GH_TOKEN; +if (!owner || !repo || !number || !headSha || !bodyPath) { console.error("usage: pr-review-post.cjs "); process.exit(2); } if (!token) { console.error("GH_TOKEN is not set; cannot post the review"); process.exit(1); } const fs = require("fs"); +const API = (process.env.GITHUB_API || "https://api.github.com") + "/repos/" + owner + "/" + repo; const MARK = "". A comment is ours only -// when its author IS the login its own marker names: anyone can type the -// marker text, nobody else can post as our identity. -const parseMark = (c) => { const m = typeof c.body === "string" && c.body.match(/^/); return m && c.user && c.user.login === m[2] ? { sha: m[1], login: m[2] } : null; }; + const markerFor = (login) => MARK + " " + headSha + " by:" + login + " -->"; -async function ours() { - const found = []; +/** {sha, login|null} for any marker line (new or legacy form), else null. */ +function readMark(c) { + if (!c || typeof c.body !== "string" || !c.user) return null; + const m = c.body.match(/^/); + return m ? { sha: m[1], login: m[2] || null } : null; +} +/** Marker comments that are provably ours; \`knownLogins\` adopts legacy/pending markers by author. */ +async function ours(knownLogins) { + const all = []; for (let page = 1; page <= 50; page += 1) { - const list = await gh("GET", api + "/issues/" + number + "/comments?per_page=100&page=" + page); - for (const c of list) { const m = parseMark(c); if (m) found.push({ c, m }); } + const list = await gh("GET", API + "/issues/" + number + "/comments?per_page=100&page=" + page); + for (const c of list) { const m = readMark(c); if (m) all.push({ c, m }); } if (list.length < 100) break; if (page === 50) { console.error("more than 5000 comments; refusing to post without a complete scan"); process.exit(1); } } - return found; + const logins = new Set(knownLogins || []); + for (const x of all) if (x.m.login && x.m.login !== "pending" && x.c.user.login === x.m.login) logins.add(x.m.login); + return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); } -async function committerDate(sha) { const c = await gh("GET", api + "/commits/" + sha); return Date.parse(c.commit.committer.date); } -// true when the comment's commit should keep the comment (it is not older than ours). +async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } +/** Should the comment carrying \`theirSha\` stay as it is (i.e. is it not older than ours)? */ async function theirsWins(theirSha) { if (theirSha === headSha) return true; - const cmp = await gh("GET", api + "/compare/" + headSha + "..." + theirSha); - if (!cmp) return true; + const cmp = await gh("GET", API + "/compare/" + headSha + "..." + theirSha, undefined, { soft: true }); + if (!cmp) return false; // a head the repo cannot resolve is not a newer head if (cmp.status === "ahead" || cmp.status === "identical") return true; if (cmp.status === "behind") return false; - // diverged (rebase / force-push): the more recently committed head owns the comment. - return (await committerDate(theirSha)) >= (await committerDate(headSha)); + const [theirs, mine] = [await committerDate(theirSha), await committerDate(headSha)]; + if (theirs === null || mine === null) return false; + return theirs >= mine; } +const byPreference = (a, b) => (a.m.sha === headSha ? -1 : b.m.sha === headSha ? 1 : Date.parse(b.c.updated_at) - Date.parse(a.c.updated_at)); +async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + id, undefined, { soft: true }); console.log("deleted duplicate comment " + id); } + (async () => { - let found = await ours(); - // Converge legacy duplicates to one comment without discarding a newer - // verdict: keep the one for our SHA, else the most recently updated. + let text = fs.readFileSync(bodyPath, "utf8"); + if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; + + // Identity first when the token allows (a user token does; an installation + // token may 403): it lets legacy markers be adopted on the first scan and + // makes the create path a single write. + const me = await gh("GET", (process.env.GITHUB_API || "https://api.github.com") + "/user", undefined, { soft: true }); + let found = await ours(me && me.login ? [me.login] : []); if (found.length > 1) { - found.sort((x, y) => (x.m.sha === headSha ? -1 : y.m.sha === headSha ? 1 : Date.parse(y.c.updated_at) - Date.parse(x.c.updated_at))); - for (const dup of found.slice(1)) { await gh("DELETE", api + "/issues/comments/" + dup.c.id); console.log("deleted duplicate comment " + dup.c.id); } + // Converge legacy duplicates to one comment without discarding a newer + // verdict: keep the one for our SHA, else the most recently updated. + found.sort(byPreference); + for (const dup of found.slice(1)) await softDelete(dup.c.id); found = [found[0]]; } const existing = found[0]; - let text = fs.readFileSync(bodyPath, "utf8"); - if (Buffer.byteLength(text) > 60000) text = Buffer.from(text).subarray(0, 60000).toString() + "\n\n_…truncated; the full review is in the run artifacts._\n"; + if (!existing) { - const posted = await gh("POST", api + "/issues/" + number + "/comments", { body: MARK + " " + headSha + " by:pending -->\n" + text }); - // Stamp our real login into the marker now that we know it. - await gh("PATCH", api + "/issues/comments/" + posted.id, { body: markerFor(posted.user.login) + "\n" + text }); - // Two wakes can both scan-then-create; converge to the lowest id. - const again = await ours(); - const lowest = again.reduce((a, b) => (a && a.c.id < b.c.id ? a : b), null); - if (lowest && lowest.c.id !== posted.id) { await gh("DELETE", api + "/issues/comments/" + posted.id); console.log("raced: kept " + lowest.c.id + ", deleted ours " + posted.id); return; } + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(me && me.login ? me.login : "pending") + "\n" + text }); + const login = posted.user.login; + if (!(me && me.login)) await gh("PATCH", API + "/issues/comments/" + posted.id, { body: markerFor(login) + "\n" + text }, { soft: true }); + // Two wakes can both scan-then-create. Re-scan (adopting any by:pending + // orphans this login left) and converge on the comment whose head wins. + const again = (await ours([login])).filter((x) => x.c.user.login === login); + if (again.length > 1) { + let keep = again.find((x) => x.c.id === posted.id) || again[0]; + for (const other of again) { + if (other.c.id === keep.c.id) continue; + if (other.m.sha === headSha) { if (other.c.id < keep.c.id) keep = other; } // same head: lowest id wins + else if (await theirsWins(other.m.sha)) keep = other; // a newer head owns the comment + } + for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); + if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } + } console.log("posted comment " + posted.id + " for " + headSha); return; } - // Re-read right before writing; never overwrite a verdict for a newer head. - const fresh = await gh("GET", api + "/issues/comments/" + existing.c.id); - const cur = parseMark(fresh); + + // Re-read right before writing; a vanished comment means "none exists". + const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); + if (fresh === null) { + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; + } + const cur = readMark(fresh); if (cur && (await theirsWins(cur.sha))) { console.log("comment already carries " + cur.sha + "; not overwriting with " + headSha); return; } - await gh("PATCH", api + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login) + "\n" + text }); + await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); console.log("updated comment " + existing.c.id + " for " + headSha); })(); `; async function postComment(f: Ctx, pr: Pr): Promise { - await f.run("cat > review/post.cjs <<'EOF'\n" + POST_SCRIPT + "\nEOF\n"); + await f.run("cat > review/post.cjs <<'EOF'\n" + POST_SCRIPT + "EOF\n"); await f.run( `node review/post.cjs ${shellWord(REPO.owner)} ${shellWord(REPO.repo)} ${shellWord(String(pr.number))} ${shellWord(pr.headSha)} ${shellWord(CONSENSUS)}`, { timeout: "2m" }, From 57d8559d2a8d1fd11f61b49625dea9e5daf1c2db Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 18:21:20 -0700 Subject: [PATCH 6/7] workflows(pr-review): keeper is the newest head, never ours by identity; never stamp 'pending' Co-Authored-By: Claude Opus 5 (1M context) --- packages/sdk/tests/pr-review-post.test.ts | 17 ++++++++ workflows/pr-review-post.cjs | 49 +++++++++++++---------- workflows/pr-review.flow.ts | 49 +++++++++++++---------- 3 files changed, 71 insertions(+), 44 deletions(-) diff --git a/packages/sdk/tests/pr-review-post.test.ts b/packages/sdk/tests/pr-review-post.test.ts index 4d8859021..6cff01a49 100644 --- a/packages/sdk/tests/pr-review-post.test.ts +++ b/packages/sdk/tests/pr-review-post.test.ts @@ -159,6 +159,23 @@ describe('workflows/pr-review-post.cjs', () => { expect(r.out).toContain('updated comment'); expect(ours()).toHaveLength(1); expect(ours()[0].body).toBe(`${mark(SHA_B, 'relay[bot]')}\nverdict body\n`); expect(fake.log.filter((l) => l.startsWith('POST'))).toEqual([]); }); + it('first-scan cleanup keeps the newest head even when an older wake runs last', async () => { + const newer = seed(SHA_B, { text: 'newer' }); seed(SHA_A, { text: 'older-dup' }); + fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; fake.compare[`${SHA_A}...${SHA_B}`] = 'ahead'; + const r = await run(SHA_A); + expect(ours()).toHaveLength(1); expect(ours()[0].id).toBe(newer.id); expect(ours()[0].body).toContain('\nnewer'); expect(r.out).toContain('not overwriting'); + }); + it('stamps the real author login when updating a by:pending comment (identity known)', async () => { + fake.user = { login: 'relay[bot]' }; + seed(SHA_A, { login: 'pending' }); fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; + const r = await run(SHA_B); + expect(r.out).toContain('updated comment'); expect(ours()).toHaveLength(1); expect(ours()[0].body.startsWith(mark(SHA_B, 'relay[bot]') + '\n')).toBe(true); + }); + it('converges a by:pending orphan to one stamped comment with an installation token', async () => { + seed(SHA_A, { login: 'pending' }); fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; fake.compare[`${SHA_A}...${SHA_B}`] = 'ahead'; + const r = await run(SHA_B); + expect(r.code).toBe(0); expect(ours()).toHaveLength(1); expect(ours()[0].body.startsWith(mark(SHA_B, 'relay[bot]') + '\n')).toBe(true); + }); it('re-posts when the comment vanished between scan and write', async () => { const c = seed(SHA_A); // Delete it on the first re-read: emulate by removing after listing. diff --git a/workflows/pr-review-post.cjs b/workflows/pr-review-post.cjs index d3501bc7f..86de1bfaf 100644 --- a/workflows/pr-review-post.cjs +++ b/workflows/pr-review-post.cjs @@ -70,18 +70,28 @@ async function ours(knownLogins) { return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); } async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } -/** Should the comment carrying `theirSha` stay as it is (i.e. is it not older than ours)? */ -async function theirsWins(theirSha) { - if (theirSha === headSha) return true; - const cmp = await gh("GET", API + "/compare/" + headSha + "..." + theirSha, undefined, { soft: true }); - if (!cmp) return false; // a head the repo cannot resolve is not a newer head +/** Does the head `a` outrank head `b` (a is not older than b)? Unresolvable heads lose. */ +async function headWins(a, b) { + if (a === b) return true; + const cmp = await gh("GET", API + "/compare/" + b + "..." + a, undefined, { soft: true }); + if (!cmp) return false; if (cmp.status === "ahead" || cmp.status === "identical") return true; if (cmp.status === "behind") return false; - const [theirs, mine] = [await committerDate(theirSha), await committerDate(headSha)]; - if (theirs === null || mine === null) return false; - return theirs >= mine; + const [da, db] = [await committerDate(a), await committerDate(b)]; + if (da === null || db === null) return false; + return da >= db; +} +/** Should the comment carrying `theirSha` stay as it is (i.e. is it not older than ours)? */ +const theirsWins = (theirSha) => headWins(theirSha, headSha); +/** Among our comments, the one whose head is newest; same head → lowest id. Never prefers ours by identity. */ +async function keeperOf(cands) { + let keep = cands[0]; + for (const other of cands.slice(1)) { + if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; } + else if (await headWins(other.m.sha, keep.m.sha)) keep = other; + } + return keep; } -const byPreference = (a, b) => (a.m.sha === headSha ? -1 : b.m.sha === headSha ? 1 : Date.parse(b.c.updated_at) - Date.parse(a.c.updated_at)); async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + id, undefined, { soft: true }); console.log("deleted duplicate comment " + id); } (async () => { @@ -94,11 +104,11 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i const me = await gh("GET", (process.env.GITHUB_API || "https://api.github.com") + "/user", undefined, { soft: true }); let found = await ours(me && me.login ? [me.login] : []); if (found.length > 1) { - // Converge legacy duplicates to one comment without discarding a newer - // verdict: keep the one for our SHA, else the most recently updated. - found.sort(byPreference); - for (const dup of found.slice(1)) await softDelete(dup.c.id); - found = [found[0]]; + // Converge duplicates to one comment without discarding a newer verdict: + // keep the one whose head is newest (never "ours" by identity). + const keep = await keeperOf(found); + for (const dup of found) if (dup.c.id !== keep.c.id) await softDelete(dup.c.id); + found = [keep]; } const existing = found[0]; @@ -110,12 +120,7 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // orphans this login left) and converge on the comment whose head wins. const again = (await ours([login])).filter((x) => x.c.user.login === login); if (again.length > 1) { - let keep = again.find((x) => x.c.id === posted.id) || again[0]; - for (const other of again) { - if (other.c.id === keep.c.id) continue; - if (other.m.sha === headSha) { if (other.c.id < keep.c.id) keep = other; } // same head: lowest id wins - else if (await theirsWins(other.m.sha)) keep = other; // a newer head owns the comment - } + const keep = await keeperOf(again); for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } } @@ -125,11 +130,11 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // Re-read right before writing; a vanished comment means "none exists". const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); if (fresh === null) { - const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; } const cur = readMark(fresh); if (cur && (await theirsWins(cur.sha))) { console.log("comment already carries " + cur.sha + "; not overwriting with " + headSha); return; } - await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("updated comment " + existing.c.id + " for " + headSha); })(); diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index fc907c230..78686f13a 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -266,18 +266,28 @@ async function ours(knownLogins) { return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); } async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } -/** Should the comment carrying \`theirSha\` stay as it is (i.e. is it not older than ours)? */ -async function theirsWins(theirSha) { - if (theirSha === headSha) return true; - const cmp = await gh("GET", API + "/compare/" + headSha + "..." + theirSha, undefined, { soft: true }); - if (!cmp) return false; // a head the repo cannot resolve is not a newer head +/** Does the head \`a\` outrank head \`b\` (a is not older than b)? Unresolvable heads lose. */ +async function headWins(a, b) { + if (a === b) return true; + const cmp = await gh("GET", API + "/compare/" + b + "..." + a, undefined, { soft: true }); + if (!cmp) return false; if (cmp.status === "ahead" || cmp.status === "identical") return true; if (cmp.status === "behind") return false; - const [theirs, mine] = [await committerDate(theirSha), await committerDate(headSha)]; - if (theirs === null || mine === null) return false; - return theirs >= mine; + const [da, db] = [await committerDate(a), await committerDate(b)]; + if (da === null || db === null) return false; + return da >= db; +} +/** Should the comment carrying \`theirSha\` stay as it is (i.e. is it not older than ours)? */ +const theirsWins = (theirSha) => headWins(theirSha, headSha); +/** Among our comments, the one whose head is newest; same head → lowest id. Never prefers ours by identity. */ +async function keeperOf(cands) { + let keep = cands[0]; + for (const other of cands.slice(1)) { + if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; } + else if (await headWins(other.m.sha, keep.m.sha)) keep = other; + } + return keep; } -const byPreference = (a, b) => (a.m.sha === headSha ? -1 : b.m.sha === headSha ? 1 : Date.parse(b.c.updated_at) - Date.parse(a.c.updated_at)); async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + id, undefined, { soft: true }); console.log("deleted duplicate comment " + id); } (async () => { @@ -290,11 +300,11 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i const me = await gh("GET", (process.env.GITHUB_API || "https://api.github.com") + "/user", undefined, { soft: true }); let found = await ours(me && me.login ? [me.login] : []); if (found.length > 1) { - // Converge legacy duplicates to one comment without discarding a newer - // verdict: keep the one for our SHA, else the most recently updated. - found.sort(byPreference); - for (const dup of found.slice(1)) await softDelete(dup.c.id); - found = [found[0]]; + // Converge duplicates to one comment without discarding a newer verdict: + // keep the one whose head is newest (never "ours" by identity). + const keep = await keeperOf(found); + for (const dup of found) if (dup.c.id !== keep.c.id) await softDelete(dup.c.id); + found = [keep]; } const existing = found[0]; @@ -306,12 +316,7 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // orphans this login left) and converge on the comment whose head wins. const again = (await ours([login])).filter((x) => x.c.user.login === login); if (again.length > 1) { - let keep = again.find((x) => x.c.id === posted.id) || again[0]; - for (const other of again) { - if (other.c.id === keep.c.id) continue; - if (other.m.sha === headSha) { if (other.c.id < keep.c.id) keep = other; } // same head: lowest id wins - else if (await theirsWins(other.m.sha)) keep = other; // a newer head owns the comment - } + const keep = await keeperOf(again); for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } } @@ -321,12 +326,12 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // Re-read right before writing; a vanished comment means "none exists". const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); if (fresh === null) { - const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; } const cur = readMark(fresh); if (cur && (await theirsWins(cur.sha))) { console.log("comment already carries " + cur.sha + "; not overwriting with " + headSha); return; } - await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.m.login || existing.c.user.login) + "\n" + text }); + await gh("PATCH", API + "/issues/comments/" + existing.c.id, { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("updated comment " + existing.c.id + " for " + headSha); })(); `; From 62a72a4c0d70fac7823eb6e6adc41966fc5258b4 Mon Sep 17 00:00:00 2001 From: Relayflow Lead Date: Fri, 18 Sep 2026 18:33:39 -0700 Subject: [PATCH 7/7] workflows(pr-review): tell transient failures from gone; unresolvable heads never win the dedupe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Soft calls return { status } so callers distinguish 404 (gone → loses / re-post) from 5xx or network (transient → stop without POST, PATCH or DELETE). headWins returns unknown on transient errors and, when a compare fails for a pair, decides by each head's existence; keeperOf leaves duplicates alone when it cannot order them. 21 cases. Co-Authored-By: Claude Opus 5 (1M context) --- packages/sdk/tests/pr-review-post.test.ts | 42 ++++++++++++---- workflows/pr-review-post.cjs | 58 +++++++++++++++++------ workflows/pr-review.flow.ts | 58 +++++++++++++++++------ 3 files changed, 122 insertions(+), 36 deletions(-) diff --git a/packages/sdk/tests/pr-review-post.test.ts b/packages/sdk/tests/pr-review-post.test.ts index 6cff01a49..896708b22 100644 --- a/packages/sdk/tests/pr-review-post.test.ts +++ b/packages/sdk/tests/pr-review-post.test.ts @@ -18,7 +18,8 @@ interface Comment { id: number; body: string; user: { login: string; type: strin interface Fake { comments: Comment[]; user: { login: string } | null; - compare: Record; + compare: Record; + rereadStatus: number | null; dates: Record; log: string[]; nextId: number; @@ -30,7 +31,7 @@ function body(req: IncomingMessage): Promise { return new Promise((res) => { let s = ''; req.on('data', (d) => { s += d; }); req.on('end', () => res(s)); }); } beforeEach(async () => { - fake = { comments: [], user: null, compare: {}, dates: {}, log: [], nextId: 100 }; + fake = { comments: [], user: null, compare: {}, dates: {}, log: [], nextId: 100, rereadStatus: null }; dir = mkdtempSync(join(tmpdir(), 'pr-review-post-')); writeFileSync(join(dir, 'body.md'), 'verdict body\n'); server = createServer(async (req, res) => { @@ -52,12 +53,12 @@ beforeEach(async () => { if (one) { const c = fake.comments.find((x) => x.id === Number(one[1])); if (!c) return json(404, { message: 'Not Found' }); - if (method === 'GET') return json(200, c); + if (method === 'GET') return fake.rereadStatus ? json(fake.rereadStatus, { message: 'x' }) : json(200, c); if (method === 'PATCH') { c.body = (JSON.parse(await body(req)) as { body: string }).body; c.updated_at = new Date().toISOString(); return json(200, c); } if (method === 'DELETE') { fake.comments = fake.comments.filter((x) => x.id !== c.id); return json(204, null); } } const cmp = path.match(/^\/repos\/o\/r\/compare\/([0-9a-f]{40})\.\.\.([0-9a-f]{40})$/); - if (cmp) { const st = fake.compare[`${cmp[1]}...${cmp[2]}`]; return st === undefined || st === 404 ? json(404, { message: 'Not Found' }) : json(200, { status: st }); } + if (cmp) { const st = fake.compare[`${cmp[1]}...${cmp[2]}`]; return st === undefined || st === 404 ? json(404, { message: 'Not Found' }) : st === 500 ? json(500, { message: 'boom' }) : json(200, { status: st }); } const commit = path.match(/^\/repos\/o\/r\/commits\/([0-9a-f]{40})$/); if (commit) { const d = fake.dates[commit[1]]; return d ? json(200, { commit: { committer: { date: d } } }) : json(404, { message: 'Not Found' }); } return json(500, { message: `unhandled ${method} ${path}` }); @@ -130,10 +131,35 @@ describe('workflows/pr-review-post.cjs', () => { fake.compare[`${SHA_A}...${SHA_C}`] = 'diverged'; fake.dates[SHA_A] = '2026-09-18T09:00:00Z'; expect((await run(SHA_A)).out).toContain('not overwriting'); }); - it('treats an unresolvable head as older (compare 404) and overwrites', async () => { - seed(SHA_B); // no compare entry → 404 + it('treats an unresolvable head as older (compare 404, commit gone) and overwrites', async () => { + seed(SHA_B); fake.dates[SHA_A] = '2026-09-18T09:00:00Z'; // SHA_B has no commit → gone expect((await run(SHA_A)).out).toContain('updated comment'); }); + it('a transient compare failure never overwrites', async () => { + seed(SHA_B, { text: 'keep' }); fake.compare[`${SHA_A}...${SHA_B}`] = 500; + const r = await run(SHA_A); + expect(r.code).toBe(0); expect(r.out).toContain('not overwriting'); expect(ours()[0].body).toContain('\nkeep'); + }); + it('a transient re-read stops without POST or PATCH', async () => { + seed(SHA_A, { text: 'keep' }); fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; fake.rereadStatus = 502; + const r = await run(SHA_B); + expect(r.code).toBe(0); expect(r.out).toContain('transient'); expect(ours()).toHaveLength(1); expect(ours()[0].body).toContain('\nkeep'); + expect(fake.log.filter((l) => /^(POST|PATCH)/.test(l))).toEqual([]); + }); + it('an unresolvable leftover never wins the dedupe over the resolvable verdict', async () => { + fake.user = { login: 'relay[bot]' }; + seed(SHA_C, { text: 'gone-head' }); const mine = seed(SHA_A, { text: 'mine' }); // SHA_C: no commit, no compare + fake.dates[SHA_A] = '2026-09-18T09:00:00Z'; + const r = await run(SHA_A); + expect(ours()).toHaveLength(1); expect(ours()[0].id).toBe(mine.id); expect(r.out).toContain('not overwriting'); + }); + it('a transient failure while ordering duplicates leaves them for the next wake', async () => { + fake.user = { login: 'relay[bot]' }; + seed(SHA_B, { text: 'x' }); seed(SHA_A, { text: 'y' }); fake.compare[`${SHA_B}...${SHA_A}`] = 500; + const r = await run(SHA_A); + expect(r.code).toBe(0); expect(r.out).toContain('leaving them'); expect(ours()).toHaveLength(2); + expect(fake.log.filter((l) => /^(DELETE|POST|PATCH)/.test(l))).toEqual([]); + }); it('ignores a spoofed marker from another author', async () => { const spoof = seed(SHA_A, { login: 'relay[bot]', author: 'mallory', text: 'spoof' }); const r = await run(SHA_B); @@ -144,7 +170,7 @@ describe('workflows/pr-review-post.cjs', () => { it('adopts legacy markers by the same login and converges duplicates, keeping the newest', async () => { seed(SHA_A, { login: null, updated: '2026-09-18T08:00:00Z', text: 'legacy-old' }); const newer = seed(SHA_B, { login: null, updated: '2026-09-18T12:00:00Z', text: 'legacy-newer' }); - fake.compare[`${SHA_A}...${SHA_B}`] = 'ahead'; + fake.compare[`${SHA_A}...${SHA_B}`] = 'ahead'; fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; // With an installation token the login is only known after posting, so // the script posts, adopts the legacy comments as the same login, and // converges on the newest — deleting its own just-posted older verdict. @@ -200,9 +226,9 @@ describe('workflows/pr-review-post.cjs', () => { if (req.method === 'GET' && u.startsWith('/repos/o/r/issues/7/comments')) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(comments)); return; } if (req.method === 'GET' && u.startsWith('/repos/o/r/issues/comments/')) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(comments[1])); return; } if (req.method === 'PATCH') { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify(comments[1])); return; } + if (req.method === 'GET' && u.includes('/compare/')) { res.writeHead(200, { 'content-type': 'application/json' }); res.end(JSON.stringify({ status: 'behind' })); return; } res.writeHead(500); res.end('{}'); }); - fake.compare[`${SHA_B}...${SHA_A}`] = 'behind'; const r = await run(SHA_B); expect(r.code).toBe(0); expect(r.out).toContain('soft-fail DELETE'); expect(r.out).toContain('updated comment'); }); diff --git a/workflows/pr-review-post.cjs b/workflows/pr-review-post.cjs index 86de1bfaf..aa55ba980 100644 --- a/workflows/pr-review-post.cjs +++ b/workflows/pr-review-post.cjs @@ -31,24 +31,29 @@ const API = (process.env.GITHUB_API || "https://api.github.com") + "/repos/" + o const MARK = ""; /** {sha, login|null} for any marker line (new or legacy form), else null. */ function readMark(c) { @@ -69,26 +74,47 @@ async function ours(knownLogins) { for (const x of all) if (x.m.login && x.m.login !== "pending" && x.c.user.login === x.m.login) logins.add(x.m.login); return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); } -async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } -/** Does the head `a` outrank head `b` (a is not older than b)? Unresolvable heads lose. */ +/** Committer date in ms; null when the commit is gone (404); undefined on a transient failure. */ +async function committerDate(sha) { + const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); + if (failed(c)) return transient(c) ? undefined : null; + return Date.parse(c.commit.committer.date); +} +/** + * Does head `a` outrank head `b`? true / false, or "unknown" on a transient + * failure. A head the repo cannot resolve (404) loses; when compare fails + * for the pair, each head's existence decides. + */ async function headWins(a, b) { if (a === b) return true; const cmp = await gh("GET", API + "/compare/" + b + "..." + a, undefined, { soft: true }); - if (!cmp) return false; + if (failed(cmp)) { + if (transient(cmp)) return "unknown"; + const [da, db] = [await committerDate(a), await committerDate(b)]; + if (da === undefined || db === undefined) return "unknown"; + if (da === null && db === null) return "unknown"; + if (da === null) return false; + if (db === null) return true; + return da >= db; + } if (cmp.status === "ahead" || cmp.status === "identical") return true; if (cmp.status === "behind") return false; const [da, db] = [await committerDate(a), await committerDate(b)]; - if (da === null || db === null) return false; + if (da === undefined || db === undefined) return "unknown"; + if (da === null) return false; + if (db === null) return true; return da >= db; } -/** Should the comment carrying `theirSha` stay as it is (i.e. is it not older than ours)? */ -const theirsWins = (theirSha) => headWins(theirSha, headSha); -/** Among our comments, the one whose head is newest; same head → lowest id. Never prefers ours by identity. */ +/** Should the comment carrying `theirSha` stay? Unknown → yes (never overwrite on doubt). */ +async function theirsWins(theirSha) { const w = await headWins(theirSha, headSha); return w === true || w === "unknown"; } +/** Among our comments, the one whose head is newest; same head → lowest id. Unknown → keep both (returns null). */ async function keeperOf(cands) { let keep = cands[0]; for (const other of cands.slice(1)) { - if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; } - else if (await headWins(other.m.sha, keep.m.sha)) keep = other; + if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; continue; } + const w = await headWins(other.m.sha, keep.m.sha); + if (w === "unknown") return null; + if (w === true) keep = other; } return keep; } @@ -105,8 +131,10 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i let found = await ours(me && me.login ? [me.login] : []); if (found.length > 1) { // Converge duplicates to one comment without discarding a newer verdict: - // keep the one whose head is newest (never "ours" by identity). + // keep the one whose head is newest (never "ours" by identity). If that + // cannot be decided right now, leave them all and try again next wake. const keep = await keeperOf(found); + if (keep === null) { console.log("could not order the existing comments (transient); leaving them"); process.exit(0); } for (const dup of found) if (dup.c.id !== keep.c.id) await softDelete(dup.c.id); found = [keep]; } @@ -121,6 +149,7 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i const again = (await ours([login])).filter((x) => x.c.user.login === login); if (again.length > 1) { const keep = await keeperOf(again); + if (keep === null) { console.log("posted comment " + posted.id + " for " + headSha + " (duplicates left for the next wake: transient)"); return; } for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } } @@ -129,7 +158,8 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // Re-read right before writing; a vanished comment means "none exists". const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); - if (fresh === null) { + if (transient(fresh)) { console.log("could not re-read comment " + existing.c.id + " (transient); not writing"); return; } + if (failed(fresh)) { const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; } diff --git a/workflows/pr-review.flow.ts b/workflows/pr-review.flow.ts index 78686f13a..be8140dc1 100644 --- a/workflows/pr-review.flow.ts +++ b/workflows/pr-review.flow.ts @@ -227,24 +227,29 @@ const API = (process.env.GITHUB_API || "https://api.github.com") + "/repos/" + o const MARK = ""; /** {sha, login|null} for any marker line (new or legacy form), else null. */ function readMark(c) { @@ -265,26 +270,47 @@ async function ours(knownLogins) { for (const x of all) if (x.m.login && x.m.login !== "pending" && x.c.user.login === x.m.login) logins.add(x.m.login); return all.filter((x) => (x.m.login && x.m.login !== "pending") ? x.c.user.login === x.m.login : logins.has(x.c.user.login)); } -async function committerDate(sha) { const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); return c ? Date.parse(c.commit.committer.date) : null; } -/** Does the head \`a\` outrank head \`b\` (a is not older than b)? Unresolvable heads lose. */ +/** Committer date in ms; null when the commit is gone (404); undefined on a transient failure. */ +async function committerDate(sha) { + const c = await gh("GET", API + "/commits/" + sha, undefined, { soft: true }); + if (failed(c)) return transient(c) ? undefined : null; + return Date.parse(c.commit.committer.date); +} +/** + * Does head \`a\` outrank head \`b\`? true / false, or "unknown" on a transient + * failure. A head the repo cannot resolve (404) loses; when compare fails + * for the pair, each head's existence decides. + */ async function headWins(a, b) { if (a === b) return true; const cmp = await gh("GET", API + "/compare/" + b + "..." + a, undefined, { soft: true }); - if (!cmp) return false; + if (failed(cmp)) { + if (transient(cmp)) return "unknown"; + const [da, db] = [await committerDate(a), await committerDate(b)]; + if (da === undefined || db === undefined) return "unknown"; + if (da === null && db === null) return "unknown"; + if (da === null) return false; + if (db === null) return true; + return da >= db; + } if (cmp.status === "ahead" || cmp.status === "identical") return true; if (cmp.status === "behind") return false; const [da, db] = [await committerDate(a), await committerDate(b)]; - if (da === null || db === null) return false; + if (da === undefined || db === undefined) return "unknown"; + if (da === null) return false; + if (db === null) return true; return da >= db; } -/** Should the comment carrying \`theirSha\` stay as it is (i.e. is it not older than ours)? */ -const theirsWins = (theirSha) => headWins(theirSha, headSha); -/** Among our comments, the one whose head is newest; same head → lowest id. Never prefers ours by identity. */ +/** Should the comment carrying \`theirSha\` stay? Unknown → yes (never overwrite on doubt). */ +async function theirsWins(theirSha) { const w = await headWins(theirSha, headSha); return w === true || w === "unknown"; } +/** Among our comments, the one whose head is newest; same head → lowest id. Unknown → keep both (returns null). */ async function keeperOf(cands) { let keep = cands[0]; for (const other of cands.slice(1)) { - if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; } - else if (await headWins(other.m.sha, keep.m.sha)) keep = other; + if (other.m.sha === keep.m.sha) { if (other.c.id < keep.c.id) keep = other; continue; } + const w = await headWins(other.m.sha, keep.m.sha); + if (w === "unknown") return null; + if (w === true) keep = other; } return keep; } @@ -301,8 +327,10 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i let found = await ours(me && me.login ? [me.login] : []); if (found.length > 1) { // Converge duplicates to one comment without discarding a newer verdict: - // keep the one whose head is newest (never "ours" by identity). + // keep the one whose head is newest (never "ours" by identity). If that + // cannot be decided right now, leave them all and try again next wake. const keep = await keeperOf(found); + if (keep === null) { console.log("could not order the existing comments (transient); leaving them"); process.exit(0); } for (const dup of found) if (dup.c.id !== keep.c.id) await softDelete(dup.c.id); found = [keep]; } @@ -317,6 +345,7 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i const again = (await ours([login])).filter((x) => x.c.user.login === login); if (again.length > 1) { const keep = await keeperOf(again); + if (keep === null) { console.log("posted comment " + posted.id + " for " + headSha + " (duplicates left for the next wake: transient)"); return; } for (const other of again) if (other.c.id !== keep.c.id) await softDelete(other.c.id); if (keep.c.id !== posted.id) { console.log("raced: kept " + keep.c.id + " (" + keep.m.sha.slice(0, 8) + "), deleted ours " + posted.id); return; } } @@ -325,7 +354,8 @@ async function softDelete(id) { await gh("DELETE", API + "/issues/comments/" + i // Re-read right before writing; a vanished comment means "none exists". const fresh = await gh("GET", API + "/issues/comments/" + existing.c.id, undefined, { soft: true }); - if (fresh === null) { + if (transient(fresh)) { console.log("could not re-read comment " + existing.c.id + " (transient); not writing"); return; } + if (failed(fresh)) { const posted = await gh("POST", API + "/issues/" + number + "/comments", { body: markerFor(existing.c.user.login) + "\n" + text }); console.log("re-posted comment " + posted.id + " for " + headSha + " (previous one vanished)"); return; }