Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions .github/workflows/booking-lifecycle.yml
Original file line number Diff line number Diff line change
@@ -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
67 changes: 67 additions & 0 deletions examples/connected-agent-tool/BOOKING_LIFECYCLE.md
Original file line number Diff line number Diff line change
@@ -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.
6 changes: 6 additions & 0 deletions examples/connected-agent-tool/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
66 changes: 66 additions & 0 deletions examples/connected-agent-tool/booking-boundary.mjs
Original file line number Diff line number Diff line change
@@ -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}));
}
Loading
Loading