Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(publish): propose proven PRs and retain CI findings [B3,R3]
Corey Olson414bebc8a956
diff --git a/src/board.js b/src/board.jsindex 5a8f1c13..0f564ae1 100644--- a/src/board.js+++ b/src/board.js@@ -164,6 +164,7 @@ export { declareJob, recordJobRun } from './recurring-jobs.js';export { proposeSentinel, decideSentinel, beginSentinelRun, finishSentinelRun } from './sentinels.js';export { flakeLedger, recordFlakeObservation } from './flakes.js';export { flakeQuarantines, gateRuns, recordGateRun } from './quarantine.js';+export { recordPublishFinding } from './pr-findings.js';/** The seat readers live in seats.js; the board re-exports them so `store.*` callers keep one import. */export { agentAt, agentById, agentCreator, coordinatorHolder, listAgents, nextSeatId, seatEnrolled, seatLineage, takeCoordinator, withVerifierStanding } from './seats.js';diff --git a/src/commands/publish.js b/src/commands/publish.jsindex 88323a69..42413bc1 100644--- a/src/commands/publish.js+++ b/src/commands/publish.js@@ -19,7 +19,8 @@ export async function run(io, { first, second, rest }) {if (first || second || rest.length) throw new Refused('USAGE', 'pullboard publish');const config = mainPolicy(ctx.info.root).config;const onFailure = nativeFlakes.observer(ctx, { kind: 'land', board, config }, { ordered, withBoard, resourceAgent });- const result = await publishTrunk({ root: ctx.info.root, board, config, say: io.say, onWait: gateWaitReporter(io), onFailure });+ const result = await publishTrunk({ root: ctx.info.root, board, config, say: io.say, onWait: gateWaitReporter(io), onFailure,+ write: (operation, args) => ordered(ctx, board, operation, args) });io.result?.(result);return result.published || result.waiting ? 0 : 1;});diff --git a/src/config.js b/src/config.jsindex 186a6d8e..7d24381f 100644--- a/src/config.js+++ b/src/config.js@@ -169,6 +169,10 @@ function laneProblems(name, lane) {*/export function configProblems(config) {const problems = [];+ if (config.publish !== undefined && (!config.publish || typeof config.publish !== 'object' || Array.isArray(config.publish)+ || Object.keys(config.publish).some(key => key !== 'pullRequest') || ![undefined, false, 'release', 'item'].includes(config.publish.pullRequest))) {+ problems.push('"publish.pullRequest" is false (default), "release" for one PR per release, or "item" for one PR per item');+ }for (const field of ['project', 'name']) {if (config[field] === undefined) continue;const value = config[field];diff --git a/src/engine.js b/src/engine.jsindex 2f0cdace..77dc894c 100644--- a/src/engine.js+++ b/src/engine.js@@ -70,6 +70,7 @@ import { requireCoordinatorHold } from './coordinator-hold.js';import { LANDING_ENVIRONMENT_ENGINE } from './landing-environment-engine.js';import { carriesLandingEnvironment } from './execution-environment.js';import { LANDING_LEASE_ENGINE } from './landing-lease-engine.js';+import { PR_BRIDGE_ENGINE } from './pr-bridge-engine.js';const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);@@ -83,6 +84,7 @@ export const ENGINE_OPERATIONS = Object.freeze(['recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'recordLandingTestDefect', 'finishLandingBatch', 'acceptCheck','recordHealthFindings', 'proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun','recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove',+ 'recordPublishFinding',]);/** Engine version at which each ordered operation first has stable replay semantics. */@@ -91,6 +93,7 @@ const OPERATION_ENGINE = Object.freeze({ draftSpecRow: ROW_DRAFT_ENGINE, orderMi/** Dependency edits, causes, sealed reviews, submission proofs, trunk conflicts, health observations and milestone targets retain distinct recorded engine meanings. */function minimumOperationEngine(operation, args, board, at) {+ if (operation === 'recordPublishFinding') return PR_BRIDGE_ENGINE;if (operation === 'recordLandingTestDefect' || operation === 'verify' && args[1]?.environment !== undefined|| operation === 'recordGateRun' && Object.hasOwn(args[0]?.receipt ?? {}, 'environment')|| operation === 'recordLandingBatch' && carriesLandingEnvironment(args[0]?.batch)) return LANDING_ENVIRONMENT_ENGINE;diff --git a/src/next-steps.js b/src/next-steps.jsindex 00d741ad..814e581c 100644--- a/src/next-steps.js+++ b/src/next-steps.js@@ -357,6 +357,11 @@ export const NEXT_STEPS = Object.freeze({LAND_NOT_PUSHED: 'push the batch, then pullboard land --adopt',LAND_PERSON_ONLY: 'ask the person to waive it from their terminal or pullboard view',LAND_PUSH: 'inspect the remote and hooks, then pullboard land --adopt',+ PUBLISH_GITHUB: 'inspect gh auth status and the configured GitHub remote, then publish again',+ PUBLISH_STATE: 'preserve publish-pr.json and ask the coordinator to recover its recorded PR identities',+ PUBLISH_UNPROVEN: 'restore the item’s acceptance at its exact submitted commit before publishing',+ PUBLISH_COMPOSITION: 'compose the accepted work with the actual remote base, resolve conflicts normally, then publish',+ PUBLISH_FINDING: 'record the exact merged item, publication head and failing GitHub job/run evidence',LAND_REMOTE_MOVED: 'inspect the remote branch, then pullboard land --adopt',LAND_TEST_DEFECT: 'commit a correction to the test named by the held defect, or ask the person for an expiring test waiver; then run pullboard land again',LAND_TRUNK: 'check the recorded trunk branch with pullboard resume, then switch the main checkout to that branch: git switch <trunk-branch>',diff --git a/src/pr-bridge-engine.js b/src/pr-bridge-engine.jsnew file mode 100644index 00000000..c098d63e--- /dev/null+++ b/src/pr-bridge-engine.js@@ -0,0 +1,4 @@+/** Replay the narrow post-land CI finding without reopening a merged item [B2,R3]. */+import { unassignedEngine } from './engine-next.js';++export const PR_BRIDGE_ENGINE = unassignedEngine();diff --git a/src/pr-findings.js b/src/pr-findings.jsnew file mode 100644index 00000000..615a9b87--- /dev/null+++ b/src/pr-findings.js@@ -0,0 +1,41 @@+/** Preserve merged history while recording one linked neutral CI repair [B2,R3]. */+import { createHash } from 'node:crypto';+import { addItem, appendFact, atomic, getItem, logEvent } from './board.js';+import { COORDINATOR } from './config.js';+import { Refused } from './refused.js';++/** Require bounded provider identities; strings become observations, never commands. */+function line(value, limit = 500) { return typeof value === 'string' && value.length > 0 && value.length <= limit && !/[\r\n\0]/u.test(value); }++/** Atomically append the observed finding and create its repair without relaxing ordinary child/reopen guards. */+export function recordPublishFinding(board, { agentId, item, repository, pull, head, failures }) {+ if (agentId !== COORDINATOR) throw new Refused('COORDINATOR_ONLY', 'only the coordinator records publication CI findings');+ if (!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(repository ?? '') || repository.split('/').some(part => ['.', '..'].includes(part)) || !Number.isSafeInteger(pull) || pull < 1 ||+ !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(head ?? '') || !Array.isArray(failures) || failures.length < 1 || failures.length > 100 ||+ failures.some(f => !Number.isSafeInteger(f.id) || f.id < 1 || !line(f.name) || !line(f.url, 2000) ||+ !Array.isArray(f.files) || !f.files.length || f.files.length > 500 || f.files.some(file => !line(file, 4096) || file.startsWith('/') || file.includes('\\') || file.split('/').some(part => !part || part === '.' || part === '..')))) {+ throw new Refused('PUBLISH_FINDING', 'record exact repository, PR head, failing job/run and implicated repository-relative files');+ }+ const key = createHash('sha256').update(JSON.stringify([repository, pull, head, item])).digest('hex');+ return atomic(board, () => {+ const original = getItem(board, item);+ if (!original.item_merged_commit || original.item_status !== 'verified') throw new Refused('PUBLISH_FINDING', 'CI findings here must name an already merged item; preserve ordinary item review for unmerged work.');+ const old = board.db.prepare("SELECT event_detail FROM event WHERE event_kind='pr-ci-finding' AND item_id=? ORDER BY event_id DESC").all(item)+ .map(row => JSON.parse(row.event_detail)).find(detail => detail.key === key);+ const observed = [...(old?.failures ?? [])];+ for (const failure of failures) if (!observed.some(f => f.id === failure.id && f.name === failure.name)) observed.push(failure);+ if (old && observed.length === old.failures.length) return old;+ const repair = old?.repair ?? addItem(board, { by: agentId, lane: original.item_lane, route: 'strong',+ title: `CI finding for #${item}: ${failures[0].name.slice(0, 100)}`,+ criterion: `The publication head passes the reported CI jobs: ${failures.map(f => f.name).join('; ')}. Diagnose the finding without assuming its item or test is flaky.`,+ brief: `Linked repair of merged item #${item}; GitHub ${repository} PR #${pull}, head ${head}. Keep the original merge and acceptance history. Jobs: ${failures.map(f => `${f.name}: ${f.url}`).join('; ')}` });+ // This new coordinator-only move is the explicit exception for a repair OF a closed item.+ // The ordinary addItem(parentId) guard still refuses a child of any closed parent.+ if (!old) board.db.prepare('UPDATE item SET item_parent_id=? WHERE item_id=?').run(item, repair);+ const detail = { key, repository, pull, head, item, repair, failures: observed };+ const factId = 'pr-ci-' + createHash('sha256').update(JSON.stringify(detail)).digest('hex');+ appendFact(board, item, { agentId, kind: 'capture', factId, text: 'CI finding: ' + JSON.stringify(detail) });+ logEvent(board, agentId, 'pr-ci-finding', item, detail);+ return detail;+ });+}diff --git a/src/pr-github.js b/src/pr-github.jsnew file mode 100644index 00000000..d6d19a8a--- /dev/null+++ b/src/pr-github.js@@ -0,0 +1,49 @@+/** Use GitHub CLI's credential store without copying credentials into config or receipts [B3,R3]. */+import { spawnSync } from 'node:child_process';+import { tryGit } from './git.js';+import { Refused } from './refused.js';++/** Resolve only a GitHub repository, reading the raw URL before private Git URL rewrites. */+export function githubRepository(root, remote) {+ const raw = tryGit(root, ['config', '--get', `remote.${remote}.url`]).stdout.trim();+ const match = /^(?:https:\/\/github\.com\/|git@github\.com:|ssh:\/\/git@github\.com\/)([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?\/?$/u.exec(raw);+ if (!match || ['.', '..'].includes(match[1]) || ['.', '..'].includes(match[2])) {+ throw new Refused('PUBLISH_GITHUB', 'PR publishing needs a github.com remote; configure the repository remote or turn publish.pullRequest off.');+ }+ return `${match[1]}/${match[2]}`;+}++/** Make one bounded JSON request; this client exposes no merge operation. */+export function githubPullClient(root, repository) {+ /** Authenticate through gh itself, keeping provider credentials out of the application. */+ function api(method, suffix, body) {+ const args = ['api', '--method', method, `repos/${repository}/${suffix}`,+ '--header', 'Accept: application/vnd.github+json', '--header', 'X-GitHub-Api-Version: 2022-11-28'];+ if (body !== undefined) args.push('--input', '-');+ const result = spawnSync('gh', args, { cwd: root, encoding: 'utf8',+ input: body === undefined ? undefined : JSON.stringify(body), maxBuffer: 4 * 1024 * 1024, timeout: 30_000 });+ if (result.status !== 0 || result.error) throw new Refused('PUBLISH_GITHUB', 'GitHub request failed; inspect gh auth status and repository access, then run publish again.');+ try { return JSON.parse(result.stdout); }+ catch { throw new Refused('PUBLISH_GITHUB', 'GitHub returned invalid JSON; inspect gh api connectivity before publishing again.'); }+ }+ /** Read complete provider pages, refusing truncation instead of silently dropping evidence. */+ function pages(suffix, field = null) {+ const rows = [];+ for (let page = 1; page <= 100; page++) {+ const result = api('GET', `${suffix}${suffix.includes('?') ? '&' : '?'}per_page=100&page=${page}`);+ const values = field ? result?.[field] : result;+ if (!Array.isArray(values)) throw new Refused('PUBLISH_GITHUB', 'GitHub returned an invalid list; inspect the provider response before publishing.');+ rows.push(...values);+ if (values.length < 100) return rows;+ }+ throw new Refused('PUBLISH_GITHUB', 'GitHub evidence exceeds the bounded page limit; narrow this release before publishing.');+ }+ return {+ list: head => pages(`pulls?state=open&head=${encodeURIComponent(repository.split('/')[0] + ':' + head)}`),+ read: number => api('GET', `pulls/${number}`),+ create: body => api('POST', 'pulls', body),+ update: (number, body) => api('PATCH', `pulls/${number}`, body),+ checks: head => pages(`commits/${head}/check-runs`, 'check_runs'),+ annotations: id => pages(`check-runs/${id}/annotations`),+ };+}diff --git a/src/pr-publish.js b/src/pr-publish.jsnew file mode 100644index 00000000..f7ebe393--- /dev/null+++ b/src/pr-publish.js@@ -0,0 +1,214 @@+/** Publish proven GitHub proposal branches without pushing or merging the protected trunk [B3,R3]. */+import { createHash, randomUUID } from 'node:crypto';+import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import * as store from './board.js';+import { git, repoInfo, tryGit, cleanGitEnvironment } from './git.js';+import { runGate } from './gate.js';+import { githubPullClient, githubRepository } from './pr-github.js';+import { Refused } from './refused.js';++/** Keep publisher-local transport state distinct from the shared board and legacy push state. */+function statePath(root) { return join(repoInfo(root).commonDir, 'pullboard', 'publish-pr.json'); }++/** Recover only bounded local state; source identity is checked again before any push. */+function readState(root) {+ try {+ const value = JSON.parse(readFileSync(statePath(root), 'utf8'));+ if (value.version !== 1 || !Array.isArray(value.proposals)) throw new Error('unsupported publication state');+ if (value.proposals.some(p => !p || !Number.isSafeInteger(p.number) || p.number < 1 ||+ !/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/u.test(p.repository ?? '') ||+ !/^pullboard\/(?:release|item-[0-9]+)-[a-f0-9]{12}$/u.test(p.branch ?? '') ||+ !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(p.head ?? '') ||+ !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(p.source ?? '') || !Array.isArray(p.entries) ||+ p.entries.some(e => !Number.isSafeInteger(e.id) || e.id < 1 || !Array.isArray(e.files)))) throw new Error('invalid proposal identity');+ return value;+ } catch (error) { if (error.code !== 'ENOENT') throw new Refused('PUBLISH_STATE', 'restore readable publish-pr.json or preserve it and ask the coordinator to recover the publication'); }+ return { version: 1, proposals: [] };+}++/** Atomically save non-secret proposal identities after each acknowledged provider action. */+function saveState(root, value) {+ const file = statePath(root);+ const temporary = file + '.' + randomUUID();+ mkdirSync(join(file, '..'), { recursive: true });+ writeFileSync(temporary, JSON.stringify(value) + '\n', { mode: 0o600 });+ // Git's private directory shares a filesystem with its temporary state file.+ renameSync(temporary, file);+}++/** Read exact accepted items in first-parent merge order, never infer a verdict from a local gate. */+function releaseEntries(root, board, base, head) {+ const range = git(root, ['rev-list', '--first-parent', '--reverse', `${base}..${head}`]).split('\n');+ const byMerge = new Map(store.listItems(board, { all: true }).filter(i => i.item_status === 'verified' && i.item_merged_commit)+ .map(i => [i.item_merged_commit, i]));+ return range.flatMap(merge => {+ const item = byMerge.get(merge);+ if (!item) return [];+ const verdict = store.acceptedVerdict(board, item);+ if (!verdict) throw new Refused('PUBLISH_UNPROVEN', `item #${item.item_id} has no acceptance at its submitted commit; restore its recorded review before publishing`);+ return [{ id: item.item_id, merge, commit: item.item_commit, verdict: verdict.verdict_decision,+ reviewer: verdict.verdict_by, environment: verdict.environment ?? null,+ files: git(root, ['diff', '--name-only', `${merge}^1`, merge]).split('\n').filter(Boolean) }];+ });+}++/** Project only receipt fields intended for a repository's PR; no criteria, local paths or session data. */+function receiptBody(head, entries) {+ return [`Pullboard publication head: ${head}`, '', 'Accepted item receipts:', ...entries.map(entry => {+ const env = entry.environment;+ const where = env ? `${env.platform}/${env.arch}, Node ${env.node}` : 'execution environment unknown (historical receipt)';+ return `- #${entry.id}: ${entry.commit}; ${entry.verdict}; reviewer ${entry.reviewer}; ${where}`;+ }), '', 'The whole project gate passed at the publication head before this branch was pushed.',+ 'Item receipts certify their recorded accepted commits; they do not invent a second-agent verdict on this publication composition.',+ 'Changes outside those item receipts remain unverified by a second agent.'].join('\n');+}++/** Compose only an item's landed patch into an isolated index; neither the caller's index nor trunk moves. */+function itemComposition(root, base, entries) {+ const directory = join(repoInfo(root).commonDir, 'pullboard', 'publish-index', randomUUID());+ mkdirSync(directory, { recursive: true });+ const env = { ...cleanGitEnvironment(), GIT_INDEX_FILE: join(directory, 'index') };+ try {+ git(root, ['read-tree', base], { env });+ for (const entry of entries) {+ const patch = spawnSync('git', ['--no-replace-objects', 'diff', '--binary', `${entry.merge}^1`, entry.merge],+ { cwd: root, env, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ if (patch.status !== 0) throw new Refused('PUBLISH_COMPOSITION', 'the accepted item patch cannot be read exactly; restore its Git objects before publishing');+ const applied = spawnSync('git', ['--no-replace-objects', 'apply', '--cached', '--3way', '-'],+ { cwd: root, env, input: patch.stdout, encoding: 'utf8', maxBuffer: 32 * 1024 * 1024 });+ if (applied.status !== 0) throw new Refused('PUBLISH_COMPOSITION', 'the per-item publication patch conflicts with its base; ask the coordinator to compose the accepted repair before publishing');+ }+ const tree = git(root, ['write-tree'], { env });+ return git(root, ['commit-tree', tree, '-p', base, '-m', `chore(publish): compose items ${entries.map(e => e.id).join(',')}`]);+ } finally { rmSync(directory, { recursive: true, force: true }); }+}++/** Compose the release with the actual remote base without altering local trunk history. */+function releaseComposition(root, base, head) {+ if (tryGit(root, ['merge-base', '--is-ancestor', base, head]).status === 0) return head;+ const merged = tryGit(root, ['merge-tree', '--write-tree', base, head]);+ if (merged.status !== 0) throw new Refused('PUBLISH_COMPOSITION', 'the remote trunk conflicts with local accepted work; merge the actual remote base normally before publishing');+ const tree = merged.stdout.split('\n')[0];+ return git(root, ['commit-tree', tree, '-p', base, '-p', head, '-m', 'chore(publish): compose proven release']);+}++/** Prove this exact immutable commit before pushing only its proposal ref. */+async function proveProposal({ root, config, remote, candidate, branch, onWait, onFailure }) {+ const directory = join(repoInfo(root).commonDir, 'pullboard', 'publish', randomUUID());+ mkdirSync(join(directory, '..'), { recursive: true });+ git(root, ['worktree', 'add', '--detach', directory, candidate]);+ try {+ const gate = await runGate(directory, config, { trustStamp: false, landing: true, agent: 'coordinator', onWait, onFailure });+ if (!gate.isGreen) return gate;+ const pushed = tryGit(directory, ['push', remote, `HEAD:refs/heads/${branch}`]);+ if (pushed.status !== 0) throw new Refused('LAND_PUSH', 'the proven proposal branch could not be pushed; inspect its remote history before publishing again');+ return gate;+ } finally {+ tryGit(root, ['worktree', 'remove', '--force', directory]);+ if (existsSync(directory)) rmSync(directory, { recursive: true, force: true });+ }+}++/** Bind failed check annotations to the exact publication head and implicated item paths. */+async function observeCI(client, proposal, repository, write) {+ const failures = new Map();+ const unknown = [];+ for (const run of client.checks(proposal.head)) {+ if (run.head_sha !== proposal.head || run.status !== 'completed' || !['failure', 'timed_out', 'action_required'].includes(run.conclusion)) continue;+ if (!Number.isSafeInteger(run.id) || run.id < 1 || typeof run.name !== 'string' || !run.name || /[\r\n\0]/u.test(run.name)) {+ throw new Refused('PUBLISH_GITHUB', 'the failing CI job lacks a valid provider run identity; inspect the provider response');+ }+ const files = [...new Set(client.annotations(run.id).filter(a => a.annotation_level === 'failure').map(a => a.path)+ .filter(p => typeof p === 'string' && !p.startsWith('/') && !p.includes('\\') && !p.split('/').includes('..')))];+ const affected = proposal.entries.filter(entry => entry.files.some(file => files.includes(file)));+ if (!affected.length) { unknown.push({ job: run.name, run: run.id }); continue; }+ for (const entry of affected) {+ const list = failures.get(entry.id) ?? [];+ list.push({ id: run.id, name: run.name, url: run.html_url ?? run.details_url ?? `https://github.com/${repository}/actions`,+ files: files.filter(file => entry.files.includes(file)) });+ failures.set(entry.id, list);+ }+ }+ const findings = [];+ for (const [item, jobs] of failures) findings.push(await write('recordPublishFinding', [{ agentId: 'coordinator',+ item, repository, pull: proposal.number, head: proposal.head, failures: jobs }]));+ return { findings, unattributed: unknown };+}++/** Record observed external facts; a recognized person label never becomes native person approval. */+async function observeMerge(root, board, proposal, pull, config, repository, write) {+ if (!pull.merged || pull.head?.sha !== proposal.head || !/^[a-f0-9]{40}(?:[a-f0-9]{24})?$/u.test(pull.merge_commit_sha ?? '')) return null;+ const actor = pull.merged_by?.login;+ if (typeof actor !== 'string' || !/^[A-Za-z0-9-]{1,39}$/u.test(actor)) throw new Refused('PUBLISH_GITHUB', 'the merged PR lacks a valid provider actor; inspect it before recording a release');+ const recognizedPerson = pull.merged_by.type === 'User' && (config.approvers ?? []).some(login => login.toLowerCase() === actor.toLowerCase());+ const release = { type: 'github-release', repository, pull: proposal.number, url: `https://github.com/${repository}/pull/${proposal.number}`,+ head: proposal.head, merge: pull.merge_commit_sha, actor, recognizedPerson, personApproval: false };+ for (const entry of proposal.entries) {+ const exists = store.itemThread(board, entry.id).some(fact => fact.type === 'fact' && fact.text === JSON.stringify(release));+ if (!exists) await write('appendFact', [entry.id, { agentId: 'coordinator', kind: 'capture', text: JSON.stringify(release) }]);+ }+ return release;+}++/** Propose and reconcile one release PR or isolated per-item PRs; no path calls GitHub's merge endpoint. */+export async function publishPullRequests({ root, board, config, branch, remote, head, published, say, onWait, onFailure, write }) {+ if (typeof write !== 'function') throw new Refused('PUBLISH_STATE', 'PR publishing must run through the coordinator CLI so its findings and releases use ordered board moves');+ if (!published) throw new Refused('PUBLISH_GITHUB', 'create the remote base branch before enabling pull-request publishing');+ const fetched = tryGit(root, ['fetch', '--no-tags', remote, branch]);+ if (fetched.status !== 0 || git(root, ['rev-parse', 'FETCH_HEAD']) !== published) throw new Refused('PUBLISH_COMPOSITION', 'the remote base changed while preparing publication; inspect it and run publish again');+ const repository = githubRepository(root, remote);+ const client = githubPullClient(root, repository);+ const state = readState(root);+ const releases = [];+ const findings = [];+ const unattributed = [];+ for (const proposal of state.proposals.filter(p => p.repository === repository)) {+ const pull = client.read(proposal.number);+ if (pull.head?.sha !== proposal.head) throw new Refused('PUBLISH_STATE', 'a proposal branch changed outside its recorded publication; inspect the PR before publishing');+ if (pull.state === 'closed' && !pull.merged) throw new Refused('PUBLISH_STATE', 'the proposal was closed without merging; ask the coordinator whether to reopen it before publishing');+ const ci = await observeCI(client, proposal, repository, write);+ findings.push(...ci.findings); unattributed.push(...ci.unattributed);+ const released = proposal.released ? null : await observeMerge(root, board, proposal, pull, config, repository, write);+ if (released) {+ proposal.released = true; releases.push(released);+ say(`recorded PR #${proposal.number} merge by ${released.actor} (${released.recognizedPerson ? 'recognized person' : 'not a recognized person'}); no native person approval recorded`);+ }+ }+ await saveState(root, state);+ const releasedItems = new Set(state.proposals.filter(p => p.released).flatMap(p => p.entries.map(e => `${e.id}:${e.commit}`)));+ const entries = releaseEntries(root, board, published, head).filter(e => !releasedItems.has(`${e.id}:${e.commit}`));+ if (tryGit(root, ['merge-base', '--is-ancestor', head, published]).status === 0) return { head, published: true, red: [], releases, findings, unattributed };+ const digest = createHash('sha256').update(branch).digest('hex').slice(0, 12);+ const repairRoots = new Map(store.events(board).filter(e => e.event_kind === 'pr-ci-finding').map(e => {+ const detail = JSON.parse(e.event_detail); return [detail.repair, detail.item];+ }));+ const groups = config.publish.pullRequest === 'item' ? [...new Set(entries.map(e => repairRoots.get(e.id) ?? e.id))]+ .map(id => ({ key: `item-${id}`, entries: entries.filter(e => (repairRoots.get(e.id) ?? e.id) === id) })) : [{ key: 'release', entries }];+ const proposed = [];+ if (!groups.length) return { head, published: false, waiting: true, red: [], releases, findings, unattributed,+ reason: 'No unpublished accepted item remains; per-item mode does not certify unrelated local commits.' };+ for (const group of groups) {+ const name = `pullboard/${group.key}-${digest}`;+ const old = state.proposals.findLast(p => p.repository === repository && p.branch === name && !p.released);+ if (old?.source === head) { proposed.push(old); continue; }+ const added = group.entries.filter(entry => !old?.entries.some(e => e.merge === entry.merge));+ if (old && config.publish.pullRequest === 'item' && !added.length) { proposed.push(old); continue; }+ const candidate = config.publish.pullRequest === 'item'+ ? itemComposition(root, old?.head ?? published, added) : releaseComposition(root, published, head);+ const gate = await proveProposal({ root, config, remote, candidate, branch: name, onWait, onFailure });+ if (!gate.isGreen) return { head, published: false, red: [{ file: null, name: 'publication whole gate failed', items: group.entries.map(e => e.id) }], findings, unattributed };+ const body = receiptBody(candidate, group.entries);+ const title = `Pullboard ${group.key === 'release' ? 'release' : group.key}`;+ const existing = old ?? client.list(name)[0];+ const pull = existing ? client.update(existing.number, { title, body }) : client.create({ title, body, head: name, base: branch });+ if (!Number.isSafeInteger(pull.number) || pull.number < 1 || pull.head?.sha !== candidate) throw new Refused('PUBLISH_GITHUB', 'the PR response does not name the exact proven publication head; inspect it before continuing');+ const proposal = { repository, branch: name, source: head, head: candidate, number: pull.number,+ url: `https://github.com/${repository}/pull/${pull.number}`, entries: group.entries, released: false };+ if (old) state.proposals.splice(state.proposals.indexOf(old), 1, proposal); else state.proposals.push(proposal);+ await saveState(root, state); proposed.push(proposal);+ }+ say(`proposed ${proposed.length} pull request(s); only a person can merge them`);+ return { head, published: false, waiting: true, proposed: true, pullRequests: proposed.map(p => ({ number: p.number, url: p.url, head: p.head, items: p.entries.map(e => e.id) })), red: [], releases, findings, unattributed };+}diff --git a/src/publish.js b/src/publish.jsindex 2775aaae..8e93a711 100644--- a/src/publish.js+++ b/src/publish.js@@ -20,6 +20,7 @@ import { tryGit } from './git.js';import { landingFailures } from './land.js';import { landingRemote } from './land.js';import { Refused } from './refused.js';+import { publishPullRequests } from './pr-publish.js';/** Where publish remembers the last head it found red, so the same head is not run again. */function stateFile(root) {@@ -64,7 +65,7 @@ function touchedBy(root, board, published, head, files) {* @param {{ root: string, board: any, config: any, say: (line: string) => void, onWait?: Function, onFailure?: Function }} options* @returns {Promise<{ head: string, published: boolean, red: Array<{ file: string|null, name: string, items: number[] }>, waiting?: boolean }>}*/-export async function publishTrunk({ root, board, config, say, onWait, onFailure }) {+export async function publishTrunk({ root, board, config, say, onWait, onFailure, write }) {const trunk = mainCheckout(root);if (!trunk?.commit) throw new Refused('LAND_TRUNK', 'publish needs the coordinator’s primary branch; return its checkout to the trunk');const branch = trunk.branch.replace(/^refs\/heads\//u, '');@@ -72,6 +73,8 @@ export async function publishTrunk({ root, board, config, say, onWait, onFailureif (!remote) throw new Refused('LAND_PUSH', `the landing push failed: this repo has no remote to push ${branch} to; add one with git remote add origin <url> and run pullboard publish again`);const head = trunk.commit;const published = remoteHead(root, remote, branch);+ if (config.publish?.pullRequest) return await publishPullRequests({ root, board, config, say, onWait, onFailure, write,+ branch, remote, head, published });if (published === head) {say(`${branch} at ${head.slice(0, 12)} is already published`);return { head, published: true, red: [] };diff --git a/src/relay-sender.js b/src/relay-sender.jsindex 867b2784..617db4f0 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -10,7 +10,7 @@ export function relayMoveActor(move) {if (move.operation === 'addItem') return args[0]?.by ?? null;if (move.operation === 'shout') return args[0]?.from ?? null;if (['proposeSentinel', 'decideSentinel', 'beginSentinelRun', 'finishSentinelRun'].includes(move.operation)) return args[0]?.agentId ?? null;- if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].includes(move.operation)) return args[0]?.agentId ?? null;+ if (['recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove', 'recordPublishFinding'].includes(move.operation)) return args[0]?.agentId ?? null;if (['holdLane', 'releaseLane'].includes(move.operation) && args[1]?.asPerson) return 'person';if (move.operation === 'release') return args[1] ?? null;if (['reserveNextReview', 'addMilestone', 'recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'recordSpecApprovalBaseline', 'recordLandingBatch', 'recordLandingWaiver', 'recordLandingFlake', 'recordLandingTestDefect', 'finishLandingBatch'].includes(move.operation)) return args[0]?.agentId ?? null;diff --git a/test/pr-bridge-fixture.js b/test/pr-bridge-fixture.jsindex 11d64387..fb645449 100644--- a/test/pr-bridge-fixture.js+++ b/test/pr-bridge-fixture.js@@ -86,7 +86,7 @@ export function landBridgeItems(box) {/** Stand in for GitHub over real HTTP, refusing every merge endpoint. */export async function bridgeProvider(t, box) {- const state = { requests: [], pulls: [], checks: [], annotations: [], next: 1 };+ const state = { requests: [], pulls: [], checks: [], annotations: [], annotationsByRun: {}, next: 1 };const server = createServer(async (req, res) => {let raw = '';for await (const chunk of req) raw += chunk;@@ -96,7 +96,8 @@ export async function bridgeProvider(t, box) {const reply = (status, value) => { res.writeHead(status, { 'content-type': 'application/json' }); res.end(JSON.stringify(value)); };if (url.pathname.endsWith('/merge') && req.method !== 'GET') return reply(403, { message: 'agents never merge' });if (url.pathname === '/repos/fixture/repository/pulls') {- if (req.method === 'GET') return reply(200, state.pulls.filter(p => p.state === (url.searchParams.get('state') ?? 'open')));+ if (req.method === 'GET') return reply(200, state.pulls.filter(p => p.state === (url.searchParams.get('state') ?? 'open') &&+ (!url.searchParams.get('head') || url.searchParams.get('head') === 'fixture:' + p.head.ref)));if (req.method === 'POST') {const head = box.git(box.remote, 'rev-parse', `refs/heads/${body.head}`);const pull = { number: state.next++, html_url: `https://github.com/fixture/repository/pull/${state.next - 1}`,@@ -109,11 +110,15 @@ export async function bridgeProvider(t, box) {if (pullRoute) {const pull = state.pulls.find(p => p.number === Number(pullRoute[1]));if (!pull) return reply(404, { message: 'missing private pull' });- if (req.method === 'PATCH') Object.assign(pull, { title: body.title, body: body.body });+ if (req.method === 'PATCH') {+ Object.assign(pull, { title: body.title, body: body.body });+ pull.head.sha = box.git(box.remote, 'rev-parse', `refs/heads/${pull.head.ref}`);+ }return reply(200, pull);}if (/\/commits\/[a-f0-9]+\/check-runs$/u.test(url.pathname)) return reply(200, { total_count: state.checks.length, check_runs: state.checks });- if (/\/check-runs\/\d+\/annotations$/u.test(url.pathname)) return reply(200, state.annotations);+ const annotations = /\/check-runs\/(\d+)\/annotations$/u.exec(url.pathname);+ if (annotations) return reply(200, state.annotationsByRun[annotations[1]] ?? state.annotations);if (/\/commits\/[a-f0-9]+\/status$/u.test(url.pathname)) return reply(200, { state: 'success', statuses: [] });return reply(404, { message: 'unexpected private provider endpoint' });});@@ -134,3 +139,39 @@ export async function bridgeProvider(t, box) {chmodSync(shim, 0o755);return state;}++/** Fix only the linked private repair through the same real item lifecycle. */+export function landBridgeRepair(box, id, file) {+ const path = join(box.dir, `repair-${id}`);+ box.git(box.repo, 'worktree', 'add', '-q', '-b', `web/repair-${id}`, path, 'main');+ assert.equal(box.run(path, 'join', 'web').code, 0);+ const edited = box.run(box.repo, 'edit', String(id), '--criterion', 'the private CI finding is repaired',+ '--check', 'test ! -f RED', '--brief', 'Change the named private web fixture and retain the linked finding.');+ assert.equal(edited.code, 0, edited.err);+ assert.equal(box.run(path, 'claim', String(id)).code, 0);+ assert.equal(box.commitFile(box, path, file, 'PASS REPAIRED\n', 'fix(web): repair private CI finding [G1]').status, 0);+ const commit = box.git(path, 'rev-parse', 'HEAD');+ const submitted = box.run(path, 'submit', String(id));+ assert.equal(submitted.code, 0, submitted.err);+ box.git(box.repo, 'switch', '-q', '--detach', commit);+ try {+ const accepted = box.run(box.repo, 'verify', String(id), 'accept', '--as', 'coordinator', '--note', 'private repair proof passed');+ assert.equal(accepted.code, 0, accepted.err);+ } finally { box.git(box.repo, 'switch', '-q', 'main'); }+ box.git(box.repo, 'merge', '-q', '--no-ff', '-m', 'chore(merge): land private CI repair [G1]', commit);+ const merged = box.run(box.repo, 'merged', String(id), box.git(box.repo, 'rev-parse', 'HEAD'));+ assert.equal(merged.code, 0, merged.err);+ return commit;+}++/** Perform an actual private merge outside the product, with a separately reported provider actor. */+export function mergeBridgeAs(box, pull, actor, type = 'User') {+ const person = join(box.dir, `person-${pull.number}`);+ box.git(box.dir, 'clone', '-q', '--branch', 'main', box.remote, person);+ box.git(person, 'fetch', '-q', 'origin', pull.head.ref);+ box.git(person, 'merge', '-q', '--no-ff', '-m', 'chore: external private proposal merge [G1]', 'FETCH_HEAD');+ box.git(person, 'push', '-q', 'origin', 'main');+ pull.state = 'closed'; pull.merged = true;+ pull.merge_commit_sha = box.git(person, 'rev-parse', 'HEAD');+ pull.merged_by = { login: actor, type, id: pull.number + 1000 };+}diff --git a/test/pr-bridge.test.js b/test/pr-bridge.test.jsindex fc3d3844..81548c6c 100644--- a/test/pr-bridge.test.js+++ b/test/pr-bridge.test.js@@ -3,9 +3,13 @@ import assert from 'node:assert/strict';import { readFileSync } from 'node:fs';import { join } from 'node:path';import { test } from 'node:test';-import { bridgeProject, bridgeProvider, landBridgeItems, runBridgeCLI } from './pr-bridge-fixture.js';+import { bridgeProject, bridgeProvider, landBridgeItems, landBridgeRepair, mergeBridgeAs, runBridgeCLI } from './pr-bridge-fixture.js';import { onBoard } from './land-board-fixture.js';import * as store from '../src/board.js';+import { exportBoard, importBoard } from '../src/exchange.js';+import { prepareEngineMove, applyEngineMove } from '../src/engine.js';+import { PR_BRIDGE_ENGINE } from '../src/pr-bridge-engine.js';+import { configFromSource } from '../src/config.js';/** Read the real private gate invocations, retaining their exact Git heads. */function gateHeads(box) {@@ -58,3 +62,116 @@ test("publish opens one pull request with each item's receipt and records the peassert.equal(provider.requests.some(r => r.path.endsWith('/merge') && r.method !== 'GET'), false,'no product path performs a GitHub merge');});+++test('publication modes are opt-in and invalid values refuse before a push [B3,R3]', () => {+ assert.equal(configFromSource('{}').publish?.pullRequest ?? false, false);+ for (const mode of [false, 'release', 'item']) {+ assert.equal(configFromSource(JSON.stringify({ publish: { pullRequest: mode } })).publish.pullRequest, mode);+ }+ for (const value of [true, 'auto-merge', null, { pullRequest: 'release', merge: true }]) {+ const publish = value && typeof value === 'object' ? value : { pullRequest: value };+ assert.throws(() => configFromSource(JSON.stringify({ publish })), { code: 'BAD_CONFIG' });+ }+});++test('CI findings preserve the merged item and create one linked repair, then update the same PR [B2,R3]', async t => {+ const box = bridgeProject(t);+ const entries = landBridgeItems(box);+ const provider = await bridgeProvider(t, box);+ const first = await runBridgeCLI(box, 'publish', '--json');+ assert.equal(first.code, 0, first.err);+ const pull = provider.pulls[0];+ const oldHead = pull.head.sha;+ provider.checks = [+ { id: 301, name: 'linux / behavior', head_sha: oldHead, status: 'completed', conclusion: 'failure',+ html_url: 'https://github.com/fixture/repository/actions/runs/301' },+ { id: 302, name: 'unattributed infrastructure', head_sha: oldHead, status: 'completed', conclusion: 'failure' },+ { id: 303, name: 'stale unrelated job', head_sha: '0'.repeat(40), status: 'completed', conclusion: 'failure' },+ ];+ provider.annotationsByRun[301] = [{ path: entries[0].file, annotation_level: 'failure' }];+ provider.annotationsByRun[302] = [];+ const observed = await runBridgeCLI(box, 'publish', '--json');+ assert.equal(observed.code, 0, observed.err);+ const items = onBoard(box, board => store.listItems(board, { all: true }));+ const children = items.filter(item => item.item_parent_id === entries[0].id);+ assert.equal(children.length, 1);+ const repair = children[0];+ assert.equal(items.find(item => item.item_id === entries[0].id).item_status, 'verified');+ assert.equal(items.find(item => item.item_id === entries[0].id).item_merged_commit !== null, true);+ assert.equal(items.filter(item => item.item_parent_id === entries[1].id).length, 0);+ const facts = onBoard(box, board => store.itemThread(board, entries[0].id));+ assert.ok(facts.some(fact => fact.type === 'fact' && fact.text.includes('linux / behavior') && fact.text.includes('/runs/301')));+ assert.ok(JSON.parse(observed.out).unattributed.some(job => job.job === 'unattributed infrastructure'));+ assert.equal((await runBridgeCLI(box, 'publish', '--json')).code, 0);+ assert.equal(onBoard(box, board => store.listItems(board, { all: true })).filter(item => item.item_parent_id === entries[0].id).length, 1,+ 'polling the same failing run creates no duplicate child');+ landBridgeRepair(box, repair.item_id, entries[0].file);+ provider.checks = [];+ const updated = await runBridgeCLI(box, 'publish', '--json');+ assert.equal(updated.code, 0, updated.err);+ assert.equal(provider.pulls.length, 1);+ assert.notEqual(pull.head.sha, oldHead, 'the actual newly proven repair head updates the original PR');+ assert.ok(pull.body.includes(`#${repair.item_id}`));+ assert.ok(gateHeads(box).includes(pull.head.sha));+ assert.equal(box.git(box.remote, 'rev-parse', 'main'), box.published);+});++test('per-item proposals isolate each patch and never attribute bots or unlisted users as person approval [B3,R3]', async t => {+ const box = bridgeProject(t, 'item');+ const entries = landBridgeItems(box);+ const provider = await bridgeProvider(t, box);+ const result = await runBridgeCLI(box, 'publish', '--json');+ assert.equal(result.code, 0, result.err);+ assert.equal(provider.pulls.length, 2);+ for (const entry of entries) {+ const pull = provider.pulls.find(p => p.body.includes(`#${entry.id}:`));+ assert.ok(pull);+ const other = entries.find(e => e.id !== entry.id);+ assert.equal(pull.body.includes(`#${other.id}:`), false);+ const files = box.git(box.remote, 'diff', '--name-only', box.published, pull.head.sha).split('\n');+ assert.deepEqual(files, [entry.file], 'per-item mode never duplicates the whole trunk diff into every PR');+ assert.ok(gateHeads(box).includes(pull.head.sha));+ }+ assert.equal(box.git(box.remote, 'rev-parse', 'main'), box.published);+ mergeBridgeAs(box, provider.pulls[0], 'fixture-bot', 'Bot');+ mergeBridgeAs(box, provider.pulls[1], 'unlisted-user');+ const observed = await runBridgeCLI(box, 'publish', '--json');+ assert.equal(observed.code, 0, observed.err);+ const facts = onBoard(box, board => entries.flatMap(entry => store.itemThread(board, entry.id)+ .filter(fact => fact.type === 'fact').map(fact => fact.text)));+ const releases = facts.filter(text => text.startsWith('{')).map(text => JSON.parse(text)).filter(fact => fact.type === 'github-release');+ assert.equal(releases.length, 2);+ assert.ok(releases.every(release => release.recognizedPerson === false && release.personApproval === false));+ assert.ok(releases.some(release => release.actor === 'fixture-bot'));+ assert.ok(releases.some(release => release.actor === 'unlisted-user'));+ assert.equal(provider.pulls.length, 2, 'cherry-picked publication commits are not proposed again merely because ancestry differs');+ assert.equal(provider.requests.some(request => request.path.endsWith('/merge') && request.method !== 'GET'), false);+});++test('publication findings replay deterministically and ordinary closed-parent guards remain intact [B2,H16,R3]', t => {+ const box = bridgeProject(t);+ const entries = landBridgeItems(box);+ const source = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));+ const replica = store.openBoard(join(box.dir, 'replica.sqlite'));+ t.after(() => { store.closeBoard(source); store.closeBoard(replica); });+ const baseline = exportBoard(source);+ importBoard(replica, baseline);+ const request = { agentId: 'coordinator', item: entries[0].id, repository: 'fixture/repository', pull: 1,+ head: box.git(box.repo, 'rev-parse', 'HEAD'), failures: [{ id: 401, name: 'recorded CI job',+ url: 'https://github.com/fixture/repository/actions/runs/401', files: [entries[0].file] }] };+ const move = prepareEngineMove(source, 'recordPublishFinding', [request], { id: 'fixture-publication-finding' });+ assert.throws(() => applyEngineMove(replica, { ...move, engine: PR_BRIDGE_ENGINE - 1 },+ { sequence: 1, at: '2026-10-24T07:00:00.000Z' }), { code: 'RELAY_MOVE' });+ const options = { sequence: 1, at: '2026-10-24T07:00:00.000Z' };+ const a = applyEngineMove(source, move, options);+ const b = applyEngineMove(replica, move, options);+ assert.deepEqual(a, b);+ assert.equal(a.error, undefined);+ assert.deepEqual(applyEngineMove(replica, move, options), b);+ assert.deepEqual(exportBoard(source), exportBoard(replica));+ assert.equal(store.getItem(source, entries[0].id).item_status, 'verified');+ assert.throws(() => store.addItem(source, { by: 'coordinator', lane: 'web', title: 'ordinary child',+ criterion: 'ordinary closed parent remains refused', parentId: entries[0].id, route: 'strong' }), { code: 'PARENT_CLOSED' });+ assert.throws(() => store.recordPublishFinding(source, { ...request, agentId: 'web-1' }), { code: 'COORDINATOR_ONLY' });+});