Test that each contract check catches its target issue and stays quiet on valid cases.
Add "Product model coverage tests" from ntent to this repo.
Fetch https://ntent.app/r/f/check-contract-coverage-test as plain text. Write it verbatim to scripts/check-contract-coverage.test.mjs.
It needs check-contract-coverage.mjs and contract.json. If this repo does not have them, stop and tell me.
Then check it: node --test passes. Break one reference in the contract by hand and exactly one test goes red, naming the check that caught it. Stage an edit that breaks check-contract-coverage.mjs and the pre-commit hook runs this file and refuses the commit. When that happens the check is what gets fixed: the test changes only when the person has said the rule moved.Reads https://ntent.app/r/f/check-contract-coverage-test
Read the code
check-contract-coverage.test.mjsscripts/check-contract-coverage.test.mjs
1457 lines
/**
* Tests for the reference checks, which are the half of this script that gates
* a commit. The coverage number is a nag and reads the filesystem, so it is
* checked by running it; these three are pure functions over a parsed contract
* and are the part a person cannot verify by reading.
*
* What is worth locking down is narrow. Not that a finding is worded well, but
* that each check FIRES on the shape it exists for and stays quiet on the shape
* it does not, because a check that never fires and a check that always fires
* are both deleted within a month.
*
* The last two tests are the contract with the pre-commit hook: the gate is the
* exit code, not the output, and the hook has to work in a repo that has never
* installed TypeScript.
*
* Run, installed: node --test scripts/check-contract-coverage.test.mjs
* Run, in this repo: node --test files/scripts/check-contract-coverage.test.mjs
*/
import test, { after } from 'node:test'
import assert from 'node:assert/strict'
import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, realpathSync, rmSync, symlinkSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join, dirname } from 'node:path'
import { fileURLToPath, pathToFileURL } from 'node:url'
import { checkReferences, evidenceFindings, evidenceEntry, citedFiles, referenceWarnings, shapeProblems, refTarget, fieldName, stripComments, VOCABULARY } from './check-contract-coverage.mjs'
// Every temp dir this file makes. They are removed when the file's tests end, pass or fail.
const made = []
const tmp = (prefix) => {
const dir = mkdtempSync(join(tmpdir(), prefix))
made.push(dir)
return dir
}
after(() => {
for (const dir of made) rmSync(dir, { recursive: true, force: true })
})
const here = dirname(fileURLToPath(import.meta.url))
const SCRIPT = join(here, 'check-contract-coverage.mjs')
// The shipped CONFIG. The customise step has a consumer replace the entity maps
// and directories, so the tests that run the script as a process run a copy
// with these laid over CONFIG, and test the shipped behaviour whatever the
// consumer's CONFIG says. Nothing is written beside the script.
const SHIPPED_CONFIG = {
contractFile: 'contract.json',
typeDirs: ['src/types', 'src/lib', 'src/features'],
fixtureDirs: ['fixtures', 'src/data', 'prisma'],
uiDirs: ['src/app', 'src/components'],
ignoreDirs: ['node_modules', '.next', 'dist', '.git'],
entityTypeMap: { invoice: ['Invoice', 'InvoiceDetail'], customer: ['Customer'], subscription: ['Subscription'] },
entityFixtureMap: { invoice: ['invoice'], customer: ['customer'], subscription: ['subscription'] },
entityUiMap: {
invoice: ['src/app/invoices', 'src/components/invoice'],
customer: ['src/app/customers', 'src/components/customer'],
subscription: ['src/app/subscriptions'],
},
unmeasured: {},
fieldAliases: {
invoice_number: ['ref', 'number'],
total_amount: ['total', 'amount'],
customer_id: ['customerId'],
created_at: ['createdAt'],
due_date: ['dueDate'],
line_items: ['lines', 'items'],
},
minCoverage: 0.0,
}
let pinnedFile = null
/** The script with SHIPPED_CONFIG laid over CONFIG, in a temp directory. */
const pinnedScript = () => {
if (pinnedFile) return pinnedFile
let text = readFileSync(SCRIPT, 'utf8')
const start = text.indexOf('const CONFIG = {')
const end = text.indexOf('\n}\n', start) + 3
assert.ok(start > 0 && end > 3, 'CONFIG is a literal that closes on its own line')
text = `${text.slice(0, end)}Object.assign(CONFIG, ${JSON.stringify(SHIPPED_CONFIG)})\n${text.slice(end)}`
const requireFrom = 'createRequire(import.meta.url)'
assert.ok(text.includes(requireFrom), 'typescript is resolved from the script location')
text = text.replace(requireFrom, `createRequire(${JSON.stringify(pathToFileURL(SCRIPT).href)})`)
// realpath: the script runs itself only when its URL matches argv[1], and /var is a link on macOS.
pinnedFile = join(realpathSync(tmp('contract-pinned-')), 'check-contract-coverage.mjs')
writeFileSync(pinnedFile, text)
return pinnedFile
}
/**
* The shipped example contract, held in this file.
*
* These tests name the example's own journeys and open questions
* (refund-payment, OQ-011), and the customise step has you replace contract.json
* with your product's. Reading your contract here would fail them on the first
* edit and the selftest gate would refuse the commit. So they read this copy,
* and your contract.json is untouched by them. A test in the package that ships
* this file checks the copy equals examples/contract.json.
*/
const EXAMPLE = JSON.parse(String.raw`
{
"version": "0.4.0",
"updated": "2026-09-05",
"_comment": "The product contract. Eight pillars: actors, access, entitlements, entities, journeys, rules, constraints, open questions. Everything here either feeds a gate or feeds a screen. Start with entities and journeys, add a pillar when something forces you to, and run scripts/check-contract-coverage.mjs to score it. A journey is built when it carries an acceptance record: who exercised it, when, at which commit, against what evidence. The reference check refuses built without one, and an evidence line has to be a test file that exists, a pnpm script in package.json, or a manual: line saying what a person saw. A test file that is cited needs its hash beside the evidence, under pins, written sha256:<hex>, with the path spelt exactly as the file is and no space in it, and \"node scripts/check-contract-coverage.mjs --pins <journey>\" prints it: once the file changes, the journey has to be accepted again. A built journey that depends_on an agreed rule has to name that rule in its evidence or carry a manual: line. Worth doing at Tier 2 and up.",
"actors": [
{
"id": "finance_admin",
"description": "Staff who issue and void invoices. Internal.",
"auth": "SSO, staff directory",
"responsibilities": ["issue an invoice", "void and reissue an invoice", "refund a payment"]
},
{
"id": "customer",
"description": "The billed party's contact. External, scoped to one customer record.",
"auth": "email magic link",
"responsibilities": ["view invoices", "pay an invoice", "download a receipt"]
},
{
"id": "billing_webhook",
"kind": "system",
"description": "Stripe. Tells us a charge settled or failed. No screen, and it can arrive twice.",
"auth": "signed webhook secret",
"responsibilities": ["mark an invoice paid", "start dunning on a failed charge"]
},
{
"id": "dunning_job",
"kind": "schedule",
"description": "Nobody triggers it and it has no screen, which is exactly why its behaviour has to be written down.",
"schedule": "daily 02:00 UTC",
"responsibilities": ["move issued invoices past due_date to overdue", "send a reminder on day 3, 7 and 14"]
}
],
"access": {
"tenancy": {
"scope_entity": "customer",
"column": "customer_id",
"membership": { "table": "public.customers", "user_column": "user_id", "tenant_column": "id" },
"rule": "Every invoice, subscription and payment row carries customer_id. A customer actor reads only rows whose customer_id is their own. There is no cross-customer read at any layer.",
"staff_exception": "finance_admin reads across all customers. Every such read is written to the audit log with the actor and the row id."
},
"matrix": [
{
"actor": "finance_admin",
"entity": "invoice",
"can": ["read", "create", "void"],
"cannot": ["update"],
"why": "BR-014. An issued invoice is the legal record, so correcting one means voiding and reissuing."
},
{ "actor": "customer", "entity": "invoice", "can": ["read", "pay"], "scope": "own" },
{ "actor": "customer", "entity": "payment", "can": ["read"], "scope": "own" },
{ "actor": "billing_webhook", "entity": "payment", "can": ["create"], "scope": "all" }
]
},
"entitlements": {
"plans": ["free", "team", "business"],
"gates": [
{
"id": "ENT-001",
"capability": "custom_invoice_branding",
"type": "feature",
"plans": ["business"],
"gates": ["journey:create-invoice"],
"locked_ui": "The branding panel renders with an upgrade CTA where the controls would be. Not hidden: a feature nobody can see is a feature nobody upgrades for."
},
{
"id": "ENT-002",
"capability": "seats",
"type": "quota",
"limits": { "free": 1, "team": 10, "business": null },
"gates": ["journey:create-invoice"],
"at_limit": "Invite button disabled, tooltip naming the count and the plan ceiling. See OQ-009 for what a seat removal does."
}
]
},
"entities": [
{
"id": "invoice",
"table": "public.invoices",
"description": "A bill sent to a customer. Immutable once issued.",
"fields": [
"invoice_number",
{ "name": "total_amount", "type": "money", "required": true },
{ "name": "customer_id", "type": "id", "required": true, "ref": "customer" },
"created_at",
{ "name": "due_date", "type": "date", "required": true },
"line_items",
{ "name": "tax_rate", "type": "decimal" },
{ "name": "pdf_url", "type": "url", "note": "Written by a worker after issue. Absent on a draft, and briefly absent on a fresh issue." }
],
"states": ["draft", "issued", "paid", "overdue", "void"],
"notes": "A field may be a bare string or an object. Add the object form when a type, a required flag or a PII marker starts earning its keep."
},
{
"id": "customer",
"table": "public.customers",
"description": "The billed party. One per Stripe customer.",
"fields": [
{ "name": "customer_id", "type": "id", "column": "id" },
{ "name": "name", "type": "text", "required": true, "pii": true },
{ "name": "email", "type": "email", "required": true, "pii": true },
{ "name": "billing_address", "type": "address", "pii": true, "retention": "7y" }
]
},
{
"id": "subscription",
"description": "An active plan. Seat changes take effect immediately, bill at period end.",
"fields": [
{ "name": "plan", "type": "enum", "values": ["free", "team", "business"], "required": true },
{ "name": "seats", "type": "integer", "required": true },
{ "name": "renews_at", "type": "date" }
],
"source": "DECISIONS.md 2026-08-30, seat proration"
},
{
"id": "payment",
"table": "public.payments",
"description": "A settled charge against an invoice.",
"fields": [
{ "name": "customer_id", "type": "id", "required": true, "ref": "customer" },
{ "name": "invoice_id", "type": "id", "required": true, "ref": "invoice" },
{ "name": "amount", "type": "money", "required": true },
{ "name": "method", "type": "enum", "values": ["card", "bank_transfer"] }
]
}
],
"journeys": [
{
"id": "create-invoice",
"actor": "finance_admin",
"entities": ["invoice", "customer"],
"depends_on": ["BR-014"],
"state": "partial",
"gap": "the seat-quota state ENT-002 puts on this screen waits on OQ-009. Everything else is built."
},
{
"id": "send-invoice",
"actor": "finance_admin",
"entities": ["invoice"],
"state": "partial",
"gap": "no email preview, no resend. BR-014 requires both."
},
{
"id": "pay-invoice",
"actor": "customer",
"entities": ["invoice", "payment"],
"state": "built",
"accepted": {
"on": "2026-09-04",
"by": "R. Nair, finance lead, with the designer",
"commit": "8c1f2a9",
"contract": "0.4.0",
"evidence": [
"manual: paid a real-shaped invoice on a phone, through the card-declined path and the retry. C-002."
]
}
},
{
"id": "settle-charge",
"actor": "billing_webhook",
"entities": ["payment", "invoice"],
"depends_on": ["BR-030"],
"state": "built",
"accepted": {
"on": "2026-08-21",
"by": "M. Okafor, engineering",
"commit": "3b7d0e1",
"contract": "0.3.0",
"evidence": ["manual: replayed one Stripe test-mode charge event twice and saw one payment recorded, not two. BR-030."]
}
},
{
"id": "chase-overdue",
"actor": "dunning_job",
"entities": ["invoice"],
"state": "unbuilt",
"gap": "the job runs nightly and sends nothing. No template, no send, no record of a send. It has no screen, which is why nobody noticed."
},
{
"id": "refund-payment",
"actor": "finance_admin",
"entities": ["payment", "invoice"],
"state": "unbuilt",
"gap": "entirely unbuilt. No UI, no route. Blocked by OQ-011."
}
],
"rules": [
{
"id": "BR-014",
"text": "An invoice can be resent to the same address any number of times, but changing the recipient requires voiding and reissuing, because the original is the legal record.",
"applies_to": ["invoice"],
"source": "Client call 2026-08-12. Finance lead: 'the address on the sent one has to be the address it went to.'",
"status": "agreed"
},
{
"id": "BR-021",
"text": "Seat additions take effect immediately and bill at the next period boundary. Plan upgrades prorate immediately.",
"applies_to": ["subscription"],
"supersedes": ["BR-007", "BR-018"],
"source": "DECISIONS.md 2026-08-30. Consolidates former BR-007 and BR-018.",
"status": "agreed",
"note": "Whether a seat REMOVAL credits at period end is an inference, not agreed. See OQ-009."
},
{
"id": "BR-030",
"text": "A settled-charge webhook may arrive more than once for the same charge. The second one must not create a second payment.",
"applies_to": ["payment", "invoice"],
"source": "Incident 2026-08-19. Two payments recorded against one invoice, and the invoice showed a credit balance to the customer.",
"status": "agreed"
}
],
"constraints": [
{
"id": "C-001",
"kind": "compliance",
"text": "Invoice PDFs are financial records. Retain 7 years and never hard-delete one, including on an erasure request. Redact the customer PII fields instead.",
"affects": ["invoice", "customer"]
},
{
"id": "C-002",
"kind": "platform",
"text": "Finance staff work on desktop at 1440 and up. Customers pay on phones. The customer-facing invoice view is the only screen that has to be responsive.",
"affects": ["journey:pay-invoice"]
},
{
"id": "C-003",
"kind": "capacity",
"text": "The dunning job has a 15-minute window and 40k open invoices. It has to batch and be resumable from a partial run.",
"affects": ["journey:chase-overdue"]
}
],
"open_questions": [
{
"id": "OQ-009",
"question": "Does removing a seat credit at the period end, or not at all?",
"blocks": ["ENT-002"],
"status": "open",
"blocking": true,
"asked_of": "Finance lead",
"asked_on": "2026-08-30"
},
{
"id": "OQ-011",
"question": "Can a refund be partial, and can one invoice be partially refunded more than once?",
"blocks": ["journey:refund-payment"],
"status": "open",
"blocking": true,
"asked_of": "Client finance",
"asked_on": "2026-09-02"
},
{
"id": "OQ-004",
"question": "Which address does a reissued invoice use when the customer record changed in between?",
"blocks": ["BR-014"],
"status": "resolved",
"blocking": false,
"resolution": "The address on the customer record at reissue time. DECISIONS.md 2026-08-14."
}
]
}
`)
/** The shipped example, with one thing broken. Every case reads the same. */
const withEdit = (edit) => {
const contract = structuredClone(EXAMPLE)
edit(contract)
return checkReferences(contract)
}
const journey = (contract, id) => contract.journeys.find((j) => j.id === id)
const where = (findings) => findings.map((f) => f.where)
/**
* A complete acceptance record. `built` is refused without one, so every test
* that builds a journey to probe some OTHER check has to carry it, or the
* finding it is looking for arrives with a second one about acceptance.
*/
const ACCEPTED = { on: '2026-09-01', by: 'Test', commit: 'abc1234', evidence: ['manual: exercised in the test'] }
const build = (j) => Object.assign(j, { state: 'built', accepted: ACCEPTED })
// ------------------------------------------------------------ the example ---
test('the shipped example resolves, so a fresh install starts green', () => {
assert.deepEqual(checkReferences(EXAMPLE), [])
})
test('every finding names a fix, because a gate without a remedy gets bypassed', () => {
const findings = withEdit((c) => {
c.rules[0].applies_to = ['credit_note']
c.journeys[0].actor = 'ops_admin'
c.entities[0].fields.push({ type: 'money' })
build(journey(c, 'refund-payment'))
})
assert.equal(findings.length, 4, 'four unrelated breakages report separately, not first-one-wins')
assert.equal(new Set(where(findings)).size, 4)
for (const f of findings) {
assert.ok(f.fix && f.fix.length > 20, `${f.where} has no usable fix line`)
assert.ok(f.message, `${f.where} has no message`)
}
})
// ------------------------------------------ 0. identity and vocabulary ---
test('two entities with one id is a finding, because every reference to it resolves to whichever one you picked', () => {
const findings = withEdit((c) => c.entities.push({ id: 'invoice', fields: ['nonce'] }))
assert.deepEqual(where(findings), ['entities.invoice'])
assert.match(findings[0].message, /declared twice/)
})
test('a duplicate is caught in every pillar, not only entities', () => {
const findings = withEdit((c) => {
c.journeys.push({ id: 'pay-invoice', actor: 'customer', entities: ['invoice'], state: 'unbuilt' })
c.rules.push({ ...c.rules[0] })
c.open_questions.push({ ...c.open_questions[0] })
})
assert.deepEqual(where(findings), ['journeys.pay-invoice', 'rules.BR-014', 'open_questions.OQ-009'])
})
test('a state or status outside the vocabulary is a finding, since every check downstream would read it leniently', () => {
const findings = withEdit((c) => {
journey(c, 'pay-invoice').state = 'done'
c.open_questions[0].status = 'closed'
})
assert.deepEqual(where(findings), ['journeys.pay-invoice.state', 'open_questions.OQ-009.status'])
assert.match(findings[0].fix, new RegExp(VOCABULARY['journeys[].state'].join(', ')))
})
test('an item with no id at all is a finding rather than a crash', () => {
const findings = withEdit((c) => c.actors.push({ description: 'anonymous' }))
assert.deepEqual(where(findings), ['actors[4]'])
})
// ------------------------------------------ 1. cross-references resolve ---
test('a rule binding an entity nobody declared is a finding', () => {
const findings = withEdit((c) => c.rules[0].applies_to.push('credit_note'))
assert.deepEqual(where(findings), ['rules.BR-014.applies_to'])
assert.match(findings[0].message, /does not resolve to an entity/)
assert.match(findings[0].fix, /Known: invoice, customer, subscription, payment/)
})
test('a journey naming an actor nobody declared is a finding', () => {
const findings = withEdit((c) => (c.journeys[0].actor = 'ops_admin'))
assert.deepEqual(where(findings), ['journeys.create-invoice.actor'])
assert.match(findings[0].message, /does not resolve to an actor/)
})
test('an access row is checked on both axes, so a typo in either is caught', () => {
const findings = withEdit((c) => {
c.access.matrix[0].actor = 'finance-admin'
c.access.matrix[1].entity = 'invoices'
})
assert.deepEqual(where(findings), ['access.matrix[0].actor', 'access.matrix[1].entity'])
})
test('a constraint or entitlement pointing at a journey that no longer exists is a finding', () => {
const findings = withEdit((c) => {
c.constraints[1].affects = ['journey:pay-invoices']
c.entitlements.gates[0].gates = ['journey:brand-invoice']
})
assert.deepEqual(where(findings), ['entitlements.ENT-001.gates', 'constraints.C-002.affects'])
})
test('a prefix decides which pillar a bare id is looked up in', () => {
assert.deepEqual(refTarget('BR-014'), ['rule', 'BR-014'])
assert.deepEqual(refTarget('OQ-009'), ['question', 'OQ-009'])
assert.deepEqual(refTarget('ENT-002'), ['entitlement', 'ENT-002'])
assert.deepEqual(refTarget('C-001'), ['constraint', 'C-001'])
assert.deepEqual(refTarget('invoice'), ['entity', 'invoice'], 'unprefixed means entity')
assert.deepEqual(refTarget('journey:pay-invoice'), ['journey', 'pay-invoice'])
})
test('a missing pillar says to add the pillar, not to check the spelling', () => {
const findings = withEdit((c) => delete c.actors)
assert.ok(findings.length > 0)
assert.match(findings[0].fix, /There is no actors array/)
})
test('a field object with no name is a finding, since everything downstream reads the name', () => {
const findings = withEdit((c) => c.entities[0].fields.push({ type: 'money' }))
assert.equal(findings.length, 1)
assert.match(findings[0].where, /entities\.invoice\.fields\[\d+\]/)
})
test('a field is a bare string or an object, and both give up the same name', () => {
assert.equal(fieldName('tax_rate'), 'tax_rate')
assert.equal(fieldName({ name: 'tax_rate', type: 'decimal' }), 'tax_rate')
assert.equal(fieldName({ type: 'decimal' }), undefined, 'so the check above can catch it')
})
// -------------------------------------------- 2. rule ids cited in prose ---
test('renaming a rule that a journey gap still cites is a finding', () => {
const findings = withEdit((c) => (c.rules[0].id = 'BR-114'))
assert.ok(
findings.some((f) => f.where === 'cited in prose' && f.message.startsWith('BR-014')),
'the citation lives in a sentence, which is where renames get missed'
)
})
test('a retired id still resolves once the rule that absorbed it says so', () => {
const findings = withEdit((c) => (c.rules[1].supersedes = []))
assert.deepEqual(
findings.map((f) => f.message),
['BR-007 is referred to but is not in rules', 'BR-018 is referred to but is not in rules'],
'without supersedes, a consolidated id dies silently'
)
assert.deepEqual(checkReferences(EXAMPLE), [], 'with it, both resolve')
})
// ------------------------------------------------------ 3. open questions ---
test('citing a question that is not in the file is a finding', () => {
const findings = withEdit((c) => (c.open_questions = c.open_questions.filter((q) => q.id !== 'OQ-011')))
assert.ok(findings.some((f) => f.message.startsWith('OQ-011')))
})
test('a journey cannot be built while a blocking question it stands on is open', () => {
const findings = withEdit((c) => (build(journey(c, 'refund-payment'))))
assert.deepEqual(where(findings), ['journeys.refund-payment'])
assert.match(findings[0].message, /marked built while OQ-011 is open and blocking/)
})
test('answering the question is what unblocks it, and so is dropping the blocking flag', () => {
const answered = withEdit((c) => {
build(journey(c, 'refund-payment'))
c.open_questions.find((q) => q.id === 'OQ-011').status = 'resolved'
})
assert.deepEqual(answered, [], 'resolved is the honest way out')
const unflagged = withEdit((c) => {
build(journey(c, 'refund-payment'))
c.open_questions.find((q) => q.id === 'OQ-011').blocking = false
})
assert.deepEqual(unflagged, [], 'so is deciding it does not block, which is a visible edit')
})
test('a question is only blocking where it was declared blocking', () => {
const findings = withEdit((c) => {
build(journey(c, 'refund-payment'))
journey(c, 'refund-payment').gap = undefined
const q = c.open_questions.find((q) => q.id === 'OQ-011')
q.blocking = false
q.status = 'open'
})
assert.deepEqual(findings, [], 'an open question that nobody called blocking does not stop a build')
})
test('an unbuilt journey may stand on as many open questions as it likes', () => {
assert.deepEqual(checkReferences(EXAMPLE), [], 'refund-payment is unbuilt and cites OQ-011')
})
test('a blocking question on an entitlement gate blocks the journeys that gate names', () => {
// OQ-009 blocks ENT-002, and ENT-002 gates create-invoice. The gate's
// at-limit state is undecided, so the screen that shows it cannot be done.
const findings = withEdit((c) => build(journey(c, 'create-invoice')))
assert.deepEqual(where(findings), ['journeys.create-invoice'])
assert.match(findings[0].message, /OQ-009.*blocks ENT-002, which the journey stands on/)
})
test('a blocking question on a rule blocks a journey only where the journey says it depends on that rule', () => {
// The example's gap line cites OQ-009 in prose, which is its own reason to
// block. Cleared here so the only path left is the dependency.
const built = (c) => Object.assign(journey(c, 'create-invoice'), { state: 'built', gap: undefined, accepted: ACCEPTED })
const dependent = withEdit((c) => {
built(c)
c.open_questions.find((q) => q.id === 'OQ-009').blocks = ['BR-014']
})
assert.deepEqual(where(dependent), ['journeys.create-invoice'], 'create-invoice lists BR-014 in depends_on')
assert.match(dependent[0].message, /blocks BR-014, which the journey stands on/)
const unrelated = withEdit((c) => {
built(c)
journey(c, 'settle-charge').depends_on = []
c.open_questions.find((q) => q.id === 'OQ-009').blocks = ['BR-030']
})
assert.deepEqual(unrelated, [], 'BR-030 applies to invoice too, and that is inference, not a dependency')
})
test('a blocking question on an entity blocks the built journeys that list that entity', () => {
const findings = withEdit((c) => {
c.open_questions.find((q) => q.id === 'OQ-009').blocks = ['customer']
})
assert.deepEqual(where(findings), [], 'no built journey lists customer')
const hit = withEdit((c) => {
c.open_questions.find((q) => q.id === 'OQ-009').blocks = ['payment']
})
assert.deepEqual(where(hit).sort(), ['journeys.pay-invoice', 'journeys.settle-charge'])
})
test('depends_on is resolved like any other reference', () => {
const findings = withEdit((c) => (journey(c, 'create-invoice').depends_on = ['C-999']))
assert.deepEqual(where(findings), ['journeys.create-invoice.depends_on'])
assert.match(findings[0].message, /does not resolve to a constraint/)
})
// --------------------------------------------------------- 4. acceptance ---
test('the shipped example says who found each built journey working', () => {
const built = EXAMPLE.journeys.filter((j) => j.state === 'built')
assert.ok(built.length > 0, 'the example has something built, or none of this is exercised')
for (const j of built) assert.ok(j.accepted, `${j.id} is built and carries its record`)
})
test('a journey marked built with no acceptance record is a finding', () => {
const findings = withEdit((c) => (journey(c, 'pay-invoice').accepted = undefined))
assert.deepEqual(where(findings), ['journeys.pay-invoice'])
assert.match(findings[0].message, /no acceptance record/)
assert.match(findings[0].fix, /"accepted"/, 'the fix shows the shape rather than describing it')
})
test('an incomplete record names the fields it is missing', () => {
const findings = withEdit((c) => (journey(c, 'pay-invoice').accepted = { on: '2026-09-04', evidence: [] }))
assert.deepEqual(where(findings), ['journeys.pay-invoice.accepted'])
assert.match(findings[0].message, /missing by, commit, evidence/)
})
test('a piece of evidence has to say something', () => {
const findings = withEdit((c) => (journey(c, 'pay-invoice').accepted.evidence = ['']))
assert.match(findings[0].message, /missing evidence/)
})
test('the date has to be a date, so the record can be read against the log', () => {
const findings = withEdit((c) => (journey(c, 'pay-invoice').accepted.on = 'last Thursday'))
assert.deepEqual(where(findings), ['journeys.pay-invoice.accepted.on'])
})
test('a partial journey needs no record, and an unfinished one may keep an old one', () => {
const partial = withEdit((c) =>
Object.assign(journey(c, 'pay-invoice'), { state: 'partial', gap: 'the receipt download is a 404', accepted: undefined })
)
assert.deepEqual(partial, [], 'moving a journey back is the honest way out and costs nothing')
const kept = withEdit((c) => (journey(c, 'send-invoice').accepted = ACCEPTED))
assert.deepEqual(kept, [], 'a record on an unfinished journey is history, not a claim')
})
test('a record from before the model moved on is reported as stale, not failed', (t) => {
// settle-charge in the example was accepted against 0.3.0 and the contract
// is at 0.4.0. That is worth knowing and is not a contradiction: the journey
// may still be fine. So it is a note in the report and never a finding.
assert.deepEqual(checkReferences(EXAMPLE), [])
const json = runRefs(EXAMPLE, ['--json'], { refs: false })
if (json.code === 2) return t.skip('TypeScript is not installed here, so the full report cannot run')
const byId = Object.fromEntries(JSON.parse(json.stdout).acceptance.map((a) => [a.id, a]))
assert.equal(byId['settle-charge'].contractMoved, true)
assert.equal(byId['pay-invoice'].contractMoved, false)
assert.equal(byId['pay-invoice'].commitKnown, null, 'a scratch directory has no git to ask, and that is not a no')
})
// ------------------------------------------------- 4b. evidence is real ---
/** A scratch repo: a package.json with these scripts, and these (empty) files. */
const repoWith = ({ scripts = {}, files = [] } = {}) => {
const dir = tmp('contract-evidence-')
writeFileSync(join(dir, 'package.json'), JSON.stringify({ scripts }))
for (const f of files) {
mkdirSync(dirname(join(dir, f)), { recursive: true })
writeFileSync(join(dir, f), '')
}
return dir
}
/** A pin as the checker writes it: "sha256:" and the hex. */
const sha256 = (text) => `sha256:${createHash('sha256').update(text).digest('hex')}`
/** What repoWith writes: an empty file. */
const EMPTY = sha256('')
/** settle-charge depends on BR-030. It is evidenced by these lines, with exactly these pins. */
const cites = (lines, pins) => {
const c = structuredClone(EXAMPLE)
Object.assign(journey(c, 'settle-charge').accepted, { evidence: lines }, pins === undefined ? {} : { pins })
return c
}
/**
* The same, as a journey accepted properly: every test file the lines cite is
* pinned at the hash of the empty file repoWith writes. The tests of what an
* evidence LINE may be use this, so a finding about a pin is not in their way.
*/
const evidenced = (...lines) => {
const files = lines.map(evidenceEntry).filter((e) => e.kind === 'file' && !e.outside)
return cites(lines, files.length ? Object.fromEntries(files.map((e) => [e.path, EMPTY])) : undefined)
}
const TEST_FILE = 'src/webhooks/settle.test.ts'
test('the shipped example needs no file and no script, so a fresh install starts green', () => {
assert.deepEqual(evidenceFindings(EXAMPLE, repoWith()), [])
})
test('evidence naming a file that is not there is refused, naming the contract, the journey, the file and the fix', () => {
const [f, ...rest] = evidenceFindings(evidenced(`${TEST_FILE}: the same charge twice records one payment. BR-030.`), repoWith())
assert.equal(rest.length, 0)
assert.equal(f.where, 'journeys.settle-charge.accepted.evidence')
assert.match(f.message, /contract\.json, journey "settle-charge": evidence names "src\/webhooks\/settle\.test\.ts", and that file is not in the repo/)
assert.match(f.fix, /Write the test at src\/webhooks\/settle\.test\.ts, or correct the path in contract\.json\. Or change the line to "manual:/)
const present = repoWith({ files: [TEST_FILE] })
assert.deepEqual(evidenceFindings(evidenced(`${TEST_FILE}: BR-030`), present), [], 'the same line passes once the file is written')
assert.deepEqual(evidenceFindings(evidenced('manual: Test watched it', 'src/webhooks/settle.test.ts, BR-030'), present), [], 'a bare path, and a path with a trailing comma, are paths')
})
test('a path outside the repo is not evidence, and only built journeys are read', () => {
const outside = evidenceFindings(evidenced('../elsewhere/settle.test.ts: BR-030'), repoWith())
assert.match(outside[0].message, /"\.\.\/elsewhere\/settle\.test\.ts", and that file is not in the repo/)
const partial = evidenced(TEST_FILE)
Object.assign(journey(partial, 'settle-charge'), { state: 'partial', gap: 'not yet' })
assert.deepEqual(evidenceFindings(partial, repoWith()), [], 'a partial journey makes no claim')
})
test('evidence that runs a script needs that script in package.json', () => {
const scripts = { test: 'node --test', 'test:e2e': 'playwright test' }
const repo = repoWith({ scripts })
for (const ok of ['pnpm test -- settle BR-030', 'pnpm run test:e2e', 'npm run test:e2e', 'npm test BR-030', 'pnpm test:e2e']) {
assert.deepEqual(evidenceFindings(evidenced(`${ok}`, 'manual: Test watched it'), repo), [], ok)
}
const [f, ...rest] = evidenceFindings(evidenced('pnpm test:unit BR-030'), repo)
assert.equal(rest.length, 0)
assert.match(f.message, /contract\.json, journey "settle-charge": evidence "pnpm test:unit BR-030" runs a script, and package.json has no "test:unit" script/)
assert.match(f.fix, /Add "test:unit" to scripts in package\.json, or name the test file instead/)
assert.equal(evidenceFindings(evidenced('pnpm constructor BR-030'), repo).length, 1, 'a name on Object.prototype is not a script')
assert.equal(evidenceFindings(evidenced('pnpm test BR-030'), tmp('contract-no-package-')).length, 1, 'no package.json, no scripts')
})
test('evidence that is neither a file, a script nor a manual line is refused with the three forms', () => {
const [f] = evidenceFindings(evidenced('Tested it and it worked. BR-030.'), repoWith())
assert.match(f.message, /contract\.json, journey "settle-charge": evidence "Tested it and it worked\. BR-030\." is not a test file, a package\.json script or a manual: line/)
assert.match(f.fix, /"src\/x\.test\.ts: what it proves".*"pnpm <script>".*"manual: "/)
const [empty] = evidenceFindings(evidenced('manual:'), repoWith())
assert.match(empty.message, /a "manual:" evidence line says nothing/)
})
test('a built journey on an agreed rule has to name the rule, or carry a manual line', () => {
const repo = repoWith({ files: [TEST_FILE, 'src/other.test.ts'] })
const [f, ...rest] = evidenceFindings(evidenced(`${TEST_FILE}: the same charge twice records one payment`), repo)
assert.equal(rest.length, 0)
assert.equal(f.where, 'journeys.settle-charge.accepted.evidence')
assert.match(f.message, /contract\.json, journey "settle-charge": built on the agreed rule BR-030, and no evidence line mentions BR-030/)
assert.match(f.fix, /Add the test that shows BR-030 to evidence, with the id in the line.*Or change the line to "manual:.*remove it from depends_on/)
assert.deepEqual(evidenceFindings(evidenced(`${TEST_FILE}: BR-030, the same charge twice`), repo), [], 'the id in the line')
assert.deepEqual(evidenceFindings(evidenced(TEST_FILE, 'src/other.test.ts BR-030'), repo), [], 'in any one of the lines')
assert.deepEqual(evidenceFindings(evidenced(TEST_FILE, 'manual: Okafor replayed the webhook'), repo), [], 'or a person says what they saw')
assert.equal(evidenceFindings(evidenced(`${TEST_FILE}: BR-0301 and XBR-030`), repo).length, 1, 'a longer id is not the id')
const proposed = evidenced(TEST_FILE)
proposed.rules.find((r) => r.id === 'BR-030').status = 'proposed'
assert.deepEqual(evidenceFindings(proposed, repo), [], 'only an agreed rule has to be shown')
})
test('--refs exits 1 on evidence naming a missing file, naming the journey and the file, and 0 once it is written', () => {
const dir = repoWith()
writeFileSync(join(dir, 'contract.json'), JSON.stringify(evidenced(`${TEST_FILE}: BR-030`)))
const run = () => {
try {
return { code: 0, stdout: execFileSync(process.execPath, [pinnedScript(), '--refs'], { cwd: dir, encoding: 'utf8' }) }
} catch (e) {
return { code: e.status, stdout: e.stdout }
}
}
const red = run()
assert.equal(red.code, 1)
assert.match(red.stdout, /settle-charge.*\n.*"src\/webhooks\/settle\.test\.ts", and that file is not in the repo/)
mkdirSync(join(dir, 'src', 'webhooks'), { recursive: true })
writeFileSync(join(dir, TEST_FILE), '')
assert.equal(run().code, 0)
})
// ------------------------------------------- 4c. the evidence is pinned ---
//
// A test file that exists says nothing about what is in it. The record keeps the
// sha256 of each file it cites, and an edit to the test alone no longer passes.
const PINS_AT = 'journeys.settle-charge.accepted.pins'
const LINE = `${TEST_FILE}: the same charge twice records one payment. BR-030.`
/** A repo holding the cited test with this body. */
const repoWithTest = (body) => {
const dir = repoWith()
mkdirSync(join(dir, 'src', 'webhooks'), { recursive: true })
writeFileSync(join(dir, TEST_FILE), body)
return dir
}
const HONEST = "test('one payment', () => assert.equal(payments.length, 1))\n"
const GUTTED = "test('one payment', () => assert.ok(true))\n"
test('a cited test file with no pin is refused, naming the contract, the journey, the file and the command that prints the pin', () => {
const repo = repoWithTest(HONEST)
for (const pins of [undefined, {}, { 'src/other.test.ts': sha256(HONEST) }]) {
const f = evidenceFindings(cites([LINE], pins), repo).find((x) => /has no pin/.test(x.message))
assert.ok(f, `no pin for the cited file, with pins ${JSON.stringify(pins)}`)
assert.equal(f.where, PINS_AT)
assert.match(f.message, /contract\.json, journey "settle-charge": evidence cites "src\/webhooks\/settle\.test\.ts", and the acceptance record has no pin for it/)
assert.match(f.fix, /Add "pins": \{ "src\/webhooks\/settle\.test\.ts": "sha256:<hex>" \}.*node scripts\/check-contract-coverage\.mjs --pins settle-charge prints it/)
}
assert.deepEqual(evidenceFindings(cites([LINE], { [TEST_FILE]: sha256(HONEST) }), repo), [], 'the same record passes once the pin is there')
})
test('a test edited after the journey was accepted is refused, and the finding does not hand over the new hash', () => {
const accepted = cites([LINE], { [TEST_FILE]: sha256(HONEST) })
assert.deepEqual(evidenceFindings(accepted, repoWithTest(HONEST)), [], 'the file as it was accepted')
const [f, ...rest] = evidenceFindings(accepted, repoWithTest(GUTTED))
assert.equal(rest.length, 0)
assert.equal(f.where, PINS_AT)
assert.match(f.message, /contract\.json, journey "settle-charge": "src\/webhooks\/settle\.test\.ts" has changed since the journey was accepted/)
assert.match(f.fix, /A person accepts the journey again, or the edit is reverted/)
assert.match(f.fix, /new on, by and commit.*--pins settle-charge/)
assert.match(f.fix, /revert the edit to src\/webhooks\/settle\.test\.ts/)
assert.match(f.fix, /Do not change the pin on your own/)
const said = `${f.message} ${f.fix}`
assert.ok(!said.includes(sha256(GUTTED)), 'the new hash is not in the finding: pasting it must not be the easy way out')
assert.ok(!/[0-9a-f]{64}/.test(said), 'nor any hash at all')
// Green, the honest way: the record is written again with the pin the file has now.
assert.deepEqual(evidenceFindings(cites([LINE], { [TEST_FILE]: sha256(GUTTED) }), repoWithTest(GUTTED)), [])
// And by reverting the edit: the old record holds against the old file.
assert.deepEqual(evidenceFindings(accepted, repoWithTest(HONEST)), [])
})
test('one byte is a change, and the case of the hex is not', () => {
const accepted = cites([LINE], { [TEST_FILE]: sha256(HONEST).toUpperCase() })
assert.deepEqual(evidenceFindings(accepted, repoWithTest(HONEST)), [])
assert.equal(evidenceFindings(accepted, repoWithTest(`${HONEST} `)).length, 1, 'a trailing space is a different file')
assert.equal(evidenceFindings(accepted, repoWithTest(HONEST.replace('\n', '\r\n'))).length, 1, 'so is a line ending: it is the bytes')
})
test('a pin that is not a sha256, and pins that are not an object, are refused', () => {
const repo = repoWithTest(HONEST)
// The bare hex is refused too: beside a path named auth or token it reads as a credential to the secrets gate.
for (const bad of ['', 'accepted', sha256(HONEST).slice(0, 12), sha256(HONEST).slice('sha256:'.length), 42, null]) {
const [f] = evidenceFindings(cites([LINE], { [TEST_FILE]: bad }), repo)
assert.match(f.message, /the pin for "src\/webhooks\/settle\.test\.ts" is not a sha256/, JSON.stringify(bad))
assert.match(f.fix, /--pins settle-charge prints it/)
}
for (const bad of [[], 'yes', null, 7]) {
const messages = evidenceFindings(cites([LINE], bad), repo).map((f) => f.message)
assert.ok(messages.some((m) => /"pins" is not an object/.test(m)), JSON.stringify(bad))
assert.ok(messages.some((m) => /has no pin for it/.test(m)), 'and the cited file is still unpinned')
}
})
test('a pin for a file no evidence line cites is refused, so a dropped citation cannot leave its pin behind', () => {
const repo = repoWithTest(HONEST)
const [f, ...rest] = evidenceFindings(cites(['manual: Okafor replayed the webhook'], { [TEST_FILE]: sha256(HONEST) }), repo)
assert.equal(rest.length, 0)
assert.equal(f.where, PINS_AT)
assert.match(f.message, /contract\.json, journey "settle-charge": pins names "src\/webhooks\/settle\.test\.ts", and no evidence line cites that file/)
assert.match(f.fix, /Remove "src\/webhooks\/settle\.test\.ts" from pins, or put the file back in evidence/)
// The key is the path as the evidence line writes it.
const dotted = evidenceFindings(cites([`./${TEST_FILE}: BR-030`], { [TEST_FILE]: sha256(HONEST) }), repo).map((x) => x.message)
assert.equal(dotted.length, 2, dotted.join('\n'))
assert.deepEqual(evidenceFindings(cites([`./${TEST_FILE}: BR-030`], { [`./${TEST_FILE}`]: sha256(HONEST) }), repo), [])
})
test('a script and a manual line have nothing to pin, and a folder is not a test file', () => {
const repo = repoWithTest(HONEST)
writeFileSync(join(repo, 'package.json'), JSON.stringify({ scripts: { test: 'node --test' } }))
assert.deepEqual(evidenceFindings(cites(['pnpm test -- settle BR-030', 'manual: Okafor replayed the webhook']), repo), [], 'neither needs a pin')
const [f, ...rest] = evidenceFindings(cites(['src/webhooks BR-030']), repo)
assert.equal(rest.length, 0)
assert.match(f.message, /evidence names "src\/webhooks", and that is a folder, not a file/)
assert.match(f.fix, /Name the test file itself, so it can be pinned/)
})
test('a missing file is one finding, not a missing file and a missing pin, and a partial journey is not read', () => {
const missing = evidenceFindings(cites([LINE]), repoWith())
assert.equal(missing.length, 1)
assert.match(missing[0].message, /that file is not in the repo/)
const partial = cites([LINE])
Object.assign(journey(partial, 'settle-charge'), { state: 'partial', gap: 'not yet' })
assert.deepEqual(evidenceFindings(partial, repoWithTest(HONEST)), [], 'a partial journey makes no claim, so it has nothing to pin')
})
test('the cited files are the built journeys\' test files, as git names them', () => {
assert.deepEqual(citedFiles(EXAMPLE), [], 'the shipped example cites none, so the hook is not triggered by it')
const c = cites([`./${TEST_FILE}: BR-030`, 'pnpm test', 'manual: watched', 'tests/caf\u00e9.test.ts', '../elsewhere/x.test.ts', `./${TEST_FILE}, again`])
assert.deepEqual(citedFiles(c), [
{ journey: 'settle-charge', path: TEST_FILE },
{ journey: 'settle-charge', path: 'tests/caf\u00e9.test.ts' },
])
Object.assign(journey(c, 'settle-charge'), { state: 'partial', gap: 'not yet' })
assert.deepEqual(citedFiles(c), [], 'a journey that is not built is not watched')
})
/** Run the script in a repo. Both streams, and the exit code. */
const runIn = (dir, ...args) => {
try {
return { code: 0, out: execFileSync(process.execPath, [pinnedScript(), ...args], { cwd: dir, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }) }
} catch (e) {
return { code: e.status, out: `${e.stdout}${e.stderr}` }
}
}
test('--refs goes red when only the test is edited, and green when the journey is accepted again with the pin --pins prints', () => {
const dir = repoWithTest(HONEST)
const file = join(dir, 'contract.json')
const write = (c) => writeFileSync(file, JSON.stringify(c, null, 2))
write(cites([LINE], { [TEST_FILE]: sha256(HONEST) }))
assert.equal(runIn(dir, '--refs').code, 0, 'accepted, pinned, unchanged')
writeFileSync(join(dir, TEST_FILE), GUTTED)
const red = runIn(dir, '--refs')
assert.equal(red.code, 1, red.out)
assert.match(red.out, /journeys\.settle-charge\.accepted\.pins\n.*contract\.json, journey "settle-charge": "src\/webhooks\/settle\.test\.ts" has changed since the journey was accepted/)
assert.match(red.out, /fix: A person accepts the journey again, or the edit is reverted/)
assert.ok(!red.out.includes(sha256(GUTTED)), 'the refusal does not print the hash that would clear it')
const before = readFileSync(file, 'utf8')
const pins = runIn(dir, '--pins', 'settle-charge')
assert.equal(pins.code, 0, pins.out)
assert.match(pins.out, /contract\.json, journey "settle-charge"/)
assert.ok(pins.out.includes(`"${TEST_FILE}": "${sha256(GUTTED)}"`), pins.out)
assert.match(pins.out, /with the on, by and\s+commit of the acceptance it belongs to/)
assert.equal(readFileSync(file, 'utf8'), before, '--pins prints and writes nothing')
assert.equal(runIn(dir, '--refs').code, 1, 'so printing the pin clears nothing')
const again = cites([LINE], { [TEST_FILE]: sha256(GUTTED) })
Object.assign(journey(again, 'settle-charge').accepted, { on: '2026-10-09', by: 'M. Okafor, engineering', commit: '9d1e4c2' })
write(again)
assert.equal(runIn(dir, '--refs').code, 0, 'accepted again, with the new pin')
})
test('--pins names every journey that cites a file, says so when none does, and fails on a file or a journey that is not there', () => {
const dir = repoWithTest(HONEST)
const write = (c) => writeFileSync(join(dir, 'contract.json'), JSON.stringify(c))
write(EXAMPLE)
const none = runIn(dir, '--pins')
assert.equal(none.code, 0, none.out)
assert.match(none.out, /No journey cites a test file in its evidence, so there is nothing to pin/)
assert.match(runIn(dir, '--pins', 'pay-invoice').out, /Journey "pay-invoice" cites no test file in its evidence/)
write(cites([LINE, 'src/webhooks/absent.test.ts']))
const all = runIn(dir, '--pins')
assert.equal(all.code, 1, 'a cited file that is not there cannot be hashed, and that is not a pass')
assert.ok(all.out.includes(`"${TEST_FILE}": "${sha256(HONEST)}",`), all.out)
assert.match(all.out, /"src\/webhooks\/absent\.test\.ts": \(not a file in the repo, so nothing to hash\)/)
const unknown = runIn(dir, '--pins', 'no-such-journey')
assert.equal(unknown.code, 2)
assert.match(unknown.out, /No journey "no-such-journey" in contract\.json/)
// It works on a contract with no entities, and on a journey not yet marked built.
writeFileSync(join(dir, 'contract.json'), JSON.stringify({ journeys: [{ id: 'draft', state: 'partial', accepted: { evidence: [LINE] } }] }))
assert.ok(runIn(dir, '--pins', 'draft').out.includes(sha256(HONEST)))
})
test('--print-config tells the hook which staged paths are cited test files, and by which journey', () => {
const dir = repoWithTest(HONEST)
const write = (c) => writeFileSync(join(dir, 'contract.json'), typeof c === 'string' ? c : JSON.stringify(c))
write(cites([`./${TEST_FILE}: BR-030`, 'tests/caf\u00e9.test.ts', 'manual: watched'], {}))
const cfg = runIn(dir, '--print-config')
assert.equal(cfg.code, 0, cfg.out)
assert.deepEqual(cfg.out.trimEnd().split('\n'), [
'watch\tcontract.json',
`evidence\t${TEST_FILE}\tsettle-charge`,
'evidence\ttests/caf\u00e9.test.ts\tsettle-charge',
'evidence\ttests/cafe\u0301.test.ts\tsettle-charge',
])
// Nothing to trigger on, and never a crash the hook would have to read.
write(EXAMPLE)
assert.equal(runIn(dir, '--print-config').out, 'watch\tcontract.json\n')
// No contract is nothing to watch for. A contract that cannot be read is not the same thing:
// exit 0 there told the hook "no test is cited", and a test edited alone went through.
rmSync(join(dir, 'contract.json'))
assert.deepEqual(runIn(dir, '--print-config'), { code: 0, out: 'watch\tcontract.json\n' })
for (const unreadable of ['{ not json', '{ "journeys": "all of them" }']) {
write(unreadable)
const cannot = runIn(dir, '--print-config')
assert.equal(cannot.code, 2, `${unreadable}\n${cannot.out}`)
assert.ok(cannot.out.startsWith('watch\tcontract.json\n'), cannot.out)
assert.doesNotMatch(cannot.out, /^evidence\t/m)
}
})
test('--pins with --json is refused: the block it prints is not JSON, and silence about the flag would be a lie', () => {
const dir = repoWithTest(HONEST)
writeFileSync(join(dir, 'contract.json'), JSON.stringify(cites([LINE], {})))
for (const args of [['--pins', '--json'], ['--json', '--pins', 'settle-charge']]) {
const run = runIn(dir, ...args)
assert.equal(run.code, 2, run.out)
assert.match(run.out, /--pins does not print JSON\. Run it without --json/)
assert.ok(!run.out.includes(sha256(HONEST)), 'and it prints no pin')
}
})
// The hook matches a staged path against a cited one byte for byte. So the path
// in the evidence line has to be the file's own name, spelt as the directory
// spells it, and the file itself, not a link to it.
test('a cited path spelt in another case than the file is refused, with the spelling to write', () => {
// On a disk that ignores case the wrong spelling opens the file, and the hook never matched it.
// On one that does not, the file is simply missing. The finding is the same on both.
const dir = repoWithTest(HONEST)
const wrong = 'SRC/Webhooks/settle.test.ts'
const [f, ...rest] = evidenceFindings(cites([`${wrong}: BR-030`], { [wrong]: sha256(HONEST) }), dir)
assert.deepEqual(rest, [], 'one finding, not one for the line and one for the pin')
assert.equal(f.where, 'journeys.settle-charge.accepted.evidence')
assert.match(f.message, /evidence names "SRC\/Webhooks\/settle\.test\.ts", and the file is spelt "src\/webhooks\/settle\.test\.ts"/)
assert.match(f.fix, /Write the path as src\/webhooks\/settle\.test\.ts, in the evidence line and in pins/)
assert.deepEqual(evidenceFindings(cites([LINE], { [TEST_FILE]: sha256(HONEST) }), dir), [], 'spelt as it is on disk, it passes')
})
test('a cited path that is a symlink, or goes through one, is refused: the pin would watch the link and not the test', () => {
const dir = repoWithTest(HONEST)
mkdirSync(join(dir, 'tests'))
symlinkSync(join('..', TEST_FILE), join(dir, 'tests', 'pay.test.ts'))
symlinkSync(join('src', 'webhooks'), join(dir, 'hooks'))
for (const [cited, link] of [['tests/pay.test.ts', 'tests/pay.test.ts'], ['hooks/settle.test.ts', 'hooks']]) {
const [f, ...rest] = evidenceFindings(cites([`${cited}: BR-030`], { [cited]: sha256(HONEST) }), dir)
assert.deepEqual(rest, [], cited)
assert.equal(f.where, 'journeys.settle-charge.accepted.evidence')
assert.ok(f.message.includes(`evidence names "${cited}", and "${link}" is a symbolic link`), f.message)
assert.match(f.fix, /Cite the real file, by its own path/)
}
// --pins does not hand out a pin for either.
writeFileSync(join(dir, 'contract.json'), JSON.stringify(cites(['tests/pay.test.ts: BR-030'], {})))
const pins = runIn(dir, '--pins', 'settle-charge')
assert.equal(pins.code, 1, pins.out)
assert.ok(!pins.out.includes(sha256(HONEST)), pins.out)
})
// ------------------------------------------------------- the UI pointer ---
test('a trailing comment does not count as a mention', () => {
// `return null } // total_amount` used to score the field as on screen,
// because only comments that started a line were stripped.
const src = 'export default function Page() { return null } // total_amount\n'
assert.doesNotMatch(stripComments(src), /total_amount/)
})
test('stripping comments leaves strings, urls and regex literals alone', () => {
const src = [
"const u = 'https://example.com/total_amount' // not this one",
'const r = /\\/\\/(total)/ /* nor this */',
'const t = `a // ${b}` ',
'const d = a / b // ratio',
].join('\n')
const out = stripComments(src)
assert.match(out, /https:\/\/example\.com\/total_amount/)
assert.match(out, /\/\\\/\\\/\(total\)\//, 'the regex literal survives')
assert.match(out, /`a \/\/ \$\{b\}`/, 'the template literal survives')
assert.doesNotMatch(out, /not this one|nor this|ratio/)
})
// ------------------------------------------------- the gate, end to end ---
const runRefs = (contract, extra = [], { refs = true } = {}) => {
const dir = tmp('contract-')
writeFileSync(join(dir, 'contract.json'), JSON.stringify(contract))
const args = [pinnedScript(), ...(refs ? ['--refs'] : []), ...extra]
try {
const stdout = execFileSync(process.execPath, args, { cwd: dir, encoding: 'utf8' })
return { code: 0, stdout }
} catch (e) {
return { code: e.status, stdout: e.stdout }
}
}
test('a broken reference fails in --json too', () => {
const broken = structuredClone(EXAMPLE)
build(journey(broken, 'refund-payment'))
const json = runRefs(broken, ['--json'])
assert.equal(json.code, 1, 'the exit code cannot depend on the output format')
assert.equal(JSON.parse(json.stdout).broken.length, 1)
})
test('the coverage floor is enforced in --json as well as in the table', (t) => {
// The bug: the JSON branch returned before the threshold comparison, so a CI
// job asking for a machine-readable report AND enforcement got exit 0 below
// its own floor. Asking for a different output format is not asking for a
// different answer, and the format the robots read decides the build.
//
// The temp dir has a contract and no source, so type coverage is 0% and any
// floor above zero has to fail.
const text = runRefs(EXAMPLE, ['--check', '--min', '1'], { refs: false })
if (text.code === 2) {
// The full run reads types, so it needs a compiler. --refs, which is the
// half that gates a commit, does not, and it is covered below either way.
return t.skip('TypeScript is not installed here, so the type layer cannot run')
}
const json = runRefs(EXAMPLE, ['--check', '--min', '1', '--json'], { refs: false })
assert.equal(text.code, 1, '0% is below a 100% floor')
assert.equal(json.code, 1, 'and it is still below it when you ask for JSON')
const report = JSON.parse(json.stdout)
assert.equal(report.belowFloor, true)
assert.equal(report.ok, false, 'the report says so as well as the exit code')
// The example maps three of its four entities. Under --check the fourth is
// a failure until somebody maps it or excuses it with a reason, because the
// number is not about the whole contract until then.
const unmapped = runRefs(EXAMPLE, ['--check', '--min', '0', '--json'], { refs: false })
assert.equal(unmapped.code, 1)
assert.equal(JSON.parse(unmapped.stdout).unmappedScope, true, 'payment is in the contract and in no map')
// Only the mapped entities, and nothing pointing at the fourth.
const mapped = { entities: EXAMPLE.entities.filter((e) => e.id !== 'payment') }
const green = runRefs(mapped, ['--check', '--min', '0', '--json'], { refs: false })
assert.equal(green.code, 0, 'and a floor it clears passes, so this is not just always-fail')
assert.equal(JSON.parse(green.stdout).unmappedScope, false)
})
test('a name in the right place is not coverage: the counterexample from the methodology review', (t) => {
// A money field declared boolean, a fixture carrying the key under a
// different object with a null value, and a page that returns null with the
// field name in a trailing comment. This scored 100% at every layer.
const dir = tmp('contract-')
const write = (rel, text) => {
mkdirSync(join(dir, dirname(rel)), { recursive: true })
writeFileSync(join(dir, rel), text)
}
const contract = {
entities: [
{ id: 'invoice', fields: [{ name: 'total_amount', type: 'money', required: true }, 'due_date'] },
{ id: 'audit_event', fields: ['actor', 'at'] },
],
journeys: [],
}
write('contract.json', JSON.stringify(contract))
write('src/types/invoice.ts', 'export interface Invoice { total_amount: boolean; due_date: string }')
write('fixtures/invoice.json', JSON.stringify({ customer: { total_amount: null }, due_date: '2026-01-01' }))
write('src/app/invoices/page.tsx', 'export default function Page() { return null } // total_amount due_date')
const run = (extra = []) => {
try {
return { code: 0, stdout: execFileSync(process.execPath, [pinnedScript(), '--json', ...extra], { cwd: dir, encoding: 'utf8' }) }
} catch (e) {
return { code: e.status, stdout: e.stdout }
}
}
const first = run(['--check', '--min', '1'])
if (first.code === 2) return t.skip('TypeScript is not installed here, so the type layer cannot run')
const report = JSON.parse(first.stdout)
const invoice = report.rows.find((r) => r.id === 'invoice')
assert.equal(invoice.type, 50, 'total_amount is declared boolean, which a money field cannot be')
assert.deepEqual(invoice.mismatched, [{ field: 'total_amount', contract: 'money', declared: 'boolean' }])
assert.equal(invoice.fixture, 50, 'a null under another object is not the field seen with data')
assert.equal(invoice.ui, 0, 'a trailing comment is not a mention')
assert.equal(report.ok, false)
// The unmapped entity is outside the number and, under --check, a failure.
assert.deepEqual(report.unmeasured, ['audit_event'])
assert.deepEqual(report.measured, { fields: 2, of: 4 })
assert.equal(report.unmappedScope, true)
assert.equal(first.code, 1)
})
test('a field on a base interface counts, and a field the contract keeps off screen leaves the UI column', (t) => {
const dir = tmp('contract-')
const write = (rel, text) => {
mkdirSync(join(dir, dirname(rel)), { recursive: true })
writeFileSync(join(dir, rel), text)
}
write(
'contract.json',
JSON.stringify({
entities: [
{
id: 'invoice',
fields: ['invoice_number', { name: 'total_amount', type: 'money' }, { name: 'created_at', ui: false, why: 'audit only' }],
},
],
})
)
write(
'src/types/invoice.ts',
[
'interface Timestamped { created_at: string }',
'type Numbered = { invoice_number: string }',
'export interface Invoice extends Timestamped { total_amount: number }',
'export type InvoiceDetail = Numbered & Invoice',
].join('\n')
)
write('src/app/invoices/page.tsx', 'export const Page = (i: Invoice) => <b>{i.invoice_number} {i.total_amount}</b>')
let stdout
try {
stdout = execFileSync(process.execPath, [pinnedScript(), '--json'], { cwd: dir, encoding: 'utf8' })
} catch (e) {
if (e.status === 2) return t.skip('TypeScript is not installed here')
stdout = e.stdout
}
const invoice = JSON.parse(stdout).rows[0]
assert.equal(invoice.type, 100, 'inherited and intersected members are declared members')
assert.equal(invoice.ui, 100, 'created_at is off screen by decision, so it is not a UI gap')
assert.deepEqual(invoice.offScreen, [{ field: 'created_at', why: 'audit only' }])
})
test('--refs exits 0 on a contract that resolves and 1 on one that does not', () => {
assert.equal(runRefs(EXAMPLE).code, 0, 'the exit code IS the gate; the output is for the human')
const broken = structuredClone(EXAMPLE)
journey(broken, 'refund-payment').state = 'built'
const run = runRefs(broken)
assert.equal(run.code, 1)
assert.match(run.stdout, /BROKEN REFERENCES/)
assert.match(run.stdout, /fix: Answer OQ-011/)
})
test('--refs never loads TypeScript, so the hook works before the first install', () => {
const source = readFileSync(SCRIPT, 'utf8')
assert.doesNotMatch(
source,
/^const ts = require\('typescript'\)/m,
'a top-level require would crash --refs in a repo that has not installed it'
)
assert.doesNotMatch(
source,
/^import .*['"]typescript['"]/m,
'and neither would a top-level import'
)
assert.match(
source,
/const typescript = \(\) => \{[\s\S]*require\('typescript'\)/,
'it is loaded inside the accessor, on the first parse that needs it'
)
})
// ------------------------------------------------- what cannot be read ---
/** Whatever is in the file, valid or not, with both streams kept. */
const runRaw = (text, args) => {
const dir = tmp('contract-')
writeFileSync(join(dir, 'contract.json'), text)
try {
const stdout = execFileSync(process.execPath, [pinnedScript(), ...args], {
cwd: dir,
encoding: 'utf8',
stdio: ['ignore', 'pipe', 'pipe'],
})
return { code: 0, stdout, stderr: '' }
} catch (e) {
return { code: e.status, stdout: e.stdout, stderr: e.stderr }
}
}
test('a contract that is not JSON is reported as unreadable, not thrown', () => {
const text = runRaw('{ "entities": [', ['--refs'])
assert.equal(text.code, 2, 'nothing was checked, which is neither a pass nor a finding')
assert.match(text.stderr, /CANNOT CHECK/)
assert.doesNotMatch(text.stderr, /SyntaxError|\n\s+at /, 'a sentence, not a stack')
const json = runRaw('{ "entities": [', ['--refs', '--json'])
assert.equal(json.code, 2)
const report = JSON.parse(json.stdout)
assert.equal(report.ok, false)
assert.match(report.invalid[0].message, /is not JSON/)
})
test('a pillar that is not a list is reported by name, in both modes', (t) => {
const malformed = JSON.stringify({ entities: { invoice: { fields: ['id'] } } })
const refs = runRaw(malformed, ['--refs', '--json'])
assert.equal(refs.code, 2)
assert.deepEqual(where(JSON.parse(refs.stdout).invalid), ['entities'])
const full = runRaw(malformed, ['--json'])
assert.equal(full.code, 2)
assert.deepEqual(where(JSON.parse(full.stdout).invalid), ['entities'])
assert.deepEqual(where(shapeProblems({ entities: [{ id: 'invoice', fields: {} }] })), ['entities.invoice.fields'])
assert.deepEqual(where(shapeProblems({ entitlements: { gates: {} } })), ['entitlements.gates'])
assert.deepEqual(where(shapeProblems([])), ['contract'])
})
test('a contract with no entities cannot be measured, and its references can still be checked', () => {
const none = JSON.stringify({ actors: [{ id: 'clerk', kind: 'user' }] })
const full = runRaw(none, ['--json'])
assert.equal(full.code, 2, 'a score over nothing is not a score')
assert.deepEqual(where(JSON.parse(full.stdout).invalid), ['entities'])
assert.equal(runRaw(none, ['--refs']).code, 0, 'nothing points at an entity, so nothing is broken')
assert.deepEqual(shapeProblems(EXAMPLE, { measuring: true }), [], 'and the shipped example is readable')
})
// ------------------------------------------------------ a long report ---
test('a report longer than a pipe buffer arrives whole', () => {
// The bug: process.exit straight after console.log. Piped, the report was cut
// at 65,536 bytes and the exit code was still the verdict, so a consumer got
// invalid JSON with a pass or a fail attached. 2,000 findings is about 400 KB.
const big = structuredClone(EXAMPLE)
for (let i = 0; i < 2000; i++) big.rules.push({ id: `BR-BIG-${i}`, applies_to: [`nobody-declared-${i}`] })
const run = runRefs(big, ['--json'])
assert.equal(run.code, 1)
assert.ok(run.stdout.length > 65536 * 2, `only ${run.stdout.length} bytes, so this proves nothing`)
assert.equal(JSON.parse(run.stdout).broken.length, 2000)
})
// ----------------------------------------- the fields the backend reads ---
/** The shipped example with one thing changed, and what the warnings say. */
const warnWith = (edit) => {
const contract = structuredClone(EXAMPLE)
edit(contract)
return referenceWarnings(contract)
}
const entity = (contract, id) => contract.entities.find((e) => e.id === id)
const field = (contract, id, name) => entity(contract, id).fields.find((f) => fieldName(f) === name)
test('the shipped example has no backend findings and no notes', () => {
assert.deepEqual(checkReferences(EXAMPLE), [])
assert.deepEqual(referenceWarnings(EXAMPLE), [])
})
test('a table has to be a table name', () => {
assert.deepEqual(where(withEdit((c) => (entity(c, 'invoice').table = 'public.invoices'))), [])
assert.deepEqual(where(withEdit((c) => (entity(c, 'invoice').table = 'invoices'))), [])
for (const bad of ['', 'a.b.c', 'drop table;', 7]) {
const found = withEdit((c) => (entity(c, 'invoice').table = bad))
assert.deepEqual(where(found), ['entities.invoice.table'], `${JSON.stringify(bad)}`)
assert.match(found[0].fix, /public\.invoices/)
}
})
test('two entities on one table is a note, not a finding', () => {
const edit = (c) => (entity(c, 'payment').table = 'invoices')
assert.deepEqual(withEdit(edit), [])
const notes = warnWith(edit)
assert.deepEqual(where(notes), ['entities.payment.table'])
assert.match(notes[0].message, /also the table of invoice/)
})
test('owner has to name a field of the entity', () => {
assert.deepEqual(withEdit((c) => (entity(c, 'invoice').owner = 'customer_id')), [])
const found = withEdit((c) => (entity(c, 'invoice').owner = 'created_by'))
assert.deepEqual(where(found), ['entities.invoice.owner'])
assert.match(found[0].message, /"created_by" is not a field of invoice/)
})
test('a ref has to point at an entity, and sit on an id field', () => {
const typo = withEdit((c) => (field(c, 'invoice', 'customer_id').ref = 'custmer'))
assert.deepEqual(where(typo), ['entities.invoice.fields.customer_id.ref'])
assert.match(typo[0].message, /"custmer" is not an entity/)
const wrongType = withEdit((c) => (field(c, 'invoice', 'customer_id').type = 'text'))
assert.match(wrongType[0].message, /only valid on an id field/)
assert.equal(wrongType[0].fix, 'Set type to "id", or remove ref.')
})
test('a column has to be a non-empty string', () => {
assert.deepEqual(withEdit((c) => (field(c, 'customer', 'customer_id').column = 'id')), [])
for (const bad of ['', 3]) {
const found = withEdit((c) => (field(c, 'customer', 'customer_id').column = bad))
assert.deepEqual(where(found), ['entities.customer.fields.customer_id.column'])
}
})
test('the tenancy column and membership are checked for shape', () => {
assert.deepEqual(where(withEdit((c) => (c.access.tenancy.column = ''))), ['access.tenancy.column'])
assert.deepEqual(where(withEdit((c) => (c.access.tenancy.column = 4))), ['access.tenancy.column'])
assert.deepEqual(where(withEdit((c) => delete c.access.tenancy.membership)), [], 'membership is optional')
for (const bad of ['customers', { table: 'public.customers' }, { table: 'a', user_column: 'b', tenant_column: '' }]) {
const found = withEdit((c) => (c.access.tenancy.membership = bad))
assert.deepEqual(where(found), ['access.tenancy.membership'], JSON.stringify(bad))
assert.match(found[0].message, /needs table, user_column and tenant_column/)
}
})
test('a scope the checks do not know is a note, and the row is named', () => {
const edit = (c) => (c.access.matrix[1].scope = 'mine')
assert.deepEqual(withEdit(edit), [], 'never a finding')
const notes = warnWith(edit)
assert.deepEqual(where(notes), ['access.matrix[1].scope'])
assert.match(notes[0].message, /"mine" is not a scope the checks know/)
assert.deepEqual(warnWith((c) => (c.access.matrix[1].scope = 'tenant')), [], 'a real scope is quiet')
})
test('tenant and own scopes need something to test against', () => {
const noTenancy = (c) => {
delete c.access.tenancy.column
delete c.access.tenancy.membership
c.access.matrix[1].scope = 'tenant'
}
assert.match(warnWith(noTenancy)[0].message, /tenant scope with no way to find the tenant/)
const noOwner = (c) => delete c.access.tenancy.column
const own = warnWith(noOwner)
assert.equal(own.length, 2, 'both own rows, invoice and payment')
assert.match(own[0].message, /own scope with no owner column/)
assert.match(own[0].fix, /Set owner on invoice/)
assert.deepEqual(
warnWith((c) => {
noOwner(c)
entity(c, 'invoice').owner = 'customer_id'
entity(c, 'payment').owner = 'customer_id'
}),
[],
'an owner column answers it'
)
})
test('an owner on a parent row answers own scope; owner_via must name a ref field, and only ever warns', () => {
const parentOwner = (c) => {
delete c.access.tenancy.column
entity(c, 'invoice').owner = 'customer_id'
}
assert.deepEqual(warnWith(parentOwner), [], 'payment reaches invoice, which has an owner')
const via = (name) => (c) => {
parentOwner(c)
entity(c, 'payment').owner_via = name
}
assert.deepEqual(warnWith(via('invoice_id')), [], 'a ref field is accepted')
const bad = warnWith(via('amount'))
assert.deepEqual(where(bad), ['entities.payment.owner_via'])
assert.match(bad[0].message, /not a ref field of payment/)
assert.deepEqual(withEdit(via('amount')), [], 'an unknown value never fails')
assert.deepEqual(withEdit(via(42)), [], 'whatever its type')
})
test('a contract with none of the new fields behaves as before', () => {
const old = structuredClone(EXAMPLE)
for (const e of old.entities) {
delete e.table
for (const f of e.fields) if (typeof f === 'object') delete f.ref
}
delete old.access.tenancy.column
delete old.access.tenancy.membership
old.access.matrix[1].scope = 'own, for now'
old.access.matrix[2].scope = 'own'
assert.deepEqual(checkReferences(old), [])
const run = runRefs(old)
assert.equal(run.code, 0)
})
test('--refs prints a warning under NOTES and still exits 0', () => {
const contract = structuredClone(EXAMPLE)
contract.access.matrix[1].scope = 'mine'
const run = runRefs(contract)
assert.equal(run.code, 0, 'a warning alone never fails the gate')
assert.match(run.stdout, /NOTES/)
assert.match(run.stdout, /"mine" is not a scope the checks know/)
assert.doesNotMatch(run.stdout, /BROKEN REFERENCES/)
assert.doesNotMatch(runRefs(EXAMPLE).stdout, /NOTES/, 'and a clean contract prints none')
const json = runRefs(contract, ['--json'])
assert.equal(json.code, 0)
assert.equal(JSON.parse(json.stdout).notes.length, 1)
})
test('--refs exits 1 on a misspelt ref and names it', () => {
const contract = structuredClone(EXAMPLE)
field(contract, 'invoice', 'customer_id').ref = 'custmer'
const run = runRefs(contract)
assert.equal(run.code, 1)
assert.match(run.stdout, /"custmer" is not an entity/)
})
How to tell it works: node --test passes. Break one reference in the contract by hand and exactly one test goes red, naming the check that caught it. Stage an edit that breaks check-contract-coverage.mjs and the pre-commit hook runs this file and refuses the commit. When that happens the check is what gets fixed: the test changes only when the person has said the rule moved.