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(spec): flag unconfirmed approved rows [S1,B26,P6]

Corey Olson61d43181194c
diff --git a/docs/api.md b/docs/api.md
index 672fb25b..1c67d8b0 100644
--- a/docs/api.md
+++ b/docs/api.md
@@ -584,3 +584,13 @@ A project may declare a `staticChecks` command in `pullboard.json` (empty by def
`pullboard sentinel propose <name> --check "<command>" --every 10m|hourly|daily --owner <seat or lane>` proposes a board row. Optional `--directory <relative path>`, `--timeout <milliseconds>` and `--next "<step>"` are part of the exact proposal. The directory defaults to this project, and must stay inside it; timeout defaults to 30000 ms and is a hang ceiling. The person approves or declines through the same person-channel guard as spec rows: `pullboard sentinel approve <name>` or `pullboard sentinel decline <name> --reason "<why>"`. An agent cannot approve. Any new command, directory, schedule, owner, timeout or next step needs fresh approval. No row in SPEC.md is edited.
An approved watch runs when due on `resume` and through the background view’s ordinary resume worker. The existing board and machine `health.sentinel: false` switches suppress it. Ordered run leases prevent duplicate concurrent observers. External checks run outside the database write lock, in the approved directory, with bounded final output and an owned-child timeout; recorded replay never executes a command. On POSIX hosts shutdown drains the owned process group; Windows uses direct-child termination. A failed check notifies its owner once with its name, final output and next step; staying red posts no duplicate, and recovery posts one cleared notice. Every red run remains a `sentinel:<name>` cause receipt for Rigor, without inventing a code change. Cancellation records its outcome without creating a failure or recovery notice. `pullboard sentinels --json` lists current rows, their owners, approval, latest result and current proposal’s run history. This is engine 56; earlier engines refuse the new moves before replay.
+
+## Approval provenance
+
+An `approved` status written directly into the Spec is reported as `agent-approved` until the exact row is backed by a person decision or a verified signed row-decision receipt. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
+
+`pullboard.json` accepts the existing `"spec": "SPEC.md"` form, or `"spec": {"file": "SPEC.md", "agentApproval": "flag"}`. `flag` is the default and keeps work moving; `allow` suppresses the outstanding approval call; explicit `refuse` prevents a new frozen citation of an unconfirmed row with `AGENT_APPROVAL_REQUIRED`.
+
+Board state adds `spec[].agentApproval` (or `null`), item `agentApproved` and `approvalQualification`, and `agent-approved` Needs-you calls carrying the available author and commit. Invalid receipt evidence remains unconfirmed and appears in `specApprovalEvidenceErrors`; it is never treated as an approval. The state cache and live watcher include receipt and signer-trust file bytes. Status JSON exposes the same calls and diagnostics.
+
+Verification output, current item detail and the ledger qualify affected accepted work as “verified against agent-approved <ids>”. A later confirmation clears the current qualification; it does not rewrite earlier acceptance receipts.
diff --git a/docs/formats.md b/docs/formats.md
index 5acb533f..dda6987a 100644
--- a/docs/formats.md
+++ b/docs/formats.md
@@ -113,7 +113,7 @@ The board file is in the repository's Git common directory at `.git/pullboard/bo
| `row grammar` | `1` | `SPEC_GRAMMAR_VERSION` in `src/spec.js`; optional `<!-- pullboard-grammar N -->` line in either file (absence means the current grammar) | Both files share the version. A declared version must match; an incompatible grammar change requires a coordinated version bump and compatible files. No automatic conversion occurs. |
| `board schema` | `2` | `SCHEMA_VERSION` in `src/board.js`, persisted as `PRAGMA user_version` | Create missing tables and indexes, add missing columns in place with declared defaults, restore missing or changed triggers, and remove stale machine triggers without replacing rows. |
| `event log` | `1` | `EVENT_LOG_VERSION` in `src/board.js`, persisted in `board_meta` as `event_log_version` | Older event-log versions upgrade in place; newer versions are refused with `EVENT_LOG_VERSION`. Preserve event rows when the board schema changes. |
-| `move engine` | `65` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |
+| `move engine` | `68` | `ENGINE_VERSION` in `src/machine.js`, carried as `engine` in every sealed executable move | Bump when a move's meaning changes, independently of the event log and sealed envelope. A newer engine is refused with `ENGINE_VERSION`, naming both versions and asking you to upgrade Pullboard. |
<!-- format-versions:end -->
Relay transport capability `apiVersion: 2` is independent of these versions and
@@ -484,3 +484,11 @@ Engine 43 (`RIGOR_NOTICE_ENGINE`) posts one coordinator shout and one typed `rig
A proved Rigor draft carries `source: rigor:<percent-encoded JSON>` with `version: 1`, its `key`, `evidence` (`items`, `occurrences`, `neverAgain`) and `proof` (`check`, `red`, `green`). The proof contains actual full commits, executed exit statuses and problem counts. The existing spec and doctrine row grammar reads this field; prose mentioning Rigor is not a typed source. The person uses ordinary Approve or Decline, and the coordinator applies the approved row without a new build item.
Engine 54 replaces the automatic strong-to-strong ceiling escalation with one coordinator notice per rejection pair, naming the builder and both rejection receipts. Ordinary rejection still reopens and clears the owner and lease. Light and mid routes keep engine-50 automatic escalation. Engines 50 through 53 retain their original ceiling escalation when replayed.
+
+## Approval provenance
+
+An `approved` status written directly into the Spec is reported as `agent-approved` until the exact row is backed by a person decision or a verified signed row-decision receipt. Git blame supplies the row's commit and author, labelled “Git author, seat unknown”; it never establishes person approval. `pullboard spec approve <id>` confirms the row and `spec decline <id> --reason "why"` declines it through the existing person channel. File application remains a coordinator step.
+
+`pullboard.json` accepts the existing `"spec": "SPEC.md"` form, or `"spec": {"file": "SPEC.md", "agentApproval": "flag"}`. `flag` is the default and keeps work moving; `allow` suppresses the outstanding approval call; explicit `refuse` prevents a new frozen citation of an unconfirmed row with `AGENT_APPROVAL_REQUIRED`.
+
+Engine 68 retains the existing validated verifier note in new acceptance-event detail. Earlier engines retain their original receipt shape; later person confirmations project current approval state beside that immutable history. No new row status or approval authority is inferred from a Git author or an unsigned receipt.
diff --git a/docs/lifecycle.md b/docs/lifecycle.md
index af1e0b1e..e6d60b08 100644
--- a/docs/lifecycle.md
+++ b/docs/lifecycle.md
@@ -53,7 +53,7 @@ Each move checks its guards in this order and refuses with the first one that do
| Move | From | To | Who | Guards, in order; result refusals |
| --- | --- | --- | --- | --- |
-| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
+| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED) |
| release | claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) |
| lapse | claimed | open | clock, when its lease runs out | none |
| submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |
@@ -62,8 +62,8 @@ Each move checks its guards in this order and refuses with the first one that do
| reject | submitted, verified | open | agent, coordinator | coordinatorSaysAs (MAIN_IS_COORDINATOR), joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), atSubmittedCommit (NOT_AT_COMMIT or OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), notMerged (ALREADY_MERGED), verdictReviewRecorded (BAD_VERDICT_REVIEW), reviewTreeCurrent (STALE_VERDICT or DIRTY or UNTRACKED or VERDICT_TRUNK_MOVED), notBuilder (SELF_VERIFY or VERIFIER_STANDING or SELF_SESSION_VERIFY), routeAllows (ROUTE), policyAllows (COORDINATOR_VERIFIES), familyAllows (O2_FAMILY_MATCH), reviewFree (REVIEW_HELD), criterionUnchanged (CRITERIA_CHANGED), reasonCoded (BAD_REASON), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), result (LAND_HEADER), result (ENGINE_VERSION), result (NOT_YOURS), result (CLOSED) |
| reopen | submitted, verified | open | coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_SUBMITTED), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), causeWellFormed (BAD_CAUSE), notMerged (ALREADY_MERGED), landingFailureRecorded (LANDING_FAILURE_REQUIRED), trunkConflicts (NOT_CONFLICTING or CONFLICT_FILES or NO_TRUNK or MERGE_CHECK_FAILED), conflictAccepted (NOT_ACCEPTED or BAD_CONFLICT or ENGINE_VERSION) |
| escalate | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED) |
-| refreeze | open, claimed, submitted | open | coordinator, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
-| refreeze | claimed | claimed | agent, coordinator, when a live claim has a pending coordinator correction | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN) |
+| refreeze | open, claimed, submitted | open | coordinator, when there is no live claim awaiting a coordinator correction | joined (NOT_JOINED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), itemExists (NO_ITEM), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED) |
+| refreeze | claimed | claimed | agent, coordinator, when a live claim has a pending coordinator correction | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), holderOrCoordinator (NOT_YOURS), inState (CLOSED), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED) |
| withdraw | open, claimed, submitted | withdrawn | coordinator | joined (NOT_JOINED or SESSION_LEDGER), coordinatorOnly (COORDINATOR_ONLY), noteGiven (NOTE_REQUIRED), itemExists (NO_ITEM), inState (CLOSED) |
## Required transition guards
@@ -109,6 +109,7 @@ Each move checks its guards in this order and refuses with the first one that do
| NO_POLICY | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | restore the committed coordinator policy |
| BAD_CONFIG | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | repair and commit the coordinator configuration |
| SPEC_BEHIND_MAIN | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | merge main from this worktree, then retry the claim |
+| AGENT_APPROVAL_REQUIRED | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | ask the coordinator to arrange the person’s confirmation or decline, or change the explicit refuse setting |
| CRITERIA_CHANGED | the criterion and the rows it cites read as they did at claim | the coordinator runs pullboard refreeze <id> |
| DIRTY | the worktree has no uncommitted changes | commit your changes, then submit |
| UNTRACKED | the worktree has no untracked files | commit or ignore them, then submit |
diff --git a/src/api.js b/src/api.js
index 50b943db..c51b5a1d 100644
--- a/src/api.js
+++ b/src/api.js
@@ -54,6 +54,7 @@ import {
projectFlowStats,
} from './stats-flow.js';
import { projectRowDecisions } from './row-decisions.js';
+import { projectSpecApprovals, specApprovalState } from './spec-approval.js';
import {
fitFile,
pendingFit,
@@ -90,6 +91,7 @@ function stateFileInputs(root, config) {
{ name: `spec:${config.spec}`, path: join(root, config.spec) },
{ name: `practice:${config.practice}`, path: join(root, config.practice) },
{ name: 'builtin:standard-doctrine.md', path: new URL('./standard-doctrine.md', import.meta.url) },
+ ...['signoffs.jsonl', 'signers', 'first-commit', 'signers.initial'].map(name => ({ name: `approval:${name}`, path: join(root, '.pullboard', name) })),
{ name: 'fit:blueprint-fit.json', path: fitFile(repoInfo(root).commonDir) },
];
}
@@ -476,7 +478,7 @@ function buildLocalBoardState(root, boardId, board, codeIsMain, { previous = nul
state.requests = projectData.requests;
state.personRequests = projectData.personRequests;
state.milestones = projectData.milestones;
- const decorated = projectFit(pendingFit(repoInfo(root).commonDir), projectRowDecisions(projectData.rowDecisions, state));
+ const decorated = projectSpecApprovals(projectFit(pendingFit(repoInfo(root).commonDir), projectRowDecisions(projectData.rowDecisions, state)), specApprovalState(root, { board, config }));
const bases = new Map(decorated.items.map((item) => [item.id, item]));
for (const id of dirtyIds) {
if (!currentById.has(id)) continue;
diff --git a/src/blueprint-set.js b/src/blueprint-set.js
index ed0fc29e..31e65a38 100644
--- a/src/blueprint-set.js
+++ b/src/blueprint-set.js
@@ -14,7 +14,7 @@ import {
bundledBlueprints,
readBlueprint,
} from './blueprints.js';
-import { CONFIG_FILE } from './config.js';
+import { CONFIG_FILE, configFromSource } from './config.js';
import { Refused } from './refused.js';
/**
@@ -46,7 +46,7 @@ export function blueprintSlot(blueprint) {
*/
export function installedBlueprints(root) {
let specFile = 'SPEC.md';
- try { specFile = JSON.parse(readFileSync(join(root, CONFIG_FILE), 'utf8')).spec ?? specFile; }
+ try { specFile = configFromSource(readFileSync(join(root, CONFIG_FILE), 'utf8')).spec; }
catch (error) {
// No pullboard.json yet, or one init will refuse on its own: the default spec file is read.
if (!(error instanceof SyntaxError) && error?.code !== 'ENOENT') throw error;
diff --git a/src/board.js b/src/board.js
index 3d8f786d..47358421 100644
--- a/src/board.js
+++ b/src/board.js
@@ -44,6 +44,7 @@ import {
storeTriggers,
} from './machine.js';
import { LOCAL_LANDING_ENGINE } from './land-engine.js';
+import { SPEC_APPROVAL_ENGINE } from './spec-approval-engine.js';
import { Refused } from './refused.js';
import { refuseMaskedExit } from './check-mask.js';
import {
@@ -1606,6 +1607,7 @@ export function verify(board, id, { agentId, decision, reason, note = '', cause,
set: (found) => ({ item_verdict: decision, item_verified_by: isAccept ? agentId : null, item_owner: isAccept ? found.item_owner : null }),
});
const detail = { reason: code, commit: item.item_commit, ...(!isAccept && cause !== undefined && cause !== null ? { cause } : {}) };
+ if (isAccept && engine >= SPEC_APPROVAL_ENGINE) detail.note = note.trim();
if (isAccept && check !== undefined) detail.check = check;
if (newReview) detail.review = { commit: review.commit, ...(Object.hasOwn(review, 'head') ? { head: review.head } : {}), trunk: review.trunk, paths: [...review.paths] };
logEvent(board, agentId, verb, id, implies?.length ? { ...detail, implies } : detail);
diff --git a/src/cli.js b/src/cli.js
index 74a18a5c..0e929657 100644
--- a/src/cli.js
+++ b/src/cli.js
@@ -212,6 +212,7 @@ import {
standings,
unmetRows,
} from './spec.js';
+import { refuseAgentApprovedRows } from './spec-approval.js';
import {
answerQuestion,
landBlueprint,
@@ -1039,6 +1040,7 @@ export function freezer(ctx, { captureVerifyPolicy = false, board } = {}) {
config = policy ? itemPolicy(ctx.info.root, { ...item, item_frozen: JSON.stringify({ policy }) }).config : ctx.config;
}
const doctrine = board ? agentDoctrine(ctx, board) : loadDoctrine(ctx.info.root, config);
+ if (board) refuseAgentApprovedRows(ctx.info.root, { board, config, item });
const frozen = frozenCriterion(loadSpec(ctx.info.root, config), item, doctrine);
if (!policy) return frozen; // Legacy criteria retain their original digest and committed claim base.
const text = JSON.stringify({ ...JSON.parse(frozen.text), policy });
diff --git a/src/commands/ledger.js b/src/commands/ledger.js
index a38b8bef..6842e155 100644
--- a/src/commands/ledger.js
+++ b/src/commands/ledger.js
@@ -1,5 +1,6 @@
/** The pullboard ledger command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
+import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';
import {
agentDisplayName,
context,
@@ -9,15 +10,17 @@ import {
/** Run `pullboard ledger` and return its exit code. */
export function run(io) {
const ctx = context(io);
- const { items, stats, agents } = withBoard(ctx, (board) => ({
+ const { items, stats, agents, approval } = withBoard(ctx, (board) => ({
items: store.listItems(board, { all: true }).map((item) => ({
...item,
check: store.verdictsFor(board, item.item_id).at(-1)?.check ?? 'unknown',
})),
stats: store.stats(board),
agents: store.listAgents(board),
+ approval: specApprovalState(ctx.info.root, { board, config: ctx.config }),
}));
- const built = items.filter((item) => item.item_built_by && item.item_status !== 'withdrawn').reverse();
+ const built = items.filter((item) => item.item_built_by && item.item_status !== 'withdrawn').reverse()
+ .map(item => ({ ...item, agentApproved: itemAgentApprovals(item, approval), approvalQualification: agentApprovalLine(itemAgentApprovals(item, approval)) }));
io.result?.({ items: built, stats });
const cell = (text) => String(text ?? '').replace(/\|/g, '/').replace(/\s+/g, ' ');
io.say(`${stats.items.verified} verified by a second agent · ${stats.items.submitted} awaiting verification · ${stats.rejected} rejection${stats.rejected === 1 ? '' : 's'} along the way`);
@@ -26,6 +29,7 @@ export function run(io) {
io.say('| --- | --- | --- | --- | --- | --- | --- | --- | --- |');
for (const item of built) {
io.say(`| ${item.item_id} | ${item.item_lane} | ${cell(item.item_title)} | ${cell(item.item_spec_ids)} | ${agentDisplayName(agents, ctx.config, item.item_built_by)} | ${agentDisplayName(agents, ctx.config, item.item_verified_by)} | ${item.check === 'none' ? 'unchecked' : item.check} | ${(item.item_commit ?? '').slice(0, 12)} | ${(item.item_merged_commit ?? '').slice(0, 12)} |`);
+ if (item.item_status === 'verified' && item.approvalQualification) io.say(` #${item.item_id}: ${item.approvalQualification}`);
}
return 0;
}
diff --git a/src/commands/show.js b/src/commands/show.js
index c83e18be..835b02f7 100644
--- a/src/commands/show.js
+++ b/src/commands/show.js
@@ -7,6 +7,7 @@ import {
barCorrections,
} from '../bar-corrections.js';
import * as store from '../board.js';
+import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';
import {
sayCheckBaseline,
} from '../check-baseline.js';
@@ -33,7 +34,7 @@ import {
export function run(io, { first, values }) {
const ctx = context(io);
const id = idArg(first);
- const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra } = withBoard(ctx, (board) => ({
+ const { item, verdicts, moves, thread, related, reviewer, agents, mainMerge, infra, approval } = withBoard(ctx, (board) => ({
item: verdictProjector(ctx.info.root, board).project(store.getItem(board, id)),
verdicts: store.verdictsFor(board, id),
moves: store.events(board, { itemId: id }).filter((event) => ['attempt', 'escalate'].includes(event.event_kind)),
@@ -41,13 +42,17 @@ export function run(io, { first, values }) {
related: store.relatedItems(board, store.getItem(board, id)),
reviewer: store.reviewHolder(board, store.getItem(board, id)),
agents: store.listAgents(board), mainMerge: mainMergeFor(board, id), infra: infraNotes.infraNoteOf(store.events(board, { itemId: id })),
+ approval: specApprovalState(ctx.info.root, { board, config: ctx.config }),
}));
const agentName = (id) => displayAgentName(agents.find((agent) => agent.agent_id === id) ?? { agent_id: id }, ctx.config.agents.names);
+ const agentApproved = itemAgentApprovals(item, approval);
+ const approvalQualification = agentApprovalLine(agentApproved);
if (values.json) {
- io.result({ ...item, verdicts, thread });
+ io.result({ ...item, verdicts, thread, agentApproved, approvalQualification });
return 0;
}
io.say(itemLine(item, agentName, Boolean(mainMerge)));
+ if (item.item_status === 'verified' && approvalQualification) io.say(approvalQualification);
if (item.item_verdict_state) io.say(staleVerdictRefusal(item, item.item_verdict_state).message);
if (item.item_criterion) io.say(`criterion: ${item.item_criterion}`);
if (item.item_check) io.say(`check: ${item.item_check}`);
diff --git a/src/commands/status.js b/src/commands/status.js
index e0d86af2..9081c0ac 100644
--- a/src/commands/status.js
+++ b/src/commands/status.js
@@ -1,5 +1,6 @@
/** The pullboard status command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
+import { personNeedsState } from '../needs-state.js';
import {
reviewQueueLine,
} from '../next-steps.js';
@@ -31,7 +32,8 @@ export function run(io, { values }) {
const summary = withBoard(ctx, (board) => {
const me = whoAmI(ctx, board);
const mine = store.listItems(board).filter((item) => item.item_status === 'claimed' && item.item_owner === me.id);
- return { me, mine, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),
+ const approvalState = personNeedsState(ctx.info.root, { board });
+ return { me, mine, needs: approvalState.needs, specApprovalEvidenceErrors: approvalState.specApprovalEvidenceErrors, stats: store.stats(board), reviewQueue: { ...store.reviewQueue(board), ...store.reviewQueueBreakdown(board) }, unread: store.unreadCount(board, me.id), relay: relayStatus(ctx.info.root),
submitInvariantProposals: submitInvariantProposals(store.events(board), ctx.config) };
});
if (values.json) {
@@ -45,6 +47,7 @@ export function run(io, { values }) {
io.say(`verdicts: ${accepted} accepted, ${rejected} rejected`);
io.say(reviewQueueLine(ctx, summary.reviewQueue, span));
for (const proposal of summary.submitInvariantProposals) io.say(submitInvariantLine(proposal));
+ for (const need of summary.needs.filter(need => need.kind === 'agent-approved')) io.say(`${need.text}; ${need.what}`);
if (Object.keys(ctx.config.products).length) {
const all = withBoard(ctx, (board) => store.listItems(board, { all: true }));
productSummaries(ctx.config, loadSpec(ctx.info.root, ctx.config), all).forEach((product) => io.say(productLine(product)));
diff --git a/src/commands/verify.js b/src/commands/verify.js
index 53e88e16..1730ec3d 100644
--- a/src/commands/verify.js
+++ b/src/commands/verify.js
@@ -1,5 +1,6 @@
/** The pullboard verify command, in its own module so an item adding another command never edits these lines. */
import * as store from '../board.js';
+import { agentApprovalLine, itemAgentApprovals, specApprovalState } from '../spec-approval.js';
import {
checkNeedsBrowser,
explicitCheckFiles,
@@ -91,6 +92,7 @@ export async function verifyHere(ctx, id, { second, values }) {
let verificationProfile = null;
let accepted = null;
let acceptedLandingCommit = null;
+ let approvalRows = [];
/** Record one verdict on the open board. */
const decide = async (board) => {
checkMainVerifier(ctx, board, values);
@@ -175,12 +177,14 @@ export async function verifyHere(ctx, id, { second, values }) {
refuseUnverifiedStack(root, board, item, checkedCommit, currentTrunk);
}
review ??= captureVerdictReview(root, board, item, verdictTrunk(root));
+ if (decision === 'ACCEPT') approvalRows = itemAgentApprovals(item, specApprovalState(root, { board, config: ctx.config }));
+ const approvalNote = agentApprovalLine(approvalRows);
if (decision === 'ACCEPT') git(root, ['update-ref', `refs/pullboard/items/${id}/${review.head.slice(0, 12)}`, review.head]);
return await ordered(ctx, board, 'verify', [id, {
agentId: me.id,
decision,
reason: values.reason,
- note: (textArg(ctx.io, values, 'note') ?? '') + unaffectedMove + (check?.guardNote ?? ''),
+ note: (textArg(ctx.io, values, 'note') ?? '') + unaffectedMove + (check?.guardNote ?? '') + (approvalNote ? `\n${approvalNote}` : ''),
...(decision === 'REJECT' && values.cause !== undefined ? { cause: values.cause } : {}),
head,
digest,
@@ -199,11 +203,11 @@ export async function verifyHere(ctx, id, { second, values }) {
}
return verdict;
});
- ctx.io.result?.({ id, ...result });
+ ctx.io.result?.({ id, ...result, ...(approvalRows.length ? { agentApproved: approvalRows, approvalQualification: agentApprovalLine(approvalRows) } : {}) });
const verifiedSummary = timingDigest(verificationProfile);
const verifiedTiming = result.decision === 'ACCEPT' && verificationProfile && verifiedSummary ? `\n${verifiedSummary}\ntiming profile: ${verificationProfile.profilePath ?? '(not saved)'}` : '';
ctx.io.say(result.decision === 'ACCEPT'
- ? `verified #${id}: ${result.reason}${result.check === 'none' ? '; no frozen check ran' : ''}${verifiedTiming}`
+ ? `verified #${id}: ${result.reason}${result.check === 'none' ? '; no frozen check ran' : ''}${approvalRows.length ? `; ${agentApprovalLine(approvalRows)}` : ''}${verifiedTiming}`
: `rejected #${id}: ${result.reason}; it is open again for rework`);
if (accepted) ctx.io.say(landNext(ctx.info, accepted, acceptedLandingCommit));
return 0;
diff --git a/src/config.js b/src/config.js
index 28302533..d8a563f2 100644
--- a/src/config.js
+++ b/src/config.js
@@ -97,9 +97,13 @@ export function durationMs(text, setting = 'lease') {
* @returns {object}
*/
function merge(base, raw) {
+ const spec = raw.spec && typeof raw.spec === 'object' && !Array.isArray(raw.spec) ? raw.spec : null;
+ if (spec && Object.keys(spec).some(key => !['file', 'agentApproval'].includes(key))) throw new Refused('BAD_CONFIG', '"spec" has only "file" and "agentApproval"');
return {
...base,
...raw,
+ spec: spec ? spec.file : raw.spec === undefined ? base.spec : raw.spec,
+ specAgentApproval: spec?.agentApproval === undefined ? 'flag' : spec.agentApproval,
commits: { ...base.commits, ...(raw.commits ?? {}) },
protect: { ...base.protect, ...(raw.protect ?? {}) },
verify: typeof raw.verify === 'string'
@@ -169,6 +173,7 @@ export function configProblems(config) {
}
}
if (typeof config.spec !== 'string' || !config.spec) problems.push('"spec" names a file');
+ if (config.specAgentApproval !== undefined && !['flag', 'allow', 'refuse'].includes(config.specAgentApproval)) problems.push('"spec.agentApproval" is flag, allow or refuse');
if (typeof config.practice !== 'string' || !config.practice) problems.push('"practice" names the doctrine file');
if (typeof config.gate !== 'string') problems.push('"gate" is a shell command, like "npm test"');
if (config.flakes !== undefined && (!config.flakes || typeof config.flakes !== 'object' || Array.isArray(config.flakes)
diff --git a/src/machine.js b/src/machine.js
index de81f194..f2d62ba6 100644
--- a/src/machine.js
+++ b/src/machine.js
@@ -165,7 +165,7 @@ export const GUARDS = [
{ id: 'itemNotHeld', refuse: 'ITEM_HELD', rule: 'the coordinator has not put this item on hold', next: 'the coordinator lifts it with pullboard hold <id> --off', source: 'board', when: 'unless the caller is renewing its own live claim' },
{ id: 'correctionRefrozen', refuse: 'PENDING_REFREEZE', rule: 'no coordinator correction to a claimed criterion or check is waiting to be frozen', next: 'pullboard refreeze <id>', source: 'board' },
{ id: 'oneLiveClaim', refuse: 'ONE_CLAIM', rule: 'the caller holds no other live top-level claim, reworks of its own rejected items aside', next: 'submit or release the other item first; child items are free', source: 'board' },
- { id: 'rowsInForce', refuse: 'UNKNOWN_SPEC', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or use a file written for grammar 1' }, { code: 'NO_POLICY', next: 'restore the committed coordinator policy' }, { code: 'BAD_CONFIG', next: 'repair and commit the coordinator configuration' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main from this worktree, then retry the claim' }], rule: 'every row the item cites exists and is in force', next: 'fix the spec, or the coordinator withdraws the item', source: 'board', when: 'only where the criterion freezes: claiming an item with no frozen criterion, and refreeze' },
+ { id: 'rowsInForce', refuse: 'UNKNOWN_SPEC', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or use a file written for grammar 1' }, { code: 'NO_POLICY', next: 'restore the committed coordinator policy' }, { code: 'BAD_CONFIG', next: 'repair and commit the coordinator configuration' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main from this worktree, then retry the claim' }, { code: 'AGENT_APPROVAL_REQUIRED', next: 'ask the coordinator to arrange the person’s confirmation or decline, or change the explicit refuse setting' }], rule: 'every row the item cites exists and is in force', next: 'fix the spec, or the coordinator withdraws the item', source: 'board', when: 'only where the criterion freezes: claiming an item with no frozen criterion, and refreeze' },
{ id: 'criterionUnchanged', refuse: 'CRITERIA_CHANGED', rule: 'the criterion and the rows it cites read as they did at claim', next: 'the coordinator runs pullboard refreeze <id>', source: 'cli' },
{ id: 'treeClean', refuse: 'DIRTY', rule: 'the worktree has no uncommitted changes', next: 'commit your changes, then submit', source: 'cli' },
{ id: 'nothingUntracked', refuse: 'UNTRACKED', rule: 'the worktree has no untracked files', next: 'commit or ignore them, then submit', source: 'cli' },
diff --git a/src/needs-state.js b/src/needs-state.js
index 00bd29ec..cd789416 100644
--- a/src/needs-state.js
+++ b/src/needs-state.js
@@ -16,6 +16,7 @@ import {
undraftedRigor,
} from './rigor-notices.js';
import { personNeeds } from './needs.js';
+import { projectSpecApprovals, specApprovalState } from './spec-approval.js';
import {
sentinelDraftNeeds,
sentinels,
@@ -27,8 +28,8 @@ export function personNeedsState(root, { board: providedBoard = null, includeRig
const board = providedBoard ?? { db: store.openBoardReadOnly(join(info.commonDir, 'pullboard', 'board.sqlite')) };
try {
const decisions = store.rowDecisions(board);
- const state = projectFit(pendingFit(info.commonDir), projectRowDecisions(decisions, projectState(root, { board })));
const config = loadConfig(root);
+ const state = projectSpecApprovals(projectFit(pendingFit(info.commonDir), projectRowDecisions(decisions, projectState(root, { board }))), specApprovalState(root, { board, config }));
const rows = projectRowDecisions(decisions, { root, spec: loadSpec(root, config).rows, practice: loadDoctrine(root, config).rows });
const rigorDrafts = rigorDraftNeeds(rows);
const projected = { ...state, rigorDrafts, sentinelDrafts: sentinelDraftNeeds(sentinels(board)), ...(includeRigorUndrafted
diff --git a/src/needs.js b/src/needs.js
index 93eafde1..08caf81c 100644
--- a/src/needs.js
+++ b/src/needs.js
@@ -17,6 +17,11 @@ export function personNeeds(state) {
ref: hold.hold_lane, text: hold.hold_reason, what: 'lane held by ' + name(hold.hold_by) })),
...rigorDrafts,
...(state.sentinelDrafts ?? []),
+ ...(state.spec ?? []).filter(row => row.agentApproval && row.agentApproval.mode !== 'allow' && row.decision?.decision !== 'decline').map(row => ({ kind: 'agent-approved', id: row.id,
+ ref: row.id, agent: row.agentApproval.agent, commit: row.agentApproval.commit, attribution: row.agentApproval.attribution,
+ text: `${row.id} is agent-approved; ${row.agentApproval.attribution}: ${row.agentApproval.agent}; commit ${row.agentApproval.commit ?? 'not committed'}`,
+ what: 'confirm or decline this row', target: `spec:${row.id}`,
+ actions: [{ verb: 'spec-approve', args: { ids: row.id } }, { verb: 'spec-decline', args: { ids: row.id } }] })),
...(drafts ? [{ kind: 'draft', id: 'drafts', count: drafts, ref: String(drafts),
text: 'draft spec rows to approve or drop' + rows.filter(row => row.staleDecision).map(row => `; ${row.stage}`).join(''), what: 'review in SPEC.md', target: 'tab:spec' }] : []),
];
diff --git a/src/spec-approval-engine.js b/src/spec-approval-engine.js
new file mode 100644
index 00000000..53481846
--- /dev/null
+++ b/src/spec-approval-engine.js
@@ -0,0 +1,2 @@
+/** Acceptance receipts retain their original verification note, including approval qualification [S1,H16]. */
+export const SPEC_APPROVAL_ENGINE = 68;
diff --git a/src/spec-approval.js b/src/spec-approval.js
new file mode 100644
index 00000000..e1c136f1
--- /dev/null
+++ b/src/spec-approval.js
@@ -0,0 +1,98 @@
+/** Approval provenance: a status word is not a person's decision [S1,B26,P6]. */
+import { readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import * as store from './board.js';
+import { tryGit } from './git.js';
+import { personNeeds } from './needs.js';
+import { Refused } from './refused.js';
+import { loadSpec, readSignoffs } from './spec.js';
+import { isVerifiedSignoff, verifyRowDecision } from './signature.js';
+
+/** Read each line's actual commit and Git author; neither identifies a person approval. */
+function rowOrigins(root, file) {
+ const result = tryGit(root, ['blame', '--line-porcelain', '--', file]);
+ const origins = new Map();
+ let line;
+ let commit;
+ let author = '';
+ for (const text of (result.status === 0 ? result.stdout : '').split('\n')) {
+ const header = /^([0-9a-f]{40,64}) \d+ (\d+)(?: \d+)?$/u.exec(text);
+ if (header) { commit = /^0+$/u.test(header[1]) ? null : header[1]; line = Number(header[2]); author = ''; }
+ else if (text.startsWith('author ')) author = text.slice(7);
+ else if (text.startsWith('\t') && line) origins.set(line, { commit, agent: author || 'unknown', attribution: 'Git author, seat unknown' });
+ }
+ return origins;
+}
+
+/** Match the exact current source, not just an id, a status word, or a Git author. */
+function matchesApproval(record, current) {
+ return record?.kind === 'spec' && record.id === current.row.id && record.file === current.file
+ && record.decision === 'approve' && record.text === current.row.text && record.replacement === current.source;
+}
+
+/** Read trustworthy receipts; an expected proof refusal leaves rows unconfirmed, never approved. */
+function approvalEvidence(root, evidenceErrors) {
+ try { return readSignoffs(root).filter(record => record.type === 'row-decision' && isVerifiedSignoff(record)); }
+ catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ evidenceErrors.push({ code: error.code, message: error.message });
+ return [];
+ }
+}
+
+/** Check a board decision against local trust without making invalid proof block flag-mode work. */
+function confirmedDecision(root, decision, evidenceErrors) {
+ try { verifyRowDecision(root, decision); return true; }
+ catch (error) {
+ if (!(error instanceof Refused)) throw error;
+ evidenceErrors.push({ id: decision.id, code: error.code, message: error.message });
+ return false;
+ }
+}
+
+/** Load one provenance view for a command; no observation here manufactures an approval event. */
+export function specApprovalState(root, { board, config, spec = loadSpec(root, config) }) {
+ if (spec.exists === false) return { mode: config.specAgentApproval ?? 'flag', rows: [] };
+ const source = readFileSync(join(root, config.spec), 'utf8').split(/\r?\n/u);
+ const decisions = store.rowDecisions(board).filter(record => record.kind === 'spec' && record.file === config.spec);
+ const evidenceErrors = [];
+ const signed = approvalEvidence(root, evidenceErrors);
+ const unconfirmed = spec.rows.filter(row => row.status === 'approved').filter(row => {
+ const current = { row, file: config.spec, source: source[row.line - 1] };
+ const decision = decisions.findLast(record => record.id === row.id);
+ if (decision) {
+ if (!matchesApproval(decision, current)) return true;
+ return !confirmedDecision(root, decision, evidenceErrors);
+ }
+ return !matchesApproval(signed.findLast(record => record.kind === 'spec' && record.file === config.spec && record.id === row.id), current);
+ });
+ const origins = unconfirmed.length ? rowOrigins(root, config.spec) : new Map();
+ return { mode: config.specAgentApproval ?? 'flag', evidenceErrors, rows: unconfirmed.map(row => ({ id: row.id, text: row.text, gate: row.gate,
+ status: 'agent-approved', ...(origins.get(row.line) ?? { commit: null, agent: 'unknown', attribution: 'Git author, seat unknown' }) })) };
+}
+
+/** Current unconfirmed citations for a raw board item or an API item projection. */
+export function itemAgentApprovals(item, approval) {
+ const ids = new Set(item.specs ?? (item.item_spec_ids ?? '').split(',').filter(Boolean));
+ return approval.rows.filter(row => ids.has(row.id));
+}
+
+/** Qualify engineering verification without suggesting the person's governing judgment was approved. */
+export function agentApprovalLine(rows) {
+ return rows.length ? `verified against agent-approved ${rows.map(row => row.id).join(', ')}` : '';
+}
+
+/** Project current confirmation beside immutable items and their historical receipts. */
+export function projectSpecApprovals(state, approval) {
+ const byId = new Map(approval.rows.map(row => [row.id, row]));
+ const projected = { ...state, specApprovalEvidenceErrors: approval.evidenceErrors ?? [], spec: state.spec.map(row => ({ ...row, agentApproval: byId.has(row.id) ? { ...byId.get(row.id), mode: approval.mode } : null })),
+ items: state.items?.map(item => ({ ...item, agentApproved: itemAgentApprovals(item, approval), approvalQualification: agentApprovalLine(itemAgentApprovals(item, approval)) })) };
+ return { ...projected, needs: personNeeds(projected) };
+}
+
+/** An explicit refuse setting blocks unconfirmed citations; flag and allow always keep work moving. */
+export function refuseAgentApprovedRows(root, { board, config, item }) {
+ if (config.specAgentApproval !== 'refuse') return;
+ const rows = itemAgentApprovals(item, specApprovalState(root, { board, config }));
+ if (rows.length) throw new Refused('AGENT_APPROVAL_REQUIRED', `${rows.map(row => row.id).join(', ')} is agent-approved and spec.agentApproval is refuse; ask the coordinator to arrange confirmation or decline in the Spec view`);
+}
diff --git a/test/machine.test.js b/test/machine.test.js
index af76bbcf..e53c72a5 100644
--- a/test/machine.test.js
+++ b/test/machine.test.js
@@ -118,6 +118,9 @@ const CAUGHT = {
'commands/submit.js#submitHere': ['native-flakes.js#observeFailure', 'cli.js#freezer', 'main-red.js#compareMainFailures', 'main-red.js#matchingReworks', 'doctrine-checks.js#checkRulesAt'],
// observeNativeFailure catches its optional pair/recording errors; they cannot become lifecycle refusals.
'commands/verify.js#verifyHere': ['cli.js#freezer', 'native-flakes.js#observeFailure'],
+ // Invalid approval evidence is data, not a lifecycle refusal; runtime controls keep it unconfirmed.
+ 'spec-approval.js#approvalEvidence': ['spec.js#readSignoffs'],
+ 'spec-approval.js#confirmedDecision': ['signature.js#verifyRowDecision'],
// Historical decline metadata is parsed inside a non-throwing boundary, covered by the Rigor history control.
'board.js#reopen': ['rigor-notices.js#declinedRigorSource'],
};
@@ -167,9 +170,10 @@ function functionsIn(source) {
* functions it calls, followed across imports and into the functions the CLI hands the board.
*
* @param {(file: string) => string} read - The source of a file in src/.
+ * @param {{ caught?: boolean }} [options] Honor explicit caller/callee catch boundaries for escaping codes.
* @returns {{ functions: (file: string) => string[], refusalsOf: (key: string, skip?: Set<string>) => Set<string> }}
*/
-function codeWalk(read) {
+function codeWalk(read, { caught = false } = {}) {
const files = new Map();
const load = (file) => {
if (!files.has(file)) {
@@ -201,7 +205,10 @@ function codeWalk(read) {
...[...body.matchAll(/(?<!\w)(?<!(?<!\.\.)\.)(\w+)\(/g)].map(([, callee]) => (bodies.has(callee) ? `${file}#${callee}` : named.get(callee) ?? CALLBACKS[file]?.[callee])),
...[...body.matchAll(/\b(\w+)\.(\w+)\(/g)].map(([, space, callee]) => (spaces.has(space) ? `${spaces.get(space)}#${callee}` : undefined)),
];
- for (const callee of callees.filter(Boolean)) for (const code of refusalsOf(callee, skip, seen)) codes.add(code);
+ for (const callee of callees.filter(Boolean)) {
+ if (caught && (CAUGHT[key] ?? []).includes(callee)) continue;
+ for (const code of refusalsOf(callee, skip, seen)) codes.add(code);
+ }
return codes;
};
return { functions: (file) => [...load(file).bodies.keys()], refusalsOf };
@@ -242,7 +249,7 @@ function declaredCodes(machine, verbs) {
* @returns {string[]}
*/
function codeProblems(machine, read = fromDisk) {
- const walk = codeWalk(read);
+ const walk = codeWalk(read, { caught: true });
const problems = new Set();
for (const { verbs, at } of ENTRY_POINTS) {
const declared = declaredCodes(machine, verbs);
@@ -503,6 +510,8 @@ test('a broken copy of the declaration fails the check against the code, both wa
assert.deepEqual(codeProblems(noRows).sort(), [
'A5_GRAMMAR_VERSION is raised by claim but not declared there',
'A5_GRAMMAR_VERSION is raised by refreeze but not declared there',
+ 'AGENT_APPROVAL_REQUIRED is raised by claim but not declared there',
+ 'AGENT_APPROVAL_REQUIRED is raised by refreeze but not declared there',
'BAD_CONFIG is raised by claim but not declared there',
'BAD_CONFIG is raised by refreeze but not declared there',
'NO_POLICY is raised by claim but not declared there',
@@ -531,6 +540,13 @@ test('a broken copy of the code fails the check: a refusal added wherever a move
'MOON_PHASE is raised by refreeze but not declared there',
], 'claim and refreeze let a freeze refusal through; submit and verify catch it');
+ const inProof = editedSource('spec-approval.js', /^function approvalEvidence\(root, evidenceErrors\) \{$/m, "$&\n if (!root) throw new Refused('MOON_PHASE', 'wait for the full moon');");
+ assert.deepEqual(codeProblems(MACHINE, inProof).sort(), [
+ 'MOON_PHASE is raised by accept and reject but not declared there',
+ 'MOON_PHASE is raised by claim but not declared there',
+ 'MOON_PHASE is raised by refreeze but not declared there',
+ ], 'only caught proof readers are excluded; a new guard inside their caller is still audited');
+
const inArrow = editedSource('route-escalation.js', /^export const canTake = .*$/m, "import { Refused } from './refused.js';\nexport const canTake = (agentRoute, itemRoute) => { if (!agentRoute) throw new Refused('NO_ROUTE', 'no route'); return ROUTES.indexOf(itemRoute) <= ROUTES.indexOf(agentRoute); };");
assert.deepEqual(codeProblems(MACHINE, inArrow).sort(), [
'NO_ROUTE is raised by accept and reject but not declared there',
diff --git a/test/spec-approval.test.js b/test/spec-approval.test.js
new file mode 100644
index 00000000..4a6f3d7d
--- /dev/null
+++ b/test/spec-approval.test.js
@@ -0,0 +1,259 @@
+/** Hand-written approval is visible without becoming a person's decision [S1,B26,P6]. */
+import assert from 'node:assert/strict';
+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { test } from 'node:test';
+import { createE2eHelpers } from './e2e-helpers.js';
+import { runFixtureChild } from './fixture-child.js';
+import { configFromSource } from '../src/config.js';
+import * as store from '../src/board.js';
+import { SPEC_APPROVAL_ENGINE } from '../src/spec-approval-engine.js';
+import { submitFixture } from './board-submit-fixture.js';
+
+/** Run the private project's real CLI and require its structured successful response. */
+function document(box, root, ...args) {
+ const result = box.run(root, ...args, '--json');
+ assert.equal(result.code, 0, `${result.out}\n${result.err}`);
+ return JSON.parse(result.out);
+}
+
+test('a row approved without a person move reads as agent-approved until the person confirms it [S1,B26,P6]', t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ // This normal fixture's setup commit writes approved rows, without any person row decision.
+ const box = helpers.project('true');
+ const sourceCommit = box.git(box.repo, 'rev-parse', 'HEAD');
+ const initial = document(box, box.repo, 'status');
+ const unconfirmed = (initial.needs ?? []).find(need => need.kind === 'agent-approved' && need.id === 'G1');
+ assert.ok(unconfirmed, 'an approved row with no person decision must appear in Needs you as agent-approved');
+ assert.equal(unconfirmed.commit, sourceCommit, 'the flag names the commit containing the unconfirmed row');
+ assert.ok(unconfirmed.agent, 'the available author attribution is shown, never inferred to be human approval');
+ assert.match(unconfirmed.text, /agent-approved/u);
+
+ const added = document(box, box.repo, 'add', 'web', 'Work on the unconfirmed requirement',
+ '--specs', 'G1', '--criterion', 'The fixture page exists.');
+ const id = added.item.item_id;
+ assert.equal(box.run(box.web, 'claim', String(id)).code, 0, 'the default flag does not block work');
+ mkdirSync(join(box.web, 'web'), { recursive: true });
+ writeFileSync(join(box.web, 'web/page.js'), 'export const page = true;\n');
+ box.git(box.web, 'add', 'web/page.js');
+ box.git(box.web, 'commit', '-q', '-m', 'feat(web): add the fixture page [G1]');
+ const commit = box.git(box.web, 'rev-parse', 'HEAD');
+ document(box, box.web, 'submit', String(id));
+ const review = join(box.dir, 'independent-review');
+ box.git(box.repo, 'worktree', 'add', '-q', '--detach', review, commit);
+ document(box, review, 'join', 'api');
+ const verified = box.run(review, 'verify', String(id), 'accept', '--note', 'The real fixture gate passed on the submitted commit.');
+ assert.equal(verified.code, 0, `${verified.out}\n${verified.err}`);
+ assert.match(verified.out, /verified against agent-approved G1/u);
+ const exported = document(box, box.repo, 'export');
+ const acceptance = exported.tables.event.findLast(event => event.item_id === id && event.event_kind === 'accept');
+ assert.ok(acceptance, 'the normal independent verification produced a receipt');
+ assert.match(acceptance.event_detail, /verified against agent-approved G1/u);
+ const ledger = box.run(box.repo, 'ledger');
+ assert.equal(ledger.code, 0, ledger.err);
+ assert.match(ledger.out, /verified against agent-approved G1/u);
+
+ // Only this isolated fixture simulates a marked agent and a separate ordinary person terminal.
+ const agent = runFixtureChild(process.execPath, [helpers.BIN, 'spec', 'approve', 'G1', '--json'], {
+ cwd: box.web, env: { ...box.env, CLAUDECODE: '1' }, encoding: 'utf8',
+ });
+ assert.equal(agent.status, 1);
+ assert.equal(JSON.parse(agent.stdout).error.code, 'B26_PERSON_CHANNEL', 'an agent cannot confirm its own approval');
+ document(box, box.repo, 'spec', 'approve', 'G1');
+ const confirmed = document(box, box.repo, 'status');
+ assert.equal((confirmed.needs ?? []).some(need => need.kind === 'agent-approved' && need.id === 'G1'), false,
+ 'one person decision confirms the exact row without a separate apply step');
+ const after = box.run(box.repo, 'ledger');
+ assert.equal(after.code, 0, after.err);
+ assert.doesNotMatch(after.out, /verified against agent-approved G1/u, 'the current ledger reflects the confirmation');
+ const kept = document(box, box.repo, 'export').tables.event.find(event => event.event_id === acceptance.event_id);
+ assert.equal(kept.event_detail, acceptance.event_detail, 'confirmation never rewrites the historical verification receipt');
+});
+
+test('agent approval settings preserve the filename form and reject ambiguous choices [S1,P6]', () => {
+ assert.equal(configFromSource('{}').specAgentApproval, 'flag');
+ assert.equal(configFromSource('{"spec":"requirements.md"}').spec, 'requirements.md');
+ for (const agentApproval of ['flag', 'allow', 'refuse']) {
+ const config = configFromSource(JSON.stringify({ spec: { file: 'requirements.md', agentApproval } }));
+ assert.equal(config.spec, 'requirements.md');
+ assert.equal(config.specAgentApproval, agentApproval);
+ }
+ for (const spec of [null, [], { file: 'SPEC.md', agentApproval: null }, { file: 'SPEC.md', agentApproval: 'trust' },
+ { file: 'SPEC.md', agentApproval: 'flag', agent: 'person' }]) {
+ assert.throws(() => configFromSource(JSON.stringify({ spec })), error => error.code === 'BAD_CONFIG');
+ }
+});
+
+test('allow suppresses approval calls and explicit refuse protects a new claim [S1,B26,P6]', t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ for (const mode of ['allow', 'refuse']) {
+ const box = helpers.project('true');
+ const file = join(box.repo, 'pullboard.json');
+ const config = JSON.parse(readFileSync(file, 'utf8'));
+ writeFileSync(file, JSON.stringify({ ...config, spec: { file: 'SPEC.md', agentApproval: mode } }, null, 2) + '\n');
+ box.git(box.repo, 'add', 'pullboard.json');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore(config): choose approval policy');
+ box.git(box.web, 'merge', '-q', '--ff-only', 'main');
+ const initial = document(box, box.repo, 'status');
+ assert.equal(initial.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), mode !== 'allow');
+ const id = document(box, box.repo, 'add', 'web', 'Policy-controlled fixture', '--specs', 'G1', '--criterion', 'A real fixture.').item.item_id;
+ const claimed = box.run(box.web, 'claim', String(id), '--json');
+ if (mode === 'allow') assert.equal(claimed.code, 0, `${claimed.out}\n${claimed.err}`);
+ else {
+ assert.equal(claimed.code, 1);
+ assert.equal(JSON.parse(claimed.out).error.code, 'AGENT_APPROVAL_REQUIRED');
+ document(box, box.repo, 'spec', 'approve', 'G1');
+ assert.equal(box.run(box.web, 'claim', String(id)).code, 0, 'the exact person decision unblocks an explicit refuse policy');
+ }
+ }
+});
+
+test('confirmation follows the exact row and an unsigned ledger cannot impersonate it [S1,S19,P6]', t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const before = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');
+ const line = before.split('\n').find(text => text.startsWith('- G1 '));
+ mkdirSync(join(box.repo, '.pullboard'), { recursive: true });
+ writeFileSync(join(box.repo, '.pullboard/signoffs.jsonl'), JSON.stringify({ version: 1, type: 'row-decision', kind: 'spec',
+ file: 'SPEC.md', id: 'G1', decision: 'approve', by: 'person', source: line, replacement: line, text: 'The page renders.' }) + '\n');
+ assert.ok(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'),
+ 'a hand-written unsigned receipt is not person approval');
+ document(box, box.repo, 'spec', 'approve', 'G1');
+ assert.equal(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false);
+ writeFileSync(join(box.repo, 'SPEC.md'), before.replace('The page renders.', 'The changed page renders.'));
+ const changed = document(box, box.repo, 'status').needs.find(need => need.kind === 'agent-approved' && need.id === 'G1');
+ assert.ok(changed, 'an approval of earlier wording cannot confirm a changed row');
+ assert.equal(changed.commit, null, 'uncommitted wording never borrows a committed row attribution');
+ document(box, box.repo, 'spec', 'approve', 'G1');
+ assert.equal(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false);
+});
+
+test('the actual API reports approval calls and accepts one person confirmation [A9,S1,P6]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const view = await helpers.startView(box, box.repo);
+ t.after(view.stop);
+ const before = (await view.state(box.repo)).project;
+ assert.ok(before.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'));
+ assert.equal(before.spec.find(row => row.id === 'G1').agentApproval.attribution, 'Git author, seat unknown');
+ const confirmed = await view.act(box.repo, { verb: 'spec-approve', args: { ids: 'G1' } });
+ assert.equal(confirmed.status, 200);
+ const after = (await view.state(box.repo)).project;
+ assert.equal(after.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false);
+ assert.equal(after.spec.find(row => row.id === 'G1').agentApproval, null);
+});
+
+test('a clone recognizes an exact signed approval without borrowing another board history [S19,S20,P6]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const key = join(box.dir, 'private-fixture-signing-key');
+ const made = runFixtureChild('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-f', key], { env: box.env, encoding: 'utf8' });
+ assert.equal(made.status, 0, made.failure ?? made.stderr);
+ box.git(box.repo, 'config', 'user.signingkey', key);
+ document(box, box.repo, 'spec', 'signers', 'add', '--key', key + '.pub', '--by', 'fixture-person');
+ const approved = document(box, box.repo, 'spec', 'approve', 'G1', '--by', 'fixture-person');
+ assert.ok(approved.decisions[0].signature, 'the fixture person produced an actual SSH signature');
+ document(box, box.repo, 'spec', 'apply');
+ box.git(box.repo, 'add', '-A');
+ box.git(box.repo, 'commit', '-q', '-m', 'chore(spec): preserve the signed approval');
+ const clone = join(box.dir, 'signed-clone');
+ box.git(box.repo, 'clone', '-q', box.repo, clone);
+ document(box, clone, 'init');
+ assert.equal(document(box, clone, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false,
+ 'a separate local board verifies the committed signed receipt');
+ const view = await helpers.startView(box, clone);
+ t.after(view.stop);
+ const before = (await view.state(clone)).project;
+ assert.equal(before.spec.find(row => row.id === 'G1').agentApproval, null);
+ const head = box.git(clone, 'rev-parse', 'HEAD');
+ const events = document(box, clone, 'export').tables.event;
+ const receiptFile = join(clone, '.pullboard/signoffs.jsonl');
+ const receipt = readFileSync(receiptFile, 'utf8');
+ rmSync(receiptFile);
+ const removed = (await view.state(clone)).project;
+ assert.ok(removed.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'),
+ 'removing only the proof file invalidates a cached confirmation');
+ writeFileSync(receiptFile, receipt);
+ assert.equal((await view.state(clone)).project.spec.find(row => row.id === 'G1').agentApproval, null,
+ 'restoring the exact verified proof confirms the row again');
+ const records = receipt.trimEnd().split('\n').map(line => JSON.parse(line));
+ const decision = records.find(record => record.type === 'row-decision' && record.id === 'G1');
+ assert.ok(decision);
+ decision.signature = 'invalid SSH signature';
+ writeFileSync(receiptFile, records.map(record => JSON.stringify(record)).join('\n') + '\n');
+ const invalid = (await view.state(clone)).project;
+ assert.ok(invalid.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'));
+ assert.equal(invalid.specApprovalEvidenceErrors[0].code, 'BAD_SIGNATURE');
+ writeFileSync(receiptFile, receipt);
+ assert.equal((await view.state(clone)).project.spec.find(row => row.id === 'G1').agentApproval, null);
+ assert.equal(box.git(clone, 'rev-parse', 'HEAD'), head, 'proof changes made no Git move');
+ assert.deepEqual(document(box, clone, 'export').tables.event, events, 'proof reads made no board event');
+ const source = readFileSync(join(clone, 'SPEC.md'), 'utf8');
+ writeFileSync(join(clone, 'SPEC.md'), source.replace('gate: web test', 'gate: web stricter-test'));
+ assert.ok(document(box, clone, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'),
+ 'a signed approval does not authorize different gate bytes');
+});
+
+test('approval projection leaves a board with no Spec readable [I10,S1,P6]', async t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ const id = document(box, box.repo, 'add', 'web', 'An item needs no spec rows').item.item_id;
+ rmSync(join(box.repo, 'SPEC.md'));
+ assert.equal(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved'), false);
+ assert.equal(document(box, box.repo, 'show', String(id)).agentApproved.length, 0);
+ assert.deepEqual(document(box, box.repo, 'ledger').items, []);
+ const view = await helpers.startView(box, box.repo);
+ t.after(view.stop);
+ const state = (await view.state(box.repo)).project;
+ assert.deepEqual(state.spec, []);
+ assert.equal(state.needs.some(need => need.kind === 'agent-approved'), false);
+});
+
+test('only new-engine acceptance receipts retain the verification note [H16,S1,P6]', t => {
+ const payloads = [];
+ const note = 'Fixture verification note; verified against agent-approved G1';
+ for (const version of [SPEC_APPROVAL_ENGINE - 1, SPEC_APPROVAL_ENGINE]) {
+ const board = store.openBoard(':memory:');
+ t.after(() => store.closeBoard(board));
+ const builder = store.register(board, { lane: 'web', path: '/fixture-builder', model: 'Fixture builder' });
+ const reviewer = store.register(board, { lane: 'review', path: '/fixture-reviewer', model: 'Fixture reviewer' });
+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Versioned receipt' });
+ const frozen = { text: JSON.stringify({ rows: [], policy: { version: 1, commit: 'a'.repeat(40), verify: { policy: 'any', family: 'off' } } }), digest: 'f'.repeat(64) };
+ store.claim(board, id, { agentId: builder, lane: 'web', leaseMs: 3_600_000, head: 'a'.repeat(40), freeze: () => frozen });
+ submitFixture(board, id, { agentId: builder, commit: 'b'.repeat(40), tree: 'c'.repeat(40) });
+ board.executionEngineVersion = version;
+ store.verify(board, id, { agentId: reviewer, decision: 'ACCEPT', note, head: 'b'.repeat(40), digest: frozen.digest,
+ policy: 'any', check: 'green', review: { commit: 'b'.repeat(40), head: 'b'.repeat(40), trunk: 'a'.repeat(40), paths: [] } });
+ const detail = JSON.parse(store.events(board, { itemId: id }).find(event => event.event_kind === 'accept').event_detail);
+ assert.equal(detail.note, version >= SPEC_APPROVAL_ENGINE ? note : undefined);
+ const { note: recorded, ...historical } = detail;
+ payloads.push(historical);
+ }
+ assert.deepEqual(payloads[0], payloads[1], 'every existing receipt field retains its earlier replay meaning');
+});
+
+
+test('malformed approval evidence stays unconfirmed without blocking default flag work [S1,B26,P6]', t => {
+ const helpers = createE2eHelpers();
+ t.after(helpers.cleanup);
+ const box = helpers.project('true');
+ document(box, box.repo, 'spec', 'approve', 'G1');
+ assert.equal(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), false);
+ mkdirSync(join(box.repo, '.pullboard'), { recursive: true });
+ document(box, box.repo, 'spec', 'decline', 'G2', '--reason', 'Not a governing requirement');
+ writeFileSync(join(box.repo, '.pullboard/signoffs.jsonl'), '{not valid JSON\n');
+ const status = document(box, box.repo, 'status');
+ assert.ok(status.needs.some(need => need.kind === 'agent-approved' && need.id === 'G1'), 'bad proof does not confirm even a board-held decision');
+ assert.ok(status.specApprovalEvidenceErrors.some(error => error.code === 'BAD_SIGNOFFS'));
+ assert.equal(document(box, box.repo, 'status').needs.some(need => need.kind === 'agent-approved' && need.id === 'G2'), false,
+ 'one person decline removes the outstanding approval call');
+ const id = document(box, box.repo, 'add', 'web', 'Default flag remains usable', '--specs', 'G1', '--criterion', 'A real fixture.').item.item_id;
+ // The malformed ledger is in the coordinator checkout; the builder independently sees an unconfirmed row.
+ assert.equal(box.run(box.web, 'claim', String(id)).code, 0);
+});