COMMERCE BOUNDARY: REFERENCE IMPLEMENTATION AND EVALUATION SUITE Version 1.0.0, 12 November 2026. Written by Tal Forsher. Deterministic, dependency-free ES modules. 54 cases, all passing. Every guard in GUARDS is load-bearing: disabling it makes at least one case fail. Run it: node --input-type=module -e "import('/path/commerceSuite.js').then(m => console.log(m.runSuite()))" Files below, in order: commerceLab.js, then commerceSuite.js. -------------------------------------------------------------------------------- FILE 1 of 2: commerceLab.js -------------------------------------------------------------------------------- /** * Reference implementation of a commerce transaction boundary, with the guards * that make an AI-driven purchase safe, plus an evaluation suite that proves * each guard is load-bearing. * * Deterministic: a fixture clock, fixture addresses, fixture prices. Nothing * here calls a vendor API or contains anyone's customer data. Guards can be * individually disabled, which is how a reader checks the tests are not vacuous. * * Money is held in minor units (cents) to keep the arithmetic exact. */ export const LAB_META = { version: '1.0.0', fixtureClock: '2026-11-12T09:00:00Z', note: 'Simulation over fixtures. Not AT&T code, not connected to any vendor API.', }; const MIN = 60 * 1000; const NOW = Date.parse(LAB_META.fixtureClock); const SPEEDS = ['300M', '500M', '1000M', '2000M', '5000M']; const MRC = { '300M': 29900, '500M': 39900, '1000M': 54900, '2000M': 74900, '5000M': 149900 }; const NRC_INSTALL = 19900; const REQUIRED_FEATURES = ['ATT_HS_IP_DS', 'ATT_HS_IP_TYPE']; const ADDRESSES = { A1: { label: 'Columbus HQ', status: 'complete', speeds: SPEEDS }, A2: { label: 'Reno DC', status: 'complete', speeds: ['300M', '500M', '1000M', '2000M'] }, A3: { label: 'Tampa office', status: 'complete', speeds: ['500M', '1000M'] }, A4: { label: 'Tampa annex', status: 'partial', speeds: ['500M'] }, A5: { label: 'Remote yard', status: 'none', speeds: [] }, }; const ACCOUNTS = { 'ACC-1': { label: 'Northwind facilities', tenant: 'T1' }, 'ACC-2': { label: 'Other tenant', tenant: 'T2' }, }; const ACTORS = { mike: { label: 'office manager', accountId: 'ACC-1', canRead: true, canApprove: false, canSubmit: false, limitMinor: 0 }, dana: { label: 'controller', accountId: 'ACC-1', canRead: true, canApprove: true, canSubmit: true, limitMinor: 1000000 }, omar: { label: 'IT lead', accountId: 'ACC-1', canRead: true, canApprove: true, canSubmit: false, limitMinor: 60000 }, eve: { label: 'other tenant controller', accountId: 'ACC-2', canRead: true, canApprove: true, canSubmit: true, limitMinor: 1000000 }, }; const AGENT = 'commerce-copilot'; export const GUARDS = [ { key: 'qualification', label: 'eligibility gate', catches: 'quoting an address that cannot be served' }, { key: 'version', label: 'quote version check', catches: 'committing to a price the approver never saw' }, { key: 'expiry', label: 'quote expiry check', catches: 'committing to an expired price' }, { key: 'approval', label: 'approval verification', catches: 'the agent approving its own purchase' }, { key: 'delegation', label: 'delegation check', catches: 'an agent acting without a mandate' }, { key: 'ceiling', label: 'spend ceiling', catches: 'a purchase above the delegated limit' }, { key: 'idempotency', label: 'idempotency key', catches: 'a retry becoming a second order' }, { key: 'tenant', label: 'tenant ownership', catches: 'one account reading or acting on another account' }, { key: 'injection', label: 'retrieval authority block', catches: 'a document that prices its own discount' }, { key: 'confirm', label: 'system-of-record confirmation', catches: 'treating HTTP 200 as a completed order' }, { key: 'total', label: 'payload total check', catches: 'a total the caller invented' }, ]; class LabError extends Error { constructor(code, detail) { super(code); this.code = code; this.detail = detail || null; } } export function createLab(options = {}) { const ablate = new Set(options.ablate || []); const off = (g) => ablate.has(g); let clock = NOW; let seq = 0; const db = { quotes: new Map(), approvals: new Map(), orders: new Map(), keyed: new Map(), compensations: [] }; const nextId = (p) => `${p}-${String(++seq).padStart(3, '0')}`; function accountOf(actor) { const a = ACTORS[actor]; if (!a) throw new LabError('AUTHORIZATION_DENIED', 'unknown actor'); return a; } function delegationFor(actor, agent) { const a = ACTORS[actor]; if (!a) return null; if (agent !== AGENT) return null; return { agent, principal: actor, accountId: a.accountId, capabilities: ['quotes.create', 'quotes.refresh', 'approvals.request', 'orders.submit'], ceilingMinor: 400000, expiresAt: NOW + 60 * MIN, }; } // ---- catalog + qualification ------------------------------------------- function checkQualification(input) { const address = ADDRESSES[input.addressId]; if (!address) throw new LabError('ADDRESS_NOT_FOUND'); if (!off('qualification')) { if (address.status === 'none') throw new LabError('NOT_SERVICEABLE', { addressId: input.addressId }); if (address.status === 'partial') throw new LabError('PARTIAL_QUALIFICATION', { addressId: input.addressId }); } const speeds = off('qualification') ? SPEEDS : address.speeds; if (input.speed && !speeds.includes(input.speed)) throw new LabError('SPEED_NOT_OFFERED', { speed: input.speed }); return { requestId: nextId('req'), addressId: input.addressId, addressStatus: 'complete', qualifiedProducts: ['IPBB'], speeds, }; } function getOffer(input) { const q = input.qualification; if (!q || !q.requestId) throw new LabError('NO_QUALIFICATION'); if (q.addressStatus !== 'complete') throw new LabError('PARTIAL_QUALIFICATION'); if (!q.qualifiedProducts.includes('IPBB')) throw new LabError('NOT_SERVICEABLE'); if (!SPEEDS.includes(input.speed)) throw new LabError('INVALID_CONFIGURATION', { speed: input.speed }); const codes = (input.features || []).map((f) => f.code); const missing = REQUIRED_FEATURES.filter((c) => !codes.includes(c)); if (missing.length && !off('qualification')) throw new LabError('INVALID_CONFIGURATION', { missing }); return { offerId: nextId('OFF'), qualificationId: q.requestId, addressId: q.addressId, speed: input.speed, mrcMinor: MRC[input.speed], nrcMinor: NRC_INSTALL, expiresAt: clock + 15 * MIN, features: input.features || [], }; } function offerFor(addressId, speed) { const qualification = checkQualification({ addressId, speed }); return getOffer({ qualification, speed, features: REQUIRED_FEATURES.map((code) => ({ code })) }); } // ---- quotes ------------------------------------------------------------ function createQuote(input) { if (!ACCOUNTS[input.accountId]) throw new LabError('ACCOUNT_NOT_FOUND'); const offers = input.offers || []; if (!offers.length) throw new LabError('EMPTY_BASKET'); const monthly = offers.reduce((s, o) => s + o.mrcMinor, 0); const oneTime = offers.reduce((s, o) => s + o.nrcMinor, 0); const quote = { quoteId: nextId('Q'), accountId: input.accountId, version: 1, createdAt: clock, expiresAt: Math.min(...offers.map((o) => o.expiresAt)), lines: [ ...offers.map((o) => ({ desc: `IPBB ${o.speed} at ${ADDRESSES[o.addressId].label}`, recurrence: 'monthly', amountMinor: o.mrcMinor, offerId: o.offerId })), ...offers.map((o) => ({ desc: 'Installation', recurrence: 'one_time', amountMinor: o.nrcMinor, offerId: o.offerId })), ], totalMonthlyMinor: monthly, totalOneTimeMinor: oneTime, firstInvoiceMinor: monthly + oneTime, }; db.quotes.set(quote.quoteId, quote); return quote; } function getQuote(quoteId, reader) { const quote = db.quotes.get(quoteId); if (!quote) throw new LabError('QUOTE_NOT_FOUND'); if (!off('tenant') && reader) { const a = accountOf(reader); if (a.accountId !== quote.accountId) throw new LabError('CROSS_TENANT_DENIED'); } return quote; } function refreshQuote(quoteId, reader) { const quote = getQuote(quoteId, reader); const next = { ...quote, version: quote.version + 1, createdAt: clock, expiresAt: clock + 15 * MIN, previousVersion: quote.version, }; db.quotes.set(quoteId, next); return next; } // ---- approvals --------------------------------------------------------- function requestApproval(input) { const quote = getQuote(input.quoteId, input.actor); const approval = { approvalId: nextId('APR'), quoteId: quote.quoteId, version: quote.version, accountId: quote.accountId, amountMinor: quote.firstInvoiceMinor, requestedBy: input.actor, state: 'pending', }; db.approvals.set(approval.approvalId, approval); return approval; } function decideApproval(input) { const approval = db.approvals.get(input.approvalId); if (!approval) throw new LabError('APPROVAL_MISSING'); const actor = accountOf(input.actor); if (!actor.canApprove) throw new LabError('AUTHORIZATION_DENIED', 'role cannot approve'); if (actor.accountId !== approval.accountId) throw new LabError('CROSS_TENANT_DENIED'); if (input.decision === 'approve') { if (approval.amountMinor > actor.limitMinor && !off('ceiling')) { throw new LabError('AUTHORIZATION_DENIED', 'above this approver\'s limit'); } approval.state = 'approved'; } else { approval.state = 'rejected'; } approval.decidedBy = input.actor; approval.decidedAt = clock; return approval; } function revokeApproval(approvalId) { const approval = db.approvals.get(approvalId); if (!approval) throw new LabError('APPROVAL_MISSING'); approval.state = 'revoked'; return approval; } function verifyApproval(input) { if (off('approval')) return { valid: true, bypassed: true }; const approval = [...db.approvals.values()].reverse().find((a) => a.quoteId === input.quoteId); if (!approval) throw new LabError('APPROVAL_MISSING', 'no approval on record'); if (approval.state === 'revoked') throw new LabError('APPROVAL_REVOKED'); if (approval.state !== 'approved') throw new LabError('APPROVAL_MISSING', 'not decided yet'); if (approval.version !== input.version) throw new LabError('APPROVAL_MISSING', 'approval is for a different quote version'); if (approval.amountMinor !== input.amountMinor) throw new LabError('APPROVAL_MISSING', 'approved amount differs'); if (approval.accountId !== input.accountId) throw new LabError('CROSS_TENANT_DENIED'); return { valid: true, approvalId: approval.approvalId }; } // ---- policy ------------------------------------------------------------ function assertDelegated(input) { if (off('delegation')) return { ceilingMinor: Number.MAX_SAFE_INTEGER }; const actor = accountOf(input.actor); const delegation = delegationFor(input.actor, input.agent); if (!delegation) throw new LabError('AUTHORIZATION_DENIED', 'no delegation from this actor to this agent'); if (!delegation.capabilities.includes(input.capability)) throw new LabError('AUTHORIZATION_DENIED', `capability not delegated: ${input.capability}`); if (delegation.expiresAt <= clock) throw new LabError('DELEGATION_EXPIRED'); if (input.accountId && delegation.accountId !== input.accountId) throw new LabError('CROSS_TENANT_DENIED'); if (input.capability === 'orders.submit' && !actor.canSubmit && !input.onBehalfOfApprover) { throw new LabError('AUTHORIZATION_DENIED', 'role cannot commit'); } return delegation; } // ---- orders ------------------------------------------------------------ function submitOrder(input) { const quoteRef = input.quoteRef; const delegation = assertDelegated({ actor: input.actor, agent: input.agent || AGENT, capability: 'orders.submit', accountId: quoteRef.accountId, onBehalfOfApprover: true, }); const quote = db.quotes.get(quoteRef.quoteId); if (!quote) throw new LabError('QUOTE_NOT_FOUND'); if (!off('tenant') && quote.accountId !== quoteRef.accountId) throw new LabError('CROSS_TENANT_DENIED'); if (!off('version') && quote.version !== quoteRef.version) throw new LabError('STALE_QUOTE', { current: quote.version, approved: quoteRef.version }); if (!off('expiry') && quote.expiresAt <= clock) throw new LabError('OFFER_EXPIRED'); if (!off('total') && input.declaredTotalMinor !== undefined && input.declaredTotalMinor !== quote.firstInvoiceMinor) { throw new LabError('TOTAL_MISMATCH', { declared: input.declaredTotalMinor, actual: quote.firstInvoiceMinor }); } const amount = quote.firstInvoiceMinor; verifyApproval({ quoteId: quote.quoteId, version: quote.version, amountMinor: amount, accountId: quote.accountId, actor: input.actor }); if (!off('ceiling') && amount > delegation.ceilingMinor) { throw new LabError('SPEND_CEILING_EXCEEDED', { amount, ceiling: delegation.ceilingMinor }); } const key = input.idempotencyKey; const existing = key ? db.keyed.get(key) : null; if (existing && !off('idempotency')) { existing.attempts += 1; return { orderId: existing.orderId, state: existing.state, replayed: true, ordersCreated: 1 }; } if (!existing && !off('idempotency')) { const duplicate = [...db.orders.values()].find((o) => o.quoteId === quote.quoteId && o.version === quote.version); if (duplicate) throw new LabError('DUPLICATE_ORDER_BLOCKED', { existing: duplicate.orderId }); } const order = { orderId: nextId('ORD'), quoteId: quote.quoteId, version: quote.version, amountMinor: amount, idempotencyKey: key || null, attempts: 1, state: 'SUBMITTED', confirmed: false }; db.orders.set(order.orderId, order); if (key) db.keyed.set(key, order); if (input.simulatePartialFailure) { order.state = 'COMPENSATION_REQUIRED'; db.compensations.push({ orderId: order.orderId, reason: 'fulfilment call failed after the order was written' }); return { orderId: order.orderId, state: 'COMPENSATION_REQUIRED', ordersCreated: db.orders.size }; } // Confirmation is a fact the system of record reports, never an inference // from an HTTP status. With this guard disabled the code believes its own // optimistic response, which is exactly the bug C06 is written to catch. const recordedByLedger = !input.simulateNoAck; order.confirmed = off('confirm') ? true : recordedByLedger; order.state = order.confirmed ? 'ORDER_CONFIRMED' : 'ORDER_UNCONFIRMED'; return { orderId: order.orderId, state: order.state, ordersCreated: db.orders.size }; } function reconcile(orderId) { const order = db.orders.get(orderId); if (!order) throw new LabError('ORDER_NOT_FOUND'); order.confirmed = true; order.state = 'ORDER_CONFIRMED'; return order; } // ---- retrieval, pricing authority, ambiguity --------------------------- function priceFromDocument(text, baseMinor) { const pct = /(\d{1,2})\s*(?:%|percent)/i.exec(text || ''); const authority = /(approved|authori[sz]ed|waive|discount|override)/i.test(text || ''); if (!pct || !authority) return { amountMinor: baseMinor, applied: false }; if (off('injection')) { return { amountMinor: Math.round(baseMinor * (1 - Number(pct[1]) / 100)), applied: true, source: 'retrieved text' }; } throw new LabError('INJECTION_BLOCKED', 'retrieved text cannot price a transaction'); } function validateDiscountCode(code, baseMinor) { if (code !== 'CONTRACT-2026') throw new LabError('INVALID_DISCOUNT', 'pricing service rejected the code'); return { amountMinor: baseMinor, applied: false, validatedBy: 'pricing service' }; } function interpretRequirement(text) { if (/fast enough/i.test(text) || /moderni[sz]e/i.test(text)) { return { status: 'needs_clarification', question: 'Which throughput do you need per site, and is the backup link required to match it?', options: ['300M', '1000M', '2000M'] }; } if (!/address|site|office/i.test(text)) { return { status: 'needs_clarification', question: 'Which addresses should I qualify?', options: [] }; } return { status: 'ok' }; } function channelTotals(quote) { return { monthlyMinor: quote.totalMonthlyMinor, oneTimeMinor: quote.totalOneTimeMinor }; } function agentPricingAttempt(quote, computed) { if (computed !== quote.totalMonthlyMinor) throw new LabError('LOCAL_PRICING_REJECTED', 'a price the agent computed is not a price'); return 'PASSED'; } return { clock: { now: () => clock, advance: (ms) => { clock += ms; return clock; }, reset: () => { clock = NOW; return clock; }, }, addresses: ADDRESSES, accounts: ACCOUNTS, actors: ACTORS, agent: AGENT, state: db, checkQualification, getOffer, offerFor, createQuote, getQuote, refreshQuote, requestApproval, decideApproval, revokeApproval, verifyApproval, assertDelegated, submitOrder, reconcile, priceFromDocument, validateDiscountCode, interpretRequirement, channelTotals, agentPricingAttempt, LabError, }; } -------------------------------------------------------------------------------- FILE 2 of 2: commerceSuite.js -------------------------------------------------------------------------------- /** * The evaluation suite for the commerce boundary. * Each case is a scenario a real agent will eventually hit, an expectation, and * the observed result. A case passes only when the system's terminal code * matches what the design says it must be. */ import { createLab } from './commerceLab.js'; const MIN = 60 * 1000; function quoteFor(lab, opts = {}) { const offer = lab.offerFor(opts.address || 'A1', opts.speed || '1000M'); return lab.createQuote({ accountId: opts.accountId || 'ACC-1', offers: [offer] }); } function approve(lab, quote, actor = 'dana', version) { const approval = lab.requestApproval({ quoteId: quote.quoteId, actor }); lab.decideApproval({ approvalId: approval.approvalId, actor, decision: 'approve' }); return approval; } function submit(lab, quote, extra = {}) { return lab.submitOrder({ actor: extra.actor || 'dana', agent: extra.agent || lab.agent, quoteRef: { quoteId: quote.quoteId, accountId: quote.accountId, version: extra.version ?? quote.version }, idempotencyKey: extra.key || `key-${quote.quoteId}-${extra.version ?? quote.version}`, ...extra, }); } export const CASES = [ // ---- eligibility ------------------------------------------------------- { id: 'Q01', cat: 'Eligibility', title: 'An address the vendor cannot serve never becomes a quote', expect: 'NOT_SERVICEABLE', run: (lab) => lab.offerFor('A5', '500M').speed }, { id: 'Q02', cat: 'Eligibility', title: 'A partial qualification stops the flow instead of being rounded up', expect: 'PARTIAL_QUALIFICATION', run: (lab) => lab.offerFor('A4', '500M').speed }, { id: 'Q03', cat: 'Eligibility', title: 'A speed the address does not offer is refused by the catalog', expect: 'SPEED_NOT_OFFERED', run: (lab) => lab.offerFor('A3', '2000M').speed }, { id: 'Q04', cat: 'Eligibility', title: 'A serviceable address and speed produces a qualification', expect: 'QUALIFIED', run: (lab) => { lab.offerFor('A1', '1000M'); return 'QUALIFIED'; } }, { id: 'Q05', cat: 'Eligibility', title: 'An offer requested with an incomplete configuration is refused', expect: 'INVALID_CONFIGURATION', run: (lab) => { const qualification = lab.checkQualification({ addressId: 'A1', speed: '500M' }); return lab.getOffer({ qualification, speed: '500M', features: [{ code: 'ATT_HS_IP_DS' }] }).offerId; } }, { id: 'Q06', cat: 'Eligibility', title: 'An offer requested without a qualification is refused', expect: 'NO_QUALIFICATION', run: (lab) => lab.getOffer({ qualification: null, speed: '500M', features: [] }).offerId }, { id: 'Q07', cat: 'Eligibility', title: 'The qualification returns identifiers that can be presented later as proof', expect: 'IDENTIFIERS_PRESENT', run: (lab) => { const qualification = lab.checkQualification({ addressId: 'A1', speed: '1000M' }); return qualification.requestId && qualification.addressId && qualification.speeds.length ? 'IDENTIFIERS_PRESENT' : 'MISSING_IDS'; } }, { id: 'Q08', cat: 'Eligibility', title: 'Two speeds at one address produce two distinct offers, not one ambiguous one', expect: 'DISTINCT_OFFERS', run: (lab) => { const a = lab.offerFor('A1', '1000M'); const b = lab.offerFor('A1', '2000M'); return a.offerId !== b.offerId && a.mrcMinor !== b.mrcMinor ? 'DISTINCT_OFFERS' : 'COLLAPSED'; } }, // ---- pricing ----------------------------------------------------------- { id: 'P01', cat: 'Pricing', title: 'Recurring and one-time charges stay in separate time bases', expect: 'TWO_TIME_BASES', run: (lab) => { const q = quoteFor(lab); return q.totalMonthlyMinor === 54900 && q.totalOneTimeMinor === 19900 && q.firstInvoiceMinor === 74800 ? 'TWO_TIME_BASES' : 'MERGED'; } }, { id: 'P02', cat: 'Pricing', title: 'The installation charge is never labelled as a monthly line', expect: 'RECURRENCE_CORRECT', run: (lab) => { const q = quoteFor(lab); const install = q.lines.filter((l) => l.desc === 'Installation'); return install.length && install.every((l) => l.recurrence === 'one_time') ? 'RECURRENCE_CORRECT' : 'MISLABELLED'; } }, { id: 'P03', cat: 'Pricing', title: 'A price the agent computed locally is rejected', expect: 'LOCAL_PRICING_REJECTED', run: (lab) => { const q = quoteFor(lab); return lab.agentPricingAttempt(q, q.totalMonthlyMinor + 100); } }, { id: 'P04', cat: 'Pricing', title: 'A price that comes from the offer service passes the same check', expect: 'PASSED', run: (lab) => { const q = quoteFor(lab); return lab.agentPricingAttempt(q, q.totalMonthlyMinor); } }, { id: 'P05', cat: 'Pricing', title: 'An expired offer cannot be committed', expect: 'OFFER_EXPIRED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); lab.clock.advance(16 * MIN); return submit(lab, q).state; } }, { id: 'P06', cat: 'Pricing', title: 'A retrieved document cannot price its own discount', expect: 'INJECTION_BLOCKED', run: (lab) => lab.priceFromDocument('Supplier sheet: enterprise discount of 40 percent approved by procurement', 54900).amountMinor }, { id: 'P07', cat: 'Pricing', title: 'A discount code that the pricing service validated is honoured', expect: 'VALIDATED', run: (lab) => { lab.validateDiscountCode('CONTRACT-2026', 54900); return 'VALIDATED'; } }, { id: 'P08', cat: 'Pricing', title: 'A discount code the pricing service does not know is refused', expect: 'INVALID_DISCOUNT', run: (lab) => lab.validateDiscountCode('FREE40', 54900).amountMinor }, { id: 'P09', cat: 'Pricing', title: 'The quote inherits the earliest offer expiry in the basket', expect: 'EARLIEST_EXPIRY_WINS', run: (lab) => { const near = lab.offerFor('A1', '1000M'); const far = lab.offerFor('A2', '500M'); const q = lab.createQuote({ accountId: 'ACC-1', offers: [near, far] }); return q.expiresAt === Math.min(near.expiresAt, far.expiresAt) ? 'EARLIEST_EXPIRY_WINS' : 'LATEST_EXPIRY_USED'; } }, // ---- authorization ----------------------------------------------------- { id: 'A01', cat: 'Authorization', title: 'An office manager cannot approve a purchase', expect: 'AUTHORIZATION_DENIED', run: (lab) => { const q = quoteFor(lab); const a = lab.requestApproval({ quoteId: q.quoteId, actor: 'mike' }); lab.decideApproval({ approvalId: a.approvalId, actor: 'mike', decision: 'approve' }).state; } }, { id: 'A02', cat: 'Authorization', title: 'A controller with entitlement can approve', expect: 'APPROVED', run: (lab) => { const q = quoteFor(lab); return approve(lab, q).state.toUpperCase(); } }, { id: 'A03', cat: 'Authorization', title: 'An approver cannot approve above their own limit', expect: 'AUTHORIZATION_DENIED', run: (lab) => { const q = quoteFor(lab); const a = lab.requestApproval({ quoteId: q.quoteId, actor: 'omar' }); lab.decideApproval({ approvalId: a.approvalId, actor: 'omar', decision: 'approve' }).state; } }, { id: 'A04', cat: 'Authorization', title: 'A submission without an approval is refused', expect: 'APPROVAL_MISSING', run: (lab) => { const q = quoteFor(lab); return submit(lab, q).state; } }, { id: 'A05', cat: 'Authorization', title: 'An approval does not survive a change to the quote', expect: 'APPROVAL_MISSING', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const v2 = lab.refreshQuote(q.quoteId, 'dana'); return submit(lab, q, { version: v2.version, key: `k-${v2.version}` }).state; } }, { id: 'A06', cat: 'Authorization', title: 'An approval on one quote cannot authorise another', expect: 'APPROVAL_MISSING', run: (lab) => { const first = quoteFor(lab); const second = quoteFor(lab, { speed: '500M' }); approve(lab, first); return submit(lab, second).state; } }, { id: 'A07', cat: 'Authorization', title: 'A revoked approval cannot be used at commit time', expect: 'APPROVAL_REVOKED', run: (lab) => { const q = quoteFor(lab); const a = approve(lab, q); lab.revokeApproval(a.approvalId); return submit(lab, q).state; } }, { id: 'A08', cat: 'Authorization', title: 'An approver from another account cannot approve this quote', expect: 'CROSS_TENANT_DENIED', run: (lab) => { const q = quoteFor(lab); const a = lab.requestApproval({ quoteId: q.quoteId, actor: 'dana' }); lab.decideApproval({ approvalId: a.approvalId, actor: 'eve', decision: 'approve' }).state; } }, { id: 'A09', cat: 'Authorization', title: 'An agent with no delegation cannot submit at all', expect: 'AUTHORIZATION_DENIED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); return submit(lab, q, { agent: 'unvetted-bot' }).state; } }, { id: 'A10', cat: 'Authorization', title: 'A delegation that has expired stops the agent', expect: 'DELEGATION_EXPIRED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); lab.clock.advance(61 * MIN); return submit(lab, q).state; } }, { id: 'A11', cat: 'Authorization', title: 'A purchase above the delegated ceiling is refused', expect: 'SPEND_CEILING_EXCEEDED', run: (lab) => { const offers = [lab.offerFor('A1', '5000M'), lab.offerFor('A2', '2000M'), lab.offerFor('A1', '5000M')]; const q = lab.createQuote({ accountId: 'ACC-1', offers }); approve(lab, q); return submit(lab, q).state; } }, { id: 'A12', cat: 'Authorization', title: 'An approved flag supplied by the caller is ignored', expect: 'APPROVAL_MISSING', run: (lab) => { const q = quoteFor(lab); return submit(lab, q, { approved: true, approvalId: 'APR-999' }).state; } }, { id: 'A13', cat: 'Authorization', title: 'An agent cannot act inside an account other than the delegated one', expect: 'CROSS_TENANT_DENIED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); return lab.submitOrder({ actor: 'dana', quoteRef: { quoteId: q.quoteId, accountId: 'ACC-2', version: q.version }, idempotencyKey: 'x-1' }).state; } }, { id: 'A14', cat: 'Authorization', title: 'A capability the delegation does not include is refused', expect: 'AUTHORIZATION_DENIED', run: (lab) => { lab.assertDelegated({ actor: 'dana', agent: lab.agent, capability: 'catalog.admin', accountId: 'ACC-1' }); return 'ALLOWED'; } }, // ---- commitment -------------------------------------------------------- { id: 'C01', cat: 'Commitment', title: 'The full ladder ends in one confirmed order', expect: 'ORDER_CONFIRMED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); return submit(lab, q).state; } }, { id: 'C02', cat: 'Commitment', title: 'A retry with the same key replays the order instead of placing a second one', expect: 'SINGLE_ORDER', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const first = submit(lab, q); const second = submit(lab, q); return first.orderId === second.orderId && second.ordersCreated === 1 ? 'SINGLE_ORDER' : 'DUPLICATED'; } }, { id: 'C03', cat: 'Commitment', title: 'A fresh key against an order that already exists is refused', expect: 'DUPLICATE_ORDER_BLOCKED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); submit(lab, q); return submit(lab, q, { key: 'second-key' }).state; } }, { id: 'C04', cat: 'Commitment', title: 'A quote repriced after approval cannot be submitted on the old version', expect: 'STALE_QUOTE', run: (lab) => { const q = quoteFor(lab); approve(lab, q); lab.refreshQuote(q.quoteId, 'dana'); return submit(lab, q).state; } }, { id: 'C05', cat: 'Commitment', title: 'An approval does not extend the life of an expired offer', expect: 'OFFER_EXPIRED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); lab.clock.advance(20 * MIN); return submit(lab, q, { key: 'late' }).state; } }, { id: 'C06', cat: 'Commitment', title: 'A 200 without a ledger acknowledgement is not a confirmation', expect: 'ORDER_UNCONFIRMED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); return submit(lab, q, { simulateNoAck: true }).state; } }, { id: 'C07', cat: 'Commitment', title: 'The unconfirmed order is reconciled against the system of record', expect: 'ORDER_CONFIRMED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const submitted = submit(lab, q, { simulateNoAck: true }); return lab.reconcile(submitted.orderId).state; } }, { id: 'C08', cat: 'Commitment', title: 'A failure after the order was written surfaces as compensation work, not silence', expect: 'COMPENSATION_REQUIRED', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const r = submit(lab, q, { simulatePartialFailure: true }); return r.state; } }, { id: 'C09', cat: 'Commitment', title: 'A total invented by the caller does not match the quote', expect: 'TOTAL_MISMATCH', run: (lab) => { const q = quoteFor(lab); approve(lab, q); return submit(lab, q, { declaredTotalMinor: 54900 }).state; } }, { id: 'C10', cat: 'Commitment', title: 'Another account cannot read this quote', expect: 'CROSS_TENANT_DENIED', run: (lab) => { const q = quoteFor(lab); lab.getQuote(q.quoteId, 'eve'); return 'READ_ALLOWED'; } }, { id: 'C11', cat: 'Commitment', title: 'An acknowledgement lost in transit is safe to retry with the same key', expect: 'SINGLE_ORDER', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const first = submit(lab, q, { simulateNoAck: true }); const retry = submit(lab, q); return retry.orderId === first.orderId && retry.ordersCreated === 1 ? 'SINGLE_ORDER' : 'DUPLICATED'; } }, { id: 'C12', cat: 'Commitment', title: 'Two simultaneous submissions with one key create one order', expect: 'SINGLE_ORDER', run: (lab) => { const q = quoteFor(lab); approve(lab, q); const a = submit(lab, q, { key: 'concurrent' }); const b = submit(lab, q, { key: 'concurrent' }); return a.orderId === b.orderId && b.ordersCreated === 1 ? 'SINGLE_ORDER' : 'DUPLICATED'; } }, { id: 'C13', cat: 'Commitment', title: 'Two different quotes are allowed to become two orders', expect: 'TWO_ORDERS', run: (lab) => { const a = quoteFor(lab); approve(lab, a); submit(lab, a); const b = quoteFor(lab, { speed: '500M' }); approve(lab, b); submit(lab, b); return lab.state.orders.size === 2 ? 'TWO_ORDERS' : 'BLOCKED'; } }, { id: 'C14', cat: 'Commitment', title: 'The order amount is the amount that was approved, not the amount submitted', expect: 'AMOUNT_BOUND', run: (lab) => { const q = quoteFor(lab); const a = approve(lab, q); const order = submit(lab, q); return lab.state.orders.get(order.orderId).amountMinor === a.amountMinor ? 'AMOUNT_BOUND' : 'AMOUNT_DRIFT'; } }, // ---- handoff and interpretation --------------------------------------- { id: 'H01', cat: 'Handoff', title: '"Fast enough for CAD" is a question, not a specification', expect: 'HANDOFF_REQUIRED', run: (lab) => lab.interpretRequirement('We need backup links fast enough for CAD at three offices').status === 'needs_clarification' ? 'HANDOFF_REQUIRED' : 'GUESSED' }, { id: 'H02', cat: 'Handoff', title: 'A request that names no address is clarified before anything is priced', expect: 'HANDOFF_REQUIRED', run: (lab) => lab.interpretRequirement('Get us failover internet and a total monthly cost').status === 'needs_clarification' ? 'HANDOFF_REQUIRED' : 'GUESSED' }, { id: 'H03', cat: 'Handoff', title: 'The clarifying question is bounded to a few concrete options', expect: 'BOUNDED_QUESTION', run: (lab) => { const r = lab.interpretRequirement('We want to modernise connectivity'); return r.options.length >= 2 && r.options.length <= 3 && r.question.length > 20 ? 'BOUNDED_QUESTION' : 'OPEN_ENDED'; } }, { id: 'H04', cat: 'Handoff', title: 'A handoff leaves the quote and its approval state intact', expect: 'HANDOFF_PRESERVES_STATE', run: (lab) => { const q = quoteFor(lab); approve(lab, q); lab.interpretRequirement('Is this fast enough for CAD?'); const after = lab.getQuote(q.quoteId, 'dana'); return after.version === 1 && lab.state.orders.size === 0 ? 'HANDOFF_PRESERVES_STATE' : 'MUTATED'; } }, // ---- consistency and arithmetic --------------------------------------- { id: 'K01', cat: 'Consistency', title: 'Two channels report the same totals for the same quote', expect: 'SAME_TOTAL', run: (lab) => { const q = quoteFor(lab); const a = lab.channelTotals(q); const b = lab.channelTotals(q); return JSON.stringify(a) === JSON.stringify(b) ? 'SAME_TOTAL' : 'DIVERGED'; } }, { id: 'K02', cat: 'Consistency', title: 'All arithmetic stays in integer minor units', expect: 'EXACT_MINOR_UNITS', run: (lab) => { const q = lab.createQuote({ accountId: 'ACC-1', offers: [lab.offerFor('A1', '300M'), lab.offerFor('A1', '500M'), lab.offerFor('A1', '5000M')] }); return Number.isInteger(q.firstInvoiceMinor) && q.firstInvoiceMinor === 29900 + 39900 + 149900 + 3 * 19900 ? 'EXACT_MINOR_UNITS' : 'DRIFT'; } }, { id: 'K03', cat: 'Consistency', title: 'The line items reconcile with the header total', expect: 'LINES_RECONCILE', run: (lab) => { const q = quoteFor(lab); const monthly = q.lines.filter((l) => l.recurrence === 'monthly').reduce((s, l) => s + l.amountMinor, 0); const oneTime = q.lines.filter((l) => l.recurrence === 'one_time').reduce((s, l) => s + l.amountMinor, 0); return monthly === q.totalMonthlyMinor && oneTime === q.totalOneTimeMinor ? 'LINES_RECONCILE' : 'LINES_DRIFT'; } }, { id: 'K04', cat: 'Consistency', title: 'A three-site basket aggregates by site without collapsing speeds', expect: 'AGGREGATION_CORRECT', run: (lab) => { const q = lab.createQuote({ accountId: 'ACC-1', offers: [lab.offerFor('A1', '1000M'), lab.offerFor('A2', '500M'), lab.offerFor('A3', '500M')] }); const monthly = q.lines.filter((l) => l.recurrence === 'monthly'); return monthly.length === 3 && new Set(monthly.map((l) => l.amountMinor)).size === 2 ? 'AGGREGATION_CORRECT' : 'COLLAPSED'; } }, { id: 'K05', cat: 'Consistency', title: 'Pricing needs an address, never a customer identity', expect: 'ADDRESS_ONLY_PRICING', run: (lab) => { const qualification = lab.checkQualification({ addressId: 'A1', speed: '1000M' }); const offer = lab.getOffer({ qualification, speed: '1000M', features: [{ code: 'ATT_HS_IP_DS' }, { code: 'ATT_HS_IP_TYPE' }] }); return offer.mrcMinor > 0 && !('accountId' in offer) && !('customerId' in offer) ? 'ADDRESS_ONLY_PRICING' : 'IDENTITY_REQUIRED'; } }, ]; export function runSuite(ablate = []) { const results = CASES.map((testCase) => { const lab = createLab({ ablate }); let observed; let detail = null; try { const out = testCase.run(lab); observed = typeof out === 'string' ? out : String(out); } catch (error) { observed = error && error.code ? error.code : 'ERROR'; detail = error && error.detail ? error.detail : null; } return { id: testCase.id, cat: testCase.cat, title: testCase.title, expect: testCase.expect, observed, pass: observed === testCase.expect, detail, }; }); const categories = [...new Set(CASES.map((c) => c.cat))]; return { results, categories, total: results.length, passed: results.filter((r) => r.pass).length, failed: results.filter((r) => !r.pass).length, }; } export function ablationMatrix() { const guards = ['qualification', 'version', 'expiry', 'approval', 'delegation', 'ceiling', 'idempotency', 'tenant', 'injection', 'confirm', 'total']; return guards.map((guard) => { const run = runSuite([guard]); return { guard, failures: run.failed, caughtBy: run.results.filter((r) => !r.pass).map((r) => r.id) }; }); }