diff --git a/README.md b/README.md index 0c749c1..7c4128c 100644 --- a/README.md +++ b/README.md @@ -52,6 +52,7 @@ idea or bug report -> bstack:triage or bstack:plan -> tickets (issues) -> ticket - **Build**: "take the next ticket" picks the first open, unblocked, unclaimed ticket (`scripts/tracker.mjs next`), builds it as one PR with `Closes #`, and the judge judges it against the ticket's acceptance criteria. - Issues are kept by the agent, never by hand. Specs are temporary: once merged, the code and tests are the truth. - `scripts/tracker.mjs labels` creates the labels a repo lacks and changes nothing else. It needs `gh` 2.94 or newer. +- `scripts/tracker.mjs board -R owner/repo [-R owner/repo ...]` rebuilds what is in flight from GitHub alone: open specs and maps with progress, claimed tickets with their PRs, open PRs with checks, latest verdict and blocking rounds, tickets waiting for a person, and `next`. It only reads, and prints no issue bodies, comments or diffs. ## What the hooks enforce diff --git a/plugins/bstack/scripts/tracker.mjs b/plugins/bstack/scripts/tracker.mjs index 61e479b..5101a94 100644 --- a/plugins/bstack/scripts/tracker.mjs +++ b/plugins/bstack/scripts/tracker.mjs @@ -1,15 +1,19 @@ #!/usr/bin/env node -// Issue tracker helper for the planning layer. Two deterministic jobs agents get wrong by eye: +// Issue tracker helper for the planning layer. Deterministic jobs agents get wrong by eye: // labels [-R owner/repo] create the bstack labels a repo lacks; never edits or deletes one // next [] [-R owner/repo] the frontier: open tickets with no open blocker and no assignee, // in the parent's sub-issue order, or the oldest ready-for-agent build // tickets with no parent (specs and maps skipped); `Proof surface:` commands not on PATH make one unprovable -// Output is JSON on stdout. Exit 1 with a message on stderr when gh fails. +// board [-R owner/repo ...] what is in flight per repo: open specs and maps, claimed tickets with their PRs, +// open PRs with their gate state, tickets waiting for a person, and next; reads only +// Output is JSON on stdout. Exit 1 with a message on stderr when gh fails; board reports a repo it cannot read and goes on. import { execFileSync } from 'node:child_process'; import { existsSync } from 'node:fs'; import path from 'node:path'; import { byCodePoint } from './transcripts.mjs'; import { isMain } from './lib/is-main.mjs'; +import { ciState, judgedResults } from './lib/merge-gate.mjs'; +import { blockingRounds, latestFor, shaOf, timeOf } from './lib/verdicts.mjs'; export const LABELS = [ ['plan:map', '5319e7', 'Map of decisions for work too big or foggy for one session'], @@ -85,36 +89,91 @@ function sort(issues, has) { return { next: out.ready[0] ?? null, ...out }; } +const row = i => ({ number: i.number, title: i.title, url: i.url }); +const hasLabel = (i, name) => names(i.labels).includes(name); +const PARENT_KINDS = { 'plan:spec': 'spec', 'plan:map': 'map' }; +const parentKind = i => names(i.labels).map(l => PARENT_KINDS[l]).find(Boolean) ?? ((i.subIssuesSummary?.total ?? 0) > 0 ? 'parent' : null); + +function checksText(rollup) { + const ci = ciState(rollup); + return ci.ok ? 'green' : ci.detail; +} + +function latestVerdict(results, head) { + const judged = results.filter(r => shaOf('verdict', r.body)).sort((a, b) => timeOf(a) - timeOf(b)).at(-1); + if (!judged) return null; + const sha = shaOf('verdict', judged.body); + return { result: latestFor('verdict', results, sha).result, sha, onHead: sha === head }; +} + +function prRow(gh, repo, pr) { + const results = judgedResults(pr, repo, gh); + return { + ...row(pr), draft: Boolean(pr.isDraft), head: pr.headRefOid, checks: checksText(pr.statusCheckRollup), + verdict: latestVerdict(results, pr.headRefOid), blockingRounds: blockingRounds(results), + closes: (pr.closingIssuesReferences ?? []).map(i => i.url), + }; +} + +function repoBoard(gh, repo) { + const issues = JSON.parse(gh(['issue', 'list', '--state', 'open', '--limit', '500', '--json', 'number,title,url,labels,assignees,subIssuesSummary', '-R', repo])); + const prs = JSON.parse(gh(['pr', 'list', '--state', 'open', '--limit', '200', '--json', 'number,title,url,isDraft,headRefOid,statusCheckRollup,closingIssuesReferences', '-R', repo])); + const prsOf = issue => prs.filter(p => (p.closingIssuesReferences ?? []).some(i => i.url === issue.url)).map(p => p.number); + const work = issues.filter(i => !parentKind(i)); + const { next } = frontier(gh, { repo }); + return { + repo, + plans: issues.filter(parentKind).map(i => ({ ...row(i), kind: parentKind(i), progress: { completed: i.subIssuesSummary?.completed ?? 0, total: i.subIssuesSummary?.total ?? 0 } })), + claimed: work.filter(i => (i.assignees ?? []).length).map(i => ({ ...row(i), prs: prsOf(i) })), + prs: prs.map(p => prRow(gh, repo, p)), + readyForHuman: work.filter(i => hasLabel(i, 'ready-for-human')).map(row), + next: next && row(next), + }; +} + +export function board(gh, repos) { + return { + repos: repos.map(repo => { + try { return repoBoard(gh, repo); } + catch (e) { return { repo, error: String(e.stderr || e.message || e).trim().split('\n')[0] }; } + }), + }; +} + export function parseArgs(argv) { const [cmd, ...rest] = argv; - let repo = null; + const repos = []; const positional = []; for (let i = 0; i < rest.length; i++) { const a = rest[i]; if (a === '-R' || a === '--repo') { - repo = rest[++i]; + const repo = rest[++i]; if (!repo || repo.startsWith('-')) throw new Error(`${a} needs owner/repo`); + repos.push(repo); } else if (a.startsWith('--repo=')) { - repo = a.slice(7); - if (!repo) throw new Error('--repo needs owner/repo'); + if (!a.slice(7)) throw new Error('--repo needs owner/repo'); + repos.push(a.slice(7)); } else if (a.startsWith('-')) throw new Error(`unknown flag ${a}`); else positional.push(a); } if (positional.length > 1) throw new Error(`one parent at most, got ${positional.join(' ')}`); - if (cmd === 'labels' && positional.length) throw new Error('labels takes no issue'); + if ((cmd === 'labels' || cmd === 'board') && positional.length) throw new Error(`${cmd} takes no issue`); + if (cmd !== 'board' && repos.length > 1) throw new Error(`${cmd} takes one repo; board takes several`); const ref = positional[0] ? String(positional[0]).replace(/^#/, '') : null; - return { cmd, repo, parent: ref }; + return { cmd, repos, parent: ref }; } const realGh = args => execFileSync('gh', args, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'], timeout: 45000, maxBuffer: 64 << 20 }); function main() { - const { cmd, repo, parent } = parseArgs(process.argv.slice(2)); + const { cmd, repos, parent } = parseArgs(process.argv.slice(2)); + const repo = repos[0] ?? null; let result; if (cmd === 'labels') result = ensureLabels(realGh, repo); else if (cmd === 'next') result = frontier(realGh, { parent, repo }); + else if (cmd === 'board') result = board(realGh, repos.length ? repos : [realGh(['repo', 'view', '--json', 'nameWithOwner', '--jq', '.nameWithOwner']).trim()]); else { - process.stderr.write('usage: tracker.mjs labels [-R owner/repo] | next [] [-R owner/repo]\n'); + process.stderr.write('usage: tracker.mjs labels [-R owner/repo] | next [] [-R owner/repo] | board [-R owner/repo ...]\n'); process.exit(1); } process.stdout.write(`${JSON.stringify(result, null, 2)}\n`); diff --git a/tests/tracker.test.mjs b/tests/tracker.test.mjs index f720055..8f0dd19 100644 --- a/tests/tracker.test.mjs +++ b/tests/tracker.test.mjs @@ -1,6 +1,6 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { ensureLabels, frontier, parseArgs, LABELS } from '../plugins/bstack/scripts/tracker.mjs'; +import { board, ensureLabels, frontier, parseArgs, LABELS } from '../plugins/bstack/scripts/tracker.mjs'; // A fake gh that answers from a table of issues and records every call. function fakeGh({ labels = [], issues = {}, parent = null } = {}) { @@ -118,11 +118,95 @@ test('an empty frontier says so instead of guessing', () => { }); test('arguments accept #n and a repo flag in either form, and refuse what they do not understand', () => { - assert.deepEqual(parseArgs(['next', '#12', '-R', 'o/r']), { cmd: 'next', repo: 'o/r', parent: '12' }); - assert.deepEqual(parseArgs(['labels', '--repo=o/r']), { cmd: 'labels', repo: 'o/r', parent: null }); + assert.deepEqual(parseArgs(['next', '#12', '-R', 'o/r']), { cmd: 'next', repos: ['o/r'], parent: '12' }); + assert.deepEqual(parseArgs(['labels', '--repo=o/r']), { cmd: 'labels', repos: ['o/r'], parent: null }); + assert.deepEqual(parseArgs(['board', '-R', 'o/a', '--repo=o/b', '-R', 'p/c']), { cmd: 'board', repos: ['o/a', 'o/b', 'p/c'], parent: null }); assert.throws(() => parseArgs(['next', '-R']), /needs owner\/repo/); assert.throws(() => parseArgs(['next', '-R', '--json']), /needs owner\/repo/); assert.throws(() => parseArgs(['next', '--all']), /unknown flag/); assert.throws(() => parseArgs(['next', '1', '2']), /one parent/); assert.throws(() => parseArgs(['labels', '12']), /takes no issue/); + assert.throws(() => parseArgs(['board', '12']), /takes no issue/); + assert.throws(() => parseArgs(['next', '-R', 'o/a', '-R', 'o/b']), /takes one repo/); +}); + +const sha = c => c.repeat(40); +const judgeStatus = (on, pr, text, createdAt) => ({ sha: on, context: 'bstack/judge', description: `${text} pr=${pr}`, targetUrl: `https://github.com/o/r/pull/${pr}`, createdAt }); + +// A fake gh for one repo per name: { issues, prs, statuses: { : [status] } }, or a string gh fails with. +function boardGh(repos) { + const calls = []; + const gh = args => { + calls.push(args); + const field = key => args.find(a => a.startsWith(`${key}=`))?.slice(key.length + 1); + const repo = args.includes('-R') ? args[args.indexOf('-R') + 1] : `${field('owner')}/${field('name')}`; + const data = repos[repo]; + if (typeof data === 'string') throw Object.assign(new Error('gh failed'), { stderr: data }); + const [group, action] = args; + if (group === 'issue' && action === 'list' && args.includes('--label')) return JSON.stringify(data.issues.filter(i => i.labels.some(l => l.name === 'ready-for-agent'))); + if (group === 'issue' && action === 'list') return JSON.stringify(data.issues); + if (group === 'pr' && action === 'list') return JSON.stringify(data.prs); + if (group === 'api' && args[1] === 'graphql') { + return (data.statuses[field('number')] ?? []).map(s => JSON.stringify(s)).join('\n'); + } + throw new Error(`unexpected gh ${args.join(' ')}`); + }; + return { gh, calls }; +} + +const green = [{ __typename: 'CheckRun', name: 'test', status: 'COMPLETED', conclusion: 'SUCCESS' }]; +const repoR = { + issues: [ + { ...issue(1, { labels: ['plan:spec'], body: 'SECRET body of the spec' }), subIssuesSummary: { total: 5, completed: 2 } }, + issue(2, { labels: ['plan:research'], assignees: ['someone'] }), + issue(3, { labels: ['ready-for-agent'], assignees: ['someone'], body: 'SECRET body of a ticket' }), + issue(4, { labels: ['ready-for-human'] }), + issue(5, { labels: ['ready-for-agent'] }), + { ...issue(6, { labels: ['plan:map'] }), subIssuesSummary: { total: 0, completed: 0 } }, + ], + prs: [ + { number: 10, title: 'pr 10', url: 'https://github.com/o/r/pull/10', isDraft: false, headRefOid: sha('b'), statusCheckRollup: green, + closingIssuesReferences: [{ number: 3, url: 'https://github.com/o/r/issues/3' }] }, + { number: 11, title: 'pr 11', url: 'https://github.com/o/r/pull/11', isDraft: true, headRefOid: sha('d'), statusCheckRollup: [], closingIssuesReferences: [] }, + ], + statuses: { + 10: [judgeStatus(sha('a'), 10, 'FAIL tier=1 blocking=2', '2026-12-01T10:00:00Z'), judgeStatus(sha('b'), 10, 'PASS tier=1', '2026-12-01T12:00:00Z')], + 11: [judgeStatus(sha('c'), 11, 'FAIL tier=1 blocking=1', '2026-12-01T10:00:00Z')], + }, +}; + +test('board shows specs and maps with progress, claimed tickets with their PR, PR gate state, tickets for a person, and next', () => { + const { gh } = boardGh({ 'o/r': repoR }); + const [r] = board(gh, ['o/r']).repos; + assert.equal(r.repo, 'o/r'); + assert.deepEqual(r.plans.map(p => [p.number, p.kind, p.progress]), [[1, 'spec', { completed: 2, total: 5 }], [6, 'map', { completed: 0, total: 0 }]]); + assert.deepEqual(r.claimed.map(c => [c.number, c.prs]), [[2, []], [3, [10]]], 'a decision ticket is work, not a parent'); + assert.deepEqual(r.prs[0], { + number: 10, title: 'pr 10', url: 'https://github.com/o/r/pull/10', draft: false, head: sha('b'), checks: 'green', + verdict: { result: 'PASS', sha: sha('b'), onHead: true }, blockingRounds: 1, closes: ['https://github.com/o/r/issues/3'], + }); + assert.equal(r.prs[1].draft, true); + assert.match(r.prs[1].checks, /no checks ran/); + assert.deepEqual(r.prs[1].verdict, { result: 'FAIL', sha: sha('c'), onHead: false }, 'a verdict on an earlier commit says it is not on the head'); + assert.equal(r.prs[1].blockingRounds, 1); + assert.deepEqual(r.readyForHuman.map(i => i.number), [4]); + assert.deepEqual(r.next, { number: 5, title: 'ticket 5', url: 'https://github.com/o/r/issues/5' }); +}); + +test('board prints numbers, titles, states and links only, and writes nothing', () => { + const { gh, calls } = boardGh({ 'o/r': repoR }); + const out = JSON.stringify(board(gh, ['o/r'])); + assert.ok(!out.includes('SECRET'), 'no issue bodies'); + assert.ok(!out.includes('someone'), 'no assignee names'); + const boardReads = calls.filter(c => c[1] === 'list' && !c.includes('--label')); + assert.ok(boardReads.every(c => !/body|comments|files/.test(c[c.indexOf('--json') + 1])), 'the board asks for no bodies, comments or diffs'); + assert.ok(calls.every(c => c[1] === 'list' || c[1] === 'graphql'), 'only reads'); +}); + +test('board reports a repo it cannot read under its name and still prints the others', () => { + const { gh } = boardGh({ 'o/gone': 'GraphQL: Could not resolve to a Repository\nmore', 'o/r': repoR }); + const out = board(gh, ['o/gone', 'o/r']); + assert.deepEqual(out.repos[0], { repo: 'o/gone', error: 'GraphQL: Could not resolve to a Repository' }); + assert.equal(out.repos[1].repo, 'o/r'); + assert.equal(out.repos[1].next.number, 5); });