Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
45 changes: 45 additions & 0 deletions plugins/bstack/scripts/cap-ok.mjs
Original file line number Diff line number Diff line change
@@ -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 <pr> -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 <pr> -R owner/repo [--follow-up <finding id>=<issue> ...]';
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);
}
}
17 changes: 11 additions & 6 deletions plugins/bstack/scripts/guard.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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';
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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');
Expand Down Expand Up @@ -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 <n> --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.';
Expand Down
6 changes: 6 additions & 0 deletions plugins/bstack/scripts/lane.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
80 changes: 80 additions & 0 deletions plugins/bstack/scripts/lib/cap-ok.mjs
Original file line number Diff line number Diff line change
@@ -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 <finding id>=<issue number>, 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 <id>=<issue>)'}`).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,
};
}
Loading
Loading