Skip to content

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.

feat(core): require independent bar readiness [B4,V2,V1,H16]

Corey Olson69d2e30409ff
diff --git a/src/bar-readiness.js b/src/bar-readiness.js
new file mode 100644
index 00000000..ddd13db8
--- /dev/null
+++ b/src/bar-readiness.js
@@ -0,0 +1,119 @@
+/** Readiness is a revision-bound peer judgement, with mechanical prerequisites [U113]. */
+import { createHash } from 'node:crypto';
+import { atomic, itemById, logEvent } from './board.js';
+import { itemCheckBaseline } from './item-check-baseline.js';
+import { agentParent } from './seats.js';
+import { ENGINE_VERSION } from './machine.js';
+import { BAR_READY_ENGINE } from './bar-ready-engine.js';
+import { Refused } from './refused.js';
+
+const FIELDS = ['item_title', 'item_criterion', 'item_check', 'item_brief', 'item_spec_ids', 'item_after', 'item_route'];
+/** Read a deterministic value kept by ordered moves; the event history retains its provenance. */
+function read(board, key) {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key);
+ return row ? JSON.parse(row.meta_value) : null;
+}
+/** Write within the caller's atomic move. */
+function save(board, key, value) {
+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value').run(key, JSON.stringify(value));
+}
+/** A primary session's own recorded identity is known; a seat-name fallback is not. */
+function parent(board, agent) {
+ return agentParent(board, agent) ?? board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(`agent_session:${agent}`)?.meta_value ?? null;
+}
+/** Bind the entire author-written bar, including coverage and measurement notes in the brief. */
+export function barDigest(item) {
+ return createHash('sha256').update(JSON.stringify(FIELDS.map(key => [key, item[key] ?? '']))).digest('hex');
+}
+/** Read the default-off board setting without consulting a replica's local configuration. */
+export function barReadySetting(board) { return read(board, 'bar_ready_setting') ?? { enabled: false, since: 0 }; }
+/** Make activation an ordered boundary; repeating on does not erase earlier obligations. */
+export function setBarReady(board, { agentId, enabled }) {
+ if (agentId !== 'coordinator') throw new Refused('COORDINATOR_ONLY', 'only the coordinator changes bar readiness; shout coordinator');
+ if (typeof enabled !== 'boolean') throw new Refused('USAGE', 'pullboard bar ready on|off');
+ return atomic(board, () => {
+ const prior = barReadySetting(board);
+ if (prior.enabled === enabled) return prior;
+ logEvent(board, agentId, 'bar-ready', null, { enabled });
+ const setting = { enabled, since: board.lastEvent.event_id };
+ save(board, 'bar_ready_setting', setting);
+ return setting;
+ });
+}
+/** Snapshot authors on semantic edits, never retroactively upgrading an unknown historical parent. */
+export function recordBarRevision(board, item, by, before = null) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < BAR_READY_ENGINE || !barReadySetting(board).enabled) return;
+ const previous = read(board, `bar_revision:${item.item_id}`);
+ const changed = FIELDS.filter(key => !previous || !before || before[key] !== item[key]);
+ if (!changed.length) return;
+ const authors = { ...(previous?.authors ?? {}) };
+ for (const field of FIELDS) {
+ if (changed.includes(field)) authors[field] = { agent: by, parent: parent(board, by) };
+ else if (!authors[field]) authors[field] = { agent: item.item_created_by, parent: parent(board, item.item_created_by) };
+ }
+ const revision = { digest: barDigest(item), authors };
+ logEvent(board, by, 'bar-revision', item.item_id, revision);
+ save(board, `bar_revision:${item.item_id}`, { ...revision, revision: board.lastEvent.event_id });
+}
+/** Parse explicit notes without pretending a regular expression can grade their adequacy. */
+export function barNotes(brief) {
+ const sections = {};
+ let key = '';
+ for (const line of String(brief).split(/\r?\n/u)) {
+ const label = /^([a-z][a-z ]*):\s*(.*)$/iu.exec(line.trim());
+ if (label) { key = label[1].toLowerCase(); sections[key] = label[2].trim(); }
+ else if (key && line.trim()) sections[key] += `\n${line.trim()}`;
+ }
+ return sections;
+}
+/** An already-frozen bar predating activation needs no backfill until its words change. */
+export function barReadinessRequired(board, item) {
+ if ((board.executionEngineVersion ?? ENGINE_VERSION) < BAR_READY_ENGINE) return false;
+ const setting = barReadySetting(board);
+ if (!setting.enabled) return false;
+ if (!item.item_frozen_digest) return true;
+ const edited = read(board, `bar_revision:${item.item_id}`)?.revision ?? 0;
+ const frozen = board.db.prepare("SELECT MAX(event_id) AS id FROM event WHERE item_id=? AND event_kind IN ('claim','refreeze')").get(item.item_id).id ?? 0;
+ return Math.max(edited, frozen) > setting.since;
+}
+/** Mechanical omissions are aggregated, so the coordinator can repair the bar in one pass. */
+export function barReadiness(board, item, { signature = true } = {}) {
+ const revision = read(board, `bar_revision:${item.item_id}`);
+ const notes = barNotes(item.item_brief);
+ const baseline = itemCheckBaseline(board, item);
+ const missing = [];
+ if (!notes['named test']) missing.push('Named test: the case this check proves');
+ if (!baseline || baseline.result !== 'red' || baseline.command !== item.item_check || !baseline.main) missing.push('a recorded red check baseline at main (an absent named case counts)');
+ if (!notes.measurements) missing.push('Measurements: a method beside each quantitative bound, or an explicit statement that there are none');
+ if (!notes['reviewer edges']) missing.push('Reviewer edges: cases a reviewer should try');
+ if (!revision || revision.digest !== barDigest(item)) missing.push('a recorded current bar revision (edit the brief)');
+ const signed = read(board, `bar_sign:${item.item_id}`);
+ const baselineDigest = createHash('sha256').update(JSON.stringify(baseline)).digest('hex');
+ if (signature && (!signed || signed.revision !== revision?.revision || signed.digest !== revision?.digest || signed.baselineDigest !== baselineDigest)) missing.push('sign-off by another parent session: pullboard bar sign '+item.item_id);
+ return { revision, notes, baseline, baselineDigest, signed, missing };
+}
+/** The same board guard protects explicit claim, next, run, renew and submit. */
+export function barReadyProblem(board, item) {
+ if (!barReadinessRequired(board, item)) return null;
+ const status = barReadiness(board, item);
+ return status.missing.length ? new Refused('BAR_NOT_READY', `#${item.item_id}'s bar needs ${status.missing.join('; ')}; ask its author to edit the brief, then another session runs pullboard bar sign ${item.item_id}`) : null;
+}
+/** Record the peer's judgement against exact words, author identities and baseline observation. */
+export function signBar(board, id, { agentId, revision, digest, note }) {
+ return atomic(board, () => {
+ const item = itemById(board, id);
+ if (['verified','withdrawn'].includes(item.item_status)) throw new Refused('CLOSED', `#${id} is ${item.item_status}; sign an open bar`);
+ const status = barReadiness(board, item, { signature: false });
+ if (status.missing.length) throw new Refused('BAR_NOT_READY', `#${id} needs ${status.missing.join('; ')}; edit the brief or wait for its baseline before signing`);
+ if (status.revision.revision !== revision || status.revision.digest !== digest) throw new Refused('BAR_SIGN_STALE', `#${id}'s bar changed; read it again before pullboard bar sign ${id}`);
+ const signerParent = parent(board, agentId);
+ const authors = Object.values(status.revision.authors);
+ if (!signerParent || authors.some(author => !author.parent)) throw new Refused('BAR_PARENT_UNKNOWN', `#${id} needs known author and signer session identities; join from the real runtime session, then author a new bar revision`);
+ if (authors.some(author => author.agent === agentId || author.parent === signerParent)) throw new Refused('BAR_SELF_SIGN', `#${id}'s author and its helpers cannot sign their own bar; ask another parent session`);
+ if (typeof note !== 'string' || !note.trim()) throw new Refused('NOTE_REQUIRED', 'say whether a builder can meet this bar and two reviewers would grade it the same: --note "..."');
+ const signed = { revision, digest, baselineDigest: status.baselineDigest, authorParents: authors, signerParent, note: note.trim() };
+ logEvent(board, agentId, 'bar-sign', id, signed);
+ save(board, `bar_sign:${id}`, { ...signed, by: agentId, event: board.lastEvent.event_id });
+ return { id, ...signed };
+ });
+}
diff --git a/src/bar-ready-engine.js b/src/bar-ready-engine.js
new file mode 100644
index 00000000..d526a56c
--- /dev/null
+++ b/src/bar-ready-engine.js
@@ -0,0 +1,2 @@
+/** Ordered bar readiness, signing and activation [U113,H16]. */
+export const BAR_READY_ENGINE = 91;
diff --git a/src/board.js b/src/board.js
index 7365374e..f3784491 100644
--- a/src/board.js
+++ b/src/board.js
@@ -1,3 +1,7 @@
+import { recordBarRevision, barReadyProblem } from './bar-readiness.js';
+export { setBarReady, signBar } from './bar-readiness.js';
+import { coordinatorCheck, normalizeCheckBaseline, saveCheckBaseline, itemCheckBaseline } from './item-check-baseline.js';
+export { coordinatorCheck, completeCheckBaseline, itemCheckAuthor } from './item-check-baseline.js';
import { recordVerdict } from './verdict-assurance.js';
import { logEvent } from './board-event-log.js';
export { logEvent };
@@ -732,6 +736,7 @@ export function addItem(board, { by, lane, title, criterion = '', specIds = [],
const id = Number(result.lastInsertRowid);
saveCheckBaseline(board, id, baseline);
logEvent(board, by, 'add', id, { lane, specIds, after, route, ...(baseline ? { checkBaseline: baseline } : {}) });
+ recordBarRevision(board, itemById(board, id), by);
return id;
});
}
@@ -819,6 +824,7 @@ export function editItem(board, id, { agentId, brief, route, criterion, check, a
...(expiredHolder ? { expiredHolder } : {}),
...bar,
});
+ recordBarRevision(board, itemById(board, id), agentId, item);
if (pendingRefreeze) {
insertShout(board, {
from: COORDINATOR,
@@ -878,86 +884,6 @@ export function validateItemEdit(board, id, { agentId, brief, route, criterion,
return { item, next, command, unfreeze, bar: barCorrectionFields(board, item, next, { reason }) };
}
-/** Normalize an explicitly supplied check only when its author is the coordinator [V2]. */
-export function coordinatorCheck(agentId, command) {
- if (command === undefined) return undefined;
- if (agentId !== COORDINATOR) {
- throw new Refused('COORDINATOR_CHECK', 'only the coordinator sets or edits an item check; ask your coordinator to supply --check');
- }
- if (typeof command !== 'string') throw new Refused('BAD_CHECK', 'an item check is a command string; ask your coordinator to supply --check "<command>"');
- return command.trim();
-}
-
-/** Validate captured baseline data without asking a replica to run Git or a shell [V2,H16]. */
-function normalizeCheckBaseline(agentId, command, baseline) {
- if (baseline === undefined) return undefined;
- coordinatorCheck(agentId, command ?? '');
- if (!command || !baseline || typeof baseline !== 'object' || Array.isArray(baseline)
- || baseline.command !== command || !['green', 'red', 'unavailable', 'pending'].includes(baseline.result)
- || !(baseline.main === null || typeof baseline.main === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(baseline.main))
- || (baseline.result !== 'unavailable' && baseline.main === null)
- || (baseline.result === 'pending' && !baseline.request)
- || (baseline.request !== undefined && (typeof baseline.request !== 'string' || !/^[a-f0-9-]{36}$/.test(baseline.request)))
- || (baseline.reason !== undefined && typeof baseline.reason !== 'string')
- || (baseline.seconds !== undefined && (!Number.isSafeInteger(baseline.seconds) || baseline.seconds < 0))) {
- throw new Refused('BAD_CHECK_BASELINE', 'the check baseline must describe this command at a main commit; set --check again from the coordinator');
- }
- return {
- command, main: baseline.main, result: baseline.result,
- ...(baseline.request === undefined ? {} : { request: baseline.request }),
- ...(baseline.reason === undefined ? {} : { reason: baseline.reason }),
- ...(baseline.seconds === undefined ? {} : { seconds: baseline.seconds }),
- ...(baseline.result === 'green' ? { warning: 'CRITERION_PROVES_NOTHING' } : {}),
- };
-}
-
-/** Record a captured result only for the still-current authorized background request [V2,H16]. */
-export function completeCheckBaseline(board, id, { agentId, expected, baseline }) {
- return atomic(board, () => {
- const result = normalizeCheckBaseline(agentId, baseline?.command, baseline);
- if (!expected || !result || result.result === 'pending' || result.command !== expected.command || result.main !== expected.main
- || typeof expected.request !== 'string' || !/^[a-f0-9-]{36}$/.test(expected.request)) {
- throw new Refused('BAD_CHECK_BASELINE', 'a completed baseline must match its authorized request; set --check again from the coordinator');
- }
- const item = itemById(board, id);
- const current = itemCheckBaseline(board, item);
- if (current?.result !== 'pending' || current.request !== expected.request || current.command !== expected.command || current.main !== expected.main) return false;
- const recorded = { ...result, request: expected.request };
- saveCheckBaseline(board, id, recorded);
- logEvent(board, agentId, 'check-baseline', id, { checkBaseline: recorded });
- return true;
- });
-}
-
-/** Store or clear an item's observation atomically with its check and immutable audit event. */
-function saveCheckBaseline(board, id, baseline) {
- const key = `item_check_baseline_${id}`;
- if (!baseline) board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(key);
- else board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')
- .run(key, JSON.stringify(baseline));
-}
-
-/** Read an observation only when it still describes the item's current check command. */
-function itemCheckBaseline(board, item) {
- const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_check_baseline_${item.item_id}`);
- if (!row) return null;
- const baseline = JSON.parse(row.meta_value);
- return baseline.command === item.item_check ? baseline : null;
-}
-
-/** Read the current check's setter from immutable edits, or its original item author [V2]. */
-export function itemCheckAuthor(board, id) {
- const item = itemById(board, id);
- const edits = board.db.prepare("SELECT event_by, event_detail FROM event WHERE item_id = ? AND event_kind = 'edit' ORDER BY event_id DESC").all(id);
- for (const edit of edits) {
- let detail;
- try { detail = JSON.parse(edit.event_detail); }
- catch { return null; }
- if (detail && Object.hasOwn(detail, 'check')) return detail.check === item.item_check ? edit.event_by : null;
- }
- return item.item_created_by;
-}
-
/**
* The refusal codes src/machine.js declares for a guard of a move: the guard's own and any
* additional typed refusals, or for the state check, the move's.
@@ -1108,6 +1034,7 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null,
const item = moveItem(board, id, 'claim', {
checks: {
joined: null, checkProvesSomething: null,
+ barReady: found => barReadyProblem(board, found),
[IN_STATE]: (found) => new Refused('NOT_CLAIMABLE', `item #${id} is ${found.item_status}`),
inLane: (found) => {
if (found.item_lane === lane) return null;
@@ -1255,6 +1182,7 @@ export function submit(board, id, { agentId, commit, tree, files = [], policyCom
moveItem(board, id, 'submit', {
checks: {
joined: null, checkProvesSomething: null,
+ barReady: found => barReadyProblem(board, found),
[IN_STATE]: notYours,
isHolder: (found) => (found.item_owner === agentId ? null : notYours()),
correctionRefrozen: () => pendingRefreezeProblem(board, id),
diff --git a/src/cli.js b/src/cli.js
index 0bbf19fd..01a9e624 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -949,7 +949,7 @@ async function bindCheckoutSession(io, positionals, values) {
if (command === 'takeover' && (positionals.length !== 1 || Object.keys(values).some((key) => key !== 'json'))) {
throw new Refused('USAGE', 'pullboard takeover takes no arguments; run pullboard takeover [--json]');
}
- const writes = ['init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
+ const writes = ['bar', 'init', 'join', 'worktree', 'hooks', 'hook', 'skills', 'add', 'edit', 'fact', 'escalate', 'run', 'sweep',
'next', 'claim', 'hold', 'release', 'submit', 'done', 'verify', 'check', 'merged', 'land', 'withdraw', 'refreeze', 'reopen', 'shout', 'answer', 'pass', 'import', 'milestone', 'takeover', 'forget'];
if (!writes.includes(command) && !(command === 'lane' && first === 'add') && !(command === 'settings' && first) && !(command === 'spec' && first === 'apply') && !(command === 'relay' && ['on', 'off'].includes(first))) return;
if (command === 'answer' && values.as === 'person') return;
diff --git a/src/commands/bar.js b/src/commands/bar.js
new file mode 100644
index 00000000..b052f463
--- /dev/null
+++ b/src/commands/bar.js
@@ -0,0 +1,33 @@
+/** Inspect, enable and independently sign acceptance bars [U113]. */
+import { getItem } from '../board.js';
+import { barReadiness, barReadySetting } from '../bar-readiness.js';
+import { actOn, idArg, ordered } from '../cli.js';
+import { Refused } from '../refused.js';
+
+/** Run the board-scoped readiness setting or show/sign one exact revision. */
+export async function run(io, { first, second, rest, values }) {
+ return actOn(io, async (ctx, board, me) => {
+ if (first === 'ready') {
+ if (rest.length || second && !['on', 'off'].includes(second)) throw new Refused('USAGE', 'pullboard bar ready [on|off]');
+ const setting = second ? await ordered(ctx, board, 'setBarReady', [{ agentId: me.id, enabled: second === 'on' }]) : barReadySetting(board);
+ io.result?.({ barReady: setting });
+ io.say(`bar readiness ${setting.enabled ? 'on' : 'off'}; bars frozen before activation keep working until edited`);
+ return 0;
+ }
+ const sign = first === 'sign';
+ if (rest.length || !sign && second) throw new Refused('USAGE', 'pullboard bar <id> | sign <id> --note "can a builder meet it, and would two reviewers grade it the same?"');
+ const id = idArg(sign ? second : first);
+ const item = getItem(board, id);
+ const status = barReadiness(board, item, { signature: !sign });
+ if (!sign) {
+ io.result?.({ id, ...status });
+ io.say(status.missing.length ? `#${id} needs: ${status.missing.join('; ')}` : `#${id}'s bar is ready`);
+ return 0;
+ }
+ io.say(`Sign-off asks: can the builder meet this bar, and would two reviewers grade it the same? Check the named baseline, every measurement method, coverage and reviewer edges in pullboard show ${id}.`);
+ const signed = await ordered(ctx, board, 'signBar', [id, { agentId: me.id, revision: status.revision?.revision, digest: status.revision?.digest, note: values.note }]);
+ io.result?.({ signed });
+ io.say(`signed #${id} revision ${signed.revision}; any bar edit needs a fresh signature`);
+ return 0;
+ });
+}
diff --git a/src/engine.js b/src/engine.js
index be957778..0e684d44 100644
--- a/src/engine.js
+++ b/src/engine.js
@@ -1,3 +1,5 @@
+import { BAR_READY_ENGINE } from './bar-ready-engine.js';
+import { barReadySetting } from './bar-readiness.js';
/** Versioned, deterministic replay through the CLI's existing board engine [H3,H16]. */
import {
createHash,
@@ -70,11 +72,11 @@ import { LANDING_ENVIRONMENT_ENGINE } from './landing-environment-engine.js';
import { carriesLandingEnvironment } from './execution-environment.js';
import { LANDING_LEASE_ENGINE } from './landing-lease-engine.js';
-const ITEM_ID_FIRST_ARGUMENT = new Set(['acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);
+const ITEM_ID_FIRST_ARGUMENT = new Set(['signBar', 'acceptCheck', 'editItem', 'escalate', 'recordAttempt', 'claim', 'release', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze', 'reopen', 'appendFact']);
/** Only these public board operations may be requested by an encrypted move. */
export const ENGINE_OPERATIONS = Object.freeze([
- 'register', 'ensureCoordinator', 'addItem', 'editItem', 'completeCheckBaseline', 'escalate', 'recordAttempt',
+ 'setBarReady', 'signBar', 'register', 'ensureCoordinator', 'addItem', 'editItem', 'completeCheckBaseline', 'escalate', 'recordAttempt',
'claim', 'release', 'submit', 'reserveReview', 'reserveNextReview', 'verify', 'merged',
'withdraw', 'refreeze', 'reopen', 'shout', 'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold',
'addMilestone', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone',
@@ -90,6 +92,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 (['setBarReady', 'signBar'].includes(operation) || board && ['claim', 'submit', 'editItem', 'addItem', 'refreeze'].includes(operation) && barReadySetting(board).enabled) return BAR_READY_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/help.js b/src/help.js
index 0b3d19e8..df627348 100644
--- a/src/help.js
+++ b/src/help.js
@@ -121,6 +121,9 @@ Work
the command and its author print first; the project gate is pullboard gate
pullboard check accept <id> the person accepts an item's check that already passes on main, as it reads now;
with checks.provesNothing "hold", claim and submit refuse that item until then
+ pullboard bar ready on|off coordinator: opt in to ready bars; existing frozen work needs no backfill
+ pullboard bar sign <id> --note "..." another parent judges buildability and repeatable grading; edits clear the signature
+ pullboard bar <id> show missing prerequisites and the current revision
pullboard claim <id> take or renew a lease; the first claim freezes the criterion
pullboard release <id> [--note "why"] hand it back; a review release needs a one-line reason
pullboard submit <id> needs a clean tree, item check and affected tests green at HEAD (alias: done)
diff --git a/src/item-check-baseline.js b/src/item-check-baseline.js
new file mode 100644
index 00000000..99100460
--- /dev/null
+++ b/src/item-check-baseline.js
@@ -0,0 +1,85 @@
+/** Baseline observations and their immutable completion fences [V2,H16]. */
+import { atomic, itemById, logEvent } from './board.js';
+import { COORDINATOR } from './config.js';
+import { Refused } from './refused.js';
+
+/** Normalize an explicitly supplied check only when its author is the coordinator [V2]. */
+export function coordinatorCheck(agentId, command) {
+ if (command === undefined) return undefined;
+ if (agentId !== COORDINATOR) {
+ throw new Refused('COORDINATOR_CHECK', 'only the coordinator sets or edits an item check; ask your coordinator to supply --check');
+ }
+ if (typeof command !== 'string') throw new Refused('BAD_CHECK', 'an item check is a command string; ask your coordinator to supply --check "<command>"');
+ return command.trim();
+}
+
+/** Validate captured baseline data without asking a replica to run Git or a shell [V2,H16]. */
+export function normalizeCheckBaseline(agentId, command, baseline) {
+ if (baseline === undefined) return undefined;
+ coordinatorCheck(agentId, command ?? '');
+ if (!command || !baseline || typeof baseline !== 'object' || Array.isArray(baseline)
+ || baseline.command !== command || !['green', 'red', 'unavailable', 'pending'].includes(baseline.result)
+ || !(baseline.main === null || typeof baseline.main === 'string' && /^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(baseline.main))
+ || (baseline.result !== 'unavailable' && baseline.main === null)
+ || (baseline.result === 'pending' && !baseline.request)
+ || (baseline.request !== undefined && (typeof baseline.request !== 'string' || !/^[a-f0-9-]{36}$/.test(baseline.request)))
+ || (baseline.reason !== undefined && typeof baseline.reason !== 'string')
+ || (baseline.seconds !== undefined && (!Number.isSafeInteger(baseline.seconds) || baseline.seconds < 0))) {
+ throw new Refused('BAD_CHECK_BASELINE', 'the check baseline must describe this command at a main commit; set --check again from the coordinator');
+ }
+ return {
+ command, main: baseline.main, result: baseline.result,
+ ...(baseline.request === undefined ? {} : { request: baseline.request }),
+ ...(baseline.reason === undefined ? {} : { reason: baseline.reason }),
+ ...(baseline.seconds === undefined ? {} : { seconds: baseline.seconds }),
+ ...(baseline.result === 'green' ? { warning: 'CRITERION_PROVES_NOTHING' } : {}),
+ };
+}
+
+/** Record a captured result only for the still-current authorized background request [V2,H16]. */
+export function completeCheckBaseline(board, id, { agentId, expected, baseline }) {
+ return atomic(board, () => {
+ const result = normalizeCheckBaseline(agentId, baseline?.command, baseline);
+ if (!expected || !result || result.result === 'pending' || result.command !== expected.command || result.main !== expected.main
+ || typeof expected.request !== 'string' || !/^[a-f0-9-]{36}$/.test(expected.request)) {
+ throw new Refused('BAD_CHECK_BASELINE', 'a completed baseline must match its authorized request; set --check again from the coordinator');
+ }
+ const item = itemById(board, id);
+ const current = itemCheckBaseline(board, item);
+ if (current?.result !== 'pending' || current.request !== expected.request || current.command !== expected.command || current.main !== expected.main) return false;
+ const recorded = { ...result, request: expected.request };
+ saveCheckBaseline(board, id, recorded);
+ logEvent(board, agentId, 'check-baseline', id, { checkBaseline: recorded });
+ return true;
+ });
+}
+
+/** Store or clear an item's observation atomically with its check and immutable audit event. */
+export function saveCheckBaseline(board, id, baseline) {
+ const key = `item_check_baseline_${id}`;
+ if (!baseline) board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(key);
+ else board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?) ON CONFLICT(meta_key) DO UPDATE SET meta_value=excluded.meta_value')
+ .run(key, JSON.stringify(baseline));
+}
+
+/** Read an observation only when it still describes the item's current check command. */
+export function itemCheckBaseline(board, item) {
+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`item_check_baseline_${item.item_id}`);
+ if (!row) return null;
+ const baseline = JSON.parse(row.meta_value);
+ return baseline.command === item.item_check ? baseline : null;
+}
+
+/** Read the current check's setter from immutable edits, or its original item author [V2]. */
+export function itemCheckAuthor(board, id) {
+ const item = itemById(board, id);
+ const edits = board.db.prepare("SELECT event_by, event_detail FROM event WHERE item_id = ? AND event_kind = 'edit' ORDER BY event_id DESC").all(id);
+ for (const edit of edits) {
+ let detail;
+ try { detail = JSON.parse(edit.event_detail); }
+ catch { return null; }
+ if (detail && Object.hasOwn(detail, 'check')) return detail.check === item.item_check ? edit.event_by : null;
+ }
+ return item.item_created_by;
+}
+
diff --git a/src/machine.js b/src/machine.js
index 2aaa53de..d33decbb 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -182,6 +182,7 @@ export const GUARDS = [
{ id: 'doctrineHolds', refuse: 'RATCHET_ROSE', alsoRefuses: [{ code: 'RATCHET_UNCOUNTED', next: 'fix the check so it exits 0 or 1 within its timeout, then submit again' }], rule: "every touched doctrine check counts (exit 0 or 1), none rises above its committed count and no changed file gains a problem; watch-mode rules only count", next: "fix the new problems, commit, submit again; only the person's signature raises count:", source: 'cli', when: 'only when accepted main has an approved doctrine rule with gate: check' },
{ id: 'itemCheckGreen', refuse: 'CHECK_RED', alsoRefuses: [{ code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'CHECK_UNVERIFIED', next: 'restore the frozen install or check environment and retry' }, { code: 'GUARD_CANNOT_FAIL', next: 'reject: the check stays green with the named guard reverted' }, { code: 'GUARD_NOT_FOUND', next: 'the named guard is not in the submitted commit; ask the coordinator to fix it' }], rule: 'the frozen item check passes at the submitted commit, or its clean reviewed composition for a stale acceptance', next: 'reject the failing behavior; the builder fixes and resubmits', source: 'cli' },
+ { id: 'barReady', refuse: 'BAR_NOT_READY', rule: 'an opted-in new bar has a named red baseline, measurement notes, reviewer edges and a revision-bound signature from another parent session', next: 'the author completes the brief, then another parent runs pullboard bar sign <id>', source: 'board', when: 'bar ready is on and this bar was frozen or edited after activation' },
{ id: 'checkProvesSomething', refuse: 'CRITERION_PROVES_NOTHING', rule: "the item's check does not already pass on main, or the person accepted that exact check", next: 'set a check that fails before the work, or the person runs pullboard check accept <id>', source: 'cli', when: 'only when accepted main sets checks.provesNothing to "hold"' },
{ id: 'gateGreen', refuse: 'GATE_RED', alsoRefuses: [{ code: 'LAND_TIMEOUT_CUSTODY', next: 'inspect the saved timed gate cleanup state and stop only its proven owned processes before starting another landing' }, { code: 'LAND_GATE_OUTPUT', next: 'inspect the retained timed gate output directory and free disk space, then start another landing' }, { code: 'SLOT_DB_LOCKED', next: 'the run never started, so it is not a red; rerun the same command once the named process releases the slot database' }, { code: 'RUNNER_BROWSER_SLOT_REQUIRED', next: 'nothing to do: the run reruns on a local gate slot; if it repeats, set gate.browserByLaunch the same on this machine and that runner' }, { code: 'PIPEFAIL_UNAVAILABLE', next: 'rewrite the gate without a pipe' }], rule: 'the gate, which submit runs itself every time, is green at HEAD', next: 'fix what the digest names, commit, submit again', source: 'cli' },
{ id: 'queuedItemLease', refuse: 'ITEM_LEASE_LOST', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or restore a spec written for grammar 1, then retry' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main into this worktree, then renew the claim and retry' }, { code: 'NOT_A_REPO', next: 'restore the worktree Git metadata, then retry the command' }, { code: 'NO_CONFIG', next: 'restore pullboard.json in this worktree, then retry the command' }], rule: 'the caller still owns the same live item claim or review and can renew it against the frozen criterion', next: 'claim or reserve the item again before retrying the command', source: 'cli', when: 'while submit or an accept waits for a machine slot, and once immediately before admission' },
@@ -213,7 +214,7 @@ export const GUARDS = [
export const MOVES = [
{
verb: 'claim', from: ['open', 'claimed'], to: 'claimed', by: ['agent', 'coordinator'], refuse: 'NOT_CLAIMABLE',
- guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'builderFirstRefusal', 'correctionRefrozen', 'laneOpen', 'oneLiveClaim', 'rowsInForce'],
+ guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'barReady', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'builderFirstRefusal', 'correctionRefrozen', 'laneOpen', 'oneLiveClaim', 'rowsInForce'],
sets: ['item_owner', 'item_lease_until', 'item_frozen_digest'], command: 'pullboard claim <id>',
},
{
@@ -223,7 +224,7 @@ export const MOVES = [
{ verb: 'lapse', from: ['claimed'], to: 'open', by: ['clock'], guards: [], when: 'its lease runs out' },
{
verb: 'submit', from: ['claimed'], to: 'submitted', by: ['agent', 'coordinator'], refuse: 'NOT_YOURS',
- guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'checkProvesSomething', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'infraExplained', 'doctrineHolds', 'gateConfigured', 'queuedItemLease', 'gateGreen', 'treeStillDuringGate', 'submissionProofValid', 'childrenDone', 'headIsNew'],
+ guards: ['joined', 'itemExists', IN_STATE, 'isHolder', 'correctionRefrozen', 'checkProvesSomething', 'barReady', 'criterionUnchanged', 'treeClean', 'nothingUntracked', 'hasCommit', 'withinLane', 'trunkMergeClean', 'noUnverifiedStack', 'infraExplained', 'doctrineHolds', 'gateConfigured', 'queuedItemLease', 'gateGreen', 'treeStillDuringGate', 'submissionProofValid', 'childrenDone', 'headIsNew'],
sets: ['item_built_by', 'item_commit'], command: 'pullboard submit <id>',
},
{
diff --git a/src/relay-sender.js b/src/relay-sender.js
index 867b2784..9ade2052 100644
--- a/src/relay-sender.js
+++ b/src/relay-sender.js
@@ -10,11 +10,11 @@ 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 (['setBarReady', 'recordHealthFindings', 'recordFlakeObservation', 'recordGateRun', 'declareJob', 'recordJobRun', 'takeCoordinator', 'landingLeaseMove'].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;
- if (['acceptCheck', 'completeCheckBaseline', 'appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',
+ if (['signBar', 'acceptCheck', 'completeCheckBaseline', 'appendFact', 'editItem', 'escalate', 'recordAttempt', 'claim', 'submit', 'reserveReview', 'verify', 'merged', 'withdraw', 'refreeze',
'passDecision', 'answerDecision', 'holdLane', 'releaseLane', 'holdItem', 'releaseItemHold', 'reopen', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone'].includes(move.operation)) return args[1]?.agentId ?? null;
return null;
}
diff --git a/test/claim-reopen.test.js b/test/claim-reopen.test.js
index 323a5df0..25f252fa 100644
--- a/test/claim-reopen.test.js
+++ b/test/claim-reopen.test.js
@@ -10,6 +10,8 @@ import { submitFixture } from './board-submit-fixture.js';
import { configFromSource, defaults } from '../src/config.js';
import { prepareEngineMove, applyEngineMove } from '../src/engine.js';
import { exportBoard, importBoard } from '../src/exchange.js';
+import { barReadiness, barReadySetting, setBarReady, signBar } from '../src/bar-readiness.js';
+import { saveAgentSession, saveAgentParent } from '../src/seats.js';
const COMMIT = 'a'.repeat(40);
const TRUNK = 'b'.repeat(40);
@@ -183,3 +185,101 @@ test('[B13,B5,D1] a builder notice preserves the reopen cause that triggers rigo
assert.equal(store.events(f.board).filter(row => row.event_kind === 'rigor-notice' && JSON.parse(row.event_detail).cause === 'refusal:CHECK_RED').length, 1);
assert.equal(notices.filter(row => row.shout_to === f.builder && row.shout_text.includes('waits for you')).length, 2);
});
+
+/** Synthetic private fixture identities model real root/child registration, never a live board. */
+function readyAuthors(f) {
+ saveAgentSession(f.board, 'coordinator', 'a'.repeat(64));
+ saveAgentParent(f.board, f.builder, 'a'.repeat(64));
+ saveAgentSession(f.board, f.builder, 'b'.repeat(64));
+ saveAgentSession(f.board, f.other, 'c'.repeat(64));
+}
+/** Add an authored bar with its exact recorded baseline, as the ordered add operation receives it. */
+function readyItem(f, result = 'red') {
+ return store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'ready bar', route: 'mid',
+ criterion: 'the named behavior works', check: 'node --test --test-name-pattern "named witness" test/a.test.js',
+ checkBaseline: { command: 'node --test --test-name-pattern "named witness" test/a.test.js', main: COMMIT, result },
+ brief: 'Files: src/a.js\nTest: named witness asserts the behavior\nNamed test: named witness\nMeasurements: no quantitative acceptance bounds\nReviewer edges: empty input and concurrent edit' });
+}
+/** Sign the currently read revision, keeping stale requests independently testable. */
+function signReady(f, id, agentId = f.other) {
+ const { revision } = barReadiness(f.board, store.getItem(f.board, id));
+ return signBar(f.board, id, { agentId, revision: revision.revision, digest: revision.digest,
+ note: 'The builder can meet this bar; two reviewers can use the named witness and listed edges to grade it alike.' });
+}
+
+test('[U113,V1,H16] a claim waits for a bar signed by another session', (t) => {
+ const f = fixture(t);
+ readyAuthors(f);
+ setBarReady(f.board, { agentId: 'coordinator', enabled: true });
+ const id = readyItem(f);
+ assert.throws(() => claim(f, id, f.builder), error => error.code === 'BAR_NOT_READY' && error.message.includes('sign-off'));
+ assert.throws(() => signReady(f, id, 'coordinator'), error => error.code === 'BAR_SELF_SIGN');
+ assert.throws(() => signReady(f, id, f.builder), error => error.code === 'BAR_SELF_SIGN', 'a helper cannot sign its parent bar');
+ signReady(f, id);
+ claim(f, id, f.builder);
+ assert.equal(store.getItem(f.board, id).item_owner, f.builder);
+ const before = barReadiness(f.board, store.getItem(f.board, id)).revision;
+ store.editItem(f.board, id, { agentId: 'coordinator', brief: store.getItem(f.board, id).item_brief+'\nAlso try a restarted session.' });
+ assert.throws(() => claim(f, id, f.builder), error => error.code === 'BAR_NOT_READY');
+ assert.throws(() => signBar(f.board, id, { agentId: f.other, revision: before.revision, digest: before.digest, note: 'stale' }), error => error.code === 'BAR_SIGN_STALE');
+ signReady(f, id);
+ claim(f, id, f.builder);
+ const replica = store.openBoard(join(f.directory, 'ready-replica.sqlite'));
+ t.after(() => store.closeBoard(replica));
+ importBoard(replica, exportBoard(f.board));
+ assert.equal(barReadiness(replica, store.getItem(replica, id)).missing.length, 0);
+});
+
+test('[U113,H16] readiness is default off and activation preserves old frozen work', (t) => {
+ const f = fixture(t);
+ assert.equal(barReadySetting(f.board).enabled, false);
+ const old = readyItem(f, 'green');
+ claim(f, old, f.builder);
+ store.release(f.board, old, f.builder);
+ const activation = setBarReady(f.board, { agentId: 'coordinator', enabled: true });
+ assert.deepEqual(setBarReady(f.board, { agentId: 'coordinator', enabled: true }), activation, 'repeating on cannot grandfather new obligations');
+ claim(f, old, f.builder);
+ store.release(f.board, old, f.builder);
+ const fresh = readyItem(f, 'green');
+ assert.throws(() => claim(f, fresh, f.builder), error => error.code === 'BAR_NOT_READY' && error.message.includes('red check baseline'));
+ setBarReady(f.board, { agentId: 'coordinator', enabled: false });
+ claim(f, fresh, f.builder);
+ store.release(f.board, fresh, f.builder);
+ setBarReady(f.board, { agentId: 'coordinator', enabled: true });
+ claim(f, fresh, f.builder);
+ assert.throws(() => setBarReady(f.board, { agentId: f.other, enabled: false }), error => error.code === 'COORDINATOR_ONLY');
+});
+
+test('[U113,V2] all missing bar parts are named and content reversal cannot revive a signature', (t) => {
+ const f = fixture(t);
+ readyAuthors(f);
+ setBarReady(f.board, { agentId: 'coordinator', enabled: true });
+ const incomplete = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'incomplete' });
+ assert.throws(() => claim(f, incomplete, f.builder), error => error.code === 'BAR_NOT_READY'
+ && ['Named test', 'red check baseline', 'Measurements', 'Reviewer edges', 'sign-off'].every(part => error.message.includes(part)));
+ const id = readyItem(f);
+ signReady(f, id);
+ const original = store.getItem(f.board, id).item_brief;
+ store.editItem(f.board, id, { agentId: 'coordinator', brief: original+'\nChanged edge.' });
+ store.editItem(f.board, id, { agentId: 'coordinator', brief: original });
+ assert.throws(() => claim(f, id, f.builder), error => error.code === 'BAR_NOT_READY' && error.message.includes('sign-off'));
+ signReady(f, id);
+ claim(f, id, f.builder);
+});
+
+test('[U113,V1] unknown lineage and a changed baseline cannot masquerade as peer approval', (t) => {
+ const f = fixture(t);
+ setBarReady(f.board, { agentId: 'coordinator', enabled: true });
+ const id = readyItem(f);
+ assert.throws(() => signReady(f, id), error => error.code === 'BAR_PARENT_UNKNOWN');
+ readyAuthors(f);
+ // Re-authoring creates new known snapshots; it does not relabel the older unknown receipt.
+ const fresh = readyItem(f);
+ signReady(f, fresh);
+ const command = store.getItem(f.board, fresh).item_check;
+ const request = '12345678-1234-1234-1234-123456789abc';
+ store.editItem(f.board, fresh, { agentId: 'coordinator', check: command, checkBaseline: { command, main: COMMIT, result: 'pending', request } });
+ assert.ok(barReadiness(f.board, store.getItem(f.board, fresh)).missing.some(part => part.includes('red check baseline')));
+ store.completeCheckBaseline(f.board, fresh, { agentId: 'coordinator', expected: { command, main: COMMIT, request }, baseline: { command, main: COMMIT, result: 'red', request } });
+ assert.ok(barReadiness(f.board, store.getItem(f.board, fresh)).missing.some(part => part.includes('sign-off')), 'new baseline observation needs a new sign-off');
+});