diff --git a/scripts/owner-approve-queue.mjs b/scripts/owner-approve-queue.mjs index 1d43b19..a9e485c 100644 --- a/scripts/owner-approve-queue.mjs +++ b/scripts/owner-approve-queue.mjs @@ -1,6 +1,6 @@ #!/usr/bin/env node -// Interactive owner queue for PRs whose CI and AI review passed but still await -// owner-approved + auto-merge. +// Interactive owner queue for PRs whose CI and AI review passed and whose +// risk-gate failure is specifically a missing owner clearing label. // // node scripts/owner-approve-queue.mjs [--list] [--approve] [--org ] [--repo ] @@ -11,6 +11,7 @@ import readline from 'node:readline/promises'; import { fileURLToPath } from 'node:url'; const HERE = dirname(fileURLToPath(import.meta.url)); +const CLEARING_REASON_RE = /needs owner-approved|clearing_label_required|diff volume exceeded/i; function checkOutcome(item) { return String(item?.conclusion || item?.state || '').toUpperCase(); @@ -20,7 +21,7 @@ function checkName(item) { return String(item?.name || item?.context || ''); } -export function isPendingOwnerApproval(pr) { +function hasPassingNonGateChecks(pr) { if (!pr || pr.state !== 'OPEN') return false; const labels = new Set((pr.labels || []).map(l => (typeof l === 'string' ? l : l?.name))); if (labels.has('owner-approved')) return false; @@ -31,9 +32,12 @@ export function isPendingOwnerApproval(pr) { if (!aiReview || checkOutcome(aiReview) !== 'SUCCESS') return false; if (!riskGate || checkOutcome(riskGate) !== 'FAILURE') return false; + const prTemplate = checks.find(c => checkName(c) === 'pr-template'); + if (prTemplate && checkOutcome(prTemplate) !== 'SUCCESS') return false; + const otherChecks = checks.filter(c => { const name = checkName(c); - return name && name !== 'risk-gate' && name !== 'ai-review'; + return name && name !== 'risk-gate' && name !== 'ai-review' && name !== 'pr-template'; }); return otherChecks.every(c => { const out = checkOutcome(c); @@ -41,6 +45,12 @@ export function isPendingOwnerApproval(pr) { }); } +export function isPendingOwnerApproval(pr) { + if (!hasPassingNonGateChecks(pr)) return false; + const riskGate = pr.statusCheckRollup.find(c => checkName(c) === 'risk-gate'); + return CLEARING_REASON_RE.test(String(riskGate?.description || '')); +} + export function filterPendingOwnerPrs(prs) { return (Array.isArray(prs) ? prs : []) .filter(isPendingOwnerApproval) @@ -52,58 +62,119 @@ export function filterPendingOwnerPrs(prs) { })); } -function parseArgs(argv) { - const args = { approve: argv.includes('--approve'), org: null, repo: null }; - const orgIdx = argv.indexOf('--org'); - if (orgIdx !== -1) args.org = argv[orgIdx + 1] || null; - const repoIdx = argv.indexOf('--repo'); - if (repoIdx !== -1) args.repo = argv[repoIdx + 1] || null; - return args; +function readFlagValue(argv, flag) { + const idx = argv.indexOf(flag); + if (idx === -1) return null; + const val = argv[idx + 1]; + if (!val || val.startsWith('-')) { + throw new Error(`Missing value for ${flag}`); + } + return val; +} + +export function parseArgs(argv) { + return { + approve: argv.includes('--approve'), + org: readFlagValue(argv, '--org'), + repo: readFlagValue(argv, '--repo'), + }; +} + +function defaultRunGh(args, opts) { + return execFileSync('gh', args, opts); } -function listOpenPrs(repo) { - const raw = execFileSync( - 'gh', - ['pr', 'list', '-R', repo, '--state', 'open', '--limit', '30', '--json', 'number,title,url,state,labels,statusCheckRollup'], +function listOpenPrs(repo, runGh) { + const raw = runGh( + ['pr', 'list', '-R', repo, '--state', 'open', '--limit', '100', '--json', 'number,title,url,state,labels,headRefOid,statusCheckRollup'], { encoding: 'utf8' }, ); return JSON.parse(raw).map(pr => ({ ...pr, repo })); } -export async function main(argv, io = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr }) { - const { approve, org, repo } = parseArgs(argv); - if (approve && (!io.stdin?.isTTY || !io.stdout?.isTTY)) { - io.stderr.write('Refusing --approve without an interactive TTY; run directly in your terminal.\n'); +function hydrateRiskGateDescription(pr, runGh, stderr) { + if (!hasPassingNonGateChecks(pr)) return pr; + const riskGate = pr.statusCheckRollup.find(c => checkName(c) === 'risk-gate'); + if (riskGate?.description || !pr.headRefOid) return pr; + + try { + const raw = runGh(['api', `repos/${pr.repo}/commits/${pr.headRefOid}/status`], { encoding: 'utf8' }); + const data = JSON.parse(raw); + const entry = Array.isArray(data?.statuses) ? data.statuses.find(s => s.context === 'risk-gate') : null; + if (!entry?.description) return pr; + return { + ...pr, + statusCheckRollup: pr.statusCheckRollup.map(c => (c === riskGate ? { ...c, description: entry.description } : c)), + }; + } catch (error) { + stderr.write(`warn: failed to read risk-gate description for ${pr.repo}#${pr.number}: ${error.message.split('\n')[0]}\n`); + return pr; + } +} + +export async function main( + argv, + deps = { stdin: process.stdin, stdout: process.stdout, stderr: process.stderr, runGh: defaultRunGh }, +) { + const stdin = deps.stdin ?? process.stdin; + const stdout = deps.stdout ?? process.stdout; + const stderr = deps.stderr ?? process.stderr; + const runGh = deps.runGh ?? defaultRunGh; + const manifestPath = deps.manifestPath ?? join(HERE, 'repos.json'); + + let parsed; + try { + parsed = parseArgs(argv); + } catch (error) { + stderr.write(`${error.message}\n`); return 2; } - const manifest = JSON.parse(readFileSync(join(HERE, 'repos.json'), 'utf8')); - const targets = repo - ? [repo] - : manifest.repositories.filter(r => !org || r.startsWith(`${org}/`)); + const { approve, org, repo } = parsed; + if (approve && (!stdin?.isTTY || !stdout?.isTTY)) { + stderr.write('Refusing --approve without an interactive TTY; run directly in your terminal.\n'); + return 2; + } + + let targets; + if (repo) { + targets = [repo]; + } else { + let manifest; + try { + manifest = JSON.parse(readFileSync(manifestPath, 'utf8')); + } catch (error) { + stderr.write(`error: failed to read ${manifestPath}: ${error.message}\n`); + return 1; + } + const repos = Array.isArray(manifest?.repositories) ? manifest.repositories : []; + const orgPrefix = org ? `${org.toLowerCase()}/` : null; + targets = repos.filter(r => !orgPrefix || r.toLowerCase().startsWith(orgPrefix)); + } const allPrs = []; for (const r of targets) { try { - allPrs.push(...listOpenPrs(r)); + allPrs.push(...listOpenPrs(r, runGh)); } catch (error) { - io.stderr.write(`warn: failed to list ${r}: ${error.message.split('\n')[0]}\n`); + stderr.write(`warn: failed to list ${r}: ${error.message.split('\n')[0]}\n`); } } - const pending = filterPendingOwnerPrs(allPrs); + const hydrated = allPrs.map(pr => hydrateRiskGateDescription(pr, runGh, stderr)); + const pending = filterPendingOwnerPrs(hydrated); if (pending.length === 0) { - io.stdout.write('No PRs awaiting owner-approved.\n'); + stdout.write('No PRs awaiting owner-approved.\n'); return 0; } pending.forEach((item, idx) => { - io.stdout.write(`${idx + 1}. ${item.repo}#${item.number} | ${item.title}\n ${item.url}\n`); + stdout.write(`${idx + 1}. ${item.repo}#${item.number} | ${item.title}\n ${item.url}\n`); }); if (!approve) return 0; - const rl = readline.createInterface({ input: io.stdin, output: io.stdout }); + const rl = readline.createInterface({ input: stdin, output: stdout }); let answer = ''; try { answer = (await rl.question(`\nApply owner-approved and enable auto-merge (squash) on ${pending.length} PR(s)? [y/N] `)).trim().toLowerCase(); @@ -111,22 +182,22 @@ export async function main(argv, io = { stdin: process.stdin, stdout: process.st rl.close(); } if (answer !== 'y' && answer !== 'yes') { - io.stdout.write('Aborted; no labels modified.\n'); + stdout.write('Aborted; no labels modified.\n'); return 0; } let failed = 0; for (const item of pending) { try { - execFileSync('gh', ['pr', 'edit', String(item.number), '-R', item.repo, '--add-label', 'owner-approved'], { stdio: 'inherit' }); + runGh(['pr', 'edit', String(item.number), '-R', item.repo, '--add-label', 'owner-approved'], { stdio: 'inherit' }); try { - execFileSync('gh', ['pr', 'merge', String(item.number), '-R', item.repo, '--auto', '--squash'], { stdio: 'inherit' }); - } catch { - io.stderr.write(`warn: labeled ${item.repo}#${item.number}, enable auto-merge manually if needed\n`); + runGh(['pr', 'merge', String(item.number), '-R', item.repo, '--auto', '--squash'], { stdio: 'inherit' }); + } catch (mergeError) { + stderr.write(`warn: labeled ${item.repo}#${item.number}, auto-merge failed (${mergeError.message.split('\n')[0]})\n`); } } catch (error) { failed += 1; - io.stderr.write(`error: failed on ${item.repo}#${item.number}: ${error.message.split('\n')[0]}\n`); + stderr.write(`error: failed on ${item.repo}#${item.number}: ${error.message.split('\n')[0]}\n`); } } return failed ? 1 : 0; diff --git a/scripts/test-owner-approve-queue.cjs b/scripts/test-owner-approve-queue.cjs index 8c74131..6a938e3 100644 --- a/scripts/test-owner-approve-queue.cjs +++ b/scripts/test-owner-approve-queue.cjs @@ -2,83 +2,270 @@ const test = require('node:test'); const assert = require('node:assert/strict'); +const { PassThrough, Readable } = require('node:stream'); const load = () => import('./owner-approve-queue.mjs'); -test('filterPendingOwnerPrs selects only PRs with green AI review/CI awaiting owner-approved', async () => { +function makeTtyIo(answerText) { + const input = Readable.from([answerText]); + input.isTTY = true; + const output = new PassThrough(); + output.isTTY = true; + let out = ''; + output.on('data', chunk => { out += chunk.toString('utf8'); }); + let err = ''; + const stderr = { write: s => { err += s; } }; + return { stdin: input, stdout: output, stderr, getOut: () => out, getErr: () => err }; +} + +test('filterPendingOwnerPrs requires risk-gate clearing-label reason and clean checks', async () => { const { filterPendingOwnerPrs } = await load(); const sample = [ { - repo: 'Pigbibi/TelegramAgentBot', - number: 263, - title: 'chore(config): update model', - url: 'https://github.com/Pigbibi/TelegramAgentBot/pull/263', + repo: 'example-org/example-bot', + number: 101, + title: 'chore(config): update setting', + url: 'https://github.com/example-org/example-bot/pull/101', state: 'OPEN', labels: [{ name: 'agent-approved' }], statusCheckRollup: [ { context: 'ai-review', state: 'SUCCESS' }, - { context: 'risk-gate', state: 'FAILURE' }, - { name: 'check (3.12)', conclusion: 'SUCCESS' }, - { name: 'Optional check', conclusion: 'SKIPPED' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: needs owner-approved or agent-approved' }, + { context: 'pr-template', state: 'SUCCESS' }, + { name: 'test (3.12)', conclusion: 'SUCCESS' }, + { name: 'optional-check', conclusion: 'SKIPPED' }, ], }, { - repo: 'QuantStrategyLab/QuantRuntimeSettings', - number: 1308, - title: 'ci still running', - url: 'https://github.com/QuantStrategyLab/QuantRuntimeSettings/pull/1308', + repo: 'example-org/example-service', + number: 102, + title: 'large diff awaiting owner', + url: 'https://github.com/example-org/example-service/pull/102', state: 'OPEN', labels: [], statusCheckRollup: [ { context: 'ai-review', state: 'SUCCESS' }, - { context: 'risk-gate', state: 'FAILURE' }, - { name: 'js', conclusion: '', status: 'IN_PROGRESS' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: diff volume exceeded; needs owner-approved or agent-approved' }, + { context: 'pr-template', state: 'SUCCESS' }, + ], + }, + { + repo: 'example-org/example-bot', + number: 103, + title: 'blocked by unresolved thread', + url: 'https://github.com/example-org/example-bot/pull/103', + state: 'OPEN', + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: unresolved review threads' }, ], }, { - repo: 'QuantStrategyLab/QuantRuntimeSettings', - number: 1306, - title: 'needs fix', - url: 'https://github.com/QuantStrategyLab/QuantRuntimeSettings/pull/1306', + repo: 'example-org/example-bot', + number: 104, + title: 'blocked by template', + url: 'https://github.com/example-org/example-bot/pull/104', state: 'OPEN', - labels: [{ name: 'agent:needs-fix' }], + labels: [], statusCheckRollup: [ - { context: 'ai-review', state: 'FAILURE' }, + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: PR template incomplete' }, + ], + }, + { + repo: 'example-org/example-bot', + number: 105, + title: 'missing risk-gate description fails closed', + url: 'https://github.com/example-org/example-bot/pull/105', + state: 'OPEN', + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, { context: 'risk-gate', state: 'FAILURE' }, ], }, { - repo: 'Pigbibi/TelegramAgentBot', - number: 264, + repo: 'other-org/sample-app', + number: 106, + title: 'ci still running', + url: 'https://github.com/other-org/sample-app/pull/106', + state: 'OPEN', + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: needs owner-approved or agent-approved' }, + { name: 'js', conclusion: '', status: 'IN_PROGRESS' }, + ], + }, + { + repo: 'example-org/example-bot', + number: 107, title: 'already approved', - url: 'https://github.com/Pigbibi/TelegramAgentBot/pull/264', + url: 'https://github.com/example-org/example-bot/pull/107', state: 'OPEN', labels: [{ name: 'owner-approved' }], statusCheckRollup: [ { context: 'ai-review', state: 'SUCCESS' }, - { context: 'risk-gate', state: 'FAILURE' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: needs owner-approved or agent-approved' }, ], }, ]; assert.deepEqual(filterPendingOwnerPrs(sample), [ { - repo: 'Pigbibi/TelegramAgentBot', - number: 263, - title: 'chore(config): update model', - url: 'https://github.com/Pigbibi/TelegramAgentBot/pull/263', + repo: 'example-org/example-bot', + number: 101, + title: 'chore(config): update setting', + url: 'https://github.com/example-org/example-bot/pull/101', + }, + { + repo: 'example-org/example-service', + number: 102, + title: 'large diff awaiting owner', + url: 'https://github.com/example-org/example-service/pull/102', }, ]); }); -test('owner-approve-queue refuses --approve without interactive TTY', async () => { +test('owner-approve-queue validates flags and refuses --approve without interactive TTY', async () => { const { main } = await load(); let err = ''; - const code = await main(['--approve'], { + const nonTtyCode = await main(['--approve'], { stdin: { isTTY: false }, stdout: { isTTY: false, write: () => {} }, stderr: { write: s => { err += s; } }, }); - assert.equal(code, 2); + assert.equal(nonTtyCode, 2); assert.match(err, /interactive TTY/i); + + let flagErr = ''; + const badFlagCode = await main(['--org', '--approve'], { + stdin: { isTTY: true }, + stdout: { isTTY: true, write: () => {} }, + stderr: { write: s => { flagErr += s; } }, + }); + assert.equal(badFlagCode, 2); + assert.match(flagErr, /Missing value for --org/); +}); + +test('owner-approve-queue --approve prompts, labels, handles merge warnings, and reports edit errors', async () => { + const { main } = await load(); + const samplePrs = [ + { + number: 201, + title: 'first candidate', + url: 'https://github.com/example-org/example-app/pull/201', + state: 'OPEN', + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE', description: 'R2: needs owner-approved or agent-approved' }, + ], + }, + ]; + + // 1. Declining confirmation triggers zero writes; --repo skips reading repos.json. + const declinedCalls = []; + const ioNo = makeTtyIo('n\n'); + const codeNo = await main(['--approve', '--repo', 'example-org/example-app'], { + ...ioNo, + manifestPath: '/nonexistent/repos.json', + runGh: args => { + declinedCalls.push(args); + return JSON.stringify(samplePrs); + }, + }); + assert.equal(codeNo, 0); + assert.equal(declinedCalls.length, 1); + assert.match(ioNo.getOut(), /Aborted/); + + // 2. Confirming runs edit + merge; merge failure logs warning with error detail and still returns 0. + const warnCalls = []; + const ioWarn = makeTtyIo('y\n'); + const codeWarn = await main(['--approve', '--repo', 'example-org/example-app'], { + ...ioWarn, + runGh: args => { + warnCalls.push(args); + if (args[1] === 'list') return JSON.stringify(samplePrs); + if (args[1] === 'merge') throw new Error('auto-merge disabled on repo'); + return ''; + }, + }); + assert.equal(codeWarn, 0); + assert.deepEqual(warnCalls.slice(1), [ + ['pr', 'edit', '201', '-R', 'example-org/example-app', '--add-label', 'owner-approved'], + ['pr', 'merge', '201', '-R', 'example-org/example-app', '--auto', '--squash'], + ]); + assert.match(ioWarn.getErr(), /auto-merge failed \(auto-merge disabled on repo\)/); + + // 3. Label edit failure returns exit code 1. + const ioFail = makeTtyIo('yes\n'); + const codeFail = await main(['--approve', '--repo', 'example-org/example-app'], { + ...ioFail, + runGh: args => { + if (args[1] === 'list') return JSON.stringify(samplePrs); + throw new Error('permission denied'); + }, + }); + assert.equal(codeFail, 1); + assert.match(ioFail.getErr(), /failed on example-org\/example-app#201: permission denied/); +}); + +test('owner-approve-queue hydrates missing risk-gate description from commit status API', async () => { + const { main } = await load(); + const shaMatch = 'a'.repeat(40); + const shaThread = 'b'.repeat(40); + const prs = [ + { + number: 301, + title: 'missing description resolved to clearing label', + url: 'https://github.com/example-org/example-app/pull/301', + state: 'OPEN', + headRefOid: shaMatch, + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE' }, + ], + }, + { + number: 302, + title: 'missing description resolved to unresolved thread', + url: 'https://github.com/example-org/example-app/pull/302', + state: 'OPEN', + headRefOid: shaThread, + labels: [], + statusCheckRollup: [ + { context: 'ai-review', state: 'SUCCESS' }, + { context: 'risk-gate', state: 'FAILURE' }, + ], + }, + ]; + + let out = ''; + let err = ''; + const apiCalls = []; + const code = await main(['--list', '--repo', 'example-org/example-app'], { + stdin: { isTTY: false }, + stdout: { isTTY: false, write: s => { out += s; } }, + stderr: { write: s => { err += s; } }, + runGh: args => { + if (args[1] === 'list') return JSON.stringify(prs); + apiCalls.push(args[1]); + if (args[1].includes(shaMatch)) { + return JSON.stringify({ statuses: [{ context: 'risk-gate', description: 'R2: needs owner-approved or agent-approved' }] }); + } + return JSON.stringify({ statuses: [{ context: 'risk-gate', description: 'R2: unresolved review threads' }] }); + }, + }); + + assert.equal(code, 0); + assert.equal(err, ''); + assert.deepEqual(apiCalls, [ + `repos/example-org/example-app/commits/${shaMatch}/status`, + `repos/example-org/example-app/commits/${shaThread}/status`, + ]); + assert.match(out, /example-org\/example-app#301/); + assert.doesNotMatch(out, /#302/); });