diff --git a/.github/scripts/cli-exit-codes.test.mjs b/.github/scripts/cli-exit-codes.test.mjs new file mode 100644 index 000000000..afca666c0 --- /dev/null +++ b/.github/scripts/cli-exit-codes.test.mjs @@ -0,0 +1,76 @@ +// 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') +}) + +// 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')]), + 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) +}) diff --git a/.github/scripts/comment-guard.mjs b/.github/scripts/comment-guard.mjs new file mode 100644 index 000000000..9f6075ec6 --- /dev/null +++ b/.github/scripts/comment-guard.mjs @@ -0,0 +1,117 @@ +// 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]') + // 0 ok / 1 a real comment would be blocked (or a duplicate was missed) / 3 input error: a mistyped + // path must not read as "a real comment is blocked". + return 3 +} + +if (process.argv[1] && process.argv[1].endsWith('comment-guard.mjs')) { + try { + const code = main() + if (code != null) process.exit(code) + } catch (e) { + console.error(`comment-guard: input error: ${e.code === 'ENOENT' ? `no such file: ${e.path}` : e.message}`) + process.exit(3) + } +} diff --git a/.github/scripts/comment-guard.test.mjs b/.github/scripts/comment-guard.test.mjs new file mode 100644 index 000000000..d1d3ff2f3 --- /dev/null +++ b/.github/scripts/comment-guard.test.mjs @@ -0,0 +1,122 @@ +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, +} 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. 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 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') + }) + +// 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/) +}) diff --git a/.github/scripts/comment-text.mjs b/.github/scripts/comment-text.mjs new file mode 100644 index 000000000..b5a9a5256 --- /dev/null +++ b/.github/scripts/comment-text.mjs @@ -0,0 +1,65 @@ +// The text side of the comment guard: markers, fingerprints, similarity. No network, no writes. +import { createHash } from 'node:crypto' + +// 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 + +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, + } +} diff --git a/.github/scripts/label-hygiene.mjs b/.github/scripts/label-hygiene.mjs new file mode 100644 index 000000000..6511939ed --- /dev/null +++ b/.github/scripts/label-hygiene.mjs @@ -0,0 +1,162 @@ +// 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: 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, +})) : 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: 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`] +} + +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`] + } + // 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}`] + 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`] +} + +// 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 } = {}) { + // 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) + const kind = kindOf(item) + const state = item.state ?? '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 +} + +// 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 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 })) +} + +const arg = (name, fallback = null) => { + const i = process.argv.indexOf(name) + 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: 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 ? 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') + + 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'}`) + // 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 +} + +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) + } +} diff --git a/.github/scripts/label-hygiene.test.mjs b/.github/scripts/label-hygiene.test.mjs new file mode 100644 index 000000000..1cab3a937 --- /dev/null +++ b/.github/scripts/label-hygiene.test.mjs @@ -0,0 +1,104 @@ +import { test } from 'node:test' +import assert from 'node:assert/strict' +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 { 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' +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', () => { + 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 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: 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: {} })), ['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. +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']) +}) + +// 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: 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', () => { + 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 }]) +}) + +// QA payload only; the cases above cover CI. +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) + 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, + [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') + 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)['"]|fetch\(/) +})