From a0947380d2658639ee516c4c4902608d528095c2 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:08:13 +0800 Subject: [PATCH 01/20] The text side of the comment guard: markers, fingerprints, similarity --- .github/scripts/comment-text.mjs | 61 ++++++++++++++++++++++++++++++++ 1 file changed, 61 insertions(+) create mode 100644 .github/scripts/comment-text.mjs diff --git a/.github/scripts/comment-text.mjs b/.github/scripts/comment-text.mjs new file mode 100644 index 000000000..2490f6a65 --- /dev/null +++ b/.github/scripts/comment-text.mjs @@ -0,0 +1,61 @@ +// The text side of the comment guard: markers, fingerprints, similarity. No network, no writes. +import { createHash } from 'node:crypto' + +export const FUZZY_THRESHOLD = 0.85 +const MARKERS = //g +const EVENT_MARKER = //g + +export const markerFor = (event) => `` +// Every HTML comment is bookkeeping we wrote, never part of the sentence a human wrote. +export const markersIn = (body) => [...String(body ?? '').matchAll(EVENT_MARKER)].map((m) => m[1]) +export const stripMarkers = (body) => String(body ?? '').replace(MARKERS, '').trimEnd() +export const sha256 = (s) => createHash('sha256').update(s).digest('hex') +// Two comments say the same thing when their text agrees once our own markers are removed: +// a marker is 38 bytes of bookkeeping, never part of the sentence. +export const bodyKey = (body) => sha256(stripMarkers(body).trim()) + +const normalize = (body) => stripMarkers(body).toLowerCase() + .replace(/https?:\/\/\S+/g, ' ') + .replace(/[^0-9a-z\u4e00-\u9fff]+/g, ' ') + .trim() +const grams = (body) => { + const text = normalize(body).replace(/ /g, '') + const set = new Set() + for (let i = 0; i + 3 <= text.length; i++) set.add(text.slice(i, i + 3)) + return set +} + +// Dice-free Jaccard over 3-grams: cheap, and it does not care about wording order. +export function similarity(a, b) { + const A = grams(a) + const B = grams(b) + if (!A.size || !B.size) return 0 + let shared = 0 + for (const g of A) if (B.has(g)) shared++ + return shared / (A.size + B.size - shared) +} + +// Duplicate detection stays inside one object: the close template is shared by every object, so +// comparing across objects would mark 91 of 94 pairs as duplicates (measured on the replay fixture). +export function auditComments(comments, { threshold = FUZZY_THRESHOLD } = {}) { + const kept = [] + const duplicates = [] + for (const c of comments ?? []) { + const id = c.id ?? null + const body = String(c.body ?? '') + const key = bodyKey(body) + const twin = kept.find((k) => k.key === key || similarity(k.body, body) >= threshold) + if (!twin) kept.push({ id, body, key }) + else duplicates.push({ + id, + first_comment_id: twin.id, + why: twin.key === key ? 'same text once the marker is removed' : `text ${similarity(twin.body, body).toFixed(3)} similar`, + }) + } + return { + duplicate: duplicates.length > 0, + first_comment_id: duplicates[0]?.first_comment_id ?? kept[0]?.id ?? null, + duplicate_comment_ids: duplicates.map((d) => d.id), + details: duplicates, + } +} From d6b4f00e04d77cf84e0b9ca98f2f01ebb0a520f9 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:08:48 +0800 Subject: [PATCH 02/20] Decide skip / review / post for a comment before it is written --- .github/scripts/comment-guard.mjs | 107 ++++++++++++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 .github/scripts/comment-guard.mjs diff --git a/.github/scripts/comment-guard.mjs b/.github/scripts/comment-guard.mjs new file mode 100644 index 000000000..bd3d97f2c --- /dev/null +++ b/.github/scripts/comment-guard.mjs @@ -0,0 +1,107 @@ +// Comment guard: decide, before posting, whether this object already carries this event. +// Report only: there is no code path here that writes to the repository. +import { readFileSync } from 'node:fs' +import { FUZZY_THRESHOLD, markersIn, bodyKey, similarity, auditComments } from './comment-text.mjs' + +export * from './comment-text.mjs' + +// The answer the poster needs: skip (already said), review (too close to call), or post. +export function guard(comments, event, draft = null, { threshold = FUZZY_THRESHOLD } = {}) { + const list = comments ?? [] + const marked = list.filter((c) => markersIn(c.body).includes(event)) + if (marked.length) return { status: 'skip', reason: `marker ${event} already on comment ${marked[0].id}` } + if (draft !== null) { + const key = bodyKey(draft) + const same = list.find((c) => bodyKey(c.body) === key) + if (same) return { status: 'skip', reason: `the same text is already on comment ${same.id}, written without a marker` } + const near = list.map((c) => ({ id: c.id, score: similarity(c.body, draft) })).sort((a, b) => b.score - a.score)[0] + if (near && near.score >= threshold) return { status: 'review', reason: `comment ${near.id} is ${near.score.toFixed(3)} similar; a human decides, the guard does not post` } + } + return { status: 'post', reason: `no marker ${event} and no matching text yet` } +} + +// A1 on the replay fixture: for every object the second write must not come back as `post`. +export function replayGuard(fixture, { threshold = FUZZY_THRESHOLD } = {}) { + return (fixture.objects ?? []).map((o) => { + const [first, ...rest] = o.comments ?? [] + const second = rest[0] ?? null + const verdict = second + ? guard([first], o.event_key, second.body, { threshold }) + : { status: 'n/a', reason: 'a single comment, so there is no second write to stop' } + return { number: o.number, duplicate_class: o.duplicate_class ?? null, event_key: o.event_key, second_comment_id: second?.id ?? null, status: verdict.status, reason: verdict.reason } + }) +} + +// One line per object, the shape the replay fixture is compared against. +export function verdicts(fixture, { threshold = FUZZY_THRESHOLD } = {}) { + const rows = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] + return rows.map((o) => { + const a = auditComments(o.comments, { threshold }) + return { number: o.number, event_key: o.event_key ?? null, duplicate: a.duplicate, first_comment_id: a.first_comment_id, duplicate_comment_ids: a.duplicate_comment_ids } + }) +} + +const arg = (name, fallback = null) => { + const i = process.argv.indexOf(name) + return i === -1 ? fallback : process.argv[i + 1] +} + +function main() { + const replay = arg('--replay') + const replayGuardFile = arg('--replay-guard') + const commentsFile = arg('--comments') + const object = arg('--object') + const event = arg('--event', 'close-stale') + const json = process.argv.includes('--json') + const read = (p) => JSON.parse(readFileSync(p, 'utf8')) + + if (replay) { + const fixture = read(replay) + const rows = verdicts(fixture) + const expected = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] + let missed = 0 + let falsePositive = 0 + rows.forEach((r, i) => { + const want = expected[i].expected === 'duplicate' + if (want && !r.duplicate) missed++ + if (!want && r.duplicate) falsePositive++ + if (!json) console.log(`${String(r.number).padEnd(6)} ${r.duplicate ? 'duplicate' : 'unique '} ${r.duplicate ? `first ${r.first_comment_id}, dup ${r.duplicate_comment_ids.join(',')}` : ''}`) + }) + if (!json) console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.duplicate).length} flagged as duplicates; ${missed} missed (a duplicate stays, a comment is only written twice); ${falsePositive} false positive (blocks a real comment).`) + if (json) console.log(JSON.stringify(rows, null, 2)) + process.exit(falsePositive ? 1 : 0) + } + + if (replayGuardFile) { + const rows = replayGuard(read(replayGuardFile)) + // A and B are text-detectable by construction; C is the documented limit and may still post. + const posted = rows.filter((r) => r.status === 'post' && /^[AB]/.test(r.duplicate_class ?? '')) + if (json) console.log(JSON.stringify(rows, null, 2)) + else { + for (const r of rows) console.log(`${String(r.number).padEnd(6)} ${r.status.padEnd(7)} ${r.reason}`) + console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.status === 'skip').length} skipped as already said, ${rows.filter((r) => r.status === 'review').length} sent to review, ${rows.filter((r) => r.status === 'post').length} would post (of which ${posted.length} are text-detectable and must not).`) + } + process.exit(posted.length ? 1 : 0) + } + + if (commentsFile) { + const comments = read(commentsFile) + const draftFile = arg('--draft') + const draft = draftFile ? readFileSync(draftFile, 'utf8') : null + const result = guard(comments, event, draft) + const audit = auditComments(comments) + if (json) console.log(JSON.stringify({ ...result, audit }, null, 2)) + else console.log(`object ${object ?? '?'} event ${event}: ${result.status} (${result.reason}); ${audit.duplicate_comment_ids.length} pre-existing duplicate(s)`) + // --check-only: exit status only, 0 = post, 3 = already said it, 4 = needs a human. + if (process.argv.includes('--check-only')) process.exit(result.status === 'skip' ? 3 : result.status === 'review' ? 4 : 0) + process.exit(0) + } + + console.error('report only, nothing is written. Usage:') + console.error(' node .github/scripts/comment-guard.mjs --replay [--json]') + console.error(' node .github/scripts/comment-guard.mjs --replay-guard [--json]') + console.error(' node .github/scripts/comment-guard.mjs --comments --event [--draft ] [--object ] [--check-only]') + process.exit(1) +} + +if (process.argv[1] && process.argv[1].endsWith('comment-guard.mjs')) main() From 4772c79eb6013e02fe15816a56df9d8754ab2a3d Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:09:21 +0800 Subject: [PATCH 03/20] Report agent-working / agent-pr labels that no longer describe anything --- .github/scripts/label-hygiene.mjs | 86 +++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 .github/scripts/label-hygiene.mjs diff --git a/.github/scripts/label-hygiene.mjs b/.github/scripts/label-hygiene.mjs new file mode 100644 index 000000000..64e4816ed --- /dev/null +++ b/.github/scripts/label-hygiene.mjs @@ -0,0 +1,86 @@ +// Label hygiene: which agent-* labels on an object no longer describe anything. +// `agent-working` means work is live; `agent-pr` means an open PR carries it. When the work or the +// PR is gone the label is an orphan and should be removed. Report only: nothing here writes. +import { readFileSync } from 'node:fs' + +export const GUARDED = ['agent-working', 'agent-pr'] + +const labelNames = (item) => (item.labels ?? []).map((l) => (typeof l === 'string' ? l : l?.name)).filter(Boolean) +const kindOf = (item) => item.kind ?? (item.pull_request ? 'pr' : 'issue') +const prFact = (facts, n) => (facts && n != null ? facts[String(n)] ?? facts[n] : null) + +// A label is an orphan when the thing it announces is gone. Every verdict carries the fact it rests +// on, so a dry run can be checked line by line instead of trusted. +export function auditLabels(items, prs = {}) { + const rows = [] + for (const item of items ?? []) { + const labels = labelNames(item) + const kind = kindOf(item) + const state = item.state ?? 'open' + if (labels.includes('agent-working')) { + let reason = null + if (state === 'closed') reason = `the ${kind} is closed` + else if (item.work_live === false) reason = 'no open PR and no branch references it' + if (reason) rows.push({ number: item.number, kind, label: 'agent-working', state, verdict: 'orphan', reason }) + } + if (labels.includes('agent-pr')) { + const announced = item.announces_pr ?? null + const fact = prFact(prs, announced) + let reason = null + if (announced != null || fact) { + if (!fact) reason = `PR #${announced} is not in the facts given, so it cannot be confirmed open` + else if (fact.state !== 'open') reason = `PR #${announced} is ${fact.state}${fact.merged ? ' and merged' : ' unmerged'}` + else if (fact.branch_exists === false) reason = `PR #${announced} is open but its branch is gone` + } else if (state === 'closed') reason = `the ${kind} is closed and no open PR is named` + if (reason) rows.push({ number: item.number, kind, label: 'agent-pr', state, verdict: 'orphan', reason }) + else if (fact) rows.push({ number: item.number, kind, label: 'agent-pr', state, verdict: 'keep', reason: `PR #${announced} is open` }) + } + } + return rows +} + +// Labels outside the guarded pair are never touched; say so instead of silently ignoring them. +export function untouched(items) { + const seen = new Map() + for (const item of items ?? []) { + for (const name of labelNames(item)) { + if (GUARDED.includes(name)) continue + seen.set(name, (seen.get(name) ?? 0) + 1) + } + } + return [...seen.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([label, count]) => ({ label, count })) +} + +const arg = (name, fallback = null) => { + const i = process.argv.indexOf(name) + return i === -1 ? fallback : process.argv[i + 1] +} + +function main() { + const issuesFile = arg('--issues') + const prsFile = arg('--prs') + const json = process.argv.includes('--json') + if (!issuesFile) { + console.error('report only, nothing is written. Usage:') + console.error(' node .github/scripts/label-hygiene.mjs --issues [--prs ] [--json]') + console.error(' items: [{number, kind, state, labels: [], announces_pr, work_live}]') + console.error(' prs: {"3067": {"state": "closed", "merged": false, "branch_exists": false}}') + process.exit(1) + } + const raw = JSON.parse(readFileSync(issuesFile, 'utf8')) + const items = Array.isArray(raw) ? raw : raw.items ?? [] + const prs = prsFile ? JSON.parse(readFileSync(prsFile, 'utf8')) : {} + const rows = auditLabels(items, prs) + + if (json) console.log(JSON.stringify({ scanned: items.length, rows, untouched: untouched(items) }, null, 2)) + else { + for (const r of rows) console.log(`#${String(r.number).padEnd(6)} ${r.label.padEnd(13)} ${r.verdict.padEnd(6)} ${r.reason}`) + const orphans = rows.filter((r) => r.verdict === 'orphan') + console.log(`\nScanned ${items.length} objects; ${orphans.length} orphan label(s) to strip, ${rows.length - orphans.length} still describe live work.`) + console.log(`Not touched: ${untouched(items).map((u) => `${u.label}×${u.count}`).join(' ') || 'nothing else is labelled'}`) + } + // Exit 1 only when something is orphaned, so a scheduled dry run can fail loudly on drift. + process.exit(rows.some((r) => r.verdict === 'orphan') ? 1 : 0) +} + +if (process.argv[1] && process.argv[1].endsWith('label-hygiene.mjs')) main() From 9d653d7f9a84b456183c929ee1e17cd1c3340f38 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:09:57 +0800 Subject: [PATCH 04/20] Test the label audit against the QA open snapshot --- .github/scripts/label-hygiene.test.mjs | 82 ++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) create mode 100644 .github/scripts/label-hygiene.test.mjs diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs new file mode 100644 index 000000000..fc0336c8c --- /dev/null +++ b/.github/scripts/label-hygiene.test.mjs @@ -0,0 +1,82 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync, existsSync } from 'node:fs' +import { auditLabels, untouched, GUARDED } from './label-hygiene.mjs' + +const item = (over = {}) => ({ number: 1, kind: 'issue', state: 'open', labels: [], ...over }) + +test('agent-working on a closed object is an orphan: nothing is being worked on', () => { + const rows = auditLabels([item({ number: 9, state: 'closed', labels: ['agent-working'] })]) + assert.deepEqual(rows, [{ number: 9, kind: 'issue', label: 'agent-working', state: 'closed', verdict: 'orphan', reason: 'the issue is closed' }]) +}) + +test('agent-working on an open object survives only while the work is live', () => { + assert.deepEqual(auditLabels([item({ labels: ['agent-working'], work_live: true })]), []) + const rows = auditLabels([item({ labels: ['agent-working'], work_live: false })]) + assert.equal(rows[0].verdict, 'orphan') + assert.match(rows[0].reason, /no open PR and no branch/) +}) + +test('agent-pr survives while its PR is open, and dies with the PR', () => { + const open = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'open' } }) + assert.deepEqual(open.map((r) => [r.label, r.verdict]), [['agent-pr', 'keep']]) + const closed = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'closed', merged: false } }) + assert.equal(closed[0].verdict, 'orphan') + assert.match(closed[0].reason, /closed unmerged/) + const merged = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'closed', merged: true } }) + assert.match(merged[0].reason, /merged/) + const branchGone = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'open', branch_exists: false } }) + assert.equal(branchGone[0].verdict, 'orphan') + assert.match(branchGone[0].reason, /branch is gone/) +}) + +test('a fact we were not given is not a verdict: an unknown PR is reported, not assumed open', () => { + const rows = auditLabels([item({ labels: ['agent-pr'], announces_pr: 999 })], {}) + assert.equal(rows[0].verdict, 'orphan') + assert.match(rows[0].reason, /not in the facts given/) + assert.deepEqual(auditLabels([item({ labels: ['agent-pr'], state: 'open' })]), [], 'no PR named and the object is open: nothing to judge') +}) + +test('only the two agent labels are in scope, and the rest is listed instead of ignored', () => { + const items = [ + item({ number: 1, labels: ['agent-working', 'hold', 'needs-human'], state: 'closed' }), + item({ number: 2, labels: ['risk:T3', 'area:security', 'hold'] }), + ] + const rows = auditLabels(items) + assert.deepEqual(rows.map((r) => r.label), ['agent-working'], 'hold and needs-human are never stripped here') + assert.deepEqual(GUARDED, ['agent-working', 'agent-pr']) + assert.deepEqual(untouched(items), [ + { label: 'hold', count: 2 }, + { label: 'area:security', count: 1 }, + { label: 'needs-human', count: 1 }, + { label: 'risk:T3', count: 1 }, + ]) +}) + +test('labels arrive either as names or as API objects', () => { + const rows = auditLabels([{ number: 5, state: 'closed', labels: [{ name: 'agent-pr' }], pull_request: {} }]) + assert.equal(rows[0].kind, 'pr') + assert.equal(rows[0].label, 'agent-pr') +}) + +// A dry run is only worth something if it can be diffed against a second opinion. +const snapshot = '/data/workspace/.qa-triage/raw/open.json' +test('dry run on the QA open snapshot names exactly one orphan and leaves the rest alone', + { skip: existsSync(snapshot) ? false : 'QA snapshot not on this machine' }, () => { + const raw = JSON.parse(readFileSync(snapshot, 'utf8')) + const items = (raw.items ?? raw).map((i) => ({ + number: i.number, kind: i.pull_request ? 'pr' : 'issue', state: i.state, + labels: (i.labels ?? []).map((l) => l.name ?? l), + ...(i.number === 3066 ? { announces_pr: 3067 } : {}), + })) + const rows = auditLabels(items, { 3067: { state: 'closed', merged: false, branch_exists: false } }) + assert.deepEqual(rows.map((r) => [r.number, r.label, r.verdict]), [[3066, 'agent-pr', 'orphan']]) + assert.equal(items.filter((i) => i.labels.includes('agent-working')).length, 0, 'agent-working is on no open object') + }) + +test('label hygiene cannot write either', () => { + const src = readFileSync(new URL('./label-hygiene.mjs', import.meta.url), 'utf8') + assert.doesNotMatch(src, /child_process/) + assert.doesNotMatch(src, /method:\s*['"](POST|PATCH|DELETE)['"]/) + assert.doesNotMatch(src, /fetch\(/) +}) From 16d83500001f8e38a64a889c3dea4899b95a6607 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:10:33 +0800 Subject: [PATCH 05/20] Test the guard on the 19 duplicate comments and the negatives --- .github/scripts/comment-guard.test.mjs | 116 +++++++++++++++++++++++++ 1 file changed, 116 insertions(+) create mode 100644 .github/scripts/comment-guard.test.mjs diff --git a/.github/scripts/comment-guard.test.mjs b/.github/scripts/comment-guard.test.mjs new file mode 100644 index 000000000..41e42a2fc --- /dev/null +++ b/.github/scripts/comment-guard.test.mjs @@ -0,0 +1,116 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { readFileSync, existsSync } from 'node:fs' +import { + FUZZY_THRESHOLD, markerFor, markersIn, stripMarkers, bodyKey, similarity, + auditComments, guard, replayGuard, verdicts, +} from './comment-guard.mjs' + +const closeComment = (anchor, extra = '') => `基于已退役布局关闭(关闭原因,非验收结论) + +- main 锚点:\`${anchor}\`(2026-11-25T12:20:16Z,2156 blobs) +- 该 PR 改动文件在 main \`${anchor}\` 上存在 0 个${extra}` + +// --- markers ------------------------------------------------------------------------------- +test('a marker is bookkeeping: it does not change the text fingerprint', () => { + const body = closeComment('d8898cad') + assert.equal(bodyKey(body), bodyKey(`${body}\n\n${markerFor('close-stale')}`)) + assert.deepEqual(markersIn(`${body}\n\n${markerFor('close-stale')}`), ['close-stale']) + assert.deepEqual(markersIn(body), []) + assert.equal(stripMarkers(`x y`), 'x y') +}) + +// --- A: same text, one side without a marker ----------------------------------------------- +test('A: two comments that differ only by the marker are one duplicate, not two opinions', () => { + const first = { id: 1, body: closeComment('d8898cad') } + const second = { id: 2, body: `${closeComment('d8898cad')}\n\n${markerFor('close-stale')}` } + const audit = auditComments([first, second]) + assert.equal(audit.duplicate, true) + assert.deepEqual(audit.duplicate_comment_ids, [2]) + assert.equal(audit.first_comment_id, 1) +}) + +// --- B: same event, rewritten by hand ------------------------------------------------------ +test('B: the same event written twice with a reworded anchor is caught, but sent to a human', () => { + // The two real pairs differ exactly here: `d8898ca` -> `d8898cad` and `12:20:16Z` -> `T12:20:16Z,2156 blobs`. + const first = { + id: 10, + body: `基于已退役布局关闭(关闭原因,非验收结论) + +- main 锚点:\`d8898ca\`(2026-11-25 12:20:16Z) +- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 +- 该 PR 改动文件在 main \`d8898ca\` 上存在 0 个(git cat-file 逐条核) +- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 +- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, + } + const second = { + id: 11, + body: `基于已退役布局关闭(关闭原因,非验收结论) + +- main 锚点:\`d8898cad\`(2026-11-25T12:20:16Z,2156 blobs) +- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 +- 该 PR 改动文件在 main \`d8898cad\` 上存在 0 个(git cat-file 逐条核) +- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 +- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, + } + assert.ok(similarity(first.body, second.body) >= FUZZY_THRESHOLD, 'the sample has to be close, or this test proves nothing') + assert.notEqual(bodyKey(first.body), bodyKey(second.body), 'and it has to differ once markers are stripped') + assert.equal(guard([first], 'close-stale', second.body).status, 'review') + assert.equal(auditComments([first, second]).duplicate, true) +}) + +// --- C and the negatives: never a false positive ------------------------------------------- +test('C: two different templates for one event are not detectable by text, and that is reported as a miss', () => { + const short = { id: 20, body: '这一批自动化提案随 0.3.0 退役。' } + const long = { id: 21, body: '旧线 Chief / Attempt / SDK 评审门已经不在 main 上,这一条描述的是那套已被删除的机器,因此按历史项关闭。' } + assert.ok(similarity(short.body, long.body) < FUZZY_THRESHOLD) + assert.equal(auditComments([short, long]).duplicate, false) + const fixture = { objects: [{ number: 1, event_key: 'k', duplicate_class: 'C-cross-template', comments: [short, long] }] } + assert.equal(replayGuard(fixture)[0].status, 'post', 'a documented limit, not something the text side can fix') +}) + +test('negative: two comments on one object for different purposes are not a duplicate', () => { + const review = { id: 30, body: '评审通过,两条建议写在下面。' } + const close = { id: 31, body: closeComment('d8898cad') } + assert.ok(similarity(review.body, close.body) < FUZZY_THRESHOLD) + assert.equal(auditComments([review, close]).duplicate, false) +}) + +test('negative: a single comment is never marked, and an empty body never matches', () => { + assert.equal(auditComments([{ id: 40, body: closeComment('d8898cad') }]).duplicate, false) + assert.equal(auditComments([]).duplicate, false) + assert.equal(similarity('', ''), 0) +}) + +// --- what the poster asks ------------------------------------------------------------------ +test('guard: already marked, already said without a marker, or free to post', () => { + const marked = [{ id: 1, body: `done\n\n${markerFor('close-stale')}` }] + assert.equal(guard(marked, 'close-stale').status, 'skip') + assert.equal(guard(marked, 'other-event', 'done').status, 'skip', 'the same words are already there, marker or not') + assert.equal(guard([{ id: 2, body: closeComment('d8898cad') }], 'other-event').status, 'post') + assert.equal(guard([], 'close-stale').status, 'post') +}) + +// --- the replay fixture, when the QA copy is on this machine ------------------------------- +const fixture = '/data/workspace/.qa-triage/replay/comments-replay.json' +test('replay: 19 duplicates found, 6 negatives clean, 1 documented miss, 0 false positives', + { skip: existsSync(fixture) ? false : 'QA fixture not on this machine' }, () => { + const data = JSON.parse(readFileSync(fixture, 'utf8')) + const rows = verdicts(data) + assert.equal(rows.length, 26) + assert.equal(rows.filter((r) => r.duplicate).length, 19) + assert.equal(data.negatives.filter((n, i) => rows[data.objects.length + i].duplicate).length, 0) + const missing = data.objects.filter((o, i) => o.expected === 'duplicate' && !rows[i].duplicate) + assert.deepEqual(missing.map((o) => [o.number, o.duplicate_class]), [[2292, 'C-cross-template']]) + const stopped = replayGuard(data).filter((r) => r.status !== 'post') + assert.equal(stopped.length, 19, 'every one of the 19 is stopped: 14 as already said, 5 sent to review') + }) + +// --- report only --------------------------------------------------------------------------- +test('the guard cannot write: no network client input, no POST, no child process', () => { + const src = readFileSync(new URL('./comment-guard.mjs', import.meta.url), 'utf8') + + readFileSync(new URL('./comment-text.mjs', import.meta.url), 'utf8') + assert.doesNotMatch(src, /child_process/) + assert.doesNotMatch(src, /method:\s*['"]POST['"]/) + assert.doesNotMatch(src, /octokit/) +}) From 00d3c77d8d8c12c22b681cec00a7963d18392286 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:33:34 +0800 Subject: [PATCH 06/20] label-hygiene: read the facts GitHub actually sends, and make an unjudgeable label red announces_pr / work_live are not fields any issue payload carries, so on the raw /issues?state=open snapshot the old version printed "0 orphan label(s)" and exited 0 while #3066 was an orphan. Both are gone: a label is now decided from the Branch: line our pickup writes, plus the two listings the caller passes in (--prs, whose /pulls shape carries head.ref, and --refs from git ls-remote). Three verdicts, and exit 1 = orphan, 2 = cannot be judged, 0 = clean. An unknown is never 0, so a scheduled run that lacks a fact goes red instead of reporting a clean board. Related #3393 --- .github/scripts/label-hygiene.mjs | 142 ++++++++++++++++++++---------- 1 file changed, 94 insertions(+), 48 deletions(-) diff --git a/.github/scripts/label-hygiene.mjs b/.github/scripts/label-hygiene.mjs index 64e4816ed..19028cbf0 100644 --- a/.github/scripts/label-hygiene.mjs +++ b/.github/scripts/label-hygiene.mjs @@ -1,39 +1,87 @@ -// Label hygiene: which agent-* labels on an object no longer describe anything. -// `agent-working` means work is live; `agent-pr` means an open PR carries it. When the work or the -// PR is gone the label is an orphan and should be removed. Report only: nothing here writes. +// Label hygiene: which agent-* labels no longer describe anything. `agent-working` claims work is +// live, `agent-pr` an open PR; the payload has neither fact, so both come from what we wrote plus the +// listings the caller passes in. Writes nothing. import { readFileSync } from 'node:fs' export const GUARDED = ['agent-working', 'agent-pr'] +const names = (i) => (i.labels ?? []).map((l) => (typeof l === 'string' ? l : l?.name)).filter(Boolean) +const kindOf = (i) => i.kind ?? (i.pull_request ? 'pr' : 'issue') -const labelNames = (item) => (item.labels ?? []).map((l) => (typeof l === 'string' ? l : l?.name)).filter(Boolean) -const kindOf = (item) => item.kind ?? (item.pull_request ? 'pr' : 'issue') -const prFact = (facts, n) => (facts && n != null ? facts[String(n)] ?? facts[n] : null) +// --prs takes a saved /pulls list (any state) or a {number: fact} map. The list also says which +// branch each PR came from, so an issue that only names a branch still reaches its PR. +const asList = (prs) => (Array.isArray(prs) ? prs.map((p) => ({ + number: p.number, state: p.state ?? 'open', merged: !!p.merged, + branch: p.branch ?? p.head?.ref ?? null, branch_exists: p.branch_exists, +})) : null) +const prFact = (prs, n) => { + if (!prs || n == null) return null + const list = asList(prs) + return list ? list.find((p) => p.number === n) ?? null : prs[String(n)] ?? prs[n] ?? null +} +const prOnBranch = (prs, branch) => { + const list = asList(prs) + if (!list || !branch) return null + const hits = list.filter((p) => p.branch === branch) + return hits.find((p) => p.state === 'open') ?? hits[0] ?? null +} + +// The conventions our own comments use, and the only way an object payload can name its PR. +export function announcedPr(item) { + if (kindOf(item) === 'pr') return item.number ?? null + const body = String(item.body ?? '') + const m = body.match(/(?:related|refs?|pr|pull request)\s*:?\s*#(\d+)/i) ?? body.match(/pull\/(\d+)/) + return m ? Number(m[1]) : null +} + +// `Branch: dev/x` is written on pickup: the only trace of the work before a PR exists. +export function claimedBranch(item) { + const m = String(item.body ?? '').match(/^\s*Branch:\s*(\S+)\s*$/m) + return m ? m[1] : null +} + +const work = (item, kind, { branches }) => { + const state = item.state ?? 'open' + const branch = claimedBranch(item) + if (state === 'closed') return ['orphan', `the ${kind} is closed`] + if (!branch) return ['unknown', 'open, with no Branch: line and no work_live fact: liveness is not in the payload'] + if (!branches) return ['unknown', `claims branch ${branch}; pass --refs to check whether it still exists`] + return branches.has(branch) ? ['keep', `branch ${branch} exists`] : ['orphan', `branch ${branch} is gone`] +} + +const carrier = (item, kind, { prs, branches }) => { + const state = item.state ?? 'open' + const branch = claimedBranch(item) + const n = announcedPr(item) ?? prOnBranch(prs, branch)?.number ?? null + if (n == null) { + if (state === 'closed') return ['orphan', `the ${kind} is closed and no open PR is named`] + if (branch && branches && !branches.has(branch)) { + return ['orphan', `claims branch ${branch}, which is gone, so no open PR carries it`] + } + if (branch && (branches || prs)) return ['unknown', `names no PR; claims branch ${branch}: pass --prs (head.ref) or --refs`] + return ['unknown', 'open, but the body names no PR and no PR list was given'] + } + if (kind === 'pr' && n === item.number) return [state === 'open' ? 'keep' : 'orphan', `PR #${n} is ${state}`] + if (!prs) return ['unknown', `announces PR #${n}; pass --prs with the saved PR list to check it`] + const f = prFact(prs, n) + if (!f) return ['orphan', `PR #${n} is not in the list given, so it is not open`] + if (f.state !== 'open') return ['orphan', `PR #${n} is ${f.state}${f.merged ? ' and merged' : ' unmerged'}`] + if (f.branch_exists === false) return ['orphan', `PR #${n} is open but its branch is gone`] + return ['keep', `PR #${n} is open`] +} -// A label is an orphan when the thing it announces is gone. Every verdict carries the fact it rests -// on, so a dry run can be checked line by line instead of trusted. -export function auditLabels(items, prs = {}) { +// Every verdict names the fact it rests on. `unknown` is not a pass: the caller did not supply the +// fact, so the run reports it instead of calling the board clean. +export function auditLabels(items, { prs = null, refs = null } = {}) { + const branches = refs == null ? null : new Set(Array.isArray(refs) ? refs : refs.refs ?? []) const rows = [] for (const item of items ?? []) { - const labels = labelNames(item) + const labels = names(item) const kind = kindOf(item) const state = item.state ?? 'open' - if (labels.includes('agent-working')) { - let reason = null - if (state === 'closed') reason = `the ${kind} is closed` - else if (item.work_live === false) reason = 'no open PR and no branch references it' - if (reason) rows.push({ number: item.number, kind, label: 'agent-working', state, verdict: 'orphan', reason }) - } - if (labels.includes('agent-pr')) { - const announced = item.announces_pr ?? null - const fact = prFact(prs, announced) - let reason = null - if (announced != null || fact) { - if (!fact) reason = `PR #${announced} is not in the facts given, so it cannot be confirmed open` - else if (fact.state !== 'open') reason = `PR #${announced} is ${fact.state}${fact.merged ? ' and merged' : ' unmerged'}` - else if (fact.branch_exists === false) reason = `PR #${announced} is open but its branch is gone` - } else if (state === 'closed') reason = `the ${kind} is closed and no open PR is named` - if (reason) rows.push({ number: item.number, kind, label: 'agent-pr', state, verdict: 'orphan', reason }) - else if (fact) rows.push({ number: item.number, kind, label: 'agent-pr', state, verdict: 'keep', reason: `PR #${announced} is open` }) + for (const [label, decide] of [['agent-working', work], ['agent-pr', carrier]]) { + if (!labels.includes(label)) continue + const [verdict, reason] = decide(item, kind, { prs, branches }) + rows.push({ number: item.number ?? null, kind, label, state, verdict, reason }) } } return rows @@ -42,11 +90,8 @@ export function auditLabels(items, prs = {}) { // Labels outside the guarded pair are never touched; say so instead of silently ignoring them. export function untouched(items) { const seen = new Map() - for (const item of items ?? []) { - for (const name of labelNames(item)) { - if (GUARDED.includes(name)) continue - seen.set(name, (seen.get(name) ?? 0) + 1) - } + for (const item of items ?? []) for (const name of names(item)) { + if (!GUARDED.includes(name)) seen.set(name, (seen.get(name) ?? 0) + 1) } return [...seen.entries()].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).map(([label, count]) => ({ label, count })) } @@ -58,29 +103,30 @@ const arg = (name, fallback = null) => { function main() { const issuesFile = arg('--issues') - const prsFile = arg('--prs') - const json = process.argv.includes('--json') if (!issuesFile) { console.error('report only, nothing is written. Usage:') - console.error(' node .github/scripts/label-hygiene.mjs --issues [--prs ] [--json]') - console.error(' items: [{number, kind, state, labels: [], announces_pr, work_live}]') - console.error(' prs: {"3067": {"state": "closed", "merged": false, "branch_exists": false}}') + console.error(' label-hygiene.mjs --issues [--prs ] [--refs ]') + console.error(' prs: [{"number": 3067, "state": "closed", "merged": false, "head": {"ref": "dev/x"}}] or {number: fact}') + console.error(' refs: ["dev/x", "main"] - every branch that exists (git ls-remote)') process.exit(1) } const raw = JSON.parse(readFileSync(issuesFile, 'utf8')) const items = Array.isArray(raw) ? raw : raw.items ?? [] - const prs = prsFile ? JSON.parse(readFileSync(prsFile, 'utf8')) : {} - const rows = auditLabels(items, prs) + const prsFile = arg('--prs') + const refsFile = arg('--refs') + const prs = prsFile ? JSON.parse(readFileSync(prsFile, 'utf8')) : null + const refs = refsFile ? JSON.parse(readFileSync(refsFile, 'utf8')) : null + const rows = auditLabels(items, { prs, refs }) + const orphans = rows.filter((r) => r.verdict === 'orphan') + const unknown = rows.filter((r) => r.verdict === 'unknown') - if (json) console.log(JSON.stringify({ scanned: items.length, rows, untouched: untouched(items) }, null, 2)) - else { - for (const r of rows) console.log(`#${String(r.number).padEnd(6)} ${r.label.padEnd(13)} ${r.verdict.padEnd(6)} ${r.reason}`) - const orphans = rows.filter((r) => r.verdict === 'orphan') - console.log(`\nScanned ${items.length} objects; ${orphans.length} orphan label(s) to strip, ${rows.length - orphans.length} still describe live work.`) - console.log(`Not touched: ${untouched(items).map((u) => `${u.label}×${u.count}`).join(' ') || 'nothing else is labelled'}`) - } - // Exit 1 only when something is orphaned, so a scheduled dry run can fail loudly on drift. - process.exit(rows.some((r) => r.verdict === 'orphan') ? 1 : 0) + for (const r of rows) console.log(`#${String(r.number).padEnd(6)} ${r.label.padEnd(13)} ${r.verdict.padEnd(7)} ${r.reason}`) + console.log(`\nScanned ${items.length} objects; ${orphans.length} orphan(s) to strip, ${rows.length - orphans.length - unknown.length} live, ${unknown.length} unjudged.`) + console.log(`Not touched: ${untouched(items).map((u) => `${u.label}\u00d7${u.count}`).join(' ') || 'nothing else is labelled'}`) + if (unknown.length) console.error(`\n${unknown.length} label(s) need a fact this run did not have: pass --prs and --refs.`) + // 1 = strip, 2 = could not judge, 0 = clean. An unknown is never 0: a scheduled run that cannot + // see the fact must be red, not quiet. + process.exit(orphans.length ? 1 : unknown.length ? 2 : 0) } if (process.argv[1] && process.argv[1].endsWith('label-hygiene.mjs')) main() From dfbaa578f63ccbf81738019225c170729c6acf9a Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:33:55 +0800 Subject: [PATCH 07/20] label-hygiene tests: pin both fixtures by sha256 and cover the branch-gone verdict The two fixture tests read payloads outside the repo, so on CI they print as skipped and their assertions could be edited without anyone noticing. Both now hash the file first (open.json b93ccd34..., comments-replay.json 5eed6b7d...) and say in their names that CI skips them. New cases: the Branch: line is the only PR pointer #3066 has, so a claimed branch that is gone decides agent-pr as an orphan from --refs alone; a payload with no listings at all still yields unknown, never a clean board. The CLI exit codes 1 / 2 / 0 are measured by spawning the script, not by reading its source. Related #3393 --- .github/scripts/label-hygiene.test.mjs | 132 ++++++++++++++----------- 1 file changed, 74 insertions(+), 58 deletions(-) diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs index fc0336c8c..18cbecd57 100644 --- a/.github/scripts/label-hygiene.test.mjs +++ b/.github/scripts/label-hygiene.test.mjs @@ -1,82 +1,98 @@ import { test } from 'node:test' import assert from 'node:assert/strict' -import { readFileSync, existsSync } from 'node:fs' -import { auditLabels, untouched, GUARDED } from './label-hygiene.mjs' +import { readFileSync, existsSync, mkdtempSync, writeFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { auditLabels, untouched, GUARDED, announcedPr, claimedBranch } from './label-hygiene.mjs' -const item = (over = {}) => ({ number: 1, kind: 'issue', state: 'open', labels: [], ...over }) +const obj = (over = {}) => ({ number: 1, kind: 'issue', state: 'open', labels: [], ...over }) +// #3066: no PR number anywhere, only the branch the pickup wrote. +const CLAIM = 'Claim-Id: dfddd1297c094b41a8dfc70778143d10\nBranch: dev/5-missing-changelog-fragment\nBase: 36efafb822fc\n' +const rows = auditLabels +const only = (r) => r.map((x) => [x.verdict, x.reason])[0] test('agent-working on a closed object is an orphan: nothing is being worked on', () => { - const rows = auditLabels([item({ number: 9, state: 'closed', labels: ['agent-working'] })]) - assert.deepEqual(rows, [{ number: 9, kind: 'issue', label: 'agent-working', state: 'closed', verdict: 'orphan', reason: 'the issue is closed' }]) + assert.deepEqual(rows([obj({ number: 9, state: 'closed', labels: ['agent-working'] })]), [ + { number: 9, kind: 'issue', label: 'agent-working', state: 'closed', verdict: 'orphan', reason: 'the issue is closed' }]) }) -test('agent-working on an open object survives only while the work is live', () => { - assert.deepEqual(auditLabels([item({ labels: ['agent-working'], work_live: true })]), []) - const rows = auditLabels([item({ labels: ['agent-working'], work_live: false })]) - assert.equal(rows[0].verdict, 'orphan') - assert.match(rows[0].reason, /no open PR and no branch/) +test('agent-working is decided by the branch it claims, once the branch list is given', () => { + assert.equal(claimedBranch({ body: CLAIM }), 'dev/5-missing-changelog-fragment') + const open = obj({ labels: ['agent-working'], body: CLAIM }) + assert.deepEqual(only(rows([open], { refs: ['main', 'dev/5-missing-changelog-fragment'] })), ['keep', 'branch dev/5-missing-changelog-fragment exists']) + assert.deepEqual(only(rows([open], { refs: ['main'] })), ['orphan', 'branch dev/5-missing-changelog-fragment is gone']) + assert.deepEqual(only(rows([open])), ['unknown', 'claims branch dev/5-missing-changelog-fragment; pass --refs to check whether it still exists']) }) -test('agent-pr survives while its PR is open, and dies with the PR', () => { - const open = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'open' } }) - assert.deepEqual(open.map((r) => [r.label, r.verdict]), [['agent-pr', 'keep']]) - const closed = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'closed', merged: false } }) - assert.equal(closed[0].verdict, 'orphan') - assert.match(closed[0].reason, /closed unmerged/) - const merged = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'closed', merged: true } }) - assert.match(merged[0].reason, /merged/) - const branchGone = auditLabels([item({ labels: ['agent-pr'], announces_pr: 3067 })], { 3067: { state: 'open', branch_exists: false } }) - assert.equal(branchGone[0].verdict, 'orphan') - assert.match(branchGone[0].reason, /branch is gone/) +test('agent-pr: on a PR its own state decides; on an issue it dies with the PR the body names', () => { + assert.deepEqual(only(rows([{ number: 7, state: 'open', pull_request: {}, labels: ['agent-pr'] }])), ['keep', 'PR #7 is open']) + assert.deepEqual(only(rows([{ number: 7, state: 'closed', pull_request: {}, labels: ['agent-pr'] }])), ['orphan', 'PR #7 is closed']) + const issue = (body = 'Related #3067') => obj({ labels: ['agent-pr'], body }) + assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'open' } } })), ['keep', 'PR #3067 is open']) + assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'closed', merged: false } } })), ['orphan', 'PR #3067 is closed unmerged']) + assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'open', branch_exists: false } } })), ['orphan', 'PR #3067 is open but its branch is gone']) + assert.deepEqual(only(rows([issue()], { prs: {} })), ['orphan', 'PR #3067 is not in the list given, so it is not open']) }) -test('a fact we were not given is not a verdict: an unknown PR is reported, not assumed open', () => { - const rows = auditLabels([item({ labels: ['agent-pr'], announces_pr: 999 })], {}) - assert.equal(rows[0].verdict, 'orphan') - assert.match(rows[0].reason, /not in the facts given/) - assert.deepEqual(auditLabels([item({ labels: ['agent-pr'], state: 'open' })]), [], 'no PR named and the object is open: nothing to judge') +// One saved /pulls list decides #3066, because each PR says which branch it came from. +test('a branch the body claims finds its PR in a saved /pulls list', () => { + assert.equal(announcedPr({ number: 3066, body: CLAIM }), null) + const at = (state, ref) => ({ number: 3067, state, merged: false, head: { ref } }) + const mine = obj({ number: 3066, labels: ['agent-pr'], body: CLAIM }) + assert.deepEqual(only(rows([mine], { prs: [at('closed', 'dev/5-missing-changelog-fragment')] })), ['orphan', 'PR #3067 is closed unmerged']) + assert.deepEqual(only(rows([mine], { prs: [at('open', 'dev/5-missing-changelog-fragment')] })), ['keep', 'PR #3067 is open']) + assert.deepEqual(only(rows([mine], { refs: ['main'] })), + ['orphan', 'claims branch dev/5-missing-changelog-fragment, which is gone, so no open PR carries it']) }) -test('only the two agent labels are in scope, and the rest is listed instead of ignored', () => { - const items = [ - item({ number: 1, labels: ['agent-working', 'hold', 'needs-human'], state: 'closed' }), - item({ number: 2, labels: ['risk:T3', 'area:security', 'hold'] }), - ] - const rows = auditLabels(items) - assert.deepEqual(rows.map((r) => r.label), ['agent-working'], 'hold and needs-human are never stripped here') - assert.deepEqual(GUARDED, ['agent-working', 'agent-pr']) - assert.deepEqual(untouched(items), [ - { label: 'hold', count: 2 }, - { label: 'area:security', count: 1 }, - { label: 'needs-human', count: 1 }, - { label: 'risk:T3', count: 1 }, - ]) +// The v1 bug: on a raw payload it printed "0 orphan" and exited 0 - a gate that can never fail. +test('a label the payload cannot decide is reported, never counted as clean', () => { + assert.deepEqual(only(rows([obj({ labels: ['agent-pr'], body: CLAIM })])), ['unknown', 'open, but the body names no PR and no PR list was given']) + assert.deepEqual(only(rows([obj({ labels: ['agent-working'] })])), ['unknown', 'open, with no Branch: line and no work_live fact: liveness is not in the payload']) }) -test('labels arrive either as names or as API objects', () => { - const rows = auditLabels([{ number: 5, state: 'closed', labels: [{ name: 'agent-pr' }], pull_request: {} }]) - assert.equal(rows[0].kind, 'pr') - assert.equal(rows[0].label, 'agent-pr') +test('only the two agent labels are in scope, and the rest is listed instead of ignored', () => { + const items = [obj({ number: 1, labels: ['agent-working', 'hold', 'needs-human'], state: 'closed' }), + obj({ number: 2, labels: [{ name: 'risk:T3' }, 'area:security', 'hold'] })] + assert.deepEqual(rows(items).map((r) => r.label), ['agent-working'], 'hold and needs-human are never stripped here') + assert.deepEqual(GUARDED, ['agent-working', 'agent-pr']) + assert.deepEqual(untouched(items), [{ label: 'hold', count: 2 }, { label: 'area:security', count: 1 }, + { label: 'needs-human', count: 1 }, { label: 'risk:T3', count: 1 }]) }) -// A dry run is only worth something if it can be diffed against a second opinion. +// QA payload only; the cases above cover CI. const snapshot = '/data/workspace/.qa-triage/raw/open.json' -test('dry run on the QA open snapshot names exactly one orphan and leaves the rest alone', - { skip: existsSync(snapshot) ? false : 'QA snapshot not on this machine' }, () => { - const raw = JSON.parse(readFileSync(snapshot, 'utf8')) - const items = (raw.items ?? raw).map((i) => ({ - number: i.number, kind: i.pull_request ? 'pr' : 'issue', state: i.state, - labels: (i.labels ?? []).map((l) => l.name ?? l), - ...(i.number === 3066 ? { announces_pr: 3067 } : {}), - })) - const rows = auditLabels(items, { 3067: { state: 'closed', merged: false, branch_exists: false } }) - assert.deepEqual(rows.map((r) => [r.number, r.label, r.verdict]), [[3066, 'agent-pr', 'orphan']]) - assert.equal(items.filter((i) => i.labels.includes('agent-working')).length, 0, 'agent-working is on no open object') +test('fixture: the raw open snapshot cannot come out clean while #3066 says a PR carries it', + { skip: existsSync(snapshot) ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { + const raw = readFileSync(snapshot) + assert.equal(createHash('sha256').update(raw).digest('hex'), + 'b93ccd34cd3a3aad2082103bed7c192fccfd9adfcfc582ced7b5b82a863b8290', 'a changed fixture voids these numbers') + const items = JSON.parse(raw).map((i) => ({ number: i.number, kind: i.pull_request ? 'pr' : 'issue', state: i.state, body: i.body, labels: i.labels })) + assert.deepEqual(only(rows(items.filter((i) => i.number === 3066))), ['unknown', 'open, but the body names no PR and no PR list was given']) + assert.equal(items.filter((i) => (i.labels ?? []).some((l) => (l.name ?? l) === 'agent-working')).length, 0, 'agent-working is on no open object') }) +test('exit status separates strip / cannot judge / clean', () => { + const dir = mkdtempSync(join(tmpdir(), 'hyg-')) + const save = (name, data) => { + const path = join(dir, `${name}.json`) + writeFileSync(path, JSON.stringify(data)) + return path + } + const status = (items, extra = []) => spawnSync(process.execPath, + ['.github/scripts/label-hygiene.mjs', '--issues', save(Math.random().toString(36).slice(2), { items }), ...extra], + { encoding: 'utf8' }).status + const refs = ['--refs', save('refs', ['dev/5-missing-changelog-fragment'])] + assert.equal(status([obj({ number: 1, state: 'closed', labels: ['agent-pr'] })]), 1, 'a closed object is a strip') + assert.equal(status([obj({ number: 2, labels: ['agent-working'], body: CLAIM })]), 2, 'no --refs, nobody can judge it') + assert.equal(status([obj({ number: 3, labels: ['hold'] })]), 0, 'a label outside the pair is clean') + assert.equal(status([obj({ number: 4, labels: ['agent-working'], body: CLAIM })], refs), 0, 'the branch exists') +}) + test('label hygiene cannot write either', () => { const src = readFileSync(new URL('./label-hygiene.mjs', import.meta.url), 'utf8') assert.doesNotMatch(src, /child_process/) - assert.doesNotMatch(src, /method:\s*['"](POST|PATCH|DELETE)['"]/) - assert.doesNotMatch(src, /fetch\(/) + assert.doesNotMatch(src, /method:\s*['"](POST|PATCH|DELETE)['"]|fetch\(/) }) From e9dd88a2852ec1d76bad4e71388d9089bf7ab71e Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:34:19 +0800 Subject: [PATCH 08/20] comment-text: lower the fuzzy threshold to 0.80, with the measured margins written down 0.85 was too tight for the data we have: the weakest real duplicate in the replay fixture is 0.861 (B class, the same event twice with one extra number), so it sat 0.011 from the line - deleting three sentences from a real duplicate dropped it to 0.771 and the guard stayed quiet. The highest pair that is genuinely different is 0.233, so 0.80 still cannot reach it. Same 19 duplicates found, same 0 false positives, same 1 documented miss. Related #3393 --- .github/scripts/comment-text.mjs | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.github/scripts/comment-text.mjs b/.github/scripts/comment-text.mjs index 2490f6a65..b5a9a5256 100644 --- a/.github/scripts/comment-text.mjs +++ b/.github/scripts/comment-text.mjs @@ -1,7 +1,11 @@ // The text side of the comment guard: markers, fingerprints, similarity. No network, no writes. import { createHash } from 'node:crypto' -export const FUZZY_THRESHOLD = 0.85 +// 0.80, not 0.85: on the replay fixture the weakest real duplicate (B class, the same event said +// twice with one more number) is 0.861, while the highest pair that is genuinely different is 0.233. +// 0.85 left 0.011 of margin - deleting three sentences from a real duplicate dropped it to 0.771 and +// the guard went quiet. 0.80 misses neither and still cannot reach the negative pairs. +export const FUZZY_THRESHOLD = 0.8 const MARKERS = //g const EVENT_MARKER = //g From 14aee02da20742898c63c4eb1bef8f93d009ab23 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:34:47 +0800 Subject: [PATCH 09/20] comment-guard tests: pin the replay fixture by sha256, and say in the name that CI skips it The fixture lives outside the repo, so on CI this test printed as skipped and anyone could edit its assertions without a red run. It now hashes comments-replay.json first (5eed6b7d...) and the name says "QA fixture only, skipped on CI", so the skip is visible in the log instead of hidden behind a passing line. Related #3393 --- .github/scripts/comment-guard.test.mjs | 25 +++++++++++++++---------- 1 file changed, 15 insertions(+), 10 deletions(-) diff --git a/.github/scripts/comment-guard.test.mjs b/.github/scripts/comment-guard.test.mjs index 41e42a2fc..252e2f89c 100644 --- a/.github/scripts/comment-guard.test.mjs +++ b/.github/scripts/comment-guard.test.mjs @@ -1,6 +1,7 @@ import { test } from 'node:test' import assert from 'node:assert/strict' import { readFileSync, existsSync } from 'node:fs' +import { createHash } from 'node:crypto' import { FUZZY_THRESHOLD, markerFor, markersIn, stripMarkers, bodyKey, similarity, auditComments, guard, replayGuard, verdicts, @@ -11,7 +12,7 @@ const closeComment = (anchor, extra = '') => `基于已退役布局关闭(关 - main 锚点:\`${anchor}\`(2026-11-25T12:20:16Z,2156 blobs) - 该 PR 改动文件在 main \`${anchor}\` 上存在 0 个${extra}` -// --- markers ------------------------------------------------------------------------------- +// markers test('a marker is bookkeeping: it does not change the text fingerprint', () => { const body = closeComment('d8898cad') assert.equal(bodyKey(body), bodyKey(`${body}\n\n${markerFor('close-stale')}`)) @@ -20,7 +21,7 @@ test('a marker is bookkeeping: it does not change the text fingerprint', () => { assert.equal(stripMarkers(`x y`), 'x y') }) -// --- A: same text, one side without a marker ----------------------------------------------- +// A: same text, one side without a marker test('A: two comments that differ only by the marker are one duplicate, not two opinions', () => { const first = { id: 1, body: closeComment('d8898cad') } const second = { id: 2, body: `${closeComment('d8898cad')}\n\n${markerFor('close-stale')}` } @@ -30,7 +31,7 @@ test('A: two comments that differ only by the marker are one duplicate, not two assert.equal(audit.first_comment_id, 1) }) -// --- B: same event, rewritten by hand ------------------------------------------------------ +// B: same event, rewritten by hand test('B: the same event written twice with a reworded anchor is caught, but sent to a human', () => { // The two real pairs differ exactly here: `d8898ca` -> `d8898cad` and `12:20:16Z` -> `T12:20:16Z,2156 blobs`. const first = { @@ -59,7 +60,7 @@ test('B: the same event written twice with a reworded anchor is caught, but sent assert.equal(auditComments([first, second]).duplicate, true) }) -// --- C and the negatives: never a false positive ------------------------------------------- +// C and the negatives: never a false positive test('C: two different templates for one event are not detectable by text, and that is reported as a miss', () => { const short = { id: 20, body: '这一批自动化提案随 0.3.0 退役。' } const long = { id: 21, body: '旧线 Chief / Attempt / SDK 评审门已经不在 main 上,这一条描述的是那套已被删除的机器,因此按历史项关闭。' } @@ -82,7 +83,7 @@ test('negative: a single comment is never marked, and an empty body never matche assert.equal(similarity('', ''), 0) }) -// --- what the poster asks ------------------------------------------------------------------ +// what the poster asks test('guard: already marked, already said without a marker, or free to post', () => { const marked = [{ id: 1, body: `done\n\n${markerFor('close-stale')}` }] assert.equal(guard(marked, 'close-stale').status, 'skip') @@ -91,11 +92,15 @@ test('guard: already marked, already said without a marker, or free to post', () assert.equal(guard([], 'close-stale').status, 'post') }) -// --- the replay fixture, when the QA copy is on this machine ------------------------------- +// The replay fixture. It sits outside the repo, so CI prints this test as skipped: the cases +// above carry the same rules there, this one holds them to QA's real payload. const fixture = '/data/workspace/.qa-triage/replay/comments-replay.json' -test('replay: 19 duplicates found, 6 negatives clean, 1 documented miss, 0 false positives', - { skip: existsSync(fixture) ? false : 'QA fixture not on this machine' }, () => { - const data = JSON.parse(readFileSync(fixture, 'utf8')) +test('replay (QA fixture only, skipped on CI): 19 duplicates, 6 negatives clean, 1 documented miss', + { skip: existsSync(fixture) ? false : 'QA fixture is not on this machine; CI covers the rules above' }, () => { + const raw = readFileSync(fixture) + assert.equal(createHash('sha256').update(raw).digest('hex'), + '5eed6b7d90ba65ebc2ea814a05a28deb210a42e67dace55080df4eb6ab347c31', 'a changed fixture voids these numbers') + const data = JSON.parse(raw) const rows = verdicts(data) assert.equal(rows.length, 26) assert.equal(rows.filter((r) => r.duplicate).length, 19) @@ -106,7 +111,7 @@ test('replay: 19 duplicates found, 6 negatives clean, 1 documented miss, 0 false assert.equal(stopped.length, 19, 'every one of the 19 is stopped: 14 as already said, 5 sent to review') }) -// --- report only --------------------------------------------------------------------------- +// report only test('the guard cannot write: no network client input, no POST, no child process', () => { const src = readFileSync(new URL('./comment-guard.mjs', import.meta.url), 'utf8') + readFileSync(new URL('./comment-text.mjs', import.meta.url), 'utf8') From f89edec7722c256b296085b31c965507f74f80c3 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 13:37:54 +0800 Subject: [PATCH 10/20] label-hygiene test: spawn the script by absolute path so the exit-code case cannot pass for the wrong reason Running the suite from anywhere but the repo root made node exit 1 on every spawn (module not found), which is exactly what the closed-object case expects: it passed without running the script. The path now comes from import.meta.url, and the suite gives 18/18 from both the repo root and .github/scripts. Related #3393 --- .github/scripts/label-hygiene.test.mjs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs index 18cbecd57..2ddec30c5 100644 --- a/.github/scripts/label-hygiene.test.mjs +++ b/.github/scripts/label-hygiene.test.mjs @@ -5,8 +5,13 @@ import { spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' import { tmpdir } from 'node:os' import { join } from 'node:path' +import { fileURLToPath } from 'node:url' import { auditLabels, untouched, GUARDED, announcedPr, claimedBranch } from './label-hygiene.mjs' +// Spawn by absolute path: a relative one only works when cwd is the repo root, and elsewhere node +// exits 1 on every case, which reads as "strip" for the closed-object assertion below. +const SCRIPT = fileURLToPath(new URL('./label-hygiene.mjs', import.meta.url)) + const obj = (over = {}) => ({ number: 1, kind: 'issue', state: 'open', labels: [], ...over }) // #3066: no PR number anywhere, only the branch the pickup wrote. const CLAIM = 'Claim-Id: dfddd1297c094b41a8dfc70778143d10\nBranch: dev/5-missing-changelog-fragment\nBase: 36efafb822fc\n' @@ -82,7 +87,7 @@ test('exit status separates strip / cannot judge / clean', () => { return path } const status = (items, extra = []) => spawnSync(process.execPath, - ['.github/scripts/label-hygiene.mjs', '--issues', save(Math.random().toString(36).slice(2), { items }), ...extra], + [SCRIPT, '--issues', save(Math.random().toString(36).slice(2), { items }), ...extra], { encoding: 'utf8' }).status const refs = ['--refs', save('refs', ['dev/5-missing-changelog-fragment'])] assert.equal(status([obj({ number: 1, state: 'closed', labels: ['agent-pr'] })]), 1, 'a closed object is a strip') From 502e0bbad31ae0fe03815012016626a6e5551926 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:21:14 +0800 Subject: [PATCH 11/20] label-hygiene: an empty listing is no fact, and a broken input is exit 3, not exit 1 Two ways this could have stripped a live label. A --refs/--prs listing that came back empty read as "the branch is gone", which is exactly what a flaked git ls-remote returns; only a non-empty list may now decide anything, and an empty one is unjudged (exit 2). And a mistyped path or unparsed payload used to throw (stack, exit 1), the same code as "orphan found", so anyone wiring `exit 1 -> strip` would have acted on their own typo; input errors now exit 3. Also: --refs takes git ls-remote output directly (`\trefs/heads/`), which is the normal input, not a hand-made JSON array. Exit codes: 0 clean / 1 orphan found / 2 unjudged / 3 input error. Related #3393 --- .github/scripts/label-hygiene.mjs | 51 ++++++++++++++++++++----------- 1 file changed, 33 insertions(+), 18 deletions(-) diff --git a/.github/scripts/label-hygiene.mjs b/.github/scripts/label-hygiene.mjs index 19028cbf0..1e0fee0f3 100644 --- a/.github/scripts/label-hygiene.mjs +++ b/.github/scripts/label-hygiene.mjs @@ -1,14 +1,12 @@ -// Label hygiene: which agent-* labels no longer describe anything. `agent-working` claims work is -// live, `agent-pr` an open PR; the payload has neither fact, so both come from what we wrote plus the -// listings the caller passes in. Writes nothing. +// Which agent-* labels no longer describe anything. Neither fact is in the payload, so both come from +// what we wrote and what the caller passes in. Writes nothing. import { readFileSync } from 'node:fs' export const GUARDED = ['agent-working', 'agent-pr'] const names = (i) => (i.labels ?? []).map((l) => (typeof l === 'string' ? l : l?.name)).filter(Boolean) const kindOf = (i) => i.kind ?? (i.pull_request ? 'pr' : 'issue') -// --prs takes a saved /pulls list (any state) or a {number: fact} map. The list also says which -// branch each PR came from, so an issue that only names a branch still reaches its PR. +// --prs: a saved /pulls list (any state) or a {number: fact} map; the list also says each PR's branch. const asList = (prs) => (Array.isArray(prs) ? prs.map((p) => ({ number: p.number, state: p.state ?? 'open', merged: !!p.merged, branch: p.branch ?? p.head?.ref ?? null, branch_exists: p.branch_exists, @@ -43,7 +41,7 @@ const work = (item, kind, { branches }) => { const state = item.state ?? 'open' const branch = claimedBranch(item) if (state === 'closed') return ['orphan', `the ${kind} is closed`] - if (!branch) return ['unknown', 'open, with no Branch: line and no work_live fact: liveness is not in the payload'] + if (!branch) return ['unknown', 'open, with no Branch: line: nothing in the payload says the work is live'] if (!branches) return ['unknown', `claims branch ${branch}; pass --refs to check whether it still exists`] return branches.has(branch) ? ['keep', `branch ${branch} exists`] : ['orphan', `branch ${branch} is gone`] } @@ -72,7 +70,11 @@ const carrier = (item, kind, { prs, branches }) => { // Every verdict names the fact it rests on. `unknown` is not a pass: the caller did not supply the // fact, so the run reports it instead of calling the board clean. export function auditLabels(items, { prs = null, refs = null } = {}) { - const branches = refs == null ? null : new Set(Array.isArray(refs) ? refs : refs.refs ?? []) + // An empty listing is not a fact: a flaked `git ls-remote` gives exactly that, and reading it as + // gone strips a live label. Only a non-empty list may decide anything. + const refList = Array.isArray(refs) ? refs : refs?.refs ?? [] + const branches = refList.length ? new Set(refList) : null + prs = (Array.isArray(prs) ? prs : Object.keys(prs ?? {})).length ? prs : null const rows = [] for (const item of items ?? []) { const labels = names(item) @@ -98,24 +100,30 @@ export function untouched(items) { const arg = (name, fallback = null) => { const i = process.argv.indexOf(name) - return i === -1 ? fallback : process.argv[i + 1] + return i === -1 ? fallback : process.argv[i + 1] ?? null +} + +// `git ls-remote` prints `\trefs/heads/` and that is the normal input; JSON is the exception. +const readRefs = (file) => { + const text = readFileSync(file, 'utf8') + if (/^\s*[\[{]/.test(text)) { const j = JSON.parse(text); return Array.isArray(j) ? j : j.refs ?? [] } + const heads = text.split('\n').map((l) => l.split(/\s+/).filter(Boolean).pop()) + .filter((n) => n?.startsWith('refs/heads/')) + return heads.map((n) => n.slice('refs/heads/'.length)) } function main() { const issuesFile = arg('--issues') if (!issuesFile) { - console.error('report only, nothing is written. Usage:') - console.error(' label-hygiene.mjs --issues [--prs ] [--refs ]') - console.error(' prs: [{"number": 3067, "state": "closed", "merged": false, "head": {"ref": "dev/x"}}] or {number: fact}') - console.error(' refs: ["dev/x", "main"] - every branch that exists (git ls-remote)') - process.exit(1) + console.error('report only, nothing is written. Usage: label-hygiene.mjs --issues [--prs ] [--refs ]') + return 3 } const raw = JSON.parse(readFileSync(issuesFile, 'utf8')) const items = Array.isArray(raw) ? raw : raw.items ?? [] const prsFile = arg('--prs') const refsFile = arg('--refs') const prs = prsFile ? JSON.parse(readFileSync(prsFile, 'utf8')) : null - const refs = refsFile ? JSON.parse(readFileSync(refsFile, 'utf8')) : null + const refs = refsFile ? readRefs(refsFile) : null const rows = auditLabels(items, { prs, refs }) const orphans = rows.filter((r) => r.verdict === 'orphan') const unknown = rows.filter((r) => r.verdict === 'unknown') @@ -124,9 +132,16 @@ function main() { console.log(`\nScanned ${items.length} objects; ${orphans.length} orphan(s) to strip, ${rows.length - orphans.length - unknown.length} live, ${unknown.length} unjudged.`) console.log(`Not touched: ${untouched(items).map((u) => `${u.label}\u00d7${u.count}`).join(' ') || 'nothing else is labelled'}`) if (unknown.length) console.error(`\n${unknown.length} label(s) need a fact this run did not have: pass --prs and --refs.`) - // 1 = strip, 2 = could not judge, 0 = clean. An unknown is never 0: a scheduled run that cannot - // see the fact must be red, not quiet. - process.exit(orphans.length ? 1 : unknown.length ? 2 : 0) + // 0 clean / 1 orphan / 2 unjudged / 3 input error: whoever wires this up reads 1 as "strip", so a + // mistyped path must never land there. + return orphans.length ? 1 : unknown.length ? 2 : 0 } -if (process.argv[1] && process.argv[1].endsWith('label-hygiene.mjs')) main() +if (process.argv[1] && process.argv[1].endsWith('label-hygiene.mjs')) { + try { + process.exit(main()) + } catch (e) { + console.error(`label-hygiene: input error: ${e.code === 'ENOENT' ? `no such file: ${e.path}` : e.message}`) + process.exit(3) + } +} From 2460421ca3b2a9021788c762e211d662b524332f Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:21:37 +0800 Subject: [PATCH 12/20] label-hygiene tests: a live branch under an empty --refs must not read as orphan The bug this pins: with refs=[] the run called a branch that still exists "gone" and exited 1, so a flaked git ls-remote plus `exit 1 -> strip` would have stripped a live label. Also covers the raw ls-remote input form, and the fixture path behind FLYBOT_QA_FIXTURES so the QA payload is not a hardcoded absolute path. Related #3393 --- .github/scripts/label-hygiene.test.mjs | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs index 2ddec30c5..8f89eb33e 100644 --- a/.github/scripts/label-hygiene.test.mjs +++ b/.github/scripts/label-hygiene.test.mjs @@ -31,6 +31,17 @@ test('agent-working is decided by the branch it claims, once the branch list is assert.deepEqual(only(rows([open])), ['unknown', 'claims branch dev/5-missing-changelog-fragment; pass --refs to check whether it still exists']) }) +// An empty list is what a flaked `git ls-remote` returns. Read as "gone" it strips a live label. +test('no listing, or an empty one, cannot call a live branch gone', () => { + const open = obj({ labels: ['agent-working'], body: CLAIM }) + for (const refs of [undefined, null, [], { refs: [] }]) { + assert.deepEqual(only(rows([open], { refs })), + ['unknown', 'claims branch dev/5-missing-changelog-fragment; pass --refs to check whether it still exists']) + } + assert.deepEqual(only(rows([obj({ labels: ['agent-pr'], body: CLAIM })], { refs: [] })), + ['unknown', 'open, but the body names no PR and no PR list was given']) +}) + test('agent-pr: on a PR its own state decides; on an issue it dies with the PR the body names', () => { assert.deepEqual(only(rows([{ number: 7, state: 'open', pull_request: {}, labels: ['agent-pr'] }])), ['keep', 'PR #7 is open']) assert.deepEqual(only(rows([{ number: 7, state: 'closed', pull_request: {}, labels: ['agent-pr'] }])), ['orphan', 'PR #7 is closed']) @@ -38,7 +49,7 @@ test('agent-pr: on a PR its own state decides; on an issue it dies with the PR t assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'open' } } })), ['keep', 'PR #3067 is open']) assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'closed', merged: false } } })), ['orphan', 'PR #3067 is closed unmerged']) assert.deepEqual(only(rows([issue()], { prs: { 3067: { state: 'open', branch_exists: false } } })), ['orphan', 'PR #3067 is open but its branch is gone']) - assert.deepEqual(only(rows([issue()], { prs: {} })), ['orphan', 'PR #3067 is not in the list given, so it is not open']) + assert.deepEqual(only(rows([issue()], { prs: {} })), ['unknown', 'announces PR #3067; pass --prs with the saved PR list to check it'], 'an empty list is no fact') }) // One saved /pulls list decides #3066, because each PR says which branch it came from. @@ -55,7 +66,7 @@ test('a branch the body claims finds its PR in a saved /pulls list', () => { // The v1 bug: on a raw payload it printed "0 orphan" and exited 0 - a gate that can never fail. test('a label the payload cannot decide is reported, never counted as clean', () => { assert.deepEqual(only(rows([obj({ labels: ['agent-pr'], body: CLAIM })])), ['unknown', 'open, but the body names no PR and no PR list was given']) - assert.deepEqual(only(rows([obj({ labels: ['agent-working'] })])), ['unknown', 'open, with no Branch: line and no work_live fact: liveness is not in the payload']) + assert.deepEqual(only(rows([obj({ labels: ['agent-working'] })])), ['unknown', 'open, with no Branch: line: nothing in the payload says the work is live']) }) test('only the two agent labels are in scope, and the rest is listed instead of ignored', () => { @@ -68,7 +79,8 @@ test('only the two agent labels are in scope, and the rest is listed instead of }) // QA payload only; the cases above cover CI. -const snapshot = '/data/workspace/.qa-triage/raw/open.json' +const QA = process.env.FLYBOT_QA_FIXTURES ?? '/data/workspace/.qa-triage' +const snapshot = `${QA}/raw/open.json` test('fixture: the raw open snapshot cannot come out clean while #3066 says a PR carries it', { skip: existsSync(snapshot) ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { const raw = readFileSync(snapshot) From c1e7e440040953709c50cad283b493ff88c5a09d Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:21:57 +0800 Subject: [PATCH 13/20] comment-guard: a missing payload is exit 3, not exit 1 Same trap as label-hygiene: `--replay` on a path that is not there threw a stack and exited 1, which a caller reading `exit 1 -> do not post` cannot tell apart from "this comment really is a duplicate". Input errors are now 3 with one line on stderr. Exit codes: 0 ok / 1 a real comment would be blocked / 3 input error. Related #3393 --- .github/scripts/comment-guard.mjs | 158 +++++++++++++----------------- 1 file changed, 67 insertions(+), 91 deletions(-) diff --git a/.github/scripts/comment-guard.mjs b/.github/scripts/comment-guard.mjs index bd3d97f2c..b65e54a44 100644 --- a/.github/scripts/comment-guard.mjs +++ b/.github/scripts/comment-guard.mjs @@ -1,107 +1,83 @@ -// Comment guard: decide, before posting, whether this object already carries this event. -// Report only: there is no code path here that writes to the repository. +// Would this comment be posted twice? GitHub cannot tell us: the same text arrives with and without +// our marker. So compare the text itself, within one object. Writes nothing. import { readFileSync } from 'node:fs' -import { FUZZY_THRESHOLD, markersIn, bodyKey, similarity, auditComments } from './comment-text.mjs' +import { norm, similar } from './comment-text.mjs' -export * from './comment-text.mjs' +export const FUZZY_THRESHOLD = 0.8 +const MARKER = //i +const marked = (text) => String(text ?? '').match(MARKER)?.[1] ?? null -// The answer the poster needs: skip (already said), review (too close to call), or post. -export function guard(comments, event, draft = null, { threshold = FUZZY_THRESHOLD } = {}) { - const list = comments ?? [] - const marked = list.filter((c) => markersIn(c.body).includes(event)) - if (marked.length) return { status: 'skip', reason: `marker ${event} already on comment ${marked[0].id}` } - if (draft !== null) { - const key = bodyKey(draft) - const same = list.find((c) => bodyKey(c.body) === key) - if (same) return { status: 'skip', reason: `the same text is already on comment ${same.id}, written without a marker` } - const near = list.map((c) => ({ id: c.id, score: similarity(c.body, draft) })).sort((a, b) => b.score - a.score)[0] - if (near && near.score >= threshold) return { status: 'review', reason: `comment ${near.id} is ${near.score.toFixed(3)} similar; a human decides, the guard does not post` } - } - return { status: 'post', reason: `no marker ${event} and no matching text yet` } -} - -// A1 on the replay fixture: for every object the second write must not come back as `post`. -export function replayGuard(fixture, { threshold = FUZZY_THRESHOLD } = {}) { - return (fixture.objects ?? []).map((o) => { - const [first, ...rest] = o.comments ?? [] - const second = rest[0] ?? null - const verdict = second - ? guard([first], o.event_key, second.body, { threshold }) - : { status: 'n/a', reason: 'a single comment, so there is no second write to stop' } - return { number: o.number, duplicate_class: o.duplicate_class ?? null, event_key: o.event_key, second_comment_id: second?.id ?? null, status: verdict.status, reason: verdict.reason } - }) -} - -// One line per object, the shape the replay fixture is compared against. -export function verdicts(fixture, { threshold = FUZZY_THRESHOLD } = {}) { - const rows = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] - return rows.map((o) => { - const a = auditComments(o.comments, { threshold }) - return { number: o.number, event_key: o.event_key ?? null, duplicate: a.duplicate, first_comment_id: a.first_comment_id, duplicate_comment_ids: a.duplicate_comment_ids } - }) +// Foreign markers are not evidence of our own template, so they do not buy a discount: still a dup. +export function classify(comments, text) { + const mine = norm(text) + const id = marked(text) + const kept = (comments ?? []).filter((c) => !c.isMinimized) + const exact = kept.filter((c) => norm(c.body) === mine) + const same = id ? exact.find((c) => marked(c.body) === id) : null + if (same) return { duplicate: true, id: same.id, score: 1, why: `this exact comment (${id}) is already there` } + if (exact.length) return { duplicate: true, id: exact[0].id, score: 1, why: 'the same text is already there, without our marker' } + const near = kept.map((c) => ({ ...c, score: similar(mine, norm(c.body)) })) + .filter((c) => c.score >= FUZZY_THRESHOLD).sort((a, b) => b.score - a.score)[0] + if (near) return { duplicate: true, id: near.id, score: near.score, why: `${near.score.toFixed(3)} like comment ${near.id} (marker differs or missing)` } + return { duplicate: false, score: exact[0]?.score ?? 0, why: 'no comment on this object is close' } } const arg = (name, fallback = null) => { const i = process.argv.indexOf(name) - return i === -1 ? fallback : process.argv[i + 1] + if (i === -1) return fallback + const next = process.argv[i + 1] + return next === undefined || next.startsWith('--') ? true : next } -function main() { +export function main() { const replay = arg('--replay') - const replayGuardFile = arg('--replay-guard') - const commentsFile = arg('--comments') - const object = arg('--object') - const event = arg('--event', 'close-stale') - const json = process.argv.includes('--json') - const read = (p) => JSON.parse(readFileSync(p, 'utf8')) - - if (replay) { - const fixture = read(replay) - const rows = verdicts(fixture) - const expected = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] - let missed = 0 - let falsePositive = 0 - rows.forEach((r, i) => { - const want = expected[i].expected === 'duplicate' - if (want && !r.duplicate) missed++ - if (!want && r.duplicate) falsePositive++ - if (!json) console.log(`${String(r.number).padEnd(6)} ${r.duplicate ? 'duplicate' : 'unique '} ${r.duplicate ? `first ${r.first_comment_id}, dup ${r.duplicate_comment_ids.join(',')}` : ''}`) - }) - if (!json) console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.duplicate).length} flagged as duplicates; ${missed} missed (a duplicate stays, a comment is only written twice); ${falsePositive} false positive (blocks a real comment).`) - if (json) console.log(JSON.stringify(rows, null, 2)) - process.exit(falsePositive ? 1 : 0) + const checkOnly = arg('--check-only') + const text = arg('--text') + if (!replay && !text) { + console.error('dry run by default, nothing is written. Usage: comment-guard.mjs --replay | --text [--comments ] [--check-only]') + return 3 } + const load = (p) => JSON.parse(readFileSync(p, 'utf8')) + if (replay && replay !== true) return report(load(replay), { checkOnly }) + const comments = load(arg('--comments')) + const body = readFileSync(text === true ? process.argv[process.argv.indexOf('--text') + 1] : text, 'utf8') + const verdict = classify(comments, body) + console.log(verdict.duplicate + ? `BLOCK ${verdict.why}; a real post would be skipped` + : `POST ${verdict.why}`) + return verdict.duplicate && !checkOnly ? 1 : 0 +} - if (replayGuardFile) { - const rows = replayGuard(read(replayGuardFile)) - // A and B are text-detectable by construction; C is the documented limit and may still post. - const posted = rows.filter((r) => r.status === 'post' && /^[AB]/.test(r.duplicate_class ?? '')) - if (json) console.log(JSON.stringify(rows, null, 2)) - else { - for (const r of rows) console.log(`${String(r.number).padEnd(6)} ${r.status.padEnd(7)} ${r.reason}`) - console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.status === 'skip').length} skipped as already said, ${rows.filter((r) => r.status === 'review').length} sent to review, ${rows.filter((r) => r.status === 'post').length} would post (of which ${posted.length} are text-detectable and must not).`) - } - process.exit(posted.length ? 1 : 0) +// The replay says what SHOULD happen to each sample, so it can fail rather than describe. +// --check-only exits 0/3/4: somebody reviews the close ones instead of a gate guessing. +function report(objects, { checkOnly }) { + let post = 0, skip = 0, review = 0, missed = 0, falsePositive = 0 + for (const o of objects ?? []) { + const v = classify(o.comments, o.text) + const want = o.expected + const got = !v.duplicate ? 'post' : v.score >= 0.999 ? 'skip' : 'review' + if (got === 'post') post += 1 + else if (got === 'skip') skip += 1 + else review += 1 + if (want === 'post' && v.duplicate) { falsePositive += 1; console.log(`FALSE POSITIVE #${o.object} ${v.why}: would block a new comment`) } + if (want !== 'post' && !v.duplicate) { missed += 1; console.log(`MISSED #${o.object} ${o.text.slice(0, 40)}...: would post a duplicate`) } + else if (v.duplicate) console.log(`${want === 'post' ? 'REVIEW ' : 'DUP '} #${String(o.object).padEnd(6)} ${v.why}`) } + const tagged = (objects ?? []).filter((o) => o.text.includes(' y`), 'x y') -}) +// A: the same PR body, differing only in the marker line. +const A = 'Root-caused this to the tag table: the label writer never reloaded.\nRelated #3067' +const marker = (id) => `\n` +// B: the same UI event written twice, second one fixing the sha and adding a count. +const B1 = 'Screenshot job is red on d8898ca: the settings page it waits for was deleted.' +const B2 = 'Screenshot job is red on d8898cad: the settings page it waits for was deleted (2156 blobs).' -// A: same text, one side without a marker -test('A: two comments that differ only by the marker are one duplicate, not two opinions', () => { - const first = { id: 1, body: closeComment('d8898cad') } - const second = { id: 2, body: `${closeComment('d8898cad')}\n\n${markerFor('close-stale')}` } - const audit = auditComments([first, second]) - assert.equal(audit.duplicate, true) - assert.deepEqual(audit.duplicate_comment_ids, [2]) - assert.equal(audit.first_comment_id, 1) +test('the marker alone cannot decide: the twin may predate it', () => { + const v = classify([{ id: 1, body: A }], A + marker('pr-2292:closed')) + assert.equal(v.duplicate, true, 'unmarked first copy, marked second: the second must be blocked') + assert.equal(v.id, 1) + assert.equal(v.score, 1) }) -// B: same event, rewritten by hand -test('B: the same event written twice with a reworded anchor is caught, but sent to a human', () => { - // The two real pairs differ exactly here: `d8898ca` -> `d8898cad` and `12:20:16Z` -> `T12:20:16Z,2156 blobs`. - const first = { - id: 10, - body: `基于已退役布局关闭(关闭原因,非验收结论) - -- main 锚点:\`d8898ca\`(2026-11-25 12:20:16Z) -- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 -- 该 PR 改动文件在 main \`d8898ca\` 上存在 0 个(git cat-file 逐条核) -- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 -- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, - } - const second = { - id: 11, - body: `基于已退役布局关闭(关闭原因,非验收结论) +test('a comment whose text was rewritten is still the same event', () => { + const { score } = classify([{ id: 5, body: B1 }], B2) + assert.ok(score >= FUZZY_THRESHOLD, `B class must clear ${FUZZY_THRESHOLD}, got ${score.toFixed(3)}`) + assert.ok(score < 1, 'and stay below an exact match, so it is reported rather than auto-skipped') +}) -- main 锚点:\`d8898cad\`(2026-11-25T12:20:16Z,2156 blobs) -- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 -- 该 PR 改动文件在 main \`d8898cad\` 上存在 0 个(git cat-file 逐条核) -- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 -- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, - } - assert.ok(similarity(first.body, second.body) >= FUZZY_THRESHOLD, 'the sample has to be close, or this test proves nothing') - assert.notEqual(bodyKey(first.body), bodyKey(second.body), 'and it has to differ once markers are stripped') - assert.equal(guard([first], 'close-stale', second.body).status, 'review') - assert.equal(auditComments([first, second]).duplicate, true) +test('similarity is bounded: a different comment on the same object still posts', () => { + const other = 'Different event: dropped the unused `fold_long_messages` migration from settings.' + assert.deepEqual(classify([{ id: 9, body: B1 }], other).duplicate, false) + assert.equal(classify([], A).duplicate, false, 'an empty history never blocks') }) -// C and the negatives: never a false positive -test('C: two different templates for one event are not detectable by text, and that is reported as a miss', () => { - const short = { id: 20, body: '这一批自动化提案随 0.3.0 退役。' } - const long = { id: 21, body: '旧线 Chief / Attempt / SDK 评审门已经不在 main 上,这一条描述的是那套已被删除的机器,因此按历史项关闭。' } - assert.ok(similarity(short.body, long.body) < FUZZY_THRESHOLD) - assert.equal(auditComments([short, long]).duplicate, false) - const fixture = { objects: [{ number: 1, event_key: 'k', duplicate_class: 'C-cross-template', comments: [short, long] }] } - assert.equal(replayGuard(fixture)[0].status, 'post', 'a documented limit, not something the text side can fix') +test('same text under two different markers is still a duplicate', () => { + const v = classify([{ id: 2, body: A + marker('pr-2292:closed') }], A + marker('pr-2292:review')) + assert.equal(v.duplicate, true) + assert.equal(v.score, 1, 'the marker line is stripped before comparison') }) -test('negative: two comments on one object for different purposes are not a duplicate', () => { - const review = { id: 30, body: '评审通过,两条建议写在下面。' } - const close = { id: 31, body: closeComment('d8898cad') } - assert.ok(similarity(review.body, close.body) < FUZZY_THRESHOLD) - assert.equal(auditComments([review, close]).duplicate, false) +test('a minimized comment is not a wall: the text is gone from the thread', () => { + assert.deepEqual(classify([{ id: 3, body: A, isMinimized: true }], A), { duplicate: false, score: 0, why: 'no comment on this object is close' }) }) -test('negative: a single comment is never marked, and an empty body never matches', () => { - assert.equal(auditComments([{ id: 40, body: closeComment('d8898cad') }]).duplicate, false) - assert.equal(auditComments([]).duplicate, false) - assert.equal(similarity('', ''), 0) +// #2292: two genuinely different templates 84 seconds apart. Merging them would lose information. +test('two different templates are not merged (the #2292 case)', () => { + const a = 'Phase 2 report: label hygiene dry run over 28 open objects, one orphan, exit 2.' + const b = 'Merged the risk table. Tier for #3112 is T3 by size, 194 files.' + assert.equal(classify([{ id: 2292, body: a }], b).duplicate, false) }) -// what the poster asks -test('guard: already marked, already said without a marker, or free to post', () => { - const marked = [{ id: 1, body: `done\n\n${markerFor('close-stale')}` }] - assert.equal(guard(marked, 'close-stale').status, 'skip') - assert.equal(guard(marked, 'other-event', 'done').status, 'skip', 'the same words are already there, marker or not') - assert.equal(guard([{ id: 2, body: closeComment('d8898cad') }], 'other-event').status, 'post') - assert.equal(guard([], 'close-stale').status, 'post') +test('exit status: a post is 0, a block is 1, a bad input is 3', () => { + const dir = tmpdir() + const at = (name, data) => { + const p = join(dir, `${name}-${process.pid}.json`) + writeFileSync(p, JSON.stringify(data)) + return p + } + const history = at('cg-history', [{ id: 1, body: A }]) + const fresh = at('cg-fresh', []) + const text = join(dir, `cg-text-${process.pid}.txt`) + writeFileSync(text, A) + const run = (...args) => spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' }) + assert.equal(run('--text', text, '--comments', fresh).status, 0, 'nothing there yet: post') + assert.equal(run('--text', text, '--comments', history).status, 1, 'already there: do not post') + const missing = run('--replay', join(dir, 'cg-no-such-file.json')) + assert.equal(missing.status, 3, 'a missing payload must not read as "do not post"') + assert.equal(missing.stderr.trim().split('\n').length, 1, 'one line, no stack') + assert.match(missing.stderr, /^comment-guard: input error: no such file: /) + const bad = at('cg-bad', { not: 'a replay' }) + writeFileSync(bad, '{') + assert.equal(run('--replay', bad).status, 3, 'unparsed payload is an input error') + assert.equal(run().status, 3, 'no argument at all is an input error, not a clean run') }) -// The replay fixture. It sits outside the repo, so CI prints this test as skipped: the cases -// above carry the same rules there, this one holds them to QA's real payload. -const fixture = '/data/workspace/.qa-triage/replay/comments-replay.json' -test('replay (QA fixture only, skipped on CI): 19 duplicates, 6 negatives clean, 1 documented miss', - { skip: existsSync(fixture) ? false : 'QA fixture is not on this machine; CI covers the rules above' }, () => { +// Real payload. Two numbers matter: it must catch the 19 duplicates and must not block a new one. +test('replay: this round\'s 19 duplicates are caught, and #2292 is not merged', + { skip: onThisMachine ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { const raw = readFileSync(fixture) assert.equal(createHash('sha256').update(raw).digest('hex'), '5eed6b7d90ba65ebc2ea814a05a28deb210a42e67dace55080df4eb6ab347c31', 'a changed fixture voids these numbers') - const data = JSON.parse(raw) - const rows = verdicts(data) - assert.equal(rows.length, 26) - assert.equal(rows.filter((r) => r.duplicate).length, 19) - assert.equal(data.negatives.filter((n, i) => rows[data.objects.length + i].duplicate).length, 0) - const missing = data.objects.filter((o, i) => o.expected === 'duplicate' && !rows[i].duplicate) - assert.deepEqual(missing.map((o) => [o.number, o.duplicate_class]), [[2292, 'C-cross-template']]) - const stopped = replayGuard(data).filter((r) => r.status !== 'post') - assert.equal(stopped.length, 19, 'every one of the 19 is stopped: 14 as already said, 5 sent to review') + const objects = JSON.parse(raw) + assert.equal(objects.length, 20) + const out = spawnSync(process.execPath, [SCRIPT, '--replay', fixture], { encoding: 'utf8' }) + assert.equal(out.status, 0, 'no new comment is lost to a near-match') + assert.match(out.stdout, /19 skipped as exact duplicates/) + assert.match(out.stdout, /1 missed/, '#2292 is two templates, not a duplicate') + assert.match(out.stdout, /0 false positive/) + assert.match(out.stdout, /14 of 20 carried a marker/) // 7 PR twins arrived unmarked first }) -// report only -test('the guard cannot write: no network client input, no POST, no child process', () => { - const src = readFileSync(new URL('./comment-guard.mjs', import.meta.url), 'utf8') - + readFileSync(new URL('./comment-text.mjs', import.meta.url), 'utf8') - assert.doesNotMatch(src, /child_process/) - assert.doesNotMatch(src, /method:\s*['"]POST['"]/) - assert.doesNotMatch(src, /octokit/) -}) +// --check-only: 0 nothing to post / 3 something would post / 4 somebody must look. +test('--replay-guard: the close ones go to a human, nobody claims a pass', + { skip: onThisMachine ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { + const out = spawnSync(process.execPath, [SCRIPT, '--replay', fixture, '--check-only'], { encoding: 'utf8' }) + assert.equal(out.status, 3, 'one of them would post') + assert.match(out.stdout, /1 would post \/ 14 already there \/ 5 for a human/) + assert.match(out.stdout, /0 are text-detectable and must not|REVIEW /) + }) From b59253a0d6920caffcf3b6c5b90ec7ffd6f80995 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:22:55 +0800 Subject: [PATCH 15/20] tests: pin the three exit-code behaviours QA flagged (F5, F6, raw --refs) - an empty or absent listing, against a branch that really exists, must exit 2 (unjudged) and never 1: a flaked git ls-remote is exactly `[]`, and 1 reads as "strip". - `git ls-remote` output must be accepted directly and produce byte-identical output to the JSON array; a tags-only listing says nothing about branches, so 2. - a missing file, unparsed JSON and a bare invocation are 3 with one line of stderr, not a stack and not 1. Same for `comment-guard --replay` on a missing path. Related #3393 --- .github/scripts/cli-exit-codes.test.mjs | 58 +++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 .github/scripts/cli-exit-codes.test.mjs diff --git a/.github/scripts/cli-exit-codes.test.mjs b/.github/scripts/cli-exit-codes.test.mjs new file mode 100644 index 000000000..f4beaae0d --- /dev/null +++ b/.github/scripts/cli-exit-codes.test.mjs @@ -0,0 +1,58 @@ +// Exit codes are the contract with whoever wires these scripts into a workflow: 0 clean, 1 a +// finding, 2 unjudged, 3 input error. The cases below are the ones that got them wrong. +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { mkdtempSync, writeFileSync } from 'node:fs' +import { spawnSync } from 'node:child_process' +import { tmpdir } from 'node:os' +import { join } from 'node:path' +import { fileURLToPath } from 'node:url' + +const here = fileURLToPath(new URL('.', import.meta.url)) +const HYGIENE = join(here, 'label-hygiene.mjs') +const GUARD = join(here, 'comment-guard.mjs') +const dir = mkdtempSync(join(tmpdir(), 'cli-')) +let n = 0 +const save = (v) => { + const path = join(dir, `${++n}.txt`) + writeFileSync(path, typeof v === 'string' ? v : JSON.stringify(v)) + return path +} +const run = (script, args) => spawnSync(process.execPath, [script, ...args], { encoding: 'utf8' }) + +// A branch that really exists on the remote today; the point is that nothing in the payload says so. +const LIVE = 'Claim-Id: dfddd1297c094b41a8dfc70778143d10\nBranch: dev/3393-write-guards\n' +const live = { items: [{ number: 1, kind: 'issue', state: 'open', labels: ['agent-working'], body: LIVE }] } + +test('an empty listing is no fact: a live branch is unjudged, never an orphan', () => { + const issues = save(live) + assert.equal(run(HYGIENE, ['--issues', issues]).status, 2, 'no --refs at all') + assert.equal(run(HYGIENE, ['--issues', issues, '--refs', save([])]).status, 2, '--refs [] is what a flaked ls-remote gives') + assert.equal(run(HYGIENE, ['--issues', issues, '--refs', save(['dev/3393-write-guards'])]).status, 0, 'the branch exists') + assert.equal(run(HYGIENE, ['--issues', issues, '--refs', save(['main'])]).status, 1, 'a non-empty list without it is a finding') + assert.equal(run(HYGIENE, ['--issues', issues, '--prs', save({})]).status, 2, 'an empty PR map is no fact either') +}) + +test('raw git ls-remote output is the normal --refs input and equals the JSON array', () => { + const issues = save(live) + const sha = (c) => c.repeat(40) + const text = `${sha('a')}\trefs/heads/dev/3393-write-guards\n${sha('b')}\trefs/heads/main\n` + const fromText = run(HYGIENE, ['--issues', issues, '--refs', save(text)]) + const fromJson = run(HYGIENE, ['--issues', issues, '--refs', save(['dev/3393-write-guards', 'main'])]) + assert.equal(fromText.status, 0) + assert.equal(fromText.stdout, fromJson.stdout, 'same verdicts, same exit code') + assert.equal(run(HYGIENE, ['--issues', issues, '--refs', save(`${sha('c')}\trefs/tags/v1\n`)]).status, 2, + 'a tags-only listing says nothing about branches') +}) + +test('input errors exit 3, never 1, and print one line instead of a stack', () => { + const cases = [run(HYGIENE, ['--issues', join(dir, 'missing.json')]), + run(HYGIENE, ['--issues', save('{not json')]), + run(GUARD, ['--replay', join(dir, 'missing.json')])] + for (const r of cases) { + assert.equal(r.status, 3, `exit 3, got ${r.status}: ${r.stderr.trim()}`) + assert.equal(r.stderr.trim().split('\n').length, 1, 'one line, no stack') + } + assert.equal(run(HYGIENE, []).status, 3, 'no arguments is a usage error, not a finding') + assert.equal(run(GUARD, []).status, 3) +}) From 766b3e08da04e4d9751de2824b52dc02b24c43c6 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:24:00 +0800 Subject: [PATCH 16/20] Revert the comment-guard body to the real one (my previous commit had a lost copy-paste) 502e0bb/2460421c were fine, but the comment-guard.mjs I pushed imported norm/similar from comment-text.mjs, which exports none of those names: the file on the branch was a mangled merge of two drafts. This restores the version that was measured, keeping the exit-3 wrapper. Related #3393 --- .github/scripts/comment-guard.mjs | 152 ++++++++++++++++++------------ 1 file changed, 93 insertions(+), 59 deletions(-) diff --git a/.github/scripts/comment-guard.mjs b/.github/scripts/comment-guard.mjs index b65e54a44..9f6075ec6 100644 --- a/.github/scripts/comment-guard.mjs +++ b/.github/scripts/comment-guard.mjs @@ -1,77 +1,111 @@ -// Would this comment be posted twice? GitHub cannot tell us: the same text arrives with and without -// our marker. So compare the text itself, within one object. Writes nothing. +// Comment guard: decide, before posting, whether this object already carries this event. +// Report only: there is no code path here that writes to the repository. import { readFileSync } from 'node:fs' -import { norm, similar } from './comment-text.mjs' +import { FUZZY_THRESHOLD, markersIn, bodyKey, similarity, auditComments } from './comment-text.mjs' -export const FUZZY_THRESHOLD = 0.8 -const MARKER = //i -const marked = (text) => String(text ?? '').match(MARKER)?.[1] ?? null +export * from './comment-text.mjs' -// Foreign markers are not evidence of our own template, so they do not buy a discount: still a dup. -export function classify(comments, text) { - const mine = norm(text) - const id = marked(text) - const kept = (comments ?? []).filter((c) => !c.isMinimized) - const exact = kept.filter((c) => norm(c.body) === mine) - const same = id ? exact.find((c) => marked(c.body) === id) : null - if (same) return { duplicate: true, id: same.id, score: 1, why: `this exact comment (${id}) is already there` } - if (exact.length) return { duplicate: true, id: exact[0].id, score: 1, why: 'the same text is already there, without our marker' } - const near = kept.map((c) => ({ ...c, score: similar(mine, norm(c.body)) })) - .filter((c) => c.score >= FUZZY_THRESHOLD).sort((a, b) => b.score - a.score)[0] - if (near) return { duplicate: true, id: near.id, score: near.score, why: `${near.score.toFixed(3)} like comment ${near.id} (marker differs or missing)` } - return { duplicate: false, score: exact[0]?.score ?? 0, why: 'no comment on this object is close' } +// The answer the poster needs: skip (already said), review (too close to call), or post. +export function guard(comments, event, draft = null, { threshold = FUZZY_THRESHOLD } = {}) { + const list = comments ?? [] + const marked = list.filter((c) => markersIn(c.body).includes(event)) + if (marked.length) return { status: 'skip', reason: `marker ${event} already on comment ${marked[0].id}` } + if (draft !== null) { + const key = bodyKey(draft) + const same = list.find((c) => bodyKey(c.body) === key) + if (same) return { status: 'skip', reason: `the same text is already on comment ${same.id}, written without a marker` } + const near = list.map((c) => ({ id: c.id, score: similarity(c.body, draft) })).sort((a, b) => b.score - a.score)[0] + if (near && near.score >= threshold) return { status: 'review', reason: `comment ${near.id} is ${near.score.toFixed(3)} similar; a human decides, the guard does not post` } + } + return { status: 'post', reason: `no marker ${event} and no matching text yet` } +} + +// A1 on the replay fixture: for every object the second write must not come back as `post`. +export function replayGuard(fixture, { threshold = FUZZY_THRESHOLD } = {}) { + return (fixture.objects ?? []).map((o) => { + const [first, ...rest] = o.comments ?? [] + const second = rest[0] ?? null + const verdict = second + ? guard([first], o.event_key, second.body, { threshold }) + : { status: 'n/a', reason: 'a single comment, so there is no second write to stop' } + return { number: o.number, duplicate_class: o.duplicate_class ?? null, event_key: o.event_key, second_comment_id: second?.id ?? null, status: verdict.status, reason: verdict.reason } + }) +} + +// One line per object, the shape the replay fixture is compared against. +export function verdicts(fixture, { threshold = FUZZY_THRESHOLD } = {}) { + const rows = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] + return rows.map((o) => { + const a = auditComments(o.comments, { threshold }) + return { number: o.number, event_key: o.event_key ?? null, duplicate: a.duplicate, first_comment_id: a.first_comment_id, duplicate_comment_ids: a.duplicate_comment_ids } + }) } const arg = (name, fallback = null) => { const i = process.argv.indexOf(name) - if (i === -1) return fallback - const next = process.argv[i + 1] - return next === undefined || next.startsWith('--') ? true : next + return i === -1 ? fallback : process.argv[i + 1] } -export function main() { +function main() { const replay = arg('--replay') - const checkOnly = arg('--check-only') - const text = arg('--text') - if (!replay && !text) { - console.error('dry run by default, nothing is written. Usage: comment-guard.mjs --replay | --text [--comments ] [--check-only]') - return 3 + const replayGuardFile = arg('--replay-guard') + const commentsFile = arg('--comments') + const object = arg('--object') + const event = arg('--event', 'close-stale') + const json = process.argv.includes('--json') + const read = (p) => JSON.parse(readFileSync(p, 'utf8')) + + if (replay) { + const fixture = read(replay) + const rows = verdicts(fixture) + const expected = [...(fixture.objects ?? []), ...(fixture.negatives ?? [])] + let missed = 0 + let falsePositive = 0 + rows.forEach((r, i) => { + const want = expected[i].expected === 'duplicate' + if (want && !r.duplicate) missed++ + if (!want && r.duplicate) falsePositive++ + if (!json) console.log(`${String(r.number).padEnd(6)} ${r.duplicate ? 'duplicate' : 'unique '} ${r.duplicate ? `first ${r.first_comment_id}, dup ${r.duplicate_comment_ids.join(',')}` : ''}`) + }) + if (!json) console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.duplicate).length} flagged as duplicates; ${missed} missed (a duplicate stays, a comment is only written twice); ${falsePositive} false positive (blocks a real comment).`) + if (json) console.log(JSON.stringify(rows, null, 2)) + process.exit(falsePositive ? 1 : 0) } - const load = (p) => JSON.parse(readFileSync(p, 'utf8')) - if (replay && replay !== true) return report(load(replay), { checkOnly }) - const comments = load(arg('--comments')) - const body = readFileSync(text === true ? process.argv[process.argv.indexOf('--text') + 1] : text, 'utf8') - const verdict = classify(comments, body) - console.log(verdict.duplicate - ? `BLOCK ${verdict.why}; a real post would be skipped` - : `POST ${verdict.why}`) - return verdict.duplicate && !checkOnly ? 1 : 0 -} -// The replay says what SHOULD happen to each sample, so it can fail rather than describe. -// --check-only exits 0/3/4: somebody reviews the close ones instead of a gate guessing. -function report(objects, { checkOnly }) { - let post = 0, skip = 0, review = 0, missed = 0, falsePositive = 0 - for (const o of objects ?? []) { - const v = classify(o.comments, o.text) - const want = o.expected - const got = !v.duplicate ? 'post' : v.score >= 0.999 ? 'skip' : 'review' - if (got === 'post') post += 1 - else if (got === 'skip') skip += 1 - else review += 1 - if (want === 'post' && v.duplicate) { falsePositive += 1; console.log(`FALSE POSITIVE #${o.object} ${v.why}: would block a new comment`) } - if (want !== 'post' && !v.duplicate) { missed += 1; console.log(`MISSED #${o.object} ${o.text.slice(0, 40)}...: would post a duplicate`) } - else if (v.duplicate) console.log(`${want === 'post' ? 'REVIEW ' : 'DUP '} #${String(o.object).padEnd(6)} ${v.why}`) + if (replayGuardFile) { + const rows = replayGuard(read(replayGuardFile)) + // A and B are text-detectable by construction; C is the documented limit and may still post. + const posted = rows.filter((r) => r.status === 'post' && /^[AB]/.test(r.duplicate_class ?? '')) + if (json) console.log(JSON.stringify(rows, null, 2)) + else { + for (const r of rows) console.log(`${String(r.number).padEnd(6)} ${r.status.padEnd(7)} ${r.reason}`) + console.log(`\nReplayed ${rows.length} objects; ${rows.filter((r) => r.status === 'skip').length} skipped as already said, ${rows.filter((r) => r.status === 'review').length} sent to review, ${rows.filter((r) => r.status === 'post').length} would post (of which ${posted.length} are text-detectable and must not).`) + } + process.exit(posted.length ? 1 : 0) } - const tagged = (objects ?? []).filter((o) => o.text.includes('` -// B: the same UI event written twice, second one fixing the sha and adding a count. -const B1 = 'Screenshot job is red on d8898ca: the settings page it waits for was deleted.' -const B2 = 'Screenshot job is red on d8898cad: the settings page it waits for was deleted (2156 blobs).' +- main 锚点:\`${anchor}\`(2026-11-25T12:20:16Z,2156 blobs) +- 该 PR 改动文件在 main \`${anchor}\` 上存在 0 个${extra}` -test('the marker alone cannot decide: the twin may predate it', () => { - const v = classify([{ id: 1, body: A }], A + marker('pr-2292:closed')) - assert.equal(v.duplicate, true, 'unmarked first copy, marked second: the second must be blocked') - assert.equal(v.id, 1) - assert.equal(v.score, 1) +// markers +test('a marker is bookkeeping: it does not change the text fingerprint', () => { + const body = closeComment('d8898cad') + assert.equal(bodyKey(body), bodyKey(`${body}\n\n${markerFor('close-stale')}`)) + assert.deepEqual(markersIn(`${body}\n\n${markerFor('close-stale')}`), ['close-stale']) + assert.deepEqual(markersIn(body), []) + assert.equal(stripMarkers(`x y`), 'x y') }) -test('a comment whose text was rewritten is still the same event', () => { - const { score } = classify([{ id: 5, body: B1 }], B2) - assert.ok(score >= FUZZY_THRESHOLD, `B class must clear ${FUZZY_THRESHOLD}, got ${score.toFixed(3)}`) - assert.ok(score < 1, 'and stay below an exact match, so it is reported rather than auto-skipped') +// A: same text, one side without a marker +test('A: two comments that differ only by the marker are one duplicate, not two opinions', () => { + const first = { id: 1, body: closeComment('d8898cad') } + const second = { id: 2, body: `${closeComment('d8898cad')}\n\n${markerFor('close-stale')}` } + const audit = auditComments([first, second]) + assert.equal(audit.duplicate, true) + assert.deepEqual(audit.duplicate_comment_ids, [2]) + assert.equal(audit.first_comment_id, 1) }) -test('similarity is bounded: a different comment on the same object still posts', () => { - const other = 'Different event: dropped the unused `fold_long_messages` migration from settings.' - assert.deepEqual(classify([{ id: 9, body: B1 }], other).duplicate, false) - assert.equal(classify([], A).duplicate, false, 'an empty history never blocks') +// B: same event, rewritten by hand +test('B: the same event written twice with a reworded anchor is caught, but sent to a human', () => { + // The two real pairs differ exactly here: `d8898ca` -> `d8898cad` and `12:20:16Z` -> `T12:20:16Z,2156 blobs`. + const first = { + id: 10, + body: `基于已退役布局关闭(关闭原因,非验收结论) + +- main 锚点:\`d8898ca\`(2026-11-25 12:20:16Z) +- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 +- 该 PR 改动文件在 main \`d8898ca\` 上存在 0 个(git cat-file 逐条核) +- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 +- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, + } + const second = { + id: 11, + body: `基于已退役布局关闭(关闭原因,非验收结论) + +- main 锚点:\`d8898cad\`(2026-11-25T12:20:16Z,2156 blobs) +- head:\`91e93f2cce49aab0430f196f5908b01955ea2228\`,base 未固定 +- 该 PR 改动文件在 main \`d8898cad\` 上存在 0 个(git cat-file 逐条核) +- 相关:FlyBot 0.3.0(2026-11-25T01:29Z)之后这一批路径已经全部不存在 +- 备注:这一条是关闭原因,不是验收结论,也没有写 parity`, + } + assert.ok(similarity(first.body, second.body) >= FUZZY_THRESHOLD, 'the sample has to be close, or this test proves nothing') + assert.notEqual(bodyKey(first.body), bodyKey(second.body), 'and it has to differ once markers are stripped') + assert.equal(guard([first], 'close-stale', second.body).status, 'review') + assert.equal(auditComments([first, second]).duplicate, true) }) -test('same text under two different markers is still a duplicate', () => { - const v = classify([{ id: 2, body: A + marker('pr-2292:closed') }], A + marker('pr-2292:review')) - assert.equal(v.duplicate, true) - assert.equal(v.score, 1, 'the marker line is stripped before comparison') +// C and the negatives: never a false positive +test('C: two different templates for one event are not detectable by text, and that is reported as a miss', () => { + const short = { id: 20, body: '这一批自动化提案随 0.3.0 退役。' } + const long = { id: 21, body: '旧线 Chief / Attempt / SDK 评审门已经不在 main 上,这一条描述的是那套已被删除的机器,因此按历史项关闭。' } + assert.ok(similarity(short.body, long.body) < FUZZY_THRESHOLD) + assert.equal(auditComments([short, long]).duplicate, false) + const fixture = { objects: [{ number: 1, event_key: 'k', duplicate_class: 'C-cross-template', comments: [short, long] }] } + assert.equal(replayGuard(fixture)[0].status, 'post', 'a documented limit, not something the text side can fix') }) -test('a minimized comment is not a wall: the text is gone from the thread', () => { - assert.deepEqual(classify([{ id: 3, body: A, isMinimized: true }], A), { duplicate: false, score: 0, why: 'no comment on this object is close' }) +test('negative: two comments on one object for different purposes are not a duplicate', () => { + const review = { id: 30, body: '评审通过,两条建议写在下面。' } + const close = { id: 31, body: closeComment('d8898cad') } + assert.ok(similarity(review.body, close.body) < FUZZY_THRESHOLD) + assert.equal(auditComments([review, close]).duplicate, false) }) -// #2292: two genuinely different templates 84 seconds apart. Merging them would lose information. -test('two different templates are not merged (the #2292 case)', () => { - const a = 'Phase 2 report: label hygiene dry run over 28 open objects, one orphan, exit 2.' - const b = 'Merged the risk table. Tier for #3112 is T3 by size, 194 files.' - assert.equal(classify([{ id: 2292, body: a }], b).duplicate, false) +test('negative: a single comment is never marked, and an empty body never matches', () => { + assert.equal(auditComments([{ id: 40, body: closeComment('d8898cad') }]).duplicate, false) + assert.equal(auditComments([]).duplicate, false) + assert.equal(similarity('', ''), 0) }) -test('exit status: a post is 0, a block is 1, a bad input is 3', () => { - const dir = tmpdir() - const at = (name, data) => { - const p = join(dir, `${name}-${process.pid}.json`) - writeFileSync(p, JSON.stringify(data)) - return p - } - const history = at('cg-history', [{ id: 1, body: A }]) - const fresh = at('cg-fresh', []) - const text = join(dir, `cg-text-${process.pid}.txt`) - writeFileSync(text, A) - const run = (...args) => spawnSync(process.execPath, [SCRIPT, ...args], { encoding: 'utf8' }) - assert.equal(run('--text', text, '--comments', fresh).status, 0, 'nothing there yet: post') - assert.equal(run('--text', text, '--comments', history).status, 1, 'already there: do not post') - const missing = run('--replay', join(dir, 'cg-no-such-file.json')) - assert.equal(missing.status, 3, 'a missing payload must not read as "do not post"') - assert.equal(missing.stderr.trim().split('\n').length, 1, 'one line, no stack') - assert.match(missing.stderr, /^comment-guard: input error: no such file: /) - const bad = at('cg-bad', { not: 'a replay' }) - writeFileSync(bad, '{') - assert.equal(run('--replay', bad).status, 3, 'unparsed payload is an input error') - assert.equal(run().status, 3, 'no argument at all is an input error, not a clean run') +// what the poster asks +test('guard: already marked, already said without a marker, or free to post', () => { + const marked = [{ id: 1, body: `done\n\n${markerFor('close-stale')}` }] + assert.equal(guard(marked, 'close-stale').status, 'skip') + assert.equal(guard(marked, 'other-event', 'done').status, 'skip', 'the same words are already there, marker or not') + assert.equal(guard([{ id: 2, body: closeComment('d8898cad') }], 'other-event').status, 'post') + assert.equal(guard([], 'close-stale').status, 'post') }) -// Real payload. Two numbers matter: it must catch the 19 duplicates and must not block a new one. -test('replay: this round\'s 19 duplicates are caught, and #2292 is not merged', - { skip: onThisMachine ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { +// The replay fixture. It sits outside the repo, so CI prints this test as skipped: the cases +// above carry the same rules there, this one holds them to QA's real payload. +const QA = process.env.FLYBOT_QA_FIXTURES ?? '/data/workspace/.qa-triage' +const fixture = `${QA}/replay/comments-replay.json` +test('replay (QA fixture only, skipped on CI): 19 duplicates, 6 negatives clean, 1 documented miss', + { skip: existsSync(fixture) ? false : 'QA fixture is not on this machine; CI covers the rules above' }, () => { const raw = readFileSync(fixture) assert.equal(createHash('sha256').update(raw).digest('hex'), '5eed6b7d90ba65ebc2ea814a05a28deb210a42e67dace55080df4eb6ab347c31', 'a changed fixture voids these numbers') - const objects = JSON.parse(raw) - assert.equal(objects.length, 20) - const out = spawnSync(process.execPath, [SCRIPT, '--replay', fixture], { encoding: 'utf8' }) - assert.equal(out.status, 0, 'no new comment is lost to a near-match') - assert.match(out.stdout, /19 skipped as exact duplicates/) - assert.match(out.stdout, /1 missed/, '#2292 is two templates, not a duplicate') - assert.match(out.stdout, /0 false positive/) - assert.match(out.stdout, /14 of 20 carried a marker/) // 7 PR twins arrived unmarked first + const data = JSON.parse(raw) + const rows = verdicts(data) + assert.equal(rows.length, 26) + assert.equal(rows.filter((r) => r.duplicate).length, 19) + assert.equal(data.negatives.filter((n, i) => rows[data.objects.length + i].duplicate).length, 0) + const missing = data.objects.filter((o, i) => o.expected === 'duplicate' && !rows[i].duplicate) + assert.deepEqual(missing.map((o) => [o.number, o.duplicate_class]), [[2292, 'C-cross-template']]) + const stopped = replayGuard(data).filter((r) => r.status !== 'post') + assert.equal(stopped.length, 19, 'every one of the 19 is stopped: 14 as already said, 5 sent to review') }) -// --check-only: 0 nothing to post / 3 something would post / 4 somebody must look. -test('--replay-guard: the close ones go to a human, nobody claims a pass', - { skip: onThisMachine ? false : 'QA payload is not on this machine; CI covers the same cases above' }, () => { - const out = spawnSync(process.execPath, [SCRIPT, '--replay', fixture, '--check-only'], { encoding: 'utf8' }) - assert.equal(out.status, 3, 'one of them would post') - assert.match(out.stdout, /1 would post \/ 14 already there \/ 5 for a human/) - assert.match(out.stdout, /0 are text-detectable and must not|REVIEW /) - }) +// report only +test('the guard cannot write: no network client input, no POST, no child process', () => { + const src = readFileSync(new URL('./comment-guard.mjs', import.meta.url), 'utf8') + + readFileSync(new URL('./comment-text.mjs', import.meta.url), 'utf8') + assert.doesNotMatch(src, /child_process/) + assert.doesNotMatch(src, /method:\s*['"]POST['"]/) + assert.doesNotMatch(src, /octokit/) +}) From 96de428a55d6bf7d3180ffbac203f28d67fec27d Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:25:15 +0800 Subject: [PATCH 18/20] Restore label-hygiene tests to the measured file (no duplicate F6 case) The extra empty-list case I added here duplicates the one in cli-exit-codes.test.mjs, which drives it through the CLI instead of the API. One file each, as measured: 21 tests. Related #3393 --- .github/scripts/label-hygiene.test.mjs | 11 ----------- 1 file changed, 11 deletions(-) diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs index 8f89eb33e..1cab3a937 100644 --- a/.github/scripts/label-hygiene.test.mjs +++ b/.github/scripts/label-hygiene.test.mjs @@ -31,17 +31,6 @@ test('agent-working is decided by the branch it claims, once the branch list is assert.deepEqual(only(rows([open])), ['unknown', 'claims branch dev/5-missing-changelog-fragment; pass --refs to check whether it still exists']) }) -// An empty list is what a flaked `git ls-remote` returns. Read as "gone" it strips a live label. -test('no listing, or an empty one, cannot call a live branch gone', () => { - const open = obj({ labels: ['agent-working'], body: CLAIM }) - for (const refs of [undefined, null, [], { refs: [] }]) { - assert.deepEqual(only(rows([open], { refs })), - ['unknown', 'claims branch dev/5-missing-changelog-fragment; pass --refs to check whether it still exists']) - } - assert.deepEqual(only(rows([obj({ labels: ['agent-pr'], body: CLAIM })], { refs: [] })), - ['unknown', 'open, but the body names no PR and no PR list was given']) -}) - test('agent-pr: on a PR its own state decides; on an issue it dies with the PR the body names', () => { assert.deepEqual(only(rows([{ number: 7, state: 'open', pull_request: {}, labels: ['agent-pr'] }])), ['keep', 'PR #7 is open']) assert.deepEqual(only(rows([{ number: 7, state: 'closed', pull_request: {}, labels: ['agent-pr'] }])), ['orphan', 'PR #7 is closed']) From 7e63870dab80a65b0fb133c81b3bb84491a38840 Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:37:00 +0800 Subject: [PATCH 19/20] Ask only for the fact that is missing, per row and in the summary An agent-pr row that already got --refs was still told "pass --prs or --refs": a caller wiring this up re-passes the flag forever and the run never settles. Each row now names just the absent fact, and when both were given it says the payload itself is what has to name the PR. The empty-PR-list case keeps the existing "no PR list was given" wording (a flaked ls-remote must not read as an orphan). No verdict changes: a live branch still cannot prove an open PR carries the label, so that row stays unknown / exit 2 by design. --- .github/scripts/label-hygiene.mjs | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/.github/scripts/label-hygiene.mjs b/.github/scripts/label-hygiene.mjs index 1e0fee0f3..6511939ed 100644 --- a/.github/scripts/label-hygiene.mjs +++ b/.github/scripts/label-hygiene.mjs @@ -55,7 +55,13 @@ const carrier = (item, kind, { prs, branches }) => { if (branch && branches && !branches.has(branch)) { return ['orphan', `claims branch ${branch}, which is gone, so no open PR carries it`] } - if (branch && (branches || prs)) return ['unknown', `names no PR; claims branch ${branch}: pass --prs (head.ref) or --refs`] + // Name only the fact that is missing: a caller who already passed --refs is not sent back for it. + if (branch && branches) { + return ['unknown', prs + ? `names no PR; branch ${branch} exists and no open PR in the list came from it: the body has to name its PR` + : `names no PR; branch ${branch} exists, but a live branch cannot show a PR still carries it: pass --prs`] + } + if (branch && prs) return ['unknown', `names no PR and no open PR in the list came from branch ${branch}: pass --refs to see whether the branch is gone`] return ['unknown', 'open, but the body names no PR and no PR list was given'] } if (kind === 'pr' && n === item.number) return [state === 'open' ? 'keep' : 'orphan', `PR #${n} is ${state}`] @@ -131,7 +137,16 @@ function main() { for (const r of rows) console.log(`#${String(r.number).padEnd(6)} ${r.label.padEnd(13)} ${r.verdict.padEnd(7)} ${r.reason}`) console.log(`\nScanned ${items.length} objects; ${orphans.length} orphan(s) to strip, ${rows.length - orphans.length - unknown.length} live, ${unknown.length} unjudged.`) console.log(`Not touched: ${untouched(items).map((u) => `${u.label}\u00d7${u.count}`).join(' ') || 'nothing else is labelled'}`) - if (unknown.length) console.error(`\n${unknown.length} label(s) need a fact this run did not have: pass --prs and --refs.`) + // Same rule as the per-row reasons: point only at what is missing, so nobody is sent to re-pass a + // flag that was already given. When both were given, the payload itself is what has to say it. + const prsGiven = (Array.isArray(prs) ? prs.length : Object.keys(prs ?? {}).length) > 0 + const refsGiven = (refs ?? []).length > 0 + const need = [!prsGiven && '--prs', !refsGiven && '--refs'].filter(Boolean) + if (unknown.length) { + console.error(need.length + ? `\n${unknown.length} label(s) need a fact this run did not have: pass ${need.join(' and ')}.` + : `\n${unknown.length} label(s) stayed unjudged: every fact a run can be given was given, so the payload has to name it.`) + } // 0 clean / 1 orphan / 2 unjudged / 3 input error: whoever wires this up reads 1 as "strip", so a // mistyped path must never land there. return orphans.length ? 1 : unknown.length ? 2 : 0 From 6641a833018c52c8834547372b32053e6eeb0e0e Mon Sep 17 00:00:00 2001 From: Danyang Chen Date: Thu, 26 Nov 2026 14:37:50 +0800 Subject: [PATCH 20/20] Test the prompt: a fact already given is never asked for again Three spawn-level cases on one fixture: --refs given (the row must not say --refs and the summary must ask for --prs), --prs given (the mirror), and both given (no flag at all, because then the payload is what is missing). The agent-pr row stays unknown/exit 2 in all three: a live branch cannot prove an open PR still carries the label. --- .github/scripts/cli-exit-codes.test.mjs | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/.github/scripts/cli-exit-codes.test.mjs b/.github/scripts/cli-exit-codes.test.mjs index f4beaae0d..afca666c0 100644 --- a/.github/scripts/cli-exit-codes.test.mjs +++ b/.github/scripts/cli-exit-codes.test.mjs @@ -45,6 +45,24 @@ test('raw git ls-remote output is the normal --refs input and equals the JSON ar 'a tags-only listing says nothing about branches') }) +// The prompt fix: a caller who already passed --refs is not sent back for it, and a live branch is +// still not a PR (agent-pr means a PR carries this, so the row stays unknown). +test('a run that was given a fact never asks for that fact again', () => { + const AP = { items: [{ number: 3066, kind: 'issue', state: 'open', labels: ['agent-pr'], body: LIVE }] } + const prsFile = save([{ number: 9, state: 'open', head: { ref: 'dev/other' } }]) + const onlyRefs = run(HYGIENE, ['--issues', save(AP), '--refs', save(['dev/3393-write-guards'])]) + assert.equal(onlyRefs.status, 2, 'a live branch is not an open PR') + assert.doesNotMatch(onlyRefs.stdout + onlyRefs.stderr, /--refs/, 'it already was given') + assert.match(onlyRefs.stderr, /pass --prs/, 'name the one fact that is missing') + const onlyPrs = run(HYGIENE, ['--issues', save(AP), '--prs', prsFile]) + assert.equal(onlyPrs.status, 2) + assert.match(onlyPrs.stderr, /pass --refs/, 'the branch list is what is missing here') + assert.doesNotMatch(onlyPrs.stdout, /--prs/, 'the row must not ask for what it was given') + const both = run(HYGIENE, ['--issues', save(AP), '--refs', save(['dev/3393-write-guards']), '--prs', prsFile]) + assert.equal(both.status, 2) + assert.doesNotMatch(both.stdout + both.stderr, /--(prs|refs)/, 'nothing is missing, so no flag is named') +}) + test('input errors exit 3, never 1, and print one line instead of a stack', () => { const cases = [run(HYGIENE, ['--issues', join(dir, 'missing.json')]), run(HYGIENE, ['--issues', save('{not json')]),