From 9f78995f17d77ece433d4fe6dff4ecd737067612 Mon Sep 17 00:00:00 2001 From: Benjamin Carrasco Date: Sat, 5 Dec 2026 19:07:44 +0100 Subject: [PATCH] feat(gate): the orchestrator's OK at the round cap The cap-ok script posts the orchestrator's OK for a PR head only when the rounds reached the cap, the checks are green, no policy file changes, a revert undoes the change and every open finding has a follow-up issue, and refuses to run in a checkout of the PR's branch. The merge gate lets that head through at the cap and posts an orchestrator-ok status; the guard refuses the line by hand or through an MCP tool. --- plugins/bstack/scripts/cap-ok.mjs | 45 +++++ plugins/bstack/scripts/guard.mjs | 17 +- plugins/bstack/scripts/lane.mjs | 6 + plugins/bstack/scripts/lib/cap-ok.mjs | 80 +++++++++ plugins/bstack/scripts/lib/merge-gate.mjs | 56 ++++-- plugins/bstack/scripts/lib/verdicts.mjs | 29 ++- plugins/bstack/scripts/risk-tier.mjs | 4 +- plugins/bstack/skills/orchestrator/SKILL.md | 14 +- tests/cap-ok.test.mjs | 188 ++++++++++++++++++++ 9 files changed, 405 insertions(+), 34 deletions(-) create mode 100644 plugins/bstack/scripts/cap-ok.mjs create mode 100644 plugins/bstack/scripts/lib/cap-ok.mjs create mode 100644 tests/cap-ok.test.mjs diff --git a/plugins/bstack/scripts/cap-ok.mjs b/plugins/bstack/scripts/cap-ok.mjs new file mode 100644 index 0000000..a586dc1 --- /dev/null +++ b/plugins/bstack/scripts/cap-ok.mjs @@ -0,0 +1,45 @@ +#!/usr/bin/env node +// The orchestrator's OK at the round cap (#327): checks the conditions for the PR's head and, when all +// hold, posts the bstack-orchestrator-ok comment the merge gate reads. Run it outside the PR's checkout. +// cap-ok.mjs -R owner/repo [--follow-up F2=341 ...] +// Exit 0: posted. Exit 1: refused, one line per failed condition. Exit 2: usage, or GitHub did not answer. +import { realDeps } from './guard.mjs'; +import { capOk } from './lib/cap-ok.mjs'; +import { isMain } from './lib/is-main.mjs'; + +const USAGE = 'usage: cap-ok.mjs -R owner/repo [--follow-up = ...]'; +const REPO = /^[\w.-]+\/[\w.-]+$/; +const COUNT = /^\d+$/; + +export function capOkArgs(args) { + const out = { followUps: [] }; + for (let i = 0; i < args.length; i++) { + const [arg, value] = [args[i], args[i + 1]]; + if (arg === '-R' && REPO.test(value ?? '') && !out.repo) { out.repo = value; i++; } + else if (arg === '--follow-up' && value) { out.followUps.push(value); i++; } + else if (COUNT.test(arg) && !out.pr) out.pr = arg; + else throw new Error(USAGE); + } + if (!out.pr || !out.repo) throw new Error(USAGE); + return out; +} + +// Returns { code, out } for the CLI. +export function runCapOk(args, deps, cwd) { + const { pr, repo, followUps } = capOkArgs(args); + const checked = capOk(pr, repo, cwd, deps, followUps); + if (checked.refused) return { code: 1, out: checked.refused.map(r => `refused: ${r}`).join('\n') }; + deps.postComment(cwd, checked.pr.url, checked.body); + return { code: 0, out: `posted the orchestrator's OK for ${checked.pr.headRefOid} on ${checked.pr.url}` }; +} + +if (isMain(import.meta.url)) { + try { + const { code, out } = runCapOk(process.argv.slice(2), realDeps, process.cwd()); + process.stdout.write(`${out}\n`); + process.exit(code); + } catch (e) { + process.stderr.write(`${e.message}\n`); + process.exit(2); + } +} diff --git a/plugins/bstack/scripts/guard.mjs b/plugins/bstack/scripts/guard.mjs index d43a4b9..af4b3fa 100644 --- a/plugins/bstack/scripts/guard.mjs +++ b/plugins/bstack/scripts/guard.mjs @@ -3,7 +3,7 @@ // in prose cannot hold: pushes to the default branch, skipped hooks, force-pushes, rebasing pushed // branches, merges without green CI and a judge verdict for the head SHA (or one carried across // merge-ins of the base branch that left the PR diff unchanged), merges through side doors -// (gh api, MCP), hand-written statuses and user-OK lines, cargo builds into a shared target dir +// (gh api, MCP), hand-written statuses, user-OK and orchestrator-OK lines, cargo builds into a shared target dir // without the target lock, foreground waits on cargo builds past the cache lifetime, a second judge on a judged head, and a judge after three blocking rounds. // Exit 2 with a message that names the right alternative. A judge or worker that may start gets its // model from MODEL_TABLE. @@ -13,7 +13,7 @@ import os from 'node:os'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { ASSIGNMENT, UNRESOLVED, commandsIn, parseGit, redirectTargets } from './lib/shell.mjs'; -import { INTERROGATE_ROUNDS, blockingRounds, kindOf, latestFor, prRefs, statusArgs } from './lib/verdicts.mjs'; +import { INTERROGATE_ROUNDS, ORCHESTRATOR_OK_MARKER, blockingRounds, kindOf, latestFor, prRefs, statusArgs } from './lib/verdicts.mjs'; import { postedOn, roundBrief } from './lib/rounds.mjs'; import { PENDING_NAME, pendingStore } from './lib/pending.mjs'; import { pathsOn } from './lib/paths.mjs'; @@ -73,7 +73,7 @@ function judgedHeadRule({ subagent_type: type, prompt }, cwd, deps) { if (!headRefOid) return null; const results = judgedResults(view, repo, args => deps.gh(cwd, args)); const rounds = blockingRounds(results); - if (rounds >= INTERROGATE_ROUNDS) return `PR ${pr} in ${repo} had ${rounds} rounds with blocking findings, so ${type} is not started on it. Report to the owner what is fixed, what is open and your recommendation; the guard merges only after the owner comments this line on the PR: bstack-user-ok sha=${headRefOid}`; + if (rounds >= INTERROGATE_ROUNDS) return `PR ${pr} in ${repo} had ${rounds} rounds with blocking findings, so ${type} is not started on it. Report what is fixed, what is open and your recommendation; a lane stops with state capped and its open findings, and asks no one. The guard merges only after the orchestrator's OK, or after the owner comments this line on the PR: bstack-user-ok sha=${headRefOid}`; const own = latestFor(kind, results, headRefOid); const blocked = openBlockingOrNull({ ...view, results }, repo, cwd, deps); const label = blocked ? `${blocked.label} for ${blocked.on === headRefOid ? 'head ' : ''}${blocked.on.slice(0, 7)}, a blocking result` : own && own.result !== 'UNPROVEN' ? `${LABELS[kind](own)} for head ${headRefOid.slice(0, 7)}` : null; @@ -352,9 +352,12 @@ function foregroundWaitRule(c, { timeout, run_in_background: background } = {}) // --- saved verdicts and the user-OK line -------------------------------------------------------- const SAVED_VERDICTS = 'Saved verdicts are written only by the bstack hook when GitHub does not answer; the guard posts them at the next merge. Run the bstack:judge agent instead.'; -const USER_OK_MARKER = /bstack-user-ok/i; const POSTS_TEXT = /^(pr (comment|review)|issue (comment|create|edit|close|reopen))$/; -const USER_OK_BY_HAND = 'Only the user writes the bstack-user-ok line on GitHub: it reopens a merge the guard stopped. Report to the user and ask them to comment it.'; +const ORCHESTRATOR_OK_BY_HAND = "Only the orchestrator's cap-ok script writes the bstack-orchestrator-ok line, outside the PR's checkout, after it checked the conditions. A lane at the cap stops with state capped and its open findings."; +const OK_LINES = [ + [/bstack-user-ok/i, 'Only the user writes the bstack-user-ok line on GitHub: it reopens a merge the guard stopped. Report to the user and ask them to comment it.'], + [ORCHESTRATOR_OK_MARKER, ORCHESTRATOR_OK_BY_HAND], +]; function pendingRule(c) { if (READ_ONLY.has(c.cmd)) return null; @@ -373,7 +376,8 @@ function userOkRule(c, deps, line) { const target = resolvedDir(word, c.cwdKnown ? c.cwd : UNKNOWN_DIR, dialect, deps.host.paths); return target === UNKNOWN_DIR ? null : deps.readFile(target); }); - return [line, c.args.join(' '), ...bodies].some(text => USER_OK_MARKER.test(text ?? '')) ? USER_OK_BY_HAND : null; + const texts = [line, c.args.join(' '), ...bodies]; + return OK_LINES.find(([marker]) => texts.some(text => marker.test(text ?? '')))?.[1] ?? null; } const PENDING_PATH = new RegExp(String.raw`(^|[\\/>=])${PENDING_NAME.source}([\\/]|$)`, 'i'); @@ -608,6 +612,7 @@ export { ciState }; // --- MCP and file writes ---------------------------------------------------------------------------- function mcpRule(tool, input) { if (WRITES_STATUS_OR_CHECK.test(tool) || GITHUB_STATUS_WRITE(tool)) return GREEN_BY_HAND; + if (ORCHESTRATOR_OK_MARKER.test(JSON.stringify(input))) return ORCHESTRATOR_OK_BY_HAND; if (/merge/i.test(tool) && /(pull|_pr|pr_)/i.test(tool)) return 'Merging through an MCP tool skips the bstack gate. Use gh pr merge --squash --delete-branch.'; if (/(push_files|create_or_update_file|delete_file|update_ref|create_commit)/i.test(tool) && DEFAULT_BRANCH.test(String(input.branch ?? input.ref ?? 'main').replace(/^refs\/heads\//, ''))) { return 'Writing to the default branch through an MCP tool is blocked. Commit on a branch and open a PR.'; diff --git a/plugins/bstack/scripts/lane.mjs b/plugins/bstack/scripts/lane.mjs index f9274d9..09da516 100644 --- a/plugins/bstack/scripts/lane.mjs +++ b/plugins/bstack/scripts/lane.mjs @@ -64,9 +64,15 @@ function lastObject(text) { throw new Error('no JSON object in the lane message'); } +// A capped lane hands over what the orchestrator decides on: the PR, its head and its open findings. +const STATE_NEEDS = { + capped: v => [...(v.pr === null ? ['the pr'] : []), ...(v.head === null ? ['the head'] : []), ...(v.open_findings.length ? [] : ['its open findings'])], +}; + export function result(text) { const value = lastObject(text); const errors = check(value); + if (!errors.length) errors.push(...(STATE_NEEDS[value.state]?.(value) ?? []).map(what => `result: state ${value.state} needs ${what}`)); if (errors.length) throw new Error(errors.join('\n')); return JSON.stringify(value); } diff --git a/plugins/bstack/scripts/lib/cap-ok.mjs b/plugins/bstack/scripts/lib/cap-ok.mjs new file mode 100644 index 0000000..75a80df --- /dev/null +++ b/plugins/bstack/scripts/lib/cap-ok.mjs @@ -0,0 +1,80 @@ +// The orchestrator's OK at the round cap (#327). It is written only when every condition holds; each +// refusal names the condition that failed and what was found. +import { INTERROGATE_ROUNDS, blockingRounds, orchestratorOkBody } from './verdicts.mjs'; +import { CAP_RISK_CONDITIONS, ciState, failedConditions, judgedResults, prRisk } from './merge-gate.mjs'; +import { postedOn } from './rounds.mjs'; +import { firstLine } from './pending.mjs'; + +const FOLLOW_UP = /^(F\d+)=#?(\d+)$/; + +export function parseFollowUps(values) { + const map = new Map(); + for (const v of values) { + const m = FOLLOW_UP.exec(v); + if (!m) throw new Error(`--follow-up takes =, like F2=341, not ${JSON.stringify(v)}`); + map.set(m[1], Number(m[2])); + } + return map; +} + +const CONDITIONS = [ + { name: 'the PR is open', fails: f => f.pr.state !== 'OPEN' && `it is ${f.pr.state}` }, + { name: `the rounds reached the cap of ${INTERROGATE_ROUNDS}`, fails: f => f.rounds < INTERROGATE_ROUNDS && `${f.rounds} round(s) had blocking findings` }, + { name: 'the checks are green on the head', fails: f => !f.ci.ok && f.ci.detail }, + ...CAP_RISK_CONDITIONS.map(c => ({ name: c.name, fails: f => c.fails(f.assessed) })), + { name: 'the judge findings can be read', fails: f => f.findings.unreadable && 'a judge report on an earlier head is not a judge report for its head' }, + { + name: 'every open blocking finding has a follow-up issue', + fails: f => { + const missing = f.findings.open.filter(o => !f.followUps.get(o.id)?.ok); + return missing.length > 0 && missing.map(o => `${o.id} ${f.followUps.get(o.id)?.why ?? 'has none (--follow-up =)'}`).join('; '); + }, + }, + { name: "the script is not running in a checkout of the PR's branch", fails: f => f.checkout }, +]; + +// An open issue in the PR's repo whose body names the PR and the finding. +function followUp(id, number, pr, repo, gh) { + let issue; + try { issue = JSON.parse(gh(['issue', 'view', String(number), '-R', repo, '--json', 'number,state,body'])); } + catch (e) { return { why: `names #${number}, which could not be read (${firstLine(e)})` }; } + const body = String(issue.body ?? ''); + if (issue.state !== 'OPEN') return { why: `names #${number}, which is ${issue.state}` }; + if (!body.includes(pr.url) || !new RegExp(`\\b${id}\\b`).test(body)) return { why: `names #${number}, whose body does not name ${pr.url} and ${id}` }; + return { ok: true, number }; +} + +// Where the script runs: a reason when it is a checkout of the PR's branch or head, else null. +function checkoutOf(pr, cwd, git) { + const read = args => { try { return git(cwd, args).trim(); } catch { return null; } }; + const branch = read(['rev-parse', '--abbrev-ref', 'HEAD']); + const head = read(['rev-parse', 'HEAD']); + if (branch && branch === pr.headRefName) return `${cwd} has ${branch} checked out`; + if (head && head === pr.headRefOid) return `${cwd} is at the PR head ${head.slice(0, 7)}`; + return null; +} + +// { refused: [condition: found] } or { body } with the comment to post. Throws when GitHub does not answer. +export function capOk(selector, repo, cwd, deps, followUpArgs = []) { + const gh = args => deps.gh(cwd, args); + const pr = JSON.parse(gh(['pr', 'view', String(selector), '-R', repo, '--json', 'number,url,state,headRefOid,headRefName,baseRefName,statusCheckRollup'])); + const assessed = prRisk(pr, repo, cwd, deps); + if (assessed.refused) throw new Error(assessed.refused); + const results = judgedResults(pr, assessed.prRepo, gh); + const findings = postedOn(pr, assessed.prRepo, gh, null); + const followUps = new Map([...parseFollowUps(followUpArgs)].map(([id, n]) => [id, followUp(id, n, pr, assessed.prRepo, gh)])); + const facts = { pr, assessed, findings, followUps, rounds: blockingRounds(results), ci: ciState(pr.statusCheckRollup), checkout: checkoutOf(pr, cwd, deps.git) }; + const refused = failedConditions(CONDITIONS, facts); + if (refused.length) return { refused }; + const filed = findings.open.map(o => `${o.id} #${followUps.get(o.id).number}`); + return { + body: orchestratorOkBody(pr.headRefOid, [ + `The orchestrator's OK at the round cap for head ${pr.headRefOid}, checked by the cap-ok script:`, + `- ${facts.rounds} rounds had blocking findings.`, + `- The checks are green on ${pr.headRefOid.slice(0, 7)}.`, + `- Risk tier ${assessed.risk.tier}, exposure ${assessed.exposure}; no policy file changes.`, + `- Follow-up issues for the open findings: ${filed.length ? filed.join(', ') : 'none open'}.`, + ]), + pr, + }; +} diff --git a/plugins/bstack/scripts/lib/merge-gate.mjs b/plugins/bstack/scripts/lib/merge-gate.mjs index eacdfbd..d8ac2a0 100644 --- a/plugins/bstack/scripts/lib/merge-gate.mjs +++ b/plugins/bstack/scripts/lib/merge-gate.mjs @@ -4,13 +4,13 @@ import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { ASSIGNMENT, words } from './shell.mjs'; -import { INTERROGATE_ROUNDS, KINDS, STATUS_CONTEXTS, blockingRounds, docsOnlyStatusArgs, latestFor, ownerOkStatusArgs, recordsOf, shaOf, statusRecords, timeOf, unprovenText, userOkFor } from './verdicts.mjs'; +import { INTERROGATE_ROUNDS, KINDS, STATUS_CONTEXTS, blockingRounds, docsOnlyStatusArgs, latestFor, okStatusArgs, orchestratorOkFor, recordsOf, shaOf, statusRecords, timeOf, unprovenText, userOkFor } from './verdicts.mjs'; import { firstLine, repoOfUrl, transient } from './pending.mjs'; import { mergeInChain, prCommits, prMergeInChain, sameChange } from './carry.mjs'; import { policyLines, readBasePolicy } from './base-policy.mjs'; import { BASELINE } from '../comments.mjs'; import { CHECKS_CONTEXT } from './checks-context.mjs'; -import { EXPOSURE, RISK_PATHS, exposureOf, gatePlan, ghFileReader, parseDiff, riskTier, tierZeroDocs } from '../risk-tier.mjs'; +import { EXPOSURE, INTERNAL_TIER_2, RISK_PATHS, exposureOf, gatePlan, ghFileReader, parseDiff, riskTier, tierZeroDocs } from '../risk-tier.mjs'; import { rowFor } from './models.mjs'; const CHECKS_SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), '..', 'checks.mjs').replace(/\\/g, '/'); @@ -113,8 +113,14 @@ export function mergeGate(args, cwd, deps, c, line) { if (masked) return masked; const judged = carrier(pr, risk, { cwd, deps, repo: prRepo, extraPaths, exposure }); const verdict = judged('verdict'); - const allow = results => postCarried(pr, risk, results, cwd, deps) ?? postOwnerOk(pr, verdict, cwd, deps); - const atCap = () => (userOkFor(pr.comments, sha) ? allow(verdict.result ? [verdict] : []) : `${rounds} rounds found blocking findings: stop and report to the user what is fixed, what is open and your recommendation. The guard merges ${short} only after the user comments this line on the PR: bstack-user-ok sha=${sha}`); + const allow = (results, by = userOkFor(pr.comments, sha) ? 'owner' : null) => postCarried(pr, risk, results, cwd, deps) ?? postOk(pr, verdict, by, cwd, deps); + const atCap = () => { + const by = userOkFor(pr.comments, sha) ? 'owner' : orchestratorOkFor(pr.comments, sha) ? 'orchestrator' : null; + const refused = by === 'orchestrator' ? failedConditions(CAP_RISK_CONDITIONS, assessed) : []; + if (by && !refused.length) return allow(verdict.result ? [verdict] : [], by); + const notHeld = refused.length ? ` The orchestrator's OK on ${short} does not hold: ${refused.join('; ')}.` : ''; + return `${rounds} rounds found blocking findings: stop and report to the user what is fixed, what is open and your recommendation; a lane stops with state capped and its open findings, and asks no one.${notHeld} The guard merges ${short} only after the orchestrator's OK, or after the user comments this line on the PR: bstack-user-ok sha=${sha}`; + }; if (capped && !verdict.result) return atCap(); if (!verdict.result) return `Tier ${risk.tier}${why}: no verdict for head ${short}.${verdict.note ?? ''} Run the bstack:judge agent on ${pr.url}; its hook posts the verdict.`; if (verdict.result.result === 'FAIL' && !(capped && verdict.result.by === 'judge')) return `The latest verdict for ${verdict.from.slice(0, 7)} is FAIL. Fix it, push, and run bstack:judge again.`; @@ -156,9 +162,29 @@ export function prRisk(pr, repo, cwd, deps) { catch (e) { return { refused: unreadable(EXPOSURE, e) }; } if (exposure === 'internal') risk = riskTier(diff, { extraPaths, readFile, exposure }); } - return { diff, prRepo, readPolicy, unreadable, extraPaths, exposure, risk, plan: gatePlan(diff, risk.tier, { extraPaths }) }; + return { diff, prRepo, readPolicy, unreadable, extraPaths, exposure, risk, readFile, plan: gatePlan(diff, risk.tier, { extraPaths }) }; } +// The conditions of the orchestrator's OK at the cap that the PR diff decides (#327), each failing +// with what it found; the gate checks them again on the head the OK names. +export const CAP_RISK_CONDITIONS = [ + { name: 'the PR changes no policy file', fails: a => a.plan.policyChange && `it changes ${RISK_PATHS} or ${EXPOSURE}` }, + { + name: 'the tier is below 2, or the repo is internal and the diff changes no schema and deletes no data', + fails: a => { + if (a.risk.tier < 2) return null; + if (a.exposure !== 'internal') return `tier 2 in a repo whose exposure is ${a.exposure} (${a.risk.reasons.slice(0, 3).join('; ')})`; + const own = riskTier(a.diff, { readFile: a.readFile, exposure: 'internal' }); + return own.tier >= 2 && own.reasons.filter(r => INTERNAL_TIER_2.has(r.split(':')[0])).slice(0, 3).join('; '); + }, + }, +]; + +export const failedConditions = (conditions, facts) => conditions.flatMap(c => { + const found = c.fails(facts); + return found ? [`${c.name}: ${found}`] : []; +}); + const CONTEXTS = 'status{contexts{context description targetUrl createdAt}}'; const STATUSES_QUERY = `query($owner:String!,$name:String!,$number:Int!,$head:GitObjectID!,$endCursor:String){repository(owner:$owner,name:$name){object(oid:$head){...on Commit{oid ${CONTEXTS}}} pullRequest(number:$number){commits(first:100,after:$endCursor){pageInfo{hasNextPage endCursor} nodes{commit{oid ${CONTEXTS}}}}}}}`; const STATUS_LINES = '.data.repository | ([.object] + [.pullRequest.commits.nodes[].commit])[] | select(. != null) | .oid as $sha | (.status.contexts // [])[] | {sha: $sha} + . | tojson'; @@ -316,21 +342,21 @@ function postDocsOnly(pr, cwd, deps) { return null; } -// A merge the owner's OK line lets through without a judge PASS. Keeps the judge's comment as the -// target, so the rounds reader still finds its findings; written once per head. -function postOwnerOk(pr, verdict, cwd, deps) { +// A merge the owner's or the orchestrator's OK lets through without a judge PASS. Keeps the judge's +// comment as the target, so the rounds reader still finds its findings; written once per head. +function postOk(pr, verdict, by, cwd, deps) { const head = pr.headRefOid; - if (/^PASS/.test(verdict.result?.result ?? '') || !userOkFor(pr.comments, head) || pr.results.some(r => r.ownerOk === head)) return null; + if (/^PASS/.test(verdict.result?.result ?? '') || !by || pr.results.some(r => r.okOn === head)) return null; const judged = verdict.result && (latestFor('judge', pr.results, verdict.from) ?? verdict.result); const comment = judged && pr.results.find(r => r.comment && shaOf('judge', r.body) === verdict.from)?.comment; - try { deps.gh(cwd, ownerOkStatusArgs(pr.url, head, judged, judged && verdict.from !== head ? verdict.from : null, comment && `${pr.url}#issuecomment-${comment}`)); } - catch (e) { return `bstack could not post the owner-OK ${STATUS_CONTEXTS.judge} status on ${head.slice(0, 7)} (${String(e.message ?? e).split('\n')[0]}), and a repo that requires it refuses the merge without it. Retry the merge; the gate fails closed.`; } + try { deps.gh(cwd, okStatusArgs(by, pr.url, head, judged, judged && verdict.from !== head ? verdict.from : null, comment && `${pr.url}#issuecomment-${comment}`)); } + catch (e) { return `bstack could not post the ${by}-OK ${STATUS_CONTEXTS.judge} status on ${head.slice(0, 7)} (${String(e.message ?? e).split('\n')[0]}), and a repo that requires it refuses the merge without it. Retry the merge; the gate fails closed.`; } return null; } -// A carried verdict also writes bstack/judge, the context a repo requires on GitHub, unless the owner's -// OK already wrote it: the newest bstack/judge on a head the gate lets through stays a success. -const carriedStatuses = (carried, ownerOk) => carried.flatMap(r => (r.kind === 'verdict' ? [r, ...(ownerOk ? [] : [{ ...r, kind: 'judge' }])] : [r])); +// A carried verdict also writes bstack/judge, the context a repo requires on GitHub, unless an OK +// already wrote it: the newest bstack/judge on a head the gate lets through stays a success. +const carriedStatuses = (carried, okd) => carried.flatMap(r => (r.kind === 'verdict' ? [r, ...(okd ? [] : [{ ...r, kind: 'judge' }])] : [r])); function postCarried(pr, risk, results, cwd, deps) { const carried = results.filter(r => r.from !== pr.headRefOid); @@ -338,7 +364,7 @@ function postCarried(pr, risk, results, cwd, deps) { const body = carriedComment(pr, risk, carried); try { if (!(pr.comments ?? []).some(c => String(c.body ?? '').trim() === body.trim())) deps.postComment(cwd, pr.url, body); - for (const r of carriedStatuses(carried, (pr.results ?? []).some(c => c.ownerOk === pr.headRefOid))) deps.postStatus(cwd, pr.url, pr.headRefOid, r.kind, r.result, r.from); + for (const r of carriedStatuses(carried, (pr.results ?? []).some(c => c.okOn === pr.headRefOid))) deps.postStatus(cwd, pr.url, pr.headRefOid, r.kind, r.result, r.from); } catch (e) { return `bstack could not post why the result on ${carried[0].from.slice(0, 7)} holds for ${pr.headRefOid.slice(0, 7)} (${String(e.message ?? e).split('\n')[0]}). Retry the merge; the gate fails closed.`; } return null; diff --git a/plugins/bstack/scripts/lib/verdicts.mjs b/plugins/bstack/scripts/lib/verdicts.mjs index 2bd43d0..ca38f72 100644 --- a/plugins/bstack/scripts/lib/verdicts.mjs +++ b/plugins/bstack/scripts/lib/verdicts.mjs @@ -250,11 +250,11 @@ function stampOf(text, createdAt) { export const docsOnlyStatusArgs = (prUrl, sha) => statusArgs(prUrl, sha, 'judge', null, null, null, 'docs only (tier 0), no judge needed'); -// The owner's OK on a head whose judge result is not a PASS. The text keeps that result after -// `judge=`, so the gate and the rounds reader read the head as they did before. -const OWNER_OK = /^owner-ok(?: judge=)?/; -export const ownerOkStatusArgs = (prUrl, sha, latest, carriedFrom, commentUrl) => - statusArgs(prUrl, sha, 'judge', latest, carriedFrom, commentUrl, latest ? 'owner-ok judge=' : 'owner-ok'); +// The owner's or the orchestrator's OK on a head whose judge result is not a PASS. The text keeps that +// result after `judge=`, so the gate and the rounds reader read the head as they did before. +const OK_STATUS = /^(?:owner|orchestrator)-ok(?: judge=)?/; +export const okStatusArgs = (by, prUrl, sha, latest, carriedFrom, commentUrl) => + statusArgs(prUrl, sha, 'judge', latest, carriedFrom, commentUrl, latest ? `${by}-ok judge=` : `${by}-ok`); // A judge result is also the verdict of its head, and the interrogate result when it judged a tier 2 // change and is not UNPROVEN. @@ -275,11 +275,11 @@ export const statusRecords = (statuses, prUrl) => (statuses ?? []).flatMap(({ sh const { text, at: createdAt } = stampOf(String(description ?? ''), postedAt); const ours = kind && (targetUrl === prUrl || commentOf(prUrl, targetUrl)) && text.endsWith(suffix) && !/[\r\n]/.test(text); if (!ours) return []; - const ownerOk = kind === 'judge' ? OWNER_OK.exec(text)?.[0] : null; - const result = text.slice(ownerOk?.length ?? 0, -suffix.length); - const body = !(ownerOk && /^PASS/.test(result)) && resultBody(kind, result, sha, '', createdAt); + const okd = kind === 'judge' ? OK_STATUS.exec(text)?.[0] : null; + const result = text.slice(okd?.length ?? 0, -suffix.length); + const body = !(okd && /^PASS/.test(result)) && resultBody(kind, result, sha, '', createdAt); const records = body && shaOf(kind, body) === sha ? recordsOf(kind, sha, body, createdAt).map((r, i) => (i ? r : { ...r, comment: commentOf(prUrl, targetUrl) })) : []; - return ownerOk ? [...records, { body: '', ownerOk: sha, createdAt }] : records; + return okd ? [...records, { body: '', okOn: sha, createdAt }] : records; }); // The records one result stands for: itself, and for a judge also its verdict and interrogate result. @@ -307,6 +307,17 @@ export const unprovenText = (missing, sha) => `the proof could not be run here: export const userOkFor = (comments, sha) => (comments ?? []).some(c => USER_OK.exec(String(c.body ?? '').trim())?.[1].toLowerCase() === sha); +// The orchestrator's OK at the round cap (#327): a comment only the cap-ok script writes, opening with +// its tag and this line, then the conditions it checked. The guard refuses the marker from agents. +export const ORCHESTRATOR_OK_TAG = ''; +export const ORCHESTRATOR_OK_MARKER = /bstack-orchestrator-ok/i; +const ORCHESTRATOR_OK = /^bstack-orchestrator-ok sha=([0-9a-f]{40})$/; +export const orchestratorOkBody = (sha, evidence) => `${ORCHESTRATOR_OK_TAG}\nbstack-orchestrator-ok sha=${sha}\n\n${evidence.join('\n')}\n`; +export const orchestratorOkFor = (comments, sha) => (comments ?? []).some(c => { + const [tag, line] = String(c.body ?? '').split(/\r?\n/); + return tag === ORCHESTRATOR_OK_TAG && ORCHESTRATOR_OK.exec(line ?? '')?.[1] === sha; +}); + // The newest result of a kind for exactly this head SHA, from `gh pr view --json comments`. export function latestFor(kind, comments, sha) { const hits = (comments ?? []) diff --git a/plugins/bstack/scripts/risk-tier.mjs b/plugins/bstack/scripts/risk-tier.mjs index a5fd57f..8120e87 100644 --- a/plugins/bstack/scripts/risk-tier.mjs +++ b/plugins/bstack/scripts/risk-tier.mjs @@ -35,7 +35,7 @@ export const RISK_PATHS = '.github/risk-paths.txt'; export const EXPOSURE = '.github/bstack-exposure.txt'; const CHECKS = '.github/bstack-checks.txt'; const POLICY_FILES = [RISK_PATHS, EXPOSURE]; -const INTERNAL_TIER_2 = new Set(['risk policy file', 'schema or migration file', 'SQL schema statement', 'SQL that deletes data', 'code that removes files', 'call that deletes']); +export const INTERNAL_TIER_2 = new Set(['risk policy file', 'schema or migration file', 'SQL schema statement', 'SQL that deletes data', 'code that removes files', 'call that deletes']); const OTHER_REASONS_SHOWN = 12; const WEAKENED = 'weakened check: '; const PATH_RULES = [ @@ -244,7 +244,7 @@ const STEPS = { 0: [], 1: JUDGED, once: [...JUDGED, 'one tier 2 judge result on a commit of this PR; a blocking finding needs a later commit and a newer verdict'], - rounds: [...JUDGED, 'tier 2 judge result for the head without blocking findings (after 3 blocking rounds: the owner OK)'], + rounds: [...JUDGED, 'tier 2 judge result for the head without blocking findings (after 3 blocking rounds: the orchestrator\'s or the owner\'s OK)'], }; // flow is null below tier 2: the judge verdict is the whole gate. diff --git a/plugins/bstack/skills/orchestrator/SKILL.md b/plugins/bstack/skills/orchestrator/SKILL.md index 992431c..a0e2abb 100644 --- a/plugins/bstack/skills/orchestrator/SKILL.md +++ b/plugins/bstack/skills/orchestrator/SKILL.md @@ -28,7 +28,7 @@ Constraints every build brief carries: - Done means the PR that says `Closes #` is squash-merged with green checks and a verdict for its head, read back as merged, the issue is closed, and the branch and worktree are removed. - Start from the default branch on origin. - No deploys. A question on the stop list of the session rules: do not ask anyone; stop and report it in `questions` with state `needs_owner`. -- Three rounds with blocking findings: stop with state `capped`. +- Three rounds with blocking findings: stop with state `capped`, the PR, its head and its open findings; ask no one. - Plus whatever the owner or the spec fixed for this ticket. Then end the turn. T3 wakes the orchestrator when a lane finishes or asks; never poll (`task_status` on a running lane, sleeps, watchers). @@ -41,9 +41,19 @@ Pipe the lane's last message to `node "${CLAUDE_PLUGIN_ROOT}/scripts/lane.mjs" r - `needs_owner` or `blocked` with `questions`, or a pending question in the lane (`t3_pending_request list` on its thread): sort each question. - **Technical** (how to build, which tool, a test approach, and any reversible choice inside the ticket's scope, even one that shapes behaviour): answer it yourself, send the answer to the lane's thread with `t3_thread_send`, and record it on the ticket in one comment (`gh issue comment`: the question, the answer, why). - **The owner's**: on the stop list of the session rules, or about goal, scope, priority or a product choice no experiment can settle. Collect it; the other lanes go on. -- `capped`: report it with its open findings; what to do at the cap is the owner's until its own ticket says otherwise. +- `capped`: see [At the cap](#at-the-cap). +- A judge verdict UNPROVEN (the lane reports what proof could not run where it is): the gate stays shut. Start a fresh judge where that proof can run, as a lane on a machine that has it (`t3_environment_links`), with the goal "Run bstack:judge on PR in " and done when its verdict for the head is posted. Only when no machine has it is it the owner's: the OK line the gate names. - A lane that failed on the account limit (`Claude API rate limit reached`): start it again on another account from its pushed branch, or report it. +## At the cap + +A `capped` lane hands over its PR, head and open findings. Choose one: +- **Another approach**: the findings show the approach is wrong. Close the PR with a comment naming the open findings, and start a fresh lane on the ticket (`model.mjs lane build --failed `) with a constraint naming the approach that failed. +- **Merge with follow-up issues**: the open findings are real but smaller than what the change is worth. File one issue per open finding in the PR's repo, its body naming the PR URL and the finding id. Then, from outside the PR's checkout, run `node "${CLAUDE_PLUGIN_ROOT}/scripts/cap-ok.mjs" -R --follow-up = ...`. It posts the orchestrator's OK for the head only when the rounds reached the cap, the checks are green, the PR changes no policy file, a revert undoes it (tier below 2, or an internal repo and no schema change or deletion of data), and every open finding has its issue; otherwise it prints each condition that failed. Then send the lane: merge and clean up. +- **Close the PR**: the change is not worth having. + +Never merge over an open finding about data loss, security or access: that goes to the owner, as does a refused OK that another approach cannot fix. A ticket whose acceptance criterion still fails stays open: before the merge, the lane replaces `Closes #` in the PR body with `Part of #`, and the ticket gets a comment naming the follow-up issues. + Before ending a turn with owner questions, ask them all at once, each with your recommended answer. Send the answers to the lanes that asked, and record each on its ticket. ## To the owner diff --git a/tests/cap-ok.test.mjs b/tests/cap-ok.test.mjs new file mode 100644 index 0000000..2d761e8 --- /dev/null +++ b/tests/cap-ok.test.mjs @@ -0,0 +1,188 @@ +// #327: the orchestrator's OK at the round cap. The cap-ok script writes it only when every condition +// holds and names each that fails; the merge gate lets that head through on it at the cap; the guard +// refuses the line from an agent by hand or through an MCP tool. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import { decide } from '../plugins/bstack/scripts/guard.mjs'; +import { runCapOk } from '../plugins/bstack/scripts/cap-ok.mjs'; +import { result as laneResult } from '../plugins/bstack/scripts/lane.mjs'; +import { commentBody, latestFor, orchestratorOkBody, statusRecords } from '../plugins/bstack/scripts/lib/verdicts.mjs'; +import { isStatusRead, resultStatuses } from './github-statuses.mjs'; + +const SHA = 'a'.repeat(40); +const PR5 = 'https://github.com/o/r/pull/5'; +const BRANCH = 'fix/cart'; +const GREEN = [{ __typename: 'CheckRun', name: 'check', status: 'COMPLETED', conclusion: 'SUCCESS' }]; +const RED = [{ __typename: 'CheckRun', name: 'check', status: 'COMPLETED', conclusion: 'FAILURE' }]; +const NOT_FOUND = () => new Error('gh: Not Found (HTTP 404)'); +const fileDiff = (file, line) => `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n+${line}\n`; +const CODE_DIFF = fileDiff('app/main.py', 'x = 1'); +const DELETES_DIFF = fileDiff('app/main.py', 'db.execute("DELETE FROM carts")'); +const POLICY_DIFF = fileDiff('.github/risk-paths.txt', 'app/**'); +const block = value => `\`\`\`json bstack-findings\n${JSON.stringify(value)}\n\`\`\``; + +const F1 = { id: 'F1', title: 'Empty cart crashes checkout', reproduction: 'node --test tests/cart.test.mjs', base: 'pass', head: 'fail', blocks: 'regression' }; +const F2 = { id: 'F2', title: 'Export has no header row', reproduction: 'curl localhost/export', base: 'not run', head: 'fail', blocks: 'criterion', criterion: '"The export starts with a header row"' }; +const judged = (id, sha, at, findings, result = 'FAIL') => ({ id, createdAt: at, body: commentBody('judge', { result, tier: 1, ...(result === 'FAIL' ? { blocking: findings.length } : {}) }, sha, `Report.\n\n${block(findings)}`) }); +const ROUND1 = judged(71, '1'.repeat(40), '2026-12-01T10:00:00Z', [F1]); +const ROUND2 = judged(72, '2'.repeat(40), '2026-12-02T10:00:00Z', [F1]); +const ROUND3 = judged(77, SHA, '2026-12-03T10:00:00Z', [F1, F2]); +const CAPPED = [ROUND1, ROUND2, ROUND3]; +const issue = (number, body, state = 'OPEN') => ({ number, state, body }); +const FILED = { 12: issue(12, `Follow-up of ${PR5} F1: empty cart.`), 13: issue(13, `Follow-up of ${PR5} F2.`) }; +const FOLLOW_UPS = ['--follow-up', 'F1=12', '--follow-up', 'F2=#13']; +const okComment = (sha = SHA) => ({ body: orchestratorOkBody(sha, ['checked']), createdAt: '2026-12-04T10:00:00Z' }); + +function github({ judgements = CAPPED, comments = [], rollup = GREEN, diff = CODE_DIFF, exposure = null, riskPaths = null, issues = FILED, state = 'OPEN', checkout = { branch: 'main', head: 'f'.repeat(40) } } = {}) { + const posted = []; + const statuses = []; + const policy = { 'risk-paths.txt': riskPaths, 'bstack-exposure.txt': exposure }; + const gh = (_cwd, args) => { + const end = String(args.at(-1)); + if (args[0] === 'pr' && args[1] === 'view') return JSON.stringify({ number: 5, url: PR5, state, headRefOid: SHA, headRefName: BRANCH, baseRefName: 'main', statusCheckRollup: rollup, comments: [...judgements, ...comments] }); + if (isStatusRead(args)) return resultStatuses(judgements, PR5); + if (args[0] === 'pr' && args[1] === 'diff') return diff; + if (args[0] === 'issue' && args[1] === 'view') return issues[args[2]] ? JSON.stringify(issues[args[2]]) : (() => { throw NOT_FOUND(); })(); + if (args[0] === 'api' && /\/issues\/comments\/\d+$/.test(args[1])) return judgements.find(c => args[1].endsWith(`/${c.id}`))?.body ?? ''; + const contents = /\/contents\/\.github\/([\w.-]+)\?ref=main$/.exec(end); + if (contents) { if (policy[contents[1]] == null) throw NOT_FOUND(); return policy[contents[1]]; } + if (/^repos\/o\/r$/.test(end)) return 'o/r'; + if (args[0] === 'api' && args[1] === `repos/o/r/statuses/${SHA}`) { statuses.push(args.find(a => a.startsWith('description=')).slice(12), args.find(a => a.startsWith('target_url=')).slice(11)); return '{}'; } + throw NOT_FOUND(); + }; + const git = (_cwd, args) => { + if (!checkout) throw new Error('not a git repository'); + return args.includes('--abbrev-ref') ? `${checkout.branch}\n` : `${checkout.head}\n`; + }; + return { + gh, git, posted, statuses, + readFile: () => null, + pending: { list: () => [], remove: () => {} }, + postComment: (_cwd, url, body) => posted.push({ url, body }), + postStatus: () => {}, + }; +} + +const capOk = (opts, args = FOLLOW_UPS) => { + const deps = github(opts); + return { ...runCapOk(['5', '-R', 'o/r', ...args], deps, '/orchestrator'), deps }; +}; +const refusals = (opts, args) => capOk(opts, args).out.split('\n').filter(l => l.startsWith('refused: ')); + +test('cap-ok posts the OK for the head when every condition holds', () => { + const { code, out, deps } = capOk({}); + assert.equal(code, 0, out); + assert.equal(deps.posted.length, 1); + assert.equal(deps.posted[0].url, PR5); + const [tag, line] = deps.posted[0].body.split('\n'); + assert.equal(tag, ''); + assert.equal(line, `bstack-orchestrator-ok sha=${SHA}`); + assert.match(deps.posted[0].body, /F1 #12, F2 #13/); + assert.equal(capOk({ checkout: null }).code, 0, 'a folder outside any git checkout is not the PR checkout'); +}); + +test('cap-ok refuses, naming each condition that failed, and posts nothing', () => { + const cases = [ + [{ state: 'MERGED' }, FOLLOW_UPS, /the PR is open: it is MERGED/], + [{ judgements: [ROUND2, ROUND3] }, FOLLOW_UPS, /the rounds reached the cap of 3: 2 round\(s\) had blocking findings/], + [{ rollup: RED }, FOLLOW_UPS, /the checks are green on the head: failed: check/], + [{ diff: POLICY_DIFF }, FOLLOW_UPS, /the PR changes no policy file: it changes \.github\/risk-paths\.txt/], + [{ diff: DELETES_DIFF }, FOLLOW_UPS, /the tier is below 2, or the repo is internal and the diff changes no schema and deletes no data: tier 2 in a repo whose exposure is external/], + [{ diff: DELETES_DIFF, exposure: 'internal\n' }, FOLLOW_UPS, /deletes no data: SQL that deletes data: app\/main\.py/], + [{ riskPaths: 'app/**\n' }, FOLLOW_UPS, /tier 2 in a repo whose exposure is external \(listed in \.github\/risk-paths\.txt/], + [{}, ['--follow-up', 'F1=12'], /every open blocking finding has a follow-up issue: F2 has none/], + [{ issues: { ...FILED, 13: issue(13, `Follow-up of ${PR5} F2.`, 'CLOSED') } }, FOLLOW_UPS, /F2 names #13, which is CLOSED/], + [{ issues: { ...FILED, 13: issue(13, 'Export header row.') } }, FOLLOW_UPS, /F2 names #13, whose body does not name https:\/\/github\.com\/o\/r\/pull\/5 and F2/], + [{ issues: { 12: FILED[12] } }, FOLLOW_UPS, /F2 names #13, which could not be read/], + [{ checkout: { branch: BRANCH, head: SHA } }, FOLLOW_UPS, /the script is not running in a checkout of the PR's branch: \/orchestrator has fix\/cart checked out/], + [{ checkout: { branch: 'HEAD', head: SHA } }, FOLLOW_UPS, /not running in a checkout of the PR's branch: \/orchestrator is at the PR head aaaaaaa/], + ]; + for (const [opts, args, reason] of cases) { + const { code, out, deps } = capOk(opts, args); + assert.equal(code, 1, `${reason}: ${out}`); + assert.match(out, reason); + assert.deepEqual(deps.posted, [], `${reason} posts nothing`); + } + assert.equal(refusals({ rollup: RED, diff: POLICY_DIFF, checkout: { branch: BRANCH, head: SHA } }, []).length, 5, 'one line per failed condition'); +}); + +test('cap-ok allows tier 2 in an internal repo when only listed paths raise it', () => { + assert.equal(capOk({ riskPaths: 'app/**\n', exposure: 'internal\n' }).code, 0); + assert.equal(capOk({ diff: fileDiff('app/session.py', 'x = 1'), exposure: 'internal\n' }).code, 0, 'auth code is tier 1 in an internal repo'); +}); + +test('cap-ok refuses a follow-up argument it cannot read', () => { + assert.throws(() => capOk({}, ['--follow-up', '12']), /--follow-up takes =/); + assert.throws(() => runCapOk(['5'], github(), '/x'), /usage: cap-ok\.mjs/); +}); + +const merge = opts => { + const deps = github(opts); + return { reason: decide({ tool_name: 'Bash', tool_input: { command: 'gh pr merge 5 -R o/r --squash' }, cwd: '/repo' }, deps), deps }; +}; + +test("the gate lets the head through on the orchestrator's OK at the cap and posts a status naming it and the judge's comment", () => { + const { reason, deps } = merge({ comments: [okComment()] }); + assert.equal(reason, null); + assert.deepEqual(deps.statuses, ['orchestrator-ok judge=FAIL tier=1 blocking=2 pr=5', `${PR5}#issuecomment-77`]); + const view = statusRecords([{ sha: SHA, context: 'bstack/judge', description: deps.statuses[0], targetUrl: deps.statuses[1], createdAt: '2026-12-04T10:00:00Z' }], PR5); + assert.deepEqual(latestFor('judge', view, SHA), { result: 'FAIL', tier: 1, blocking: 2 }, 'the status reads as the judge result it let through'); + assert.ok(view.some(r => r.okOn === SHA)); +}); + +test("every other head is gated as today: no OK, an OK for another head, a quoted line, before the cap, UNPROVEN", () => { + const capMessage = /3 rounds found blocking findings: stop and report to the user.*a lane stops with state capped and its open findings, and asks no one.*orchestrator's OK.*bstack-user-ok sha=a{40}/s; + assert.match(merge({}).reason ?? '', capMessage); + assert.match(merge({ comments: [okComment('b'.repeat(40))] }).reason ?? '', capMessage); + assert.match(merge({ comments: [{ body: `See:\nbstack-orchestrator-ok sha=${SHA}\n`, createdAt: '2026-12-04T10:00:00Z' }] }).reason ?? '', capMessage); + assert.match(merge({ comments: [{ body: `bstack-orchestrator-ok sha=${SHA}\n`, createdAt: '2026-12-04T10:00:00Z' }] }).reason ?? '', capMessage, 'the line without its tag'); + assert.match(merge({ judgements: [ROUND2, ROUND3], comments: [okComment()] }).reason ?? '', /latest verdict for aaaaaaa is FAIL/, 'before the cap the OK counts for nothing'); + const unproven = { id: 78, createdAt: '2026-12-03T12:00:00Z', body: commentBody('judge', { result: 'UNPROVEN', tier: 1, missing: 'a phone' }, SHA, `No device.\n\n${block({ findings: [], missing: 'a phone' })}`) }; + assert.match(merge({ judgements: [ROUND1, ROUND2, judged(77, '3'.repeat(40), '2026-12-03T10:00:00Z', [F1]), unproven], comments: [okComment()] }).reason ?? '', /is UNPROVEN.*Owner:/s); + assert.match(merge({ rollup: RED, comments: [okComment()] }).reason ?? '', /CI is not green/); +}); + +test("the gate checks the OK's diff conditions again, and the owner's line works as today", () => { + assert.match(merge({ diff: POLICY_DIFF, comments: [okComment()] }).reason ?? '', /The orchestrator's OK on aaaaaaa does not hold: the PR changes no policy file/); + assert.match(merge({ diff: DELETES_DIFF, exposure: 'internal\n', comments: [okComment()] }).reason ?? '', /does not hold: .*SQL that deletes data/); + assert.match(merge({ riskPaths: 'app/**\n', comments: [okComment()] }).reason ?? '', /does not hold: .*exposure is external/); + assert.equal(merge({ riskPaths: 'app/**\n', exposure: 'internal\n', comments: [okComment()] }).reason, null); + const owner = merge({ diff: POLICY_DIFF, comments: [{ body: `bstack-user-ok sha=${SHA}\n`, createdAt: '2026-12-04T10:00:00Z' }] }); + assert.equal(owner.reason, null); + assert.equal(owner.deps.statuses[0], 'owner-ok judge=FAIL tier=1 blocking=2 pr=5'); +}); + +const shell = command => ({ tool_name: 'Bash', tool_input: { command }, cwd: '/repo' }); +const BY_HAND = /Only the orchestrator's cap-ok script writes the bstack-orchestrator-ok line/; + +test('the guard refuses the orchestrator OK line written by hand or through an MCP tool', () => { + const deps = { ...github(), readFile: f => (f.replace(/\\/g, '/').endsWith('/repo/ok.md') ? `\nbstack-orchestrator-ok sha=${SHA}\n` : null) }; + for (const line of [ + `gh pr comment 5 --body "bstack-orchestrator-ok sha=${SHA}"`, + 'gh pr comment 5 --body-file ok.md', + `gh api repos/o/r/issues/5/comments -f body="bstack-orchestrator-ok sha=${SHA}"`, + `echo "bstack-orchestrator-ok sha=${SHA}" | gh pr comment 5 -F -`, + ]) assert.match(decide(shell(line), deps) ?? '', BY_HAND, line); + for (const [tool, input] of [ + ['mcp__t3-code__pull_request_respond', { pr: 5, body: `\nbstack-orchestrator-ok sha=${SHA}` }], + ['mcp__github__add_issue_comment', { owner: 'o', repo: 'r', issue_number: 5, body: `bstack-orchestrator-ok sha=${SHA}` }], + ]) assert.match(decide({ tool_name: tool, tool_input: input, cwd: '/repo' }, deps) ?? '', BY_HAND, tool); + assert.equal(decide(shell('node plugins/bstack/scripts/cap-ok.mjs 5 -R o/r --follow-up F1=12'), deps), null, 'the script itself runs'); + assert.equal(decide({ tool_name: 'mcp__github__add_issue_comment', tool_input: { body: 'Follow-up of PR 5 F1' }, cwd: '/repo' }, deps), null); +}); + +test('a capped lane result carries its PR, head and open findings', () => { + const capped = { ticket: 7, pr: 5, state: 'capped', head: SHA, open_findings: [{ id: 'F1', title: 'Empty cart' }], questions: [], decisions: [] }; + assert.equal(laneResult(JSON.stringify(capped)), JSON.stringify(capped)); + assert.throws(() => laneResult(JSON.stringify({ ...capped, open_findings: [] })), /state capped needs its open findings/); + assert.throws(() => laneResult(JSON.stringify({ ...capped, pr: null, head: null })), /state capped needs the pr\nresult: state capped needs the head/); + assert.equal(laneResult(JSON.stringify({ ...capped, state: 'merged', open_findings: [] })).length > 0, true); +}); + +test('the orchestrator skill names the three choices at the cap and when the owner decides', () => { + const skill = fs.readFileSync(new URL('../plugins/bstack/skills/orchestrator/SKILL.md', import.meta.url), 'utf8'); + for (const words of [/\*\*Another approach\*\*/, /\*\*Merge with follow-up issues\*\*/, /\*\*Close the PR\*\*/, /cap-ok\.mjs/, /Never merge over an open finding about data loss, security or access/, /acceptance criterion still fails stays open/, /UNPROVEN.*fresh judge where that proof can run.*Only when no machine has it/s]) { + assert.match(skill, words); + } +});