Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
a094738
The text side of the comment guard: markers, fingerprints, similarity
Birfy Nov 26, 2026
d6b4f00
Decide skip / review / post for a comment before it is written
Birfy Nov 26, 2026
4772c79
Report agent-working / agent-pr labels that no longer describe anything
Birfy Nov 26, 2026
9d653d7
Test the label audit against the QA open snapshot
Birfy Nov 26, 2026
16d8350
Test the guard on the 19 duplicate comments and the negatives
Birfy Nov 26, 2026
00d3c77
label-hygiene: read the facts GitHub actually sends, and make an unju…
Birfy Nov 26, 2026
dfbaa57
label-hygiene tests: pin both fixtures by sha256 and cover the branch…
Birfy Nov 26, 2026
e9dd88a
comment-text: lower the fuzzy threshold to 0.80, with the measured ma…
Birfy Nov 26, 2026
14aee02
comment-guard tests: pin the replay fixture by sha256, and say in the…
Birfy Nov 26, 2026
f89edec
label-hygiene test: spawn the script by absolute path so the exit-cod…
Birfy Nov 26, 2026
502e0bb
label-hygiene: an empty listing is no fact, and a broken input is exi…
Birfy Nov 26, 2026
2460421
label-hygiene tests: a live branch under an empty --refs must not rea…
Birfy Nov 26, 2026
c1e7e44
comment-guard: a missing payload is exit 3, not exit 1
Birfy Nov 26, 2026
02a2c8b
comment-guard tests: read the QA payload through FLYBOT_QA_FIXTURES
Birfy Nov 26, 2026
b59253a
tests: pin the three exit-code behaviours QA flagged (F5, F6, raw --r…
Birfy Nov 26, 2026
766b3e0
Revert the comment-guard body to the real one (my previous commit had…
Birfy Nov 26, 2026
f105c6a
Restore the comment-guard tests that go with that body
Birfy Nov 26, 2026
96de428
Restore label-hygiene tests to the measured file (no duplicate F6 case)
Birfy Nov 26, 2026
7e63870
Ask only for the fact that is missing, per row and in the summary
Birfy Nov 26, 2026
6641a83
Test the prompt: a fact already given is never asked for again
Birfy Nov 26, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
76 changes: 76 additions & 0 deletions .github/scripts/cli-exit-codes.test.mjs
Original file line number Diff line number Diff line change
@@ -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)
})
117 changes: 117 additions & 0 deletions .github/scripts/comment-guard.mjs
Original file line number Diff line number Diff line change
@@ -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 <fixture.json> [--json]')
console.error(' node .github/scripts/comment-guard.mjs --replay-guard <fixture.json> [--json]')
console.error(' node .github/scripts/comment-guard.mjs --comments <comments.json> --event <key> [--draft <body.txt>] [--object <n>] [--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)
}
}
122 changes: 122 additions & 0 deletions .github/scripts/comment-guard.test.mjs
Original file line number Diff line number Diff line change
@@ -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 <!-- flybot:a --> 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/)
})
Loading
Loading