From bbaf62f3b043541fbdcd8aa397ba8c2b1a385f0f Mon Sep 17 00:00:00 2001 From: ONCE <325000613+stringsofthemind-oss@users.noreply.github.com> Date: Sat, 10 Oct 2026 08:26:51 +0100 Subject: [PATCH] test: add controlled booking lifecycle reference with provider journal --- .github/workflows/booking-lifecycle.yml | 33 ++++ .../connected-agent-tool/BOOKING_LIFECYCLE.md | 67 +++++++ examples/connected-agent-tool/README.md | 6 + .../connected-agent-tool/booking-boundary.mjs | 66 +++++++ .../booking-lifecycle.mjs | 173 ++++++++++++++++++ .../check-booking-evidence.mjs | 33 ++++ 6 files changed, 378 insertions(+) create mode 100644 .github/workflows/booking-lifecycle.yml create mode 100644 examples/connected-agent-tool/BOOKING_LIFECYCLE.md create mode 100644 examples/connected-agent-tool/booking-boundary.mjs create mode 100644 examples/connected-agent-tool/booking-lifecycle.mjs create mode 100644 examples/connected-agent-tool/check-booking-evidence.mjs diff --git a/.github/workflows/booking-lifecycle.yml b/.github/workflows/booking-lifecycle.yml new file mode 100644 index 00000000..9f6c85aa --- /dev/null +++ b/.github/workflows/booking-lifecycle.yml @@ -0,0 +1,33 @@ +name: Controlled booking lifecycle reference +on: + pull_request: + paths: + - 'examples/connected-agent-tool/**' + - '.github/workflows/booking-lifecycle.yml' + workflow_dispatch: +permissions: + contents: read +jobs: + booking: + runs-on: ${{ matrix.os }} + timeout-minutes: 5 + strategy: + fail-fast: false + matrix: + os: [ubuntu-latest, windows-latest] + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '24.19.0' + - run: npm install --prefix booking-consumer --ignore-scripts --no-audit --no-fund @once-agent/sdk@0.1.25 + - name: Run against clean published SDK consumer + shell: bash + run: | + SDK_URL=$(node -e "console.log(require('node:url').pathToFileURL(require('node:path').resolve('booking-consumer/node_modules/@once-agent/sdk/dist/index.js')).href)") + node examples/connected-agent-tool/booking-lifecycle.mjs "$SDK_URL" evidence/booking.json + - run: node examples/connected-agent-tool/check-booking-evidence.mjs evidence/booking.json + - uses: actions/upload-artifact@v4 + with: + name: booking-lifecycle-${{ matrix.os }} + path: evidence/booking.json diff --git a/examples/connected-agent-tool/BOOKING_LIFECYCLE.md b/examples/connected-agent-tool/BOOKING_LIFECYCLE.md new file mode 100644 index 00000000..975c2800 --- /dev/null +++ b/examples/connected-agent-tool/BOOKING_LIFECYCLE.md @@ -0,0 +1,67 @@ +# Controlled booking lifecycle reference + +This extends the existing fake booking `verify.mjs` example with creation, +modification and cancellation, using published `wrapTool` from SDK 0.1.25. +It contacts only a disposable loopback provider, never a real reservation system. +Its provider commits reservations and a separate operation-effect journal in one +SQLite transaction. Every accepted mutation adds a journal row; there is no +provider-native operation deduplication. Refused expired inventory or stale +reservation versions are recorded as attempts but cause no mutation. + +The host owns one stable intent for each desired lifecycle action. The complete +effect includes action, tenant, resource, UTC start/end instants, named timezone, +participants, party size, price/currency, terms version, quote expiry, +reservation ID and expected reservation version. Transport attempts are not +identity. Reusing an identity with changed effects conflicts. Intentional new +actions use new identities even when their effects are identical. Modification +and cancellation need their own identities and optimistic reservation versions. +All routes in the protected tests enter the reviewed boundary. A direct provider +route is used only by a labelled negative control proving duplicates are detected. + +Run with Node 24.19.0 (same-machine SQLite requires Node 24.15+): + +```sh +npm install --prefix booking-consumer --ignore-scripts --no-audit --no-fund @once-agent/sdk@0.1.25 +node examples/connected-agent-tool/booking-lifecycle.mjs file:///ABSOLUTE/PATH/booking-consumer/node_modules/@once-agent/sdk/dist/index.js evidence/booking.json +node examples/connected-agent-tool/check-booking-evidence.mjs evidence/booking.json +``` + +On Windows use `file:///C:/...`. Supply the absolute SDK file URL; no package +installation happens implicitly inside the lab. `--local` can replace that URL +for a built source checkout, but the CI workflow tests clean published consumers +on Windows and Ubuntu. Its artifacts contain independently queried provider +journal rows, reservation state, worker statuses and before/after counts. + +The lab asserts receipt replay across fresh Node processes, every declared +effect drift, missing identity/expected state, schema refusal, expired quote +and stale-version refusals, three lost-acknowledgement lifecycle operations, +durable UNKNOWN blocking, delayed truth and NOT_FOUND blocking, mismatched and +non-unique lookup rejection, exact authoritative reconciliation, twelve +concurrent duplicate attempts and two raw duplicate mutations as a negative +control. Lost acknowledgement is a deliberate throw after parsing the accepted +response, not a network fault. Positive reconciliation reads the provider's +historical operation journal and matches the complete effect and receipt; +current reservation state alone cannot prove an earlier modify/cancel action. +The delayed/NOT_FOUND/mismatched/non-unique observations are explicit fixture +fault injection. Neither a missing lookup row nor UNKNOWN permits redispatch. + +The expected final journal has thirteen mutation rows: eleven protected effects +including one concurrent operation, and two deliberately unprotected duplicates. +Rejected inventory/version actions add no mutation rows. The receipt can be a +confirmed business rejection; confirmed execution does not imply a booking exists. + +This is a working reference contract, **not a production booking adapter**. +The mock has no real authentication, inventory service, occupancy/capacity policy, +money, cancellation penalties, timezone/DST scheduling policy or customer data. +Expiry is the fixture quote deadline checked against the provider clock. A real +provider must supply an authoritative operation/receipt lookup, complete account +and effect binding, and validated inventory/version semantics; otherwise refuse +the integration rather than inventing confirmation or retry permission. Native +provider idempotency or constraints should be used when sufficient. No claim of +universal exactly-once, distributed authority, adoption or real-provider readiness. + +Only the protection worker restarts; the provider process stays running with +durable journal storage. The lab does not qualify whole application/provider +restart, OS power loss, cancellation races, opaque provider retries, filesystem +attacks or distributed storage. Cold SQLite opening may fail closed with +STATE_UNAVAILABLE; subsequent retries must retain the same authority and intent. diff --git a/examples/connected-agent-tool/README.md b/examples/connected-agent-tool/README.md index 6e84e192..d7f664e8 100644 --- a/examples/connected-agent-tool/README.md +++ b/examples/connected-agent-tool/README.md @@ -48,3 +48,9 @@ For a real-provider integration example, see [GitHub issue recovery](../../sdk/typescript/examples/GITHUB_ISSUE_RECOVERY.md). It shows lost-acknowledgement recovery without a retained issue number and a caller outcome table for IN_FLIGHT, UNKNOWN, CONFLICT, and receipt errors. + +For a richer controlled booking reference using published `wrapTool`, see +[booking lifecycle](BOOKING_LIFECYCLE.md). It extends this fake provider example +with create/modify/cancel, independently journalled effects, expiry/version +refusals, lost-response recovery and concurrent workers. It remains a local mock +integration rather than a production booking adapter. diff --git a/examples/connected-agent-tool/booking-boundary.mjs b/examples/connected-agent-tool/booking-boundary.mjs new file mode 100644 index 00000000..3bf9575b --- /dev/null +++ b/examples/connected-agent-tool/booking-boundary.mjs @@ -0,0 +1,66 @@ +// Controlled booking mock only. Host owns identity, provider URL and durable path. +import { readFileSync, existsSync } from 'node:fs'; +import { isDeepStrictEqual } from 'node:util'; +const request = JSON.parse(readFileSync(0, 'utf8')); +const { wrapTool } = await import(request.sdkUrl); +try { + const fields = ['action','tenant','resource','startsAt','endsAt','timezone','participants', + 'partySize','priceMinor','currency','termsVersion','validUntil','reservationId','expectedVersion']; + const effect = request.args; + const invalid = () => {throw Object.assign(Error('Controlled booking fixture requires its complete reviewed effect schema'), {code:'INVALID_BOOKING_EFFECT'});}; + if (!effect || typeof effect !== 'object' || Array.isArray(effect) || + !isDeepStrictEqual(Object.keys(effect).sort(), fields.sort()) || + !['create','modify','cancel'].includes(effect.action) || + ['tenant','resource','timezone','currency','termsVersion'].some(key => typeof effect[key] !== 'string' || !effect[key].trim()) || + !Number.isSafeInteger(effect.priceMinor) || effect.priceMinor < 0 || + !Number.isSafeInteger(effect.validUntil) || effect.validUntil < 0 || + !Array.isArray(effect.participants) || !Number.isSafeInteger(effect.partySize) || effect.partySize < 1 || + effect.participants.length !== effect.partySize || + effect.participants.some(person => !person || !isDeepStrictEqual(Object.keys(person).sort(), ['customerId','name']) || + typeof person.customerId !== 'string' || !person.customerId || typeof person.name !== 'string' || !person.name) || + ![effect.startsAt,effect.endsAt].every(value => typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/.test(value)) || + !Number.isFinite(Date.parse(effect.startsAt)) || !Number.isFinite(Date.parse(effect.endsAt)) || + Date.parse(effect.endsAt) <= Date.parse(effect.startsAt)) invalid(); + try {new Intl.DateTimeFormat('en', {timeZone: effect.timezone});} catch {invalid();} + if (effect.action === 'create' ? effect.reservationId !== null || effect.expectedVersion !== null : + !Number.isSafeInteger(effect.reservationId) || effect.reservationId < 1 || + !Number.isSafeInteger(effect.expectedVersion) || effect.expectedVersion < 1) invalid(); + if (request.expectedState && !existsSync(request.statePath)) { + throw Object.assign(Error('Expected booking authority missing'), {code: 'STATE_UNAVAILABLE'}); + } + const booking = wrapTool(async effectArgs => { + const response = await fetch(request.providerUrl + '/booking', { + method: 'POST', headers: {'content-type': 'application/json'}, + body: JSON.stringify({operationId: request.intent, args: effectArgs}), + signal: AbortSignal.timeout(5000), + }); + if (!response.ok) throw Error('Booking provider response unavailable'); + const receipt = await response.json(); + if (request.lostAck) throw Error('Fixture acknowledgement lost after response parsing'); + return receipt; + }, { + operationId: input => input.intent, + effect: input => ({tool: 'fixture.booking.lifecycle', args: input.args}), + statePath: request.statePath, leaseMs: 30000, + reconcile: request.reconcile ? async ({operationId, effect}) => { + const response = await fetch(request.providerUrl + '/lookup/' + encodeURIComponent(operationId), + {signal: AbortSignal.timeout(5000)}); + if (!response.ok) return {status: 'UNKNOWN'}; + const observation = await response.json(); + if (observation.status === 'NOT_FOUND') return {status: 'NOT_FOUND'}; + if (observation.status !== 'FOUND' || observation.rows.length !== 1) return {status: 'UNKNOWN'}; + const row = observation.rows[0]; + // Exact complete effect and authoritative historical operation receipt; + // current reservation state alone cannot prove an earlier modification. + if (!isDeepStrictEqual(row.args, effect.args) || !isDeepStrictEqual(row.receipt?.args, effect.args) || + row.receipt.status !== (effect.args.action === 'cancel' ? 'CANCELLED' : 'ACTIVE') || + !Number.isSafeInteger(row.receipt.reservationId) || row.receipt.reservationId < 1 || + row.receipt.version !== (effect.args.action === 'create' ? 1 : effect.args.expectedVersion + 1) || + (effect.args.action !== 'create' && row.receipt.reservationId !== effect.args.reservationId)) return {status: 'UNKNOWN'}; + return {status: 'CONFIRMED', result: row.receipt}; + } : undefined, + }); + console.log(JSON.stringify({status: 'CONFIRMED', result: await booking({intent: request.intent, args: request.args})})); +} catch (error) { + console.log(JSON.stringify({status: error.code || 'ERROR', message: error.message})); +} diff --git a/examples/connected-agent-tool/booking-lifecycle.mjs b/examples/connected-agent-tool/booking-lifecycle.mjs new file mode 100644 index 00000000..19c1bcad --- /dev/null +++ b/examples/connected-agent-tool/booking-lifecycle.mjs @@ -0,0 +1,173 @@ +// Independent durable mock-provider journal. Never contacts a booking service. +import assert from 'node:assert/strict'; +import { DatabaseSync } from 'node:sqlite'; +import { createServer } from 'node:http'; +import { spawn } from 'node:child_process'; +import { mkdtempSync, rmSync, writeFileSync, mkdirSync, readFileSync } from 'node:fs'; +import {createHash} from 'node:crypto'; +import { tmpdir } from 'node:os'; +import { join, dirname } from 'node:path'; +import { fileURLToPath } from 'node:url'; +const [sdkArgument, output] = process.argv.slice(2); +assert(sdkArgument && output, 'Usage: node booking-lifecycle.mjs SDK_FILE_URL OUTPUT.json'); +rmSync(output, {force: true}); +const sdkUrl = sdkArgument === '--local' ? new URL('../../sdk/typescript/dist/index.js', import.meta.url).href : sdkArgument; +const root = mkdtempSync(join(tmpdir(), 'once-booking-lifecycle-')); +const db = new DatabaseSync(join(root, 'provider.sqlite')); +db.exec(`CREATE TABLE reservations(id INTEGER PRIMARY KEY, args TEXT, version INTEGER, status TEXT); + CREATE TABLE effects(id INTEGER PRIMARY KEY, operation TEXT, args TEXT, receipt TEXT); + CREATE TABLE attempts(id INTEGER PRIMARY KEY, operation TEXT);`); +const counts = () => ({effects: db.prepare('SELECT count(*) AS n FROM effects').get().n, + attempts: db.prepare('SELECT count(*) AS n FROM attempts').get().n}); +const visibility = new Map(); +const server = createServer(async (req, res) => { + res.setHeader('content-type', 'application/json'); + if (req.method === 'GET' && req.url.startsWith('/lookup/')) { + const operation = decodeURIComponent(req.url.slice('/lookup/'.length)); + const mode = visibility.get(operation); + if (mode) return res.end(JSON.stringify(typeof mode === 'string' ? {status: mode} : mode)); + const rows = db.prepare('SELECT args,receipt FROM effects WHERE operation=? ORDER BY id').all(operation) + .map(row => ({args: JSON.parse(row.args), receipt: JSON.parse(row.receipt)})); + return res.end(JSON.stringify({status: rows.length ? 'FOUND' : 'NOT_FOUND', rows})); + } + if (req.method !== 'POST' || req.url !== '/booking') {res.statusCode = 404; return res.end('{}');} + let body = ''; for await (const chunk of req) body += chunk; + const {operationId, args} = JSON.parse(body); + db.prepare('INSERT INTO attempts(operation) VALUES (?)').run(operationId); + const current = args.reservationId === null ? undefined : db.prepare('SELECT * FROM reservations WHERE id=?').get(args.reservationId); + let receipt; + if (args.validUntil <= Date.now()) receipt = {status: 'REJECTED', reason: 'INVENTORY_EXPIRED'}; + else if (args.action !== 'create' && (!current || current.status !== 'ACTIVE' || + current.version !== args.expectedVersion || JSON.parse(current.args).tenant !== args.tenant)) { + receipt = {status: 'REJECTED', reason: 'RESERVATION_VERSION_OR_AUTHORITY_MISMATCH'}; + } else { + db.exec('BEGIN IMMEDIATE'); + try { + let id, version; + if (args.action === 'create') { + id = Number(db.prepare("INSERT INTO reservations(args,version,status) VALUES (?,1,'ACTIVE')").run(JSON.stringify(args)).lastInsertRowid); + version = 1; + } else { + id = args.reservationId; version = current.version + 1; + db.prepare('UPDATE reservations SET args=?,version=?,status=? WHERE id=?') + .run(JSON.stringify(args), version, args.action === 'cancel' ? 'CANCELLED' : 'ACTIVE', id); + } + receipt = {status: args.action === 'cancel' ? 'CANCELLED' : 'ACTIVE', reservationId: id, version, args}; + db.prepare('INSERT INTO effects(operation,args,receipt) VALUES (?,?,?)') + .run(operationId, JSON.stringify(args), JSON.stringify(receipt)); + db.exec('COMMIT'); + } catch (error) { db.exec('ROLLBACK'); throw error; } + } + // Acceptance precedes response; overlapping callers can observe IN_FLIGHT. + await new Promise(resolve => setTimeout(resolve, 100)); + res.end(JSON.stringify(receipt)); +}); +await new Promise(resolve => server.listen(0, '127.0.0.1', resolve)); +const providerUrl = `http://127.0.0.1:${server.address().port}`; +const base = {action: 'create', tenant: 'tenant-A', resource: 'room-A', + startsAt: '2026-11-10T14:00:00Z', endsAt: '2026-11-10T15:00:00Z', timezone: 'Europe/London', + participants: [{customerId: 'customer-1', name: 'Fixture Person'}], + partySize: 1, priceMinor: 1200, currency: 'GBP', termsVersion: 'fixture-v1', + validUntil: Date.now() + 3600000, reservationId: null, expectedVersion: null}; +const statePath = join(root, 'once.sqlite'); +const call = (intent, args, options = {}) => new Promise((resolve, reject) => { + const child = spawn(process.execPath, [fileURLToPath(new URL('booking-boundary.mjs', import.meta.url))]); + let stdout = '', stderr = ''; + const timer = setTimeout(() => {child.kill(); reject(Error('Booking worker timed out'));}, 15000); + child.stdout.on('data', chunk => stdout += chunk); child.stderr.on('data', chunk => stderr += chunk); + child.on('error', reject); + child.on('exit', code => {clearTimeout(timer); try {assert.equal(code, 0, stderr); resolve(JSON.parse(stdout));} catch (error) {reject(error);}}); + child.stdin.end(JSON.stringify({sdkUrl, providerUrl, statePath, intent, args, ...options})); +}); +const evidence = {schema_version: 1, scope: 'controlled booking lifecycle; local same-machine authority', + sdkUrl, sdkVersion: JSON.parse(readFileSync(new URL('../package.json',sdkUrl),'utf8')).version, + hashes: Object.fromEntries([['lab',import.meta.url],['boundary',new URL('booking-boundary.mjs',import.meta.url)],['sdkEntry',sdkUrl]] + .map(([name,url])=>[name,createHash('sha256').update(readFileSync(new URL(url))).digest('hex')])), + node: process.version, platform: process.platform, probes: []}; +const probe = async (name, intent, args, options, status, delta = 0) => { + const before = counts(); const response = await call(intent, args, options); const after = counts(); + assert.equal(response.status, status, JSON.stringify(response)); assert.equal(after.effects - before.effects, delta); + if (delta === 0 && status !== 'CONFIRMED') assert.equal(after.attempts, before.attempts); + evidence.probes.push({name, before, after, response}); return response; +}; +try { + const created = await probe('create', 'create-1', base, {}, 'CONFIRMED', 1); + const replay = await probe('fresh-process-create-replay', 'create-1', base, {expectedState: true}, 'CONFIRMED'); + assert.deepEqual(replay, created); + for (const [field, value] of Object.entries({tenant: 'tenant-B', resource: 'room-B', timezone: 'UTC', + startsAt: '2026-11-10T14:30:00Z', endsAt: '2026-11-10T16:00:00Z', participants: [{customerId: 'other', name: 'Other'}], + priceMinor: 1300, currency: 'USD', termsVersion: 'v2', validUntil: base.validUntil + 1})) { + await probe('drift-' + field, 'create-1', {...base, [field]: value}, {}, 'CONFLICT'); + } + await probe('missing-identity', '', base, {}, 'IDENTITY_REQUIRED'); + await probe('missing-expected-state', 'create-1', base, {expectedState:true, statePath:join(root,'missing.sqlite')}, 'STATE_UNAVAILABLE'); + await probe('drift-party-size', 'create-1', {...base, partySize:2, + participants:[...base.participants, {customerId:'customer-2', name:'Second Person'}]}, {}, 'CONFLICT'); + for (const args of [null, {...base, participants: []}, {...base, providerUrl: 'unreviewed'}, + {...base, timezone: 'not-a-zone'}, {...base, endsAt: base.startsAt}, {...base, action:'unknown'}]) { + await probe('unsupported-effect', 'unsafe', args, {}, 'INVALID_BOOKING_EFFECT'); + } + const modification = {...base, action: 'modify', reservationId: created.result.reservationId, + expectedVersion: 1, endsAt: '2026-11-10T16:00:00Z'}; + const modified = await probe('modify', 'modify-1', modification, {}, 'CONFIRMED', 1); + assert.deepEqual(await probe('modify-replay', 'modify-1', modification, {}, 'CONFIRMED'), modified); + await probe('modify-target-drift', 'modify-1', {...modification, reservationId: 999}, {}, 'CONFLICT'); + await probe('modify-version-drift', 'modify-1', {...modification, expectedVersion: 2}, {}, 'CONFLICT'); + const cancellation = {...modification, action: 'cancel', expectedVersion: 2}; + const cancelled = await probe('cancel', 'cancel-1', cancellation, {}, 'CONFIRMED', 1); + assert.equal(cancelled.result.status, 'CANCELLED'); + assert.deepEqual(await probe('cancel-replay', 'cancel-1', cancellation, {}, 'CONFIRMED'), cancelled); + await probe('new-identical-intent', 'create-2', base, {}, 'CONFIRMED', 1); + const expired = await probe('expired-inventory', 'expired-1', {...base, validUntil: 0}, {}, 'CONFIRMED'); + assert.deepEqual(expired.result, {status: 'REJECTED', reason: 'INVENTORY_EXPIRED'}); + const expiryAttempts = counts().attempts; + assert.deepEqual(await probe('expired-inventory-replay', 'expired-1', {...base, validUntil:0}, {}, 'CONFIRMED'), expired); + assert.equal(counts().attempts, expiryAttempts); + const stale = await probe('stale-version', 'stale-1', modification, {}, 'CONFIRMED'); + assert.equal(stale.result.reason, 'RESERVATION_VERSION_OR_AUTHORITY_MISMATCH'); + for (const action of ['create', 'modify', 'cancel']) { + const setup = await probe('lost-ack-setup-' + action, 'setup-' + action, base, {}, 'CONFIRMED', 1); + const effect = action === 'create' ? base : {...base, action, reservationId: setup.result.reservationId, expectedVersion: 1}; + const intent = 'lost-' + action; + await probe('lost-ack-' + action, intent, effect, {lostAck: true}, 'UNKNOWN', 1); + await probe('restart-unknown-' + action, intent, effect, {}, 'UNKNOWN'); + visibility.set(intent, 'UNKNOWN'); + await probe('delayed-truth-' + action, intent, effect, {reconcile: true}, 'UNKNOWN'); + visibility.set(intent, 'NOT_FOUND'); + await probe('non-authoritative-absence-' + action, intent, effect, {reconcile: true}, 'UNKNOWN'); + visibility.delete(intent); + const actual = db.prepare('SELECT args,receipt FROM effects WHERE operation=?').get(intent); + const row = {args: JSON.parse(actual.args), receipt: JSON.parse(actual.receipt)}; + visibility.set(intent, {status: 'FOUND', rows: [{...row, args: {...row.args, resource:'wrong'}}]}); + await probe('mismatched-truth-' + action, intent, effect, {reconcile:true}, 'UNKNOWN'); + visibility.set(intent, {status: 'FOUND', rows: [row, row]}); + await probe('nonunique-truth-' + action, intent, effect, {reconcile:true}, 'UNKNOWN'); + visibility.delete(intent); + const reconciled = await probe('exact-reconciliation-' + action, intent, effect, {reconcile: true}, 'CONFIRMED'); + assert.deepEqual(reconciled.result.args, effect); + assert.deepEqual(await probe('reconciled-replay-' + action, intent, effect, {}, 'CONFIRMED'), reconciled); + } + const before = counts(); + const concurrent = await Promise.all(Array.from({length: 12}, () => call('concurrent-1', base))); + assert.equal(counts().effects - before.effects, 1); + assert(concurrent.some(item => item.status === 'CONFIRMED')); + assert(concurrent.every(item => ['CONFIRMED','IN_FLIGHT','STATE_UNAVAILABLE','UNKNOWN'].includes(item.status))); + const final = await call('concurrent-1', base); + assert.equal(final.status, 'CONFIRMED'); + for (const item of concurrent.filter(item => item.status !== 'CONFIRMED')) assert.deepEqual(await call('concurrent-1', base), final); + evidence.concurrent = {before, after: counts(), results: concurrent, replay: final}; + // Negative control deliberately bypasses protection twice: journal must catch it. + const negativeBefore = counts(); + for (let index=0; index<2; index++) { + const response = await fetch(providerUrl + '/booking', {method: 'POST', headers: {'content-type':'application/json'}, + body: JSON.stringify({operationId: 'raw-duplicate', args: base})}); assert.equal(response.status, 200); + } + assert.equal(counts().effects - negativeBefore.effects, 2); + evidence.negative = {before: negativeBefore, after: counts(), expected_duplicates: 2}; + evidence.provider_effects = db.prepare('SELECT * FROM effects ORDER BY id').all().map(row => ({...row,args: JSON.parse(row.args),receipt: JSON.parse(row.receipt)})); + evidence.reservations = db.prepare('SELECT * FROM reservations ORDER BY id').all().map(row => ({...row,args: JSON.parse(row.args)})); + evidence.status = 'PASS'; mkdirSync(dirname(output), {recursive:true}); writeFileSync(output, JSON.stringify(evidence,null,2)); + console.log(`PASS ${evidence.probes.length} probes; 12 concurrent workers; ${counts().effects} effects including 2 raw-control duplicates`); +} finally { + await new Promise(resolve => server.close(resolve)); db.close(); rmSync(root,{recursive:true,force:true}); +} diff --git a/examples/connected-agent-tool/check-booking-evidence.mjs b/examples/connected-agent-tool/check-booking-evidence.mjs new file mode 100644 index 00000000..11c7d21f --- /dev/null +++ b/examples/connected-agent-tool/check-booking-evidence.mjs @@ -0,0 +1,33 @@ +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +for (const filename of process.argv.slice(2)) { + const evidence = JSON.parse(readFileSync(filename,'utf8')); + assert.equal(evidence.status,'PASS'); assert.equal(evidence.schema_version,1); + assert.equal(evidence.sdkVersion,'0.1.25'); + assert(Object.values(evidence.hashes).every(value=>/^[a-f0-9]{64}$/.test(value))); + assert(evidence.probes.length >= 57); + for (const probe of evidence.probes) { + const mutation = probe.after.effects - probe.before.effects; + assert(mutation === 0 || mutation === 1); + if (probe.response.status !== 'CONFIRMED' && mutation === 0) assert.equal(probe.after.attempts,probe.before.attempts); + } + for (const action of ['create','modify','cancel']) { + for (const prefix of ['lost-ack','restart-unknown','delayed-truth','non-authoritative-absence','mismatched-truth','nonunique-truth']) { + assert.equal(evidence.probes.find(probe=>probe.name===prefix+'-'+action).response.status,'UNKNOWN'); + } + assert.equal(evidence.probes.find(probe=>probe.name==='exact-reconciliation-'+action).response.status,'CONFIRMED'); + assert.equal(evidence.provider_effects.filter(row=>row.operation==='lost-'+action).length,1); + } + assert.equal(evidence.concurrent.results.length,12); + assert.equal(evidence.concurrent.after.effects-evidence.concurrent.before.effects,1); + assert.equal(evidence.provider_effects.filter(row=>row.operation==='concurrent-1').length,1); + assert.equal(evidence.provider_effects.filter(row=>row.operation==='raw-duplicate').length,2); + assert.equal(evidence.negative.after.effects-evidence.negative.before.effects,2); + assert.equal(evidence.provider_effects.length,13); + assert.equal(evidence.provider_effects.filter(row=>row.args.action==='modify').length,2); + assert.equal(evidence.provider_effects.filter(row=>row.args.action==='cancel').length,2); + assert.equal(evidence.probes.filter(probe=>probe.name==='unsupported-effect').length,6); + assert(evidence.probes.filter(probe=>probe.name==='unsupported-effect').every(probe=>probe.response.status==='INVALID_BOOKING_EFFECT')); + assert.equal(evidence.reservations.filter(row=>row.status==='CANCELLED').length,2); + console.log(filename+': booking evidence PASS'); +}