Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(spec): propose approved-row revisions [P6,B23,N39]
Corey Olsonfb00cb0e14aa
diff --git a/src/board.js b/src/board.jsindex 79f49d64..41ed5392 100644--- a/src/board.js+++ b/src/board.js@@ -186,6 +186,9 @@ import {} from './machine.js';import { LOCAL_LANDING_ENGINE } from './land-engine.js';import { SPEC_APPROVAL_ENGINE } from './spec-approval-engine.js';+import { SPEC_REVISION_ENGINE } from './spec-revision-engine.js';+import { validRevisionApproval } from './spec-revisions.js';+export { decideSpecRevisions } from './spec-revisions.js';import * as landingEnvironment from './landing-environment-guards.js';import { Refused } from './refused.js';import { saveJoinedSession } from './parent-session.js';@@ -2205,9 +2208,10 @@ export function recordRowDecisions(board, { agentId, channel, decisions }) {const validDeclineText = record.decision !== 'decline' || (engineVersion >= 12? record.text === original[0]?.text: target?.text === record.reason);- if (original.length !== 1 || original[0].id !== record.id || replacement.length !== 1 || target.id !== record.id+ const revision = record.revision !== undefined && engineVersion >= SPEC_REVISION_ENGINE && validRevisionApproval(board, record);+ if (!revision && (record.revision !== undefined || original.length !== 1 || original[0].id !== record.id || replacement.length !== 1 || target.id !== record.id|| target.status !== (record.decision === 'approve' ? 'approved' : 'wont') || target.text !== record.text- || !validDeclineText) throw new Refused('ROW_DECISION', 'the exact row must match its recorded approval or decline; use pullboard spec approve or decline');+ || !validDeclineText)) throw new Refused('ROW_DECISION', 'the exact row must match its recorded approval or decline; use pullboard spec approve or decline');const key = `${record.kind}:${record.id}`;if (keys.has(key)) throw new Refused('ROW_DECISION', `${key} is named twice; use each row once`);keys.add(key);diff --git a/src/cli-main.js b/src/cli-main.jsindex 0bad3f05..af99f380 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -38,6 +38,8 @@ const OPTIONS = {specs: { type: 'string' },parent: { type: 'string' },reason: { type: 'string' },+ revises: { type: 'string' },+ status: { type: 'string' },off: { type: 'boolean' },port: { type: 'string' },slots: { type: 'string' },diff --git a/src/commands/spec.js b/src/commands/spec.jsindex 5a1de7c6..93a5d1d3 100644--- a/src/commands/spec.js+++ b/src/commands/spec.js@@ -1,5 +1,9 @@/** The pullboard spec command, in its own module so an item adding another command never edits these lines. */import { planAutomaticRigorApply } from '../rigor-auto-apply.js';+import {+ planSpecRevision,+ prepareSpecRevisionDecisions,+} from '../spec-revisions.js';import {fitCommand,} from '../blueprint-fit-command.js';@@ -133,7 +137,7 @@ export async function specCommand(io, { first, second, rest, values }) {unmet: ['must'],signoff: ['by', 'note', 'note-file'],signers: ['key', 'by'],- draft: ['aim', 'gate', 'section', 'doctrine', 'source'],+ draft: ['aim', 'gate', 'section', 'doctrine', 'source', 'revises', 'reason', 'status'],approve: ['by', 'text'],decline: ['reason'],answer: [],@@ -165,6 +169,18 @@ export async function specCommand(io, { first, second, rest, values }) {if (values.gate !== undefined && (!values.gate.trim() || /[\r\n|]/u.test(values.gate))) {throw new Refused('USAGE', 'give one nonempty, single-line gate without a field separator, or omit --gate to use review');}+ if (values.revises !== undefined) {+ if (values.doctrine || values.aim || values.section || values.source) throw new Refused('FLAG_NOT_ALLOWED', 'a revision keeps the approved row\'s section and tier; use --revises with text, --gate, --status and --reason');+ const drafts = hookRead(ctx, board => store.rowDrafts(board)) ?? [];+ const row = planSpecRevision(ctx.info.root, ctx.config, { revises: values.revises, text: second.trim(),+ gate: values.gate?.trim(), status: values.status, reason: values.reason,+ taken: [...drafts.map(draft => draft.id), ...trunkRowIds(ctx.info.root, primaryCheckoutRoot(ctx.info), ctx.config)] });+ const entry = await reserveRow(ctx, row, false);+ io.result?.({ id: entry.id, row: entry });+ io.say(entry.id);+ return 0;+ }+ if (values.status !== undefined || values.reason !== undefined) throw new Refused('FLAG_NOT_ALLOWED', '--status and --reason belong to spec draft --revises <id>');if (values.doctrine) {if (typeof values.source !== 'string' || !values.source.trim() || /[\r\n|]/u.test(values.source)) {throw new Refused('USAGE', 'a doctrine ruling needs its source; give --source "shout 42" or --source "chat, 2026-10-16"');@@ -195,6 +211,17 @@ export async function specCommand(io, { first, second, rest, values }) {const me = whoAmI(ctx, board);if (!ctx.info.isMain || me.id !== COORDINATOR) throw new Refused('B26_PERSON_APPROVAL', 'only the person from the main checkout approves or declines rows; use pullboard view for the person to decide');const ids = [second, ...rest].filter(Boolean).flatMap((text) => text.split(/[\s,]+/u)).filter(Boolean);+ const drafts = store.rowDrafts(board);+ const revisionIds = ids.filter(id => drafts.some(draft => draft.id === id && draft.revises));+ if (revisionIds.length) {+ if (revisionIds.length !== ids.length || values.text !== undefined) throw new Refused('SPEC_REVISION', 'decide exact revision proposals separately; draft a new proposal to change its text');+ const records = prepareSpecRevisionDecisions(ctx.info.root, ctx.config, drafts, { ids, decision: first,+ reason: values.reason, by: values.by, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' });+ const decisions = await ordered(ctx, board, 'decideSpecRevisions', [{ agentId: store.PERSON, channel: io.personChannel ?? 'terminal', decisions: records }]);+ io.result?.({ decisions });+ revisionIds.forEach(id => io.say(`${id}: ${first === 'approve' ? 'approved, pending apply' : 'declined; approved row unchanged'}`));+ return 0;+ }// An approve keeps a pending answer: plain, it approves the answered text; --text says what it replaces.const kept = first === 'approve' ? pendingAnswers(ctx.info.root, ctx.config, ids, store.rowDecisions(board)) : new Map();const decide = { decision: first, reason: values.reason, by: values.by, on: new Date().toISOString(), commit: headCommit(ctx.info.root) ?? '' };diff --git a/src/help.js b/src/help.jsindex 0bf71342..8e47dd14 100644--- a/src/help.js+++ b/src/help.js@@ -242,6 +242,7 @@ Specpullboard spec show <id> | unmet [--must] | signoff <ids> [--by <principal>]signoff: --note "what was checked" stays with the receiptpullboard spec draft <text> [--section <letter>] [--aim] [--gate "<gate>"] any agent appends a draft row; never approves it+ pullboard spec draft <text> --revises <id> --reason "why" [--gate "<gate>"] [--status <status>] propose an approved-row change in Needs you[--doctrine --source "<shout id or chat, date>"] the coordinator proposes a sourced doctrine ruling--section chooses the section prefix; defaults to G, or DR with --doctrineDefaults to must and gate review.diff --git a/src/moves/decideSpecRevisions.js b/src/moves/decideSpecRevisions.jsnew file mode 100644index 00000000..88e34106--- /dev/null+++ b/src/moves/decideSpecRevisions.js@@ -0,0 +1,20 @@+/** A new person-only revision disposition cannot be replayed by an older reader [P6,H16]. */+import { SPEC_REVISION_ENGINE } from '../spec-revision-engine.js';+import { LANDING_LEASE_ENGINE } from '../landing-lease-engine.js';+import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';+import { BOARD_SENTINEL_ENGINE } from '../sentinel-engine.js';++/** Retain every applicable surrounding operation floor, including overlapping payload features. */+function minimumEngine(args) {+ return Math.max(SPEC_REVISION_ENGINE, args[0]?.landingFence === undefined ? 0 : LANDING_LEASE_ENGINE,+ args[1]?.cause?.startsWith('conflict:') ? RIGOR_AUTO_ENGINE : 0,+ args[1]?.cause?.startsWith('sentinel:') ? BOARD_SENTINEL_ENGINE : 0);+}++/** The operation's first argument carries its authenticated person actor. */+function actor(move) { return move.args[0]?.agentId ?? null; }++export default Object.freeze({ operation: 'decideSpecRevisions', engine: SPEC_REVISION_ENGINE,+ itemIdFirstArgument: false, minimumEngine, actor,+ nextSteps: Object.freeze({ SPEC_REVISION: 'refresh Needs you and decide the exact pending proposal',+ B26_PERSON_APPROVAL: 'ask the person to decide in pullboard view' }) });diff --git a/src/moves/draftSpecRow.js b/src/moves/draftSpecRow.jsindex ae1320e1..471c8b33 100644--- a/src/moves/draftSpecRow.js+++ b/src/moves/draftSpecRow.js@@ -3,9 +3,14 @@ import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';import { ROW_DRAFT_ENGINE } from '../engine-metadata.js';import { LANDING_LEASE_ENGINE } from '../landing-lease-engine.js';import { BOARD_SENTINEL_ENGINE } from '../sentinel-engine.js';+import { SPEC_REVISION_ENGINE } from '../spec-revision-engine.js';/** Preserve this operation's historical first-matching engine conditions [H16]. */function minimumEngine(args, board, at) {+ if (args[0]?.row?.revises !== undefined) return Math.max(SPEC_REVISION_ENGINE, ROW_DRAFT_ENGINE,+ args[0]?.landingFence === undefined ? 0 : LANDING_LEASE_ENGINE,+ args[1]?.cause?.startsWith('conflict:') ? RIGOR_AUTO_ENGINE : 0,+ args[1]?.cause?.startsWith('sentinel:') ? BOARD_SENTINEL_ENGINE : 0);if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('conflict:')) return RIGOR_AUTO_ENGINE;if (args[0]?.landingFence !== undefined) return LANDING_LEASE_ENGINE;if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;diff --git a/src/moves/recordRowDecisions.js b/src/moves/recordRowDecisions.jsindex 2dbb9832..09191939 100644--- a/src/moves/recordRowDecisions.js+++ b/src/moves/recordRowDecisions.js@@ -2,9 +2,14 @@ import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';/** Routing metadata owned by recordRowDecisions, discovered without a shared registry edit [C7,V4,H16]. */import { LANDING_LEASE_ENGINE } from '../landing-lease-engine.js';import { BOARD_SENTINEL_ENGINE } from '../sentinel-engine.js';+import { SPEC_REVISION_ENGINE } from '../spec-revision-engine.js';/** Preserve this operation's historical first-matching engine conditions [H16]. */function minimumEngine(args, board, at) {+ if (args[0]?.decisions?.some(record => record.revision !== undefined)) return Math.max(SPEC_REVISION_ENGINE,+ args[0]?.landingFence === undefined ? 0 : LANDING_LEASE_ENGINE,+ args[1]?.cause?.startsWith('conflict:') ? RIGOR_AUTO_ENGINE : 0,+ args[1]?.cause?.startsWith('sentinel:') ? BOARD_SENTINEL_ENGINE : 0);if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('conflict:')) return RIGOR_AUTO_ENGINE;if (args[0]?.landingFence !== undefined) return LANDING_LEASE_ENGINE;if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:')) return BOARD_SENTINEL_ENGINE;diff --git a/src/needs-state.js b/src/needs-state.jsindex a5c1868a..92067dab 100644--- a/src/needs-state.js+++ b/src/needs-state.js@@ -4,6 +4,7 @@ import { join } from 'node:path';import * as store from './board.js';import { repoInfo } from './git.js';import { projectRowDecisions } from './row-decisions.js';+import { projectSpecRevisions } from './spec-revisions.js';import {pendingFit,projectFit,@@ -38,8 +39,8 @@ export function personNeedsState(root, { board: providedBoard = null, includeRigconst drafts = store.rowDrafts(board);const rigorDrafts = rigorDraftNeeds(rows, drafts, decisions);const rigor = includeRigorUndrafted ? resumeRigorCounters(board, rows, { person: store.PERSON, drafts, decisions }) : null;- const projected = { ...state, rigorDrafts, sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(info.commonDir, board), ...(includeRigorUndrafted- ? { rigorUndrafted: rigor.causes, rigorNotice: rigor.notice } : {}) };+ const projected = projectSpecRevisions({ ...state, rigorDrafts, sentinelDrafts: sentinelDraftNeeds(sentinels(board)), blocks: recentBlocks(info.commonDir, board), ...(includeRigorUndrafted+ ? { rigorUndrafted: rigor.causes, rigorNotice: rigor.notice } : {}) }, drafts, decisions);return { ...projected, needs: personNeeds(projected) };} finally {if (!providedBoard) store.closeBoard(board);diff --git a/src/needs.js b/src/needs.jsindex 2886ba96..988fe977 100644--- a/src/needs.js+++ b/src/needs.js@@ -30,6 +30,12 @@ export function personNeeds(state) {...(state.holds ?? []).map(hold => ({ kind: 'hold', id: hold.hold_lane,ref: hold.hold_lane, text: hold.hold_reason, what: 'lane held by ' + name(hold.hold_by) })),...rigorDrafts,+ ...(state.specRevisions ?? []).map(revision => ({ kind: 'spec-revision', id: revision.id,+ ref: `${revision.id} revises ${revision.revises}`, text: `${revision.reason}\nOld: ${revision.source}\nNew: ${revision.replacement}`,+ old: revision.old, proposed: revision.proposed, source: revision.source, replacement: revision.replacement,+ reason: revision.reason, what: revision.decision === 'approve' ? 'approved; pending spec apply' : 'approve or decline revision',+ target: `spec-revision:${revision.id}`, actions: revision.decision ? [] : [+ { verb: 'spec-approve', args: { ids: revision.id } }, { verb: 'spec-decline', args: { ids: revision.id } }] })),...(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,diff --git a/src/recorded-move.js b/src/recorded-move.jsindex 52a13f05..187175dd 100644--- a/src/recorded-move.js+++ b/src/recorded-move.js@@ -31,7 +31,7 @@ export function requestedCommandMove(command, operation) {shout: ['shout'], answer: ['answerDecision'], pass: ['passDecision'], fact: ['appendFact'],hold: ['holdLane', 'releaseLane', 'holdItem', 'releaseItemHold'],bar: ['setBarReady', 'signBar'], settings: ['setLineSetting', 'setPersonSigning'], check: ['acceptCheck'],- spec: ['recordRowDecisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'editItem', 'withdraw'],+ spec: ['recordRowDecisions', 'decideSpecRevisions', 'applyRowDecisions', 'draftSpecRow', 'appendFact', 'editItem', 'withdraw'],blueprint: ['draftSpecRow', 'addItem', 'appendFact'], rigor: ['draftSpecRow', 'proposeSentinel'], sweep: ['addItem'],milestone: ['addMilestone', 'editMilestoneItems', 'orderMilestoneItems', 'moveMilestone', 'editMilestone', 'removeMilestone', 'shipMilestone'],land: ['recordLandingBatch', 'recordLandingWaiver', 'finishLandingBatch'],diff --git a/src/relay-outbox.js b/src/relay-outbox.jsindex 6fc35d50..aee9e3e8 100644--- a/src/relay-outbox.js+++ b/src/relay-outbox.js@@ -162,7 +162,7 @@ export const ITEM_SLOTS = Object.freeze({recordPublishFinding: [[0, 'item']],register: [], ensureCoordinator: [], shout: [], passDecision: [], holdLane: [], releaseLane: [],moveMilestone: [], editMilestone: [], removeMilestone: [], shipMilestone: [],- recordRowDecisions: [], applyRowDecisions: [], draftSpecRow: [], recordSpecApprovalBaseline: [],+ recordRowDecisions: [], decideSpecRevisions: [], applyRowDecisions: [], draftSpecRow: [], recordSpecApprovalBaseline: [],recordLandingBatch: [], recordLandingWaiver: [], recordLandingFlake: [], recordLandingTestDefect: [], finishLandingBatch: [],recordHealthFindings: [], decideSentinel: [], beginSentinelRun: [], finishSentinelRun: [],recordFlakeObservation: [], recordGateRun: [], declareJob: [], recordJobRun: [], takeCoordinator: [], openHandoff: [], landingLeaseMove: [],diff --git a/src/relay-requests.js b/src/relay-requests.jsindex be8536ae..da9df6c0 100644--- a/src/relay-requests.js+++ b/src/relay-requests.js@@ -135,7 +135,7 @@ function fulfilsIntent(record, move) {const rows = value?.decisions;const ids = args.ids.split(/[\s,]+/u).filter(Boolean);return value?.agentId === 'person' && value.channel === 'view' && Array.isArray(rows) && rows.length === ids.length- && rows.every((row, index) => (row.kind === 'doctrine' ? 'doctrine:' : '') + row.id === ids[index]+ && rows.every((row, index) => (move.operation === 'decideSpecRevisions' ? row.revision?.proposal : (row.kind === 'doctrine' ? 'doctrine:' : '') + row.id) === ids[index]&& row.decision === (intent.verb === 'spec-approve' ? 'approve' : 'decline')&& (intent.verb !== 'spec-decline' || row.reason === args.reason.trim())&& (args.text === undefined || row.text === args.text.trim()));@@ -197,7 +197,8 @@ export function requestMoveProblem(board, move, { checkExecutorLease = true } =if (!['coordinator', 'person'].includes(actor)) return new Refused('PERSON_REQUEST_RECEIPT', 'only the coordinator fulfils an authenticated person request');if (tag.phase === 'execute') {const expected = { add: 'addItem', shout: 'shout', answer: 'answerDecision', hold: record.move.args.off ? 'releaseLane' : 'holdLane', 'spec-approve': 'recordRowDecisions', 'spec-decline': 'recordRowDecisions', 'sentinel-approve': 'decideSentinel', 'sentinel-decline': 'decideSentinel' }[record.move.verb];- if (move.operation !== expected || !fulfilsIntent(record, move)) return new Refused('PERSON_REQUEST_RECEIPT', 'the ordinary move does not fulfil this request; execute its original CLI intent');+ const revision = ['spec-approve', 'spec-decline'].includes(record.move.verb) && move.operation === 'decideSpecRevisions';+ if ((!revision && move.operation !== expected) || !fulfilsIntent(record, move)) return new Refused('PERSON_REQUEST_RECEIPT', 'the ordinary move does not fulfil this request; execute its original CLI intent');}if (move.engine >= 6 && ['claim', 'repo-request', 'refuse'].includes(tag.phase) && !fulfilsStage(record, move, tag)) return new Refused('PERSON_REQUEST_RECEIPT', 'publish only the exact stage for this authenticated phone request');if (['claim', 'repo-request', 'refuse'].includes(tag.phase) && !(move.operation === 'shout' && move.args[0]?.from === 'person' && move.args[0]?.to === 'coordinator'diff --git a/src/relay-sender.js b/src/relay-sender.jsindex 5d7601e6..2f69d18c 100644--- a/src/relay-sender.js+++ b/src/relay-sender.js@@ -33,7 +33,7 @@ function personBarMove(move) {* session makes one [E4].*/function personAuthority(move) {- return personBarMove(move) || personFact(move) || ['recordRowDecisions', 'decideSentinel'].includes(move?.operation) || move?.operation === 'answerDecision' && Boolean(move.args?.[1]?.asPerson) ||+ return personBarMove(move) || personFact(move) || ['recordRowDecisions', 'decideSpecRevisions', 'decideSentinel'].includes(move?.operation) || move?.operation === 'answerDecision' && Boolean(move.args?.[1]?.asPerson) ||move?.operation === 'shout' && Boolean(move.args?.[0]?.request) || relayMoveActor(move) === 'person';}@@ -75,7 +75,7 @@ export function relaySenderProblem(move, sender, kind, { phoneReceipt = false }move.operation === 'ensureCoordinator' && typeof move.args?.[0] === 'string')) return null;return new Refused('RELAY_PERSON_ONLY', 'a machine cannot act as the person; approve this action on the paired phone');}- if (personBarMove(move) || kind === 'snapshot' || move?.operation === 'recordRowDecisions' || move?.operation === 'decideSentinel' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||+ if (personBarMove(move) || kind === 'snapshot' || ['recordRowDecisions', 'decideSpecRevisions'].includes(move?.operation) || move?.operation === 'decideSentinel' || move?.operation === 'answerDecision' && move.args?.[1]?.asPerson ||move?.operation === 'shout' && move.args?.[0]?.request || relayMoveActor(move) === 'person') {return new Refused('RELAY_PERSON_ONLY', `agent ${sender.agent} cannot make a person-only relay ${kind}; use the person's authenticated session`);}@@ -92,7 +92,7 @@ export function credentialActor(move) {return typeof creator === 'string' && creator !== 'machine' ? creator : 'machine';}if (move.personRequest || ['register', 'ensureCoordinator'].includes(move.operation)) return 'machine';- if (personBarMove(move) || ['recordRowDecisions', 'recordLandingWaiver'].includes(move.operation)+ if (personBarMove(move) || ['recordRowDecisions', 'decideSpecRevisions', 'recordLandingWaiver'].includes(move.operation)|| move.operation === 'answerDecision' && args[1]?.asPerson|| move.operation === 'shout' && args[0]?.request) return 'person';return relayMoveActor(move);diff --git a/src/row-draft-store.js b/src/row-draft-store.jsindex dc44d37a..0c064b8c 100644--- a/src/row-draft-store.js+++ b/src/row-draft-store.js@@ -12,14 +12,15 @@ export function recordRowDraft(board, { agentId, row, written = false }) {// The same writer asking again for the same definition, as a resumed blueprint add does, keeps the id// it reserved; a different gate, tier, section, target or writer is another proposal and gets its own id.const same = current.find((draft) => draft.id === row.id && draft.by === agentId && draft.written === Boolean(written)- && ['text', 'gate', 'tier', 'section'].every((key) => (draft[key] ?? '') === (row[key] ?? '')) && draft.target === (row.target ?? 'spec'));+ && ['text', 'gate', 'tier', 'section', 'revises', 'file', 'source', 'replacement', 'status', 'reason'].every((key) => (draft[key] ?? '') === (row[key] ?? '')) && draft.target === (row.target ?? 'spec'));if (same) return same;const [, prefix, number] = /^(.*?)(\d+)$/u.exec(row.id);let next = Number(number);while (current.some((draft) => draft.id === `${prefix}${next}`)) next += 1;logEvent(board, agentId, 'row_draft', null, { row, written: Boolean(written) });const entry = { id: `${prefix}${next}`, text: row.text, gate: row.gate ?? '', tier: row.tier ?? '', section: row.section ?? '', target: row.target ?? 'spec',- written: Boolean(written), by: agentId, event: board.lastEvent.event_id, at: board.lastEvent.event_at };+ written: Boolean(written), by: agentId, event: board.lastEvent.event_id, at: board.lastEvent.event_at,+ ...(row.revises ? Object.fromEntries(['revises', 'file', 'source', 'replacement', 'status', 'reason'].map(key => [key, row[key]])) : {}) };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('row_drafts', JSON.stringify([...current, entry]));return entry;diff --git a/src/row-drafts.js b/src/row-drafts.jsindex 2f1744ae..a62ecd99 100644--- a/src/row-drafts.js+++ b/src/row-drafts.js@@ -18,6 +18,7 @@ import {import { cleanGitEnvironment } from './git.js';import { trunkRef } from './trusted-policy-read.js';import { recordRowDraft } from './row-draft-store.js';+import { validSpecRevision } from './spec-revisions.js';export { rowDrafts } from './board-query.js';/**@@ -33,11 +34,12 @@ export { rowDrafts } from './board-query.js';*/export function draftSpecRow(board, { agentId, row, written = false }) {if (!agentId || agentId === PERSON) throw new Refused('ROW_DRAFT', 'an agent drafts a row and the person approves it; run pullboard spec draft "<text>" from an agent seat');- const needed = written ? ['text'] : ['text', 'gate', 'tier', 'section'];+ const needed = written ? ['text'] : row?.revises !== undefined ? ['text', 'tier', 'section'] : ['text', 'gate', 'tier', 'section'];if (!row || !/^[A-Z][A-Z0-9]*\d+$/u.test(String(row.id)) || !['spec', 'doctrine', undefined].includes(row.target)|| needed.some((key) => typeof row[key] !== 'string' || !row[key].trim() || /[\r\n|]/u.test(row[key]))) {throw new Refused('ROW_DRAFT', 'a drafted row needs its id and a one-line text, gate, tier and section; run pullboard spec draft "<text>"');}+ if (row.revises !== undefined && (written || !validSpecRevision(row))) throw new Refused('SPEC_REVISION', 'a revision needs its exact approved source, proposed replacement and reason');return recordRowDraft(board, { agentId, row, written });}@@ -61,7 +63,7 @@ export function trunkRowIds(root, mainRoot, config) {/** A lane's spec drafts: the reservations spec apply writes, unlike a writer's own reservation. */function laneDrafts(drafts) {- return drafts.filter((draft) => !draft.written && (draft.target ?? 'spec') === 'spec');+ return drafts.filter((draft) => !draft.revises && !draft.written && (draft.target ?? 'spec') === 'spec');}/** Board drafts from lanes that SPEC.md does not have yet, for spec apply to write. */diff --git a/src/signature.js b/src/signature.jsindex 058050e7..f29521c9 100644--- a/src/signature.js+++ b/src/signature.js@@ -149,7 +149,7 @@ function readInitialSignerHash(root) {/** Serialize canonical signed content with stable field order. */export function canonical(record) {if (record.type === 'row-decision') {- return JSON.stringify({ version: 1, type: record.type, firstCommit: record.firstCommit, initialHash: record.initialHash, id: record.id, file: record.file, kind: record.kind, source: record.source, replacement: record.replacement, text: record.text, decision: record.decision, reason: record.reason, commit: record.commit, by: record.by, on: record.on, note: record.note ?? '' });+ return JSON.stringify({ version: 1, type: record.type, firstCommit: record.firstCommit, initialHash: record.initialHash, id: record.id, file: record.file, kind: record.kind, source: record.source, replacement: record.replacement, text: record.text, decision: record.decision, reason: record.reason, commit: record.commit, by: record.by, on: record.on, note: record.note ?? '', ...(record.revision === undefined ? {} : { revision: record.revision }) });}if (record.type === 'signers') {return JSON.stringify({ version: 1, type: record.type, firstCommit: record.firstCommit, initialHash: record.initialHash, previousHash: record.previousHash, previousSigners: record.previousSigners, hash: record.hash, by: record.by, on: record.on });diff --git a/src/spec-gate-renames.js b/src/spec-gate-renames.jsnew file mode 100644index 00000000..acd90efd--- /dev/null+++ b/src/spec-gate-renames.js@@ -0,0 +1,29 @@+/** Real Git rename hints for approved requirements whose gate disappeared [B23,N39]. */+import { existsSync } from 'node:fs';+import { join } from 'node:path';+import { spawnSync } from 'node:child_process';+import { cleanGitEnvironment } from './git.js';++/** Follow recorded renames in chronological order; never guess a replacement from similar names. */+export function renamedGatePath(root, file) {+ const result = spawnSync('git', ['log', '--reverse', '--format=', '--name-status', '-z', '--find-renames', '--diff-filter=R', 'HEAD'],+ { cwd: root, env: cleanGitEnvironment(), encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });+ if (result.status !== 0) return null;+ const parts = result.stdout.split('\0');+ let current = file;+ for (let index = 0; index < parts.length;) {+ const status = parts[index++].trim();+ if (!/^R\d+$/u.test(status)) continue;+ const from = parts[index++];+ const to = parts[index++];+ if (from === current && to) current = to;+ }+ return current !== file && existsSync(join(root, current)) ? current : null;+}++/** Quote exact row text and a suggested gate as literal shell arguments. */+export function revisionGateCommand(row, gate, from, to) {+ /** Shell quoting preserves literal requirement text and paths in the suggested command. */+ const quote = value => `'${String(value).replaceAll("'", "'\\''")}'`;+ return `pullboard spec draft ${quote(row.text)} --revises ${quote(row.id)} --gate ${quote(gate)} --reason ${quote(`Gate renamed from ${from} to ${to}.`)}`;+}diff --git a/src/spec-revision-engine.js b/src/spec-revision-engine.jsnew file mode 100644index 00000000..c5b281cf--- /dev/null+++ b/src/spec-revision-engine.js@@ -0,0 +1,4 @@+/** Approved-row revision payloads require a reader that preserves their exact effect [P6,H16]. */+import { unassignedEngine } from './engine-next.js';++export const SPEC_REVISION_ENGINE = unassignedEngine();diff --git a/src/spec-revisions.js b/src/spec-revisions.jsnew file mode 100644index 00000000..9676c6c3--- /dev/null+++ b/src/spec-revisions.js@@ -0,0 +1,133 @@+/** Board-only proposed changes to approved requirements [P6,B23,N39]. */+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import {+ atomic,+ logEvent,+ PERSON,+ recordRowDecisions,+} from './board.js';+import { rowDrafts } from './board-query.js';+import { Refused } from './refused.js';+import {+ defaultPrincipal,+ hasSignerFile,+ signRowDecision,+} from './signature.js';+import { draftRow } from './spec-draft.js';+import {+ loadSpec,+ parseSpec,+ STATUSES,+} from './spec.js';++/** Capture a target's exact current source, refusing ambiguous or unapproved targets. */+function approvedSource(root, config, id) {+ const spec = loadSpec(root, config);+ const matches = spec.rows.filter(row => row.id === id);+ if (matches.length !== 1 || matches[0].status !== 'approved') throw new Refused('SPEC_REVISION', `${id} must name one approved requirement; use pullboard spec show <id>`);+ return { row: matches[0], source: readFileSync(join(root, config.spec), 'utf8').split(/\r?\n/u)[matches[0].line - 1] };+}++/** Plan a new proposal without writing either the approved row or a draft row into SPEC.md. */+export function planSpecRevision(root, config, { revises, text, gate, status, reason, taken }) {+ if (typeof reason !== 'string' || !reason.trim() || /[\r\n|]/u.test(reason)) throw new Refused('SPEC_REVISION', 'give the reason for changing the approved row: --reason "why"');+ const { row, source } = approvedSource(root, config, revises);+ const wanted = status ?? row.status;+ if (!STATUSES.includes(wanted)) throw new Refused('SPEC_REVISION', `unknown status ${wanted}; use one of ${STATUSES.join(', ')}`);+ const nextGate = gate ?? row.gate;+ let replacement = source.replace(/\[[a-z]+(?=,|\])/u, () => `[${wanted}`)+ .replace(/(\]\s+)[^|]*/u, (_, start) => `${start}${text} `);+ replacement = /\|\s*gate\s*:/u.test(replacement)+ ? replacement.replace(/(\|\s*gate\s*:\s*)[^|]*/u, (_, start) => `${start}${nextGate} `)+ : `${replacement.trimEnd()} | gate: ${nextGate}`;+ replacement = replacement.trimEnd();+ if (replacement === source) throw new Refused('SPEC_REVISION', 'the proposed row is unchanged; give new text, gate or status');+ const prefix = /^([A-Z][A-Z0-9]*?)\d+(?:\.\d+)*$/u.exec(revises)?.[1];+ const plan = draftRow(root, config, { target: 'spec', text, gate: nextGate, tier: row.tier, section: prefix, taken, write: false });+ return { ...plan.row, revises, file: config.spec, source, replacement, status: wanted, reason: reason.trim() };+}++/** The signed reference includes the immutable complete proposal, not mutable display labels. */+export function revisionReference(draft) {+ return { proposal: draft.id, target: draft.revises, file: draft.file, source: draft.source,+ replacement: draft.replacement, reason: draft.reason, by: draft.by };+}++/** Validate the deterministic proposal payload before it enters the ordered board history. */+export function validSpecRevision(row) {+ const before = typeof row?.source === 'string' ? parseSpec(`## Revision\n${row.source}\n`).rows : [];+ const after = typeof row?.replacement === 'string' ? parseSpec(`## Revision\n${row.replacement}\n`).rows : [];+ return row?.target === 'spec' && typeof row.file === 'string' && row.file.trim()+ && typeof row.source === 'string' && !/[\r\n]/u.test(row.source)+ && typeof row.replacement === 'string' && !/[\r\n]/u.test(row.replacement)+ && typeof row.reason === 'string' && row.reason.trim() && !/[\r\n|]/u.test(row.reason)+ && before.length === 1 && before[0].status === 'approved' && before[0].id === row.revises+ && after.length === 1 && after[0].id === row.revises && after[0].text === row.text+ && after[0].gate === row.gate && after[0].status === row.status && row.source !== row.replacement;+}++/** Accept only the exact approved effect of a still-pending board proposal. */+export function validRevisionApproval(board, record) {+ const draft = rowDrafts(board).find(entry => entry.id === record.revision?.proposal);+ return Boolean(draft && !draft.decision && validSpecRevision(draft) && record.decision === 'approve'+ && record.kind === 'spec' && record.id === draft.revises && record.file === draft.file+ && record.source === draft.source && record.replacement === draft.replacement && record.text === draft.text+ && JSON.stringify(record.revision) === JSON.stringify(revisionReference(draft)));+}++/** Build exact person decisions, retaining normal optional SSH signatures and current-source checks. */+export function prepareSpecRevisionDecisions(root, config, drafts, { ids, decision, reason = '', by, on, commit }) {+ const signed = decision === 'approve' && hasSignerFile(root);+ return ids.map(id => {+ const draft = drafts.find(entry => entry.id === id && entry.revises);+ if (!draft || draft.decision) throw new Refused('SPEC_REVISION', `${id} is not an undecided revision proposal; read Needs you`);+ if (decision === 'approve') {+ const current = approvedSource(root, config, draft.revises);+ if (draft.file !== config.spec || current.source !== draft.source) throw new Refused('STALE_ROW_DECISION', `${draft.revises} changed after ${id} was proposed; draft a fresh revision`);+ }+ if (decision === 'decline' && (!reason.trim() || /[\r\n|]/u.test(reason))) throw new Refused('SPEC_REVISION', 'declining a revision needs a one-line --reason "why"');+ const record = { version: 1, type: 'row-decision', kind: 'spec', file: draft.file, id: draft.revises,+ source: draft.source, replacement: draft.replacement, text: draft.text, decision,+ reason: decision === 'decline' ? reason.trim() : '', by: by ?? (signed ? defaultPrincipal(root) : 'person'),+ on, commit, note: '', revision: revisionReference(draft) };+ return signed ? signRowDecision(root, record) : record;+ });+}++/** Person-only atomic proposal disposition; a decline never replaces its target's approval. */+export function decideSpecRevisions(board, { agentId, channel, decisions }) {+ if (agentId !== PERSON || !['terminal', 'view'].includes(channel)) throw new Refused('B26_PERSON_APPROVAL', 'only the person decides revisions through their terminal or view');+ if (!Array.isArray(decisions) || !decisions.length) throw new Refused('SPEC_REVISION', 'name a pending revision proposal');+ return atomic(board, () => {+ let drafts = rowDrafts(board);+ const seen = new Set();+ const results = decisions.map(record => {+ const draft = drafts.find(entry => entry.id === record?.revision?.proposal);+ if (!draft || !validSpecRevision(draft) || draft.decision || seen.has(draft.id)+ || record.kind !== 'spec' || record.version !== 1 || record.type !== 'row-decision'+ || JSON.stringify(record.revision) !== JSON.stringify(revisionReference(draft))+ || record.id !== draft.revises || record.file !== draft.file || record.source !== draft.source+ || record.replacement !== draft.replacement || record.text !== draft.text+ || !['approve', 'decline'].includes(record.decision)+ || (record.decision === 'decline' && !String(record.reason ?? '').trim())) throw new Refused('SPEC_REVISION', 'the decision must match one undecided revision exactly; refresh Needs you');+ seen.add(draft.id);+ const approved = record.decision === 'approve' ? recordRowDecisions(board, { agentId, channel, decisions: [record] })[0] : null;+ logEvent(board, PERSON, 'spec_revision_decision', null, { proposal: draft.id, record, channel });+ drafts = drafts.map(entry => entry.id === draft.id ? { ...entry, decision: record.decision,+ decisionEvent: approved?.event ?? board.lastEvent.event_id, decidedBy: PERSON, decidedAt: board.lastEvent.event_at } : entry);+ return approved ?? record;+ });+ board.db.prepare('UPDATE board_meta SET meta_value=? WHERE meta_key=?').run(JSON.stringify(drafts), 'row_drafts');+ return results;+ });+}++/** Expose both sides of each outstanding revision through the shared person projection. */+export function projectSpecRevisions(state, drafts, decisions) {+ const revisions = drafts.filter(draft => draft.revises && draft.decision !== 'decline'+ && !(draft.decision === 'approve' && decisions.some(record => record.event === draft.decisionEvent && record.applied)))+ .map(draft => ({ ...draft, old: parseSpec(`## Revision\n${draft.source}\n`).rows[0],+ proposed: parseSpec(`## Revision\n${draft.replacement}\n`).rows[0] }));+ return { ...state, specRevisions: revisions };+}diff --git a/src/spec.js b/src/spec.jsindex 2f71ac8e..a3915046 100644--- a/src/spec.js+++ b/src/spec.js@@ -26,6 +26,10 @@ import {} from './config.js';import { cleanGitEnvironment } from './git.js';import { Refused } from './refused.js';+import {+ renamedGatePath,+ revisionGateCommand,+} from './spec-gate-renames.js';import {hasSignerFile,isVerifiedSignoff,@@ -296,7 +300,10 @@ export function missingGateFindings(spec, root) {if (existsSync(join(root, file))) continue;const lost = lastCommitOf(root, file);if (row.status === 'approved' && row.tier === 'must' && lost) {- findings.push({ level: 'error', line: row.line, id: row.id, message: `gate file ${file} was removed from the repository (last in ${lost}); restore it or point the row at its new home` });+ const renamed = renamedGatePath(root, file);+ const revisedGate = renamed ? row.gate.replace(GATE_FILE_RE, (match, path) => posix.normalize(path) === file ? match.slice(0, match.length - path.length) + renamed : match) : null;+ const next = renamed ? `renamed to ${renamed}; propose the change: ${revisionGateCommand(row, revisedGate, file, renamed)}` : 'restore it or point the row at its new home';+ findings.push({ level: 'error', line: row.line, id: row.id, message: `gate file ${file} was removed from the repository (last in ${lost}); ${next}` });} else {findings.push({ level: 'warning', line: row.line, id: row.id, message: `gate file ${file} does not exist yet; write the test it names` });}diff --git a/test/spec-revise.test.js b/test/spec-revise.test.jsindex e4779c1d..535ec372 100644--- a/test/spec-revise.test.js+++ b/test/spec-revise.test.js@@ -1,6 +1,7 @@/** Approved requirements change only through a visible person decision [P6,B23,N39]. */import assert from 'node:assert/strict';import {+ mkdirSync,readFileSync,writeFileSync,} from 'node:fs';@@ -65,6 +66,14 @@ test('a proposed change to an approved row waits in Needs you and applies only wassert.equal(readFileSync(file, 'utf8'), approved, 'declining a revision never retires or rejects its approved target');assert.ok(!personNeedsState(box.repo).needs.some(entry => entry.id === declined.id));+ writeFileSync(file, approved.replace('The page renders accessibly.', 'An agent silently changed it.'));+ box.git(box.repo, 'add', 'SPEC.md');+ const handEdit = box.tryGit(box.repo, 'commit', '-q', '-m', 'feat: silently rewrite the approved requirement [G1]');+ assert.notEqual(handEdit.status, 0, 'the real commit hook refuses a direct approved-row rewrite');+ assert.match(handEdit.stderr, /APPROVED_ROW_CHANGE|approved row|changes approved text/u);+ writeFileSync(file, approved);+ box.git(box.repo, 'add', 'SPEC.md');+const retired = JSON.parse(succeeds(box.run(box.web, 'spec', 'draft', 'The page renders accessibly.','--revises', 'G1', '--status', 'retired', '--reason', 'The feature is no longer supported.', '--json')).out);succeeds(box.run(box.repo, 'spec', 'approve', retired.id));@@ -72,8 +81,41 @@ test('a proposed change to an approved row waits in Needs you and applies only wassert.equal(row(box, 'G1').status, 'retired', 'the person can approve an explicit status revision');assert.notEqual(box.run(box.web, 'spec', 'draft', 'Change a retired row.', '--revises', 'G1', '--reason', 'Not approved.').code, 0);- writeFileSync(file, approved.replace('The page renders accessibly.', 'An agent silently changed it.'));- const check = box.run(box.repo, 'spec', 'check');- assert.notEqual(check.code, 0, 'a direct edit cannot reuse the earlier approval');- writeFileSync(file, approved);+});++test('[P6,B23,N39] revisions require a reason and stale proposals cannot change a newer approved row', { timeout: 120_000 }, () => {+ const box = fixtures.project('true');+ assert.notEqual(box.run(box.web, 'spec', 'draft', 'Missing reason.', '--revises', 'G1').code, 0);+ assert.notEqual(box.run(box.web, 'spec', 'draft', 'Missing target.', '--revises', 'G99', '--reason', 'No such row.').code, 0);+ const first = JSON.parse(succeeds(box.run(box.web, 'spec', 'draft', 'An obsolete proposal.', '--revises', 'G1', '--reason', 'First idea.', '--json')).out);+ const second = JSON.parse(succeeds(box.run(box.web, 'spec', 'draft', 'The replacement the person chooses.', '--revises', 'G1', '--reason', 'Better idea.', '--json')).out);+ succeeds(box.run(box.repo, 'spec', 'approve', second.id));+ succeeds(box.run(box.repo, 'spec', 'apply'));+ const approved = readFileSync(join(box.repo, 'SPEC.md'), 'utf8');+ assert.notEqual(box.run(box.repo, 'spec', 'approve', first.id).code, 0, 'a stale source cannot be approved over a different current row');+ succeeds(box.run(box.repo, 'spec', 'decline', first.id, '--reason', 'Superseded.'));+ succeeds(box.run(box.repo, 'spec', 'apply'));+ assert.equal(readFileSync(join(box.repo, 'SPEC.md'), 'utf8'), approved);+ assert.ok(!personNeedsState(box.repo).needs.some(entry => entry.id === first.id));+});++test('[B23,N39] a real gate rename gives the new path and an exact revision command', { timeout: 120_000 }, () => {+ const box = fixtures.sandbox();+ const root = join(box.dir, 'existing-repo');+ mkdirSync(root);+ mkdirSync(join(root, 'test'));+ box.git(root, 'init', '-q', '-b', 'main');+ writeFileSync(join(root, 'pullboard.json'), JSON.stringify({ ...fixtures.CONFIG, gate: 'true' }));+ writeFileSync(join(root, 'SPEC.md'), '# Existing project\n\n## G · Goals\n- G1 [approved, must] The page renders. | gate: node --test test/old.test.js\n');+ writeFileSync(join(root, 'test/old.test.js'), '// A tracked test in the project before Pullboard was installed.\n');+ box.git(root, 'add', '-A');+ box.git(root, 'commit', '-q', '-m', 'test: establish the existing gate');+ box.git(root, 'mv', 'test/old.test.js', 'test/new.test.js');+ box.git(root, 'commit', '-q', '-m', 'test: rename the gate');+ succeeds(box.run(root, 'init'));+ const check = box.run(root, 'spec', 'check');+ assert.notEqual(check.code, 0);+ const output = check.out + check.err;+ assert.match(output, /renamed to test\/new\.test\.js/u);+ assert.ok(output.includes("pullboard spec draft 'The page renders.' --revises 'G1' --gate 'node --test test/new.test.js' --reason 'Gate renamed from test/old.test.js to test/new.test.js.'"));});