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(offers): persist atomic outcomes and minimal receipts [B2,H3,H16]
Corey Olsonb4b8042def2a
diff --git a/src/item-offer-contract.js b/src/item-offer-contract.jsnew file mode 100644index 00000000..3957525e--- /dev/null+++ b/src/item-offer-contract.js@@ -0,0 +1,20 @@+/** Common exact wire primitives; board identity resolution is always supplied by the consumer [H3,H16]. */+import { Refused } from './refused.js';++/** A wire record has explicit fields, never arbitrary properties or array indices. */+export function exactOfferFields(value, keys, code = 'ITEM_OFFER') {+ if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).length !== keys.length || keys.some(key => !Object.hasOwn(value, key))) throw new Refused(code, 'use the exact permitted fields and canonical board references');+}+/** Opaque references retain their spelling; the supplied canonical resolver owns identity. */+export function offerReference(value) { return typeof value === 'string' && value.length > 0 && value.length <= 256 && !/[\u0000-\u001f\u007f]/u.test(value); }+/** Item ids stay local to the board named beside them. */+export function offerItemId(value) { return Number.isSafeInteger(value) && value > 0; }+/** Stable JSON binds permitted fields independently of a caller's object insertion order. */+export function offerBytes(value) {+ return JSON.stringify(value, (_, entry) => entry && typeof entry === 'object' && !Array.isArray(entry)+ ? Object.fromEntries(Object.keys(entry).sort().map(key => [key, entry[key]])) : entry);+}+/** Resolve an opaque id through the consumer's single canonical boundary, never through display names. */+export function resolveOfferBoard(id, resolveBoardRef, code = 'ITEM_OFFER') {+ if (!offerReference(id) || typeof resolveBoardRef !== 'function' || resolveBoardRef(id)?.boardId !== id) throw new Refused(code, 'use the exact permitted fields and canonical board references');+}diff --git a/src/item-offer.js b/src/item-offer.jsnew file mode 100644index 00000000..959c073c--- /dev/null+++ b/src/item-offer.js@@ -0,0 +1,97 @@+/** Shared offer contracts; orchestration supplies canonical board resolution and authority [B2,H3,H16]. */+import { createHash } from 'node:crypto';+import { atomic, itemById, boardId } from './board.js';+import { Refused } from './refused.js';+import { exactOfferFields, offerReference, offerItemId, offerBytes, resolveOfferBoard } from './item-offer-contract.js';+export { minimalItemReceipt, verifyItemReceipt } from './item-receipt.js';++const FIELDS = ['version', 'offerId', 'sourceBoardId', 'parentItem', 'destinationBoardId', 'proposedContent', 'disposition', 'childRef', 'reason'];+const STATE = FIELDS.filter(key => key !== 'proposedContent');++/** Refuse a malformed contract before a callback can observe or act on it. */+function refuse(code = 'ITEM_OFFER') { throw new Refused(code, 'use the exact item-offer contract and its canonical board references; refresh the offer before retrying'); }+/** Bind exact wire content without retaining its private text in the retry ledger. */+function digest(value) { return createHash('sha256').update(offerBytes(value)).digest('hex'); }+/** Validate an offer or its separate content-free state announcement. */+function validate(value, stateOnly = false) {+ exactOfferFields(value, stateOnly ? STATE : FIELDS);+ if (value.version !== 1 || !offerReference(value.offerId) || !offerReference(value.sourceBoardId)+ || !offerReference(value.destinationBoardId) || value.sourceBoardId === value.destinationBoardId || !offerItemId(value.parentItem)) refuse();+ if (!stateOnly) {+ const content = value.proposedContent, allowed = ['lane', 'title', 'criterion', 'specIds', 'brief', 'route', 'check'];+ if (!content || typeof content !== 'object' || Array.isArray(content) || Object.keys(content).some(key => !allowed.includes(key))+ || !offerReference(content.lane) || typeof content.title !== 'string' || !content.title.trim()+ || ['criterion', 'brief', 'route', 'check'].some(key => Object.hasOwn(content, key) && typeof content[key] !== 'string')+ || Object.hasOwn(content, 'specIds') && (!Array.isArray(content.specIds) || content.specIds.some(id => !offerReference(id)))) refuse();+ }+ if (value.disposition === 'accepted') {+ exactOfferFields(value.childRef, ['boardId', 'item']);+ if (value.childRef.boardId !== value.destinationBoardId || !offerItemId(value.childRef.item) || value.reason !== null) refuse();+ } else if (value.disposition === 'declined') {+ if (value.childRef !== null || typeof value.reason !== 'string' || !value.reason.trim() || value.reason.length > 2048) refuse();+ } else if (value.disposition !== 'pending' || value.childRef !== null || value.reason !== null) refuse();+ return structuredClone(value);+}+/** Only the explicitly disclosed proposal reaches the recipient; state replication uses another shape. */+export function itemOfferAnnouncement(value) {+ const offer = validate(value);+ return Object.fromEntries(STATE.map(key => [key, offer[key]]));+}+/** Resolve both boards and require the consumer's authenticated authority for this exact action. */+function authorize(board, value, ports, action, local) {+ if (ports?.boardId !== value[local] || boardId(board) !== ports.boardId) refuse('OFFER_AUTHORITY');+ resolveOfferBoard(value.sourceBoardId, ports.resolveBoardRef);+ resolveOfferBoard(value.destinationBoardId, ports.resolveBoardRef);+ if (typeof ports.authorize !== 'function' || ports.authorize({ action, boardId: ports.boardId, document: structuredClone(value) }) !== true) refuse('OFFER_AUTHORITY');+}+/** The destination's transaction serializes simultaneous deliveries of the same source offer. */+function key(sourceBoardId, offerId) { return `item_offer:${digest([sourceBoardId, offerId])}`; }+/** Read the durable state-only result; the ledger never contains proposed item text. */+export function readItemOffer(board, sourceBoardId, offerId) {+ const row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key(sourceBoardId, offerId));+ return row ? JSON.parse(row.meta_value).result : null;+}+/** Persist one immutable result inside the caller's transaction. */+function save(board, offer, binding, result) {+ board.db.prepare('INSERT INTO board_meta(meta_key,meta_value) VALUES (?,?)').run(key(offer.sourceBoardId, offer.offerId), JSON.stringify({ binding, result }));+}+/** Create a child and its idempotency result together, or decline without creating anything. */+function decide(board, input, ports, disposition, reason = null) {+ const offer = validate(input);+ if (offer.disposition !== 'pending') refuse();+ return atomic(board, () => {+ authorize(board, offer, ports, disposition, 'destinationBoardId');+ const binding = digest(offer), row = board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key=?').get(key(offer.sourceBoardId, offer.offerId));+ if (row) {+ const saved = JSON.parse(row.meta_value);+ if (saved.binding !== binding || saved.result.disposition !== disposition || saved.result.reason !== reason) refuse('OFFER_CONFLICT');+ return { ...offer, ...saved.result };+ }+ let childRef = null;+ if (disposition === 'accepted') {+ if (typeof ports.createChild !== 'function') refuse();+ const item = ports.createChild(structuredClone(offer.proposedContent));+ if (!offerItemId(item) || !itemById(board, item)) refuse();+ childRef = { boardId: ports.boardId, item };+ }+ const result = validate({ ...offer, disposition, reason, childRef });+ save(board, offer, binding, itemOfferAnnouncement(result));+ return result;+ });+}+/** The synchronous child port must create on this same SQLite board, under the consumer's ordered move. */+export function acceptItemOffer(board, offer, ports) { return decide(board, offer, ports, 'accepted'); }+/** The resulting state announcement carries the decline reason to both boards by retryable delivery. */+export function declineItemOffer(board, offer, reason, ports) { return decide(board, offer, ports, 'declined', reason); }+/** Record an authenticated destination result at its source; this is not a two-board transaction. */+export function recordItemOfferResult(board, input, ports) {+ const result = validate(input, true);+ if (result.disposition === 'pending') refuse();+ return atomic(board, () => {+ authorize(board, result, ports, 'receive-result', 'sourceBoardId');+ const saved = readItemOffer(board, result.sourceBoardId, result.offerId);+ if (saved && offerBytes(saved) !== offerBytes(result)) refuse('OFFER_CONFLICT');+ if (!saved) save(board, result, null, result);+ return result;+ });+}diff --git a/src/item-receipt.js b/src/item-receipt.jsnew file mode 100644index 00000000..801c6fe0--- /dev/null+++ b/src/item-receipt.js@@ -0,0 +1,35 @@+/** Minimal private-landing receipts contain integrity-bound references, never item prose [H3,H16]. */+import { createHash } from 'node:crypto';+import { exactOfferFields, offerBytes, offerItemId, offerReference, resolveOfferBoard } from './item-offer-contract.js';+import { Refused } from './refused.js';+const FIELDS = ['version', 'sourceBoardId', 'item', 'commit', 'verifier', 'verdict'];+/** Refuse malformed, mismatched or unauthenticated private receipts before a consumer can apply them. */+function refuse() { throw new Refused('ITEM_RECEIPT', 'use the exact minimal receipt from the source board and verify its source, item, commit and verdict binding'); }+/** Validate permitted references without copying any title, criterion or note into the envelope. */+function fields(value) {+ exactOfferFields(value, FIELDS, 'ITEM_RECEIPT');+ if (value.version !== 1 || !offerReference(value.sourceBoardId) || !offerItemId(value.item)+ || typeof value.commit !== 'string' || !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/u.test(value.commit)+ || !offerReference(value.verifier) || !offerReference(value.verdict)) refuse();+ return structuredClone(value);+}+/** Sign canonical permitted bytes through the source authority port; a digest alone is not authority. */+export function minimalItemReceipt(input, { sign } = {}) {+ const value = fields(input), bytes = offerBytes(value);+ if (typeof sign !== 'function') refuse();+ const signature = sign(bytes);+ if (typeof signature !== 'string' || !signature || signature.length > 16384) refuse();+ return { ...value, integrity: { digest: createHash('sha256').update(bytes).digest('hex'), signature } };+}+/** Match the consumer's exact expected identity and verify against its established source trust port. */+export function verifyItemReceipt(input, { resolveBoardRef, verify } = {}, expected) {+ exactOfferFields(input, [...FIELDS, 'integrity'], 'ITEM_RECEIPT');+ const { integrity, ...rest } = input, value = fields(rest), wanted = fields(expected);+ exactOfferFields(integrity, ['digest', 'signature'], 'ITEM_RECEIPT');+ resolveOfferBoard(value.sourceBoardId, resolveBoardRef, 'ITEM_RECEIPT');+ const bytes = offerBytes(value), digest = createHash('sha256').update(bytes).digest('hex');+ if (offerBytes(value) !== offerBytes(wanted) || integrity.digest !== digest || typeof integrity.signature !== 'string'+ || !integrity.signature || integrity.signature.length > 16384 || typeof verify !== 'function'+ || verify(bytes, integrity.signature, value.sourceBoardId) !== true) refuse();+ return true;+}diff --git a/test/item-offer.test.js b/test/item-offer.test.jsindex 551c5365..c7381d6a 100644--- a/test/item-offer.test.js+++ b/test/item-offer.test.js@@ -13,8 +13,8 @@ test('an accepted offer makes at most one child and a receipt carries no text [Bassert.ok(existsSync(module), 'the shared item-offer contract must exist');const api = await import(module.href);const directory = mkdtempSync(join(tmpdir(), 'pullboard-item-offer-'));- t.after(() => rmSync(directory, { recursive: true, force: true }));const boards = [];+ t.after(() => { for (const entry of boards) store.closeBoard(entry.board); rmSync(directory, { recursive: true, force: true }); });for (const name of ['source', 'destination']) {const root = join(directory, name);mkdirSync(root);@@ -25,7 +25,6 @@ test('an accepted offer makes at most one child and a receipt carries no text [Bstore.ensureCoordinator(board, root);boards.push({ board, file, id: store.boardId(board) });}- t.after(() => { for (const entry of boards) store.closeBoard(entry.board); });const [source, destination] = boards;const parent = store.addItem(source.board, { by: 'coordinator', lane: 'web', title: 'Private parent' });const offer = { version: 1, offerId: 'offer-1', sourceBoardId: source.id, parentItem: parent,@@ -36,6 +35,7 @@ test('an accepted offer makes at most one child and a receipt carries no text [Blet allowed = true;const ports = { boardId: destination.id, resolveBoardRef, authorize: () => allowed,createChild: content => store.addItem(destination.board, { by: 'coordinator', ...content }) };+ assert.throws(() => api.acceptItemOffer(source.board, offer, ports), { code: 'OFFER_AUTHORITY' });const accepted = api.acceptItemOffer(destination.board, offer, ports);assert.equal(accepted.childRef.boardId, destination.id);assert.equal(store.listItems(destination.board, { all: true }).length, 1);@@ -46,6 +46,9 @@ test('an accepted offer makes at most one child and a receipt carries no text [Bassert.equal(store.listItems(destination.board, { all: true }).length, 1);assert.throws(() => api.acceptItemOffer(destination.board, { ...offer, proposedContent: { ...offer.proposedContent, title: 'Changed' } }, ports), { code: 'OFFER_CONFLICT' });assert.throws(() => api.acceptItemOffer(destination.board, { ...offer, offerId: 'bad', title: 'Hidden' }, ports), { code: 'ITEM_OFFER' });+ const count = store.listItems(destination.board, { all: true }).length;+ assert.throws(() => api.acceptItemOffer(destination.board, { ...offer, offerId: 'rollback' }, { ...ports, createChild: content => { ports.createChild(content); return -1; } }), { code: 'ITEM_OFFER' });+ assert.equal(store.listItems(destination.board, { all: true }).length, count, 'invalid child creation rolls back the real insert and retry state');allowed = false;assert.throws(() => api.acceptItemOffer(destination.board, { ...offer, offerId: 'denied' }, ports), { code: 'OFFER_AUTHORITY' });allowed = true;