@danceiny/gotry 0.0.1-rc.17 → 0.0.1-rc.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +185 -148
- package/README.zh-CN.md +195 -154
- package/bin/gotry-bootstrap.js +246 -26
- package/bin/gotry-inner.js +68 -38
- package/bin/gotry-runtime-resolution.d.ts +1 -1
- package/bin/gotry-runtime-resolution.js +7 -8
- package/cordis.gotry-patch.yml +15 -5
- package/data/stations-12306-verify.json +524 -0
- package/dist/capabilities/agent-reach.js +4 -4
- package/dist/capabilities/channel-health.js +103 -0
- package/dist/capabilities/channel-registry.js +213 -0
- package/dist/capabilities/doctor.js +285 -0
- package/dist/capabilities/effect.js +178 -5
- package/dist/capabilities/flyai.js +13 -0
- package/dist/capabilities/session/adapters/ctrip-hotel.js +207 -0
- package/dist/capabilities/session/adapters/rail-12306.js +285 -0
- package/dist/capabilities/session/extension-bridge.js +14 -1
- package/dist/capabilities/session/extension-channel.js +4 -2
- package/dist/capabilities/session/extension-distribution.js +1 -1
- package/dist/capabilities/session-search.js +311 -0
- package/dist/capabilities/visa-policy.js +126 -0
- package/dist/scripts/agent-planning-turn-deadline-e2e.js +304 -0
- package/dist/scripts/agent-planning-turn-deadline-tests.js +281 -0
- package/dist/scripts/benchmark-environment-bridge-e2e.js +5 -10
- package/dist/scripts/benchmark-environment-bridge-tests.js +148 -142
- package/dist/scripts/booking-copilot-availability-ledger-binding-tests.js +26 -26
- package/dist/scripts/{booking-copilot-availability-policy-v2-tests.js → booking-copilot-availability-policy-tests.js} +115 -115
- package/dist/scripts/booking-copilot-crossrepo-fixture-server.js +41 -1
- package/dist/scripts/booking-copilot-dsh-core-proof-tests.js +75 -120
- package/dist/scripts/booking-copilot-dsh-planner-proof-tests.js +370 -61
- package/dist/scripts/booking-copilot-dsh-plugin-proof-tests.js +2 -2
- package/dist/scripts/booking-copilot-event-sequence-concurrency-proof-tests.js +7 -3
- package/dist/scripts/booking-copilot-gap-code-contract-proof-tests.js +15 -9
- package/dist/scripts/booking-copilot-operation-ledger-concurrency-proof-tests.js +19 -11
- package/dist/scripts/booking-copilot-receipt-ledger-concurrency-proof-tests.js +16 -52
- package/dist/scripts/booking-copilot-runtime-proof-tests.js +3953 -155
- package/dist/scripts/booking-copilot-server-proof-tests.js +58 -23
- package/dist/scripts/booking-copilot-startup-proof-tests.js +10 -119
- package/dist/scripts/booking-surface-contract-proof-tests.js +1154 -326
- package/dist/scripts/bootstrap-tests.js +115 -44
- package/dist/scripts/build-metrics-report.js +339 -0
- package/dist/scripts/channel-probe-tests.js +148 -0
- package/dist/scripts/channel-probe.js +252 -0
- package/dist/scripts/channel-registry-tests.js +262 -0
- package/dist/scripts/doctor-tests.js +121 -0
- package/dist/scripts/effect-tests.js +274 -1
- package/dist/scripts/extension-tests.js +129 -11
- package/dist/scripts/fact-gate-tests.js +91 -2
- package/dist/scripts/flyai-tests.js +17 -1
- package/dist/scripts/hbcli-e2e-tests.js +1 -3
- package/dist/scripts/metrics-report-tests.js +288 -0
- package/dist/scripts/persona-surface-guard-tests.js +19 -0
- package/dist/scripts/session-tests.js +401 -1
- package/dist/scripts/smoke.js +100 -83
- package/dist/scripts/turn-handoff-collect-tests.js +216 -0
- package/dist/scripts/turn-handoff-collect.js +189 -0
- package/dist/scripts/turn-policy-tests.js +56 -0
- package/dist/scripts/typed-contract-canary.js +261 -0
- package/dist/scripts/visa-policy-tests.js +75 -0
- package/dist/scripts/wish-channel-gate-tests.js +111 -0
- package/dist/src/artifact-gate.js +91 -3
- package/dist/src/benchmark-agent-conformance.js +7 -4
- package/dist/src/benchmark-environment-bridge.js +68 -7
- package/dist/src/bookable-facts.js +62 -3
- package/dist/src/booking-surface/{availability-policy-v2.js → availability-policy.js} +89 -89
- package/dist/src/booking-surface/canonical-schema.js +8 -22
- package/dist/src/booking-surface/contracts.js +70 -19
- package/dist/src/booking-surface/dsh-planner.js +310 -177
- package/dist/src/booking-surface/dsh-plugin.js +3 -3
- package/dist/src/booking-surface/index.js +1 -5
- package/dist/src/booking-surface/profile.js +1 -1
- package/dist/src/booking-surface/runtime.js +1682 -247
- package/dist/src/booking-surface/server.js +371 -185
- package/dist/src/booking-surface/startup.js +17 -27
- package/dist/src/booking-surface/validation.js +270 -760
- package/dist/src/index.js +735 -149
- package/dist/src/turn-deadline.js +292 -0
- package/dist/src/turn-policy.js +146 -0
- package/dist/src/wish-pool.js +5 -0
- package/extension/background.js +23 -4
- package/extension/content-main.js +47 -9
- package/extension/manifest.json +27 -9
- package/package.json +6 -26
- package/schemas/booking.surface.schema.json +2593 -0
- package/ts/capabilities/agent-reach.ts +4 -4
- package/ts/capabilities/flyai.ts +21 -3
- package/ts/capabilities/session/action-cache.ts +1 -1
- package/ts/capabilities/session/adapters/ctrip-hotel.ts +238 -0
- package/ts/capabilities/session/adapters/rail-12306.ts +293 -0
- package/ts/capabilities/session/extension-bridge.ts +32 -2
- package/ts/capabilities/session/extension-channel.ts +9 -8
- package/ts/capabilities/session/extension-distribution.ts +3 -1
- package/ts/capabilities/session/health-watch.ts +1 -1
- package/ts/capabilities/session/read-guard.ts +1 -1
- package/ts/capabilities/session/wizard.ts +1 -1
- package/ts/capabilities/session-search.ts +323 -1
- package/ts/package.json +1 -0
- package/ts/scripts/turn-handoff-collect.ts +178 -0
- package/ts/src/artifact-gate.ts +82 -2
- package/ts/src/benchmark-agent-conformance.ts +14 -6
- package/ts/src/benchmark-environment-bridge.ts +29 -10
- package/ts/src/bookable-facts.ts +109 -5
- package/ts/src/booking-saga.ts +1 -1
- package/ts/src/booking-surface/{availability-policy-v2.ts → availability-policy.ts} +124 -125
- package/ts/src/booking-surface/canonical-schema.js +8 -22
- package/ts/src/booking-surface/contracts.ts +278 -239
- package/ts/src/booking-surface/dsh-planner.ts +333 -194
- package/ts/src/booking-surface/dsh-plugin.js +3 -3
- package/ts/src/booking-surface/index.ts +1 -5
- package/ts/src/booking-surface/profile.ts +11 -11
- package/ts/src/booking-surface/runtime.ts +1351 -351
- package/ts/src/booking-surface/server.ts +282 -175
- package/ts/src/booking-surface/startup.ts +36 -48
- package/ts/src/booking-surface/validation.ts +194 -442
- package/ts/src/contracts.ts +1 -1
- package/ts/src/index.ts +489 -171
- package/ts/src/loop.ts +1 -1
- package/ts/src/state-ledger.ts +1 -1
- package/ts/src/turn-deadline.ts +361 -0
- package/ts/src/turn-policy.ts +154 -0
- package/ts/src/wish-pool.ts +17 -4
- package/dist/scripts/agent-planning-budget-e2e.js +0 -227
- package/dist/scripts/agent-planning-budget-tests.js +0 -173
- package/dist/scripts/booking-copilot-v2-runtime-proof-tests.js +0 -3935
- package/dist/scripts/booking-surface-v2-contract-proof-tests.js +0 -1174
- package/dist/src/booking-surface/contracts-v2.js +0 -89
- package/dist/src/booking-surface/runtime-v2.js +0 -1771
- package/dist/src/booking-surface/server-v2.js +0 -334
- package/dist/src/booking-surface/validation-v2.js +0 -319
- package/dist/src/tool-budget.js +0 -136
- package/schemas/booking.surface.v1.schema.json +0 -927
- package/schemas/booking.surface.v2.schema.json +0 -61
- package/ts/src/booking-surface/contracts-v2.ts +0 -118
- package/ts/src/booking-surface/runtime-v2.ts +0 -1466
- package/ts/src/booking-surface/server-v2.ts +0 -247
- package/ts/src/booking-surface/validation-v2.ts +0 -205
- package/ts/src/tool-budget.ts +0 -165
|
@@ -1,1771 +0,0 @@
|
|
|
1
|
-
import { createHash, randomUUID } from 'node:crypto';
|
|
2
|
-
import { BOOKING_READ_ACTION_KINDS_V2, BOOKING_COPILOT_MAX_OPERATIONS_V2 } from './contracts-v2.js';
|
|
3
|
-
import { validateApprovalAgainstBlocker, validateCriterionBlockerV2, validateBookingReadActionV2, validateBookingSurfaceEventV2, validateBookingSurfaceV2, isBookingDateTimeV2, isSafeBookingRequestKeyV2 } from './validation-v2.js';
|
|
4
|
-
import { assertWorkspaceLoadedOfferRefsUniqueV2, canIssueOfferCheckV2, createAvailabilityPolicyV2, reduceAvailabilityActionV2, reduceAvailabilityReceiptV2, validateOffersReceiptWorkspaceV2, availabilityPolicyResultV2, validateAvailabilityPolicyV2 } from './availability-policy-v2.js';
|
|
5
|
-
import { normalizeBookingErrorCode, safeBookingErrorMessage } from './error-codes.js';
|
|
6
|
-
const LEDGER_SCHEMA = 'booking.copilot.ledger.v2';
|
|
7
|
-
const ACTOR = 'system:booking-copilot-v2';
|
|
8
|
-
const STARTED = 'booking.copilot.v2.task.started';
|
|
9
|
-
const TURN = 'booking.copilot.v2.user.turn.observed';
|
|
10
|
-
const ACTION = 'booking.copilot.v2.action.issued';
|
|
11
|
-
const RECEIPT = 'booking.copilot.v2.receipt.observed';
|
|
12
|
-
const EVENT = 'booking.copilot.v2.event.emitted';
|
|
13
|
-
const APPROVAL_GRANTED = 'booking.copilot.v2.approval.granted';
|
|
14
|
-
const APPROVAL_OFFERED = 'booking.copilot.v2.approval.option.offered';
|
|
15
|
-
const APPROVAL_CONSUMED = 'booking.copilot.v2.approval.consumed';
|
|
16
|
-
const DECISION_BATCH = 'booking.copilot.v2.decision.batch';
|
|
17
|
-
const REQUEST_BINDING = 'booking.copilot.v2.request.binding';
|
|
18
|
-
function stable(value) {
|
|
19
|
-
if (Array.isArray(value)) return value.map(stable);
|
|
20
|
-
if (!value || typeof value !== 'object') return value;
|
|
21
|
-
const out = {};
|
|
22
|
-
for (const key of Object.keys(value).sort())out[key] = stable(value[key]);
|
|
23
|
-
return out;
|
|
24
|
-
}
|
|
25
|
-
export function bookingV2Digest(value) {
|
|
26
|
-
return createHash('sha256').update(JSON.stringify(stable(value))).digest('hex');
|
|
27
|
-
}
|
|
28
|
-
export function bookingV2WorkspaceDigest(workspace) {
|
|
29
|
-
const { contextRef: _contextRef, ...contextBoundWorkspace } = workspace;
|
|
30
|
-
return bookingV2Digest(contextBoundWorkspace);
|
|
31
|
-
}
|
|
32
|
-
function bookingV2WorkspaceSemanticDigest(workspace) {
|
|
33
|
-
const { contextRef: _contextRef, revision: _revision, ...semanticWorkspace } = workspace;
|
|
34
|
-
return bookingV2Digest(semanticWorkspace);
|
|
35
|
-
}
|
|
36
|
-
export function bookingV2TurnDigest(turn) {
|
|
37
|
-
return bookingV2Digest(turn);
|
|
38
|
-
}
|
|
39
|
-
function canonicalReceiptDigest(value) {
|
|
40
|
-
return bookingV2Digest(value);
|
|
41
|
-
}
|
|
42
|
-
function replayDigestMatches(recordedDigest, raw, normalized) {
|
|
43
|
-
return typeof recordedDigest === 'string' && (recordedDigest === bookingV2Digest(raw) || recordedDigest === bookingV2Digest(normalized));
|
|
44
|
-
}
|
|
45
|
-
function replayWorkspaceDigestMatches(recordedDigest, raw, normalized) {
|
|
46
|
-
return typeof recordedDigest === 'string' && (recordedDigest === bookingV2WorkspaceDigest(raw) || recordedDigest === bookingV2WorkspaceDigest(normalized));
|
|
47
|
-
}
|
|
48
|
-
function replayWorkspaceSemanticDigestMatches(recordedDigest, raw, normalized) {
|
|
49
|
-
return typeof recordedDigest === 'string' && (recordedDigest === bookingV2WorkspaceSemanticDigest(raw) || recordedDigest === bookingV2WorkspaceSemanticDigest(normalized));
|
|
50
|
-
}
|
|
51
|
-
function rememberReplayWorkspaceDigest(digests, recordedDigest, raw, normalized) {
|
|
52
|
-
const normalizedDigest = bookingV2WorkspaceDigest(normalized);
|
|
53
|
-
digests.set(bookingV2WorkspaceDigest(raw), normalizedDigest);
|
|
54
|
-
if (typeof recordedDigest === 'string') digests.set(recordedDigest, normalizedDigest);
|
|
55
|
-
}
|
|
56
|
-
function legacyOfferVersionRef(contextRef, offer) {
|
|
57
|
-
return `legacy-offer-version:${bookingV2Digest({
|
|
58
|
-
contextRef,
|
|
59
|
-
offerRef: offer.offerRef,
|
|
60
|
-
hotelRef: offer.hotelRef,
|
|
61
|
-
evidenceLevel: offer.evidenceLevel,
|
|
62
|
-
factRefs: Array.isArray(offer.factRefs) ? offer.factRefs : []
|
|
63
|
-
}).slice(0, 40)}`;
|
|
64
|
-
}
|
|
65
|
-
function normalizeWorkspaceForReplay(raw) {
|
|
66
|
-
const candidate = raw;
|
|
67
|
-
if (!raw || typeof raw !== 'object' || Array.isArray(raw) || !Array.isArray(candidate.loadedOffers) || typeof candidate.contextRef !== 'string') throw new Error('booking_v2_malformed_workspace');
|
|
68
|
-
const workspace = structuredClone(raw);
|
|
69
|
-
workspace.loadedOffers = workspace.loadedOffers.map((offer)=>offer.offerVersionRef ? offer : {
|
|
70
|
-
...offer,
|
|
71
|
-
offerVersionRef: legacyOfferVersionRef(workspace.contextRef, offer)
|
|
72
|
-
});
|
|
73
|
-
delete workspace.verifiedOfferRef;
|
|
74
|
-
return workspace;
|
|
75
|
-
}
|
|
76
|
-
function resolveReplayOfferVersion(offerRef, workspace, action, actionId, priorAvailability) {
|
|
77
|
-
const priorAttempt = actionId ? priorAvailability?.attempts.find((attempt)=>attempt.actionId === actionId) : undefined;
|
|
78
|
-
if (priorAttempt?.offerVersionRef) return priorAttempt.offerVersionRef;
|
|
79
|
-
if (action?.kind === 'offer.check' && action.actionId === actionId && action.input.offerRef === offerRef && typeof action.input.offerVersionRef === 'string') return action.input.offerVersionRef;
|
|
80
|
-
const match = workspace?.loadedOffers.find((offer)=>offer.offerRef === offerRef);
|
|
81
|
-
if (match?.offerVersionRef) return match.offerVersionRef;
|
|
82
|
-
throw new Error('booking_v2_replan_required:offer_version_unbound');
|
|
83
|
-
}
|
|
84
|
-
function normalizeAvailabilityPolicyForReplay(raw, workspace, action, priorAvailability, workspaceDigestMap = new Map(), receipt) {
|
|
85
|
-
const normalized = structuredClone(raw);
|
|
86
|
-
if (normalized.hotels && typeof normalized.hotels === 'object') {
|
|
87
|
-
for (const [hotelRef, hotel] of Object.entries(normalized.hotels)){
|
|
88
|
-
const rawHotel = raw.hotels?.[hotelRef];
|
|
89
|
-
const priorHotel = priorAvailability?.hotels[hotelRef];
|
|
90
|
-
if (!Array.isArray(hotel.tombstonedOfferRefs)) hotel.tombstonedOfferRefs = priorHotel ? [
|
|
91
|
-
...priorHotel.tombstonedOfferRefs
|
|
92
|
-
] : [];
|
|
93
|
-
if (!Array.isArray(hotel.tombstonedOfferVersionRefs)) hotel.tombstonedOfferVersionRefs = priorHotel ? [
|
|
94
|
-
...priorHotel.tombstonedOfferVersionRefs
|
|
95
|
-
] : [];
|
|
96
|
-
if (rawHotel && Array.isArray(rawHotel.tombstonedOfferRefs) && priorHotel) {
|
|
97
|
-
for (const ref of priorHotel.tombstonedOfferRefs)if (!hotel.tombstonedOfferRefs.includes(ref)) throw new Error('booking_v2_replan_required:tombstone_regression');
|
|
98
|
-
}
|
|
99
|
-
if (rawHotel && Array.isArray(rawHotel.tombstonedOfferVersionRefs) && priorHotel) {
|
|
100
|
-
for (const ref of priorHotel.tombstonedOfferVersionRefs)if (!hotel.tombstonedOfferVersionRefs.includes(ref)) throw new Error('booking_v2_replan_required:tombstone_regression');
|
|
101
|
-
}
|
|
102
|
-
const source = hotel.currentGeneration?.source;
|
|
103
|
-
if (source?.kind === 'workspace_snapshot') {
|
|
104
|
-
const mappedDigest = workspaceDigestMap.get(source.workspaceDigest);
|
|
105
|
-
if (mappedDigest) source.workspaceDigest = mappedDigest;
|
|
106
|
-
}
|
|
107
|
-
}
|
|
108
|
-
}
|
|
109
|
-
if (Array.isArray(normalized.attempts)) {
|
|
110
|
-
normalized.attempts = normalized.attempts.map((attempt)=>attempt.offerVersionRef ? attempt : {
|
|
111
|
-
...attempt,
|
|
112
|
-
offerVersionRef: resolveReplayOfferVersion(attempt.offerRef, workspace, action, attempt.actionId, priorAvailability)
|
|
113
|
-
});
|
|
114
|
-
}
|
|
115
|
-
const availability = receipt?.observation.kind === 'offer.availability' ? receipt.observation : undefined;
|
|
116
|
-
if (receipt && action?.kind === 'offer.check' && availability && availability.offerRef === action.input.offerRef && availability.checkedOfferVersionRef === action.input.offerVersionRef) {
|
|
117
|
-
const attempt = normalized.attempts.find((candidate)=>candidate.actionId === action.actionId);
|
|
118
|
-
const hotel = attempt ? normalized.hotels[attempt.hotelRef] : undefined;
|
|
119
|
-
if (hotel) {
|
|
120
|
-
if (receipt.status === 'changed' && availability.available === true && availability.currentOfferVersionRef && availability.currentOfferVersionRef !== action.input.offerVersionRef) {
|
|
121
|
-
if (!hotel.tombstonedOfferVersionRefs.includes(action.input.offerVersionRef)) hotel.tombstonedOfferVersionRefs.push(action.input.offerVersionRef);
|
|
122
|
-
}
|
|
123
|
-
const completeNegative = (receipt.status === 'unavailable' || receipt.status === 'no_match') && receipt.resultContract.outcome === 'empty' && receipt.resultContract.gapCodes.length === 0 && receipt.resultContract.blockers.length === 0 && availability.available === false && !availability.currentOfferVersionRef && !availability.verifiedOfferRef && !availability.gapCodes?.length;
|
|
124
|
-
if (completeNegative) {
|
|
125
|
-
if (!hotel.tombstonedOfferVersionRefs.includes(action.input.offerVersionRef)) hotel.tombstonedOfferVersionRefs.push(action.input.offerVersionRef);
|
|
126
|
-
if (!hotel.tombstonedOfferRefs.includes(action.input.offerRef)) hotel.tombstonedOfferRefs.push(action.input.offerRef);
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
}
|
|
130
|
-
return normalized;
|
|
131
|
-
}
|
|
132
|
-
function normalizeActionCheckpointForReplay(raw, workspace) {
|
|
133
|
-
if (![
|
|
134
|
-
'offer.select',
|
|
135
|
-
'offer.check',
|
|
136
|
-
'checkout.prepare'
|
|
137
|
-
].includes(raw.kind) || typeof raw.input.offerVersionRef === 'string') return raw;
|
|
138
|
-
if (typeof raw.input.offerRef !== 'string') throw new Error('booking_v2_replan_required:offer_version_unbound');
|
|
139
|
-
const offerVersionRef = resolveReplayOfferVersion(raw.input.offerRef, workspace, undefined, raw.actionId);
|
|
140
|
-
const input = {
|
|
141
|
-
...raw.input,
|
|
142
|
-
offerVersionRef
|
|
143
|
-
};
|
|
144
|
-
if (raw.kind === 'checkout.prepare' && (!workspace?.verifiedOffer || workspace.verifiedOffer.offerRef !== input.offerRef || workspace.verifiedOffer.offerVersionRef !== offerVersionRef || workspace.verifiedOffer.verifiedOfferRef !== input.verifiedOfferRef)) throw new Error('booking_v2_replan_required:legacy_checkout_unverified');
|
|
145
|
-
const { actionDigest: _rawActionDigest, ...rawBase } = raw;
|
|
146
|
-
const normalizedBase = {
|
|
147
|
-
...rawBase,
|
|
148
|
-
input,
|
|
149
|
-
inputDigest: bookingV2Digest(input)
|
|
150
|
-
};
|
|
151
|
-
return {
|
|
152
|
-
...normalizedBase,
|
|
153
|
-
actionDigest: checkpointDigest(normalizedBase)
|
|
154
|
-
};
|
|
155
|
-
}
|
|
156
|
-
function checkpointDigestMatchesForReplay(raw, normalized) {
|
|
157
|
-
const { actionDigest: _rawDigest, ...rawBase } = raw;
|
|
158
|
-
const { actionDigest: _normalizedDigest, ...normalizedBase } = normalized;
|
|
159
|
-
return raw.actionDigest === checkpointDigest(rawBase) || raw.actionDigest === checkpointDigest(normalizedBase);
|
|
160
|
-
}
|
|
161
|
-
function replanAfterReplayUpgradeGap(state, workspace = state.workspaceSnapshot, revision = workspace?.revision) {
|
|
162
|
-
if (!workspace) return {
|
|
163
|
-
...state,
|
|
164
|
-
phase: 'error',
|
|
165
|
-
pendingAction: undefined
|
|
166
|
-
};
|
|
167
|
-
const safeRevision = typeof revision === 'number' && Number.isSafeInteger(revision) ? revision : state.revision;
|
|
168
|
-
return {
|
|
169
|
-
...state,
|
|
170
|
-
revision: safeRevision,
|
|
171
|
-
phase: 'planning',
|
|
172
|
-
pendingAction: undefined,
|
|
173
|
-
awaitingApproval: undefined,
|
|
174
|
-
workspaceDigest: bookingV2WorkspaceDigest(workspace),
|
|
175
|
-
workspaceSemanticDigest: bookingV2WorkspaceSemanticDigest(workspace),
|
|
176
|
-
workspaceSnapshot: workspace,
|
|
177
|
-
availability: createAvailabilityPolicyV2(workspace),
|
|
178
|
-
replayUpgradeRequired: true
|
|
179
|
-
};
|
|
180
|
-
}
|
|
181
|
-
function assertReplayUpgradeReanchored(state) {
|
|
182
|
-
if (state.replayUpgradeRequired) throw new Error('reanchor_turn_required');
|
|
183
|
-
}
|
|
184
|
-
function consumedIdentityKey(eventId, sequence) {
|
|
185
|
-
return `${eventId}\0${sequence}`;
|
|
186
|
-
}
|
|
187
|
-
function clearPendingBatch(consumed) {
|
|
188
|
-
consumed.pendingBatchKeys.clear();
|
|
189
|
-
consumed.pendingBatchOpen = false;
|
|
190
|
-
}
|
|
191
|
-
function rememberPendingBatchKey(consumed, key) {
|
|
192
|
-
consumed.pendingBatchKeys.add(key);
|
|
193
|
-
}
|
|
194
|
-
function rememberConsumedEventIdentity(consumed, payload) {
|
|
195
|
-
if (payload.eventKind === 'status' && (payload.status === 'submitted' || payload.status === 'working') && !consumed.pendingBatchOpen) {
|
|
196
|
-
clearPendingBatch(consumed);
|
|
197
|
-
consumed.pendingBatchOpen = true;
|
|
198
|
-
}
|
|
199
|
-
const key = consumedIdentityKey(payload.eventId, payload.sequence);
|
|
200
|
-
consumed.events.set(key, payload);
|
|
201
|
-
rememberPendingBatchKey(consumed, key);
|
|
202
|
-
}
|
|
203
|
-
function rememberConsumedActionIdentity(consumed, action) {
|
|
204
|
-
const key = consumedIdentityKey(action.eventId, action.sequence);
|
|
205
|
-
consumed.actions.set(key, action);
|
|
206
|
-
rememberPendingBatchKey(consumed, key);
|
|
207
|
-
}
|
|
208
|
-
function consumeSkippedActionOrdinal(state, payload, consumed) {
|
|
209
|
-
const action = payload.action;
|
|
210
|
-
const operationCount = payload.operationCount ?? state.operationCount + 1;
|
|
211
|
-
if (!action || typeof action !== 'object') throw new Error('skip_action_invalid');
|
|
212
|
-
const { actionDigest: _actionDigest, ...actionBase } = action;
|
|
213
|
-
if (action.actionDigest !== checkpointDigest(actionBase) || !Number.isSafeInteger(operationCount) || operationCount !== state.operationCount + 1 || operationCount > BOOKING_COPILOT_MAX_OPERATIONS_V2 || !Number.isSafeInteger(action.sequence) || action.sequence <= state.lastSequence) throw new Error('skip_action_invalid');
|
|
214
|
-
state.operationCount = operationCount;
|
|
215
|
-
state.lastSequence = action.sequence;
|
|
216
|
-
if (consumed) {
|
|
217
|
-
rememberConsumedActionIdentity(consumed, action);
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
function eventDraftDigest(event) {
|
|
221
|
-
if (event.kind === 'status') return bookingV2Digest({
|
|
222
|
-
kind: event.kind,
|
|
223
|
-
status: event.status
|
|
224
|
-
});
|
|
225
|
-
if (event.kind === 'question') return bookingV2Digest({
|
|
226
|
-
kind: event.kind,
|
|
227
|
-
question: event.question
|
|
228
|
-
});
|
|
229
|
-
if (event.kind === 'explanation') return bookingV2Digest({
|
|
230
|
-
kind: event.kind,
|
|
231
|
-
explanation: event.explanation
|
|
232
|
-
});
|
|
233
|
-
if (event.kind === 'terminal') return bookingV2Digest({
|
|
234
|
-
kind: event.kind,
|
|
235
|
-
terminal: event.terminal
|
|
236
|
-
});
|
|
237
|
-
return bookingV2Digest({
|
|
238
|
-
kind: event.kind,
|
|
239
|
-
error: event.error
|
|
240
|
-
});
|
|
241
|
-
}
|
|
242
|
-
function eventPayloadMatchesEvent(payload, event) {
|
|
243
|
-
const expectedDigest = eventDraftDigest(event);
|
|
244
|
-
const legacyTerminalDigest = event.kind === 'terminal' ? bookingV2Digest(event.terminal) : undefined;
|
|
245
|
-
return payload.eventId === event.eventId && payload.sequence === event.sequence && payload.emittedAt === event.emittedAt && payload.contextRef === event.contextRef && payload.eventKind === event.kind && (event.kind !== 'status' || payload.status === event.status) && (payload.contentDigest === expectedDigest || payload.contentDigest === legacyTerminalDigest);
|
|
246
|
-
}
|
|
247
|
-
function actionFromOperationEventForReplay(event, checkpoint) {
|
|
248
|
-
const action = event.action;
|
|
249
|
-
if ((action.kind === 'offer.select' || action.kind === 'offer.check' || action.kind === 'checkout.prepare') && typeof action.input.offerRef === 'string' && typeof action.input.offerVersionRef !== 'string' && typeof checkpoint.input.offerVersionRef === 'string') {
|
|
250
|
-
return {
|
|
251
|
-
...action,
|
|
252
|
-
input: {
|
|
253
|
-
...action.input,
|
|
254
|
-
offerVersionRef: checkpoint.input.offerVersionRef
|
|
255
|
-
}
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
return action;
|
|
259
|
-
}
|
|
260
|
-
function operationEventMatchesAction(event, checkpoint) {
|
|
261
|
-
return event.eventId === checkpoint.eventId && event.sequence === checkpoint.sequence && event.emittedAt === checkpoint.emittedAt && event.contextRef === checkpoint.contextRef && matchesCheckpoint(actionFromOperationEventForReplay(event, checkpoint), checkpoint);
|
|
262
|
-
}
|
|
263
|
-
function normalizeDecisionBatchEnvelopeForReplay(payload, consumed, requireSchemaValid = false) {
|
|
264
|
-
if (typeof payload.requestKey !== 'string' || !payload.requestKey || !payload.events.length) throw new Error('skip_decision_batch_invalid');
|
|
265
|
-
let lastBatchSequence = -1;
|
|
266
|
-
const seen = new Set();
|
|
267
|
-
const normalizedEvents = [];
|
|
268
|
-
for (const event of payload.events){
|
|
269
|
-
if (!Number.isSafeInteger(event.sequence) || event.sequence <= lastBatchSequence) throw new Error('skip_decision_batch_invalid');
|
|
270
|
-
lastBatchSequence = event.sequence;
|
|
271
|
-
const key = consumedIdentityKey(event.eventId, event.sequence);
|
|
272
|
-
if (seen.has(key)) throw new Error('skip_decision_batch_invalid');
|
|
273
|
-
seen.add(key);
|
|
274
|
-
if (event.kind === 'operation') {
|
|
275
|
-
const checkpoint = consumed.actions.get(key);
|
|
276
|
-
if (!checkpoint || !operationEventMatchesAction(event, checkpoint)) throw new Error('skip_decision_batch_invalid');
|
|
277
|
-
const normalized = {
|
|
278
|
-
...event,
|
|
279
|
-
action: actionFromOperationEventForReplay(event, checkpoint)
|
|
280
|
-
};
|
|
281
|
-
if (requireSchemaValid && !validateBookingSurfaceEventV2(normalized).ok) throw new Error('skip_decision_batch_invalid');
|
|
282
|
-
normalizedEvents.push(normalized);
|
|
283
|
-
} else {
|
|
284
|
-
const recorded = consumed.events.get(key);
|
|
285
|
-
if (!recorded || !validateBookingSurfaceEventV2(event).ok || !eventPayloadMatchesEvent(recorded, event)) throw new Error('skip_decision_batch_invalid');
|
|
286
|
-
normalizedEvents.push(event);
|
|
287
|
-
}
|
|
288
|
-
if (!consumed.pendingBatchKeys.has(key)) throw new Error('skip_decision_batch_invalid');
|
|
289
|
-
}
|
|
290
|
-
if (seen.size !== consumed.pendingBatchKeys.size) throw new Error('skip_decision_batch_invalid');
|
|
291
|
-
for (const key of consumed.pendingBatchKeys)if (!seen.has(key)) throw new Error('skip_decision_batch_invalid');
|
|
292
|
-
clearPendingBatch(consumed);
|
|
293
|
-
return normalizedEvents;
|
|
294
|
-
}
|
|
295
|
-
function consumeSkippedEventSequence(state, payload, consumed) {
|
|
296
|
-
if (!payload || typeof payload !== 'object') throw new Error('skip_event_invalid');
|
|
297
|
-
if ('sequence' in payload) {
|
|
298
|
-
const eventPayload = payload;
|
|
299
|
-
if (typeof eventPayload.eventId !== 'string' || !eventPayload.eventId || ![
|
|
300
|
-
'status',
|
|
301
|
-
'question',
|
|
302
|
-
'explanation',
|
|
303
|
-
'terminal',
|
|
304
|
-
'error'
|
|
305
|
-
].includes(String(eventPayload.eventKind)) || typeof eventPayload.contentDigest !== 'string' || !/^[0-9a-f]{64}$/.test(eventPayload.contentDigest) || typeof eventPayload.sequence !== 'number' || !Number.isSafeInteger(eventPayload.sequence) || eventPayload.sequence <= state.lastSequence) throw new Error('skip_event_invalid');
|
|
306
|
-
state.lastSequence = eventPayload.sequence;
|
|
307
|
-
rememberConsumedEventIdentity(consumed, eventPayload);
|
|
308
|
-
} else if ('events' in payload && Array.isArray(payload.events)) {
|
|
309
|
-
normalizeDecisionBatchEnvelopeForReplay(payload, consumed);
|
|
310
|
-
}
|
|
311
|
-
}
|
|
312
|
-
function normalizeReceiptForReplay(raw, action, workspace) {
|
|
313
|
-
const receipt = structuredClone(raw);
|
|
314
|
-
if (action.kind === 'offer.select' && receipt.observation.kind === 'offer.selection' && receipt.observation.offerRef === action.input.offerRef && !receipt.observation.offerVersionRef) {
|
|
315
|
-
receipt.observation.offerVersionRef = action.input.offerVersionRef;
|
|
316
|
-
}
|
|
317
|
-
if (action.kind === 'checkout.prepare' && receipt.observation.kind === 'checkout.handoff' && receipt.observation.offerRef === action.input.offerRef && !receipt.observation.offerVersionRef) {
|
|
318
|
-
if (!workspace.verifiedOffer || workspace.verifiedOffer.offerRef !== action.input.offerRef || workspace.verifiedOffer.offerVersionRef !== action.input.offerVersionRef || workspace.verifiedOffer.verifiedOfferRef !== action.input.verifiedOfferRef) throw new Error('booking_v2_replan_required:legacy_checkout_unverified');
|
|
319
|
-
receipt.observation.offerVersionRef = action.input.offerVersionRef;
|
|
320
|
-
}
|
|
321
|
-
if (action.kind === 'offer.check' && receipt.observation.kind === 'offer.availability' && receipt.observation.offerRef === action.input.offerRef) {
|
|
322
|
-
if (!receipt.observation.checkedOfferVersionRef) receipt.observation.checkedOfferVersionRef = action.input.offerVersionRef;
|
|
323
|
-
if (receipt.status === 'applied' && receipt.observation.available === true && !receipt.observation.currentOfferVersionRef) receipt.observation.currentOfferVersionRef = action.input.offerVersionRef;
|
|
324
|
-
if (receipt.status === 'changed' && receipt.observation.available === true && !receipt.observation.currentOfferVersionRef) {
|
|
325
|
-
const current = workspace.loadedOffers.find((offer)=>offer.offerRef === action.input.offerRef && offer.offerVersionRef !== action.input.offerVersionRef);
|
|
326
|
-
if (!current) throw new Error('booking_v2_replan_required:changed_version_unbound');
|
|
327
|
-
receipt.observation.currentOfferVersionRef = current.offerVersionRef;
|
|
328
|
-
}
|
|
329
|
-
if (receipt.status === 'applied' && receipt.observation.verifiedOfferRef && (!workspace.verifiedOffer || workspace.verifiedOffer.offerRef !== action.input.offerRef || workspace.verifiedOffer.offerVersionRef !== action.input.offerVersionRef || workspace.verifiedOffer.verifiedOfferRef !== receipt.observation.verifiedOfferRef)) throw new Error('booking_v2_replan_required:legacy_verified_scalar');
|
|
330
|
-
}
|
|
331
|
-
if (receipt.resultContract.blockers.length && bookingV2Digest(raw) !== bookingV2Digest(receipt)) throw new Error('booking_v2_replan_required:legacy_blocker_digest');
|
|
332
|
-
return receipt;
|
|
333
|
-
}
|
|
334
|
-
function errorText(result) {
|
|
335
|
-
return result.ok ? '' : result.errors.join('; ');
|
|
336
|
-
}
|
|
337
|
-
function assertTaskId(taskId) {
|
|
338
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(taskId)) throw new Error('invalid_task_id');
|
|
339
|
-
}
|
|
340
|
-
function assertSafeRef(value) {
|
|
341
|
-
if (!/^[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(value)) throw new Error('unsafe_opaque_ref');
|
|
342
|
-
}
|
|
343
|
-
function safeIdentity(value) {
|
|
344
|
-
return typeof value === 'string' && /^[A-Za-z0-9][A-Za-z0-9:._-]*$/.test(value);
|
|
345
|
-
}
|
|
346
|
-
function sameActions(a, b) {
|
|
347
|
-
return a.length === b.length && [
|
|
348
|
-
...a
|
|
349
|
-
].sort().every((x, i)=>x === [
|
|
350
|
-
...b
|
|
351
|
-
].sort()[i]);
|
|
352
|
-
}
|
|
353
|
-
function availabilityPolicyTerminal(state) {
|
|
354
|
-
return availabilityPolicyResultV2(state);
|
|
355
|
-
}
|
|
356
|
-
function taskHasTerminalBudget(state) {
|
|
357
|
-
return state.operationCount >= BOOKING_COPILOT_MAX_OPERATIONS_V2 || Boolean(state.availability.terminal);
|
|
358
|
-
}
|
|
359
|
-
function assertRequestKey(requestKey) {
|
|
360
|
-
if (!isSafeBookingRequestKeyV2(requestKey)) throw new Error('unsafe_request_key');
|
|
361
|
-
}
|
|
362
|
-
function assertInternalDecisionKey(requestKey) {
|
|
363
|
-
if (typeof requestKey !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9:._-]{0,2047}$/.test(requestKey)) throw new Error('unsafe_internal_decision_key');
|
|
364
|
-
}
|
|
365
|
-
function assertDecisionBatchFinality(decisions) {
|
|
366
|
-
let finalSeen = false;
|
|
367
|
-
for (const decision of decisions){
|
|
368
|
-
const isFinal = decision.kind === 'terminal' || decision.kind === 'error';
|
|
369
|
-
if (finalSeen) throw new Error('decision_batch_finality');
|
|
370
|
-
if (isFinal) finalSeen = true;
|
|
371
|
-
}
|
|
372
|
-
}
|
|
373
|
-
function assertPrincipal(principal) {
|
|
374
|
-
if (!principal || typeof principal.subject !== 'string' || !principal.subject || principal.subject.length > 256 || typeof principal.scope !== 'string' || !principal.scope || principal.scope.length > 256) throw new Error('trusted_principal_required');
|
|
375
|
-
}
|
|
376
|
-
function assertAvailabilityLiveness(state, decisions) {
|
|
377
|
-
if (!state.availability.recoveryStarted || state.awaitingApproval) return;
|
|
378
|
-
const operations = decisions.filter((decision)=>decision.kind === 'operation');
|
|
379
|
-
if (operations.length !== 1 || !state.workspaceSnapshot) throw new Error('availability_operation_required');
|
|
380
|
-
const action = operations[0].action;
|
|
381
|
-
const activeHotelRef = state.availability.hotelRefs[state.availability.activeHotelOrdinal];
|
|
382
|
-
if (!activeHotelRef) throw new Error('availability_active_hotel_missing');
|
|
383
|
-
if (state.availability.availabilityPhase === 'need_offers') {
|
|
384
|
-
if (action.kind !== 'offers.query' || action.input.hotelRefs.length !== 1 || action.input.hotelRefs[0] !== activeHotelRef) throw new Error('availability_operation_incompatible');
|
|
385
|
-
} else if (state.availability.availabilityPhase === 'need_check') {
|
|
386
|
-
if (action.kind !== 'offer.check' || action.input.offerRef === undefined || action.input.offerVersionRef === undefined || !state.availability.hotels[activeHotelRef]?.currentOfferRefs.includes(action.input.offerRef) || !canIssueOfferCheckV2(state.availability, state.workspaceSnapshot, action.input.offerRef, action.input.offerVersionRef).ok) throw new Error('availability_operation_incompatible');
|
|
387
|
-
} else {
|
|
388
|
-
throw new Error('availability_operation_incompatible');
|
|
389
|
-
}
|
|
390
|
-
}
|
|
391
|
-
function checkpointDigest(action) {
|
|
392
|
-
return bookingV2Digest(action);
|
|
393
|
-
}
|
|
394
|
-
function checkpointFor(action, eventId, sequence, emittedAt, sourceTurnId) {
|
|
395
|
-
const base = {
|
|
396
|
-
actionId: action.actionId,
|
|
397
|
-
kind: action.kind,
|
|
398
|
-
contextRef: action.contextRef,
|
|
399
|
-
expectedRevision: action.expectedRevision,
|
|
400
|
-
factRefs: [
|
|
401
|
-
...action.factRefs
|
|
402
|
-
],
|
|
403
|
-
reasonDigest: bookingV2Digest(action.reason),
|
|
404
|
-
inputDigest: bookingV2Digest(action.input),
|
|
405
|
-
input: action.input,
|
|
406
|
-
eventId,
|
|
407
|
-
sequence,
|
|
408
|
-
emittedAt,
|
|
409
|
-
sourceTurnId,
|
|
410
|
-
...action.relaxationApprovalRef ? {
|
|
411
|
-
relaxationApprovalRef: action.relaxationApprovalRef
|
|
412
|
-
} : {}
|
|
413
|
-
};
|
|
414
|
-
return {
|
|
415
|
-
...base,
|
|
416
|
-
actionDigest: checkpointDigest(base)
|
|
417
|
-
};
|
|
418
|
-
}
|
|
419
|
-
function matchesCheckpoint(action, checkpoint) {
|
|
420
|
-
const candidate = checkpointFor(action.relaxationApprovalRef || !checkpoint.relaxationApprovalRef ? action : {
|
|
421
|
-
...action,
|
|
422
|
-
relaxationApprovalRef: checkpoint.relaxationApprovalRef
|
|
423
|
-
}, checkpoint.eventId, checkpoint.sequence, checkpoint.emittedAt, checkpoint.sourceTurnId);
|
|
424
|
-
const { actionDigest: _ignored, ...candidateBase } = candidate;
|
|
425
|
-
return checkpoint.actionDigest === checkpointDigest(candidateBase);
|
|
426
|
-
}
|
|
427
|
-
function receiptSourceDigest(receipt) {
|
|
428
|
-
return bookingV2Digest({
|
|
429
|
-
...receipt,
|
|
430
|
-
resultContract: {
|
|
431
|
-
...receipt.resultContract,
|
|
432
|
-
blockers: receipt.resultContract.blockers.map(({ sourceReceiptDigest: _ignored, ...blocker })=>blocker)
|
|
433
|
-
}
|
|
434
|
-
});
|
|
435
|
-
}
|
|
436
|
-
function assertCanonicalReceipt(receipt) {
|
|
437
|
-
const expected = receiptSourceDigest(receipt);
|
|
438
|
-
if (receipt.resultContract.blockers.some((blocker)=>blocker.sourceReceiptDigest !== expected)) throw new Error('receipt_source_digest_mismatch');
|
|
439
|
-
}
|
|
440
|
-
function receiptObservationMatchesAction(observation, action) {
|
|
441
|
-
if (observation === 'gap') return true;
|
|
442
|
-
const expected = {
|
|
443
|
-
'search.patch': 'search.state',
|
|
444
|
-
'search.run': 'search.state',
|
|
445
|
-
'results.view.patch': 'results.state',
|
|
446
|
-
'hotel.focus': 'hotel.focus',
|
|
447
|
-
'hotel.select': 'hotel.selection',
|
|
448
|
-
'offers.query': 'offers.state',
|
|
449
|
-
'offers.view.patch': 'offers.state',
|
|
450
|
-
'offers.compare': 'offers.state',
|
|
451
|
-
'offer.select': 'offer.selection',
|
|
452
|
-
'offer.check': 'offer.availability',
|
|
453
|
-
'checkout.prepare': 'checkout.handoff',
|
|
454
|
-
'order.observe': 'order.state'
|
|
455
|
-
};
|
|
456
|
-
return expected[action] === observation;
|
|
457
|
-
}
|
|
458
|
-
function sameRefSet(a, b) {
|
|
459
|
-
return a.length === b.length && [
|
|
460
|
-
...a
|
|
461
|
-
].sort().every((value, index)=>value === [
|
|
462
|
-
...b
|
|
463
|
-
].sort()[index]);
|
|
464
|
-
}
|
|
465
|
-
function receiptTargetMatchesAction(receipt, action) {
|
|
466
|
-
const observation = receipt.observation;
|
|
467
|
-
const input = action.input;
|
|
468
|
-
if (action.kind === 'hotel.focus' && observation.kind === 'hotel.focus') return observation.hotelRef === input.hotelRef;
|
|
469
|
-
if (action.kind === 'hotel.select' && observation.kind === 'hotel.selection') return observation.hotelRef === input.hotelRef;
|
|
470
|
-
if (action.kind === 'offer.select' && observation.kind === 'offer.selection') return observation.offerRef === input.offerRef && observation.offerVersionRef === input.offerVersionRef;
|
|
471
|
-
if (action.kind === 'offer.check' && observation.kind === 'offer.availability') return observation.offerRef === input.offerRef && observation.checkedOfferVersionRef === input.offerVersionRef;
|
|
472
|
-
if (action.kind === 'checkout.prepare' && observation.kind === 'checkout.handoff') return observation.offerRef === input.offerRef && observation.offerVersionRef === input.offerVersionRef && observation.verifiedOfferRef === input.verifiedOfferRef;
|
|
473
|
-
if (action.kind === 'offers.query' && observation.kind === 'offers.state') return sameRefSet(observation.hotelRefs, input.hotelRefs);
|
|
474
|
-
if (action.kind === 'offers.view.patch' && observation.kind === 'offers.state') return observation.hotelRefs.includes(input.hotelRef);
|
|
475
|
-
if (action.kind === 'offers.compare' && observation.kind === 'offers.state') return input.offerRefs.every((offerRef)=>observation.offerRefs.includes(offerRef));
|
|
476
|
-
if (action.kind === 'order.observe' && observation.kind === 'order.state') return observation.orderRef === input.orderRef;
|
|
477
|
-
return observation.kind === 'gap' || action.kind === 'search.patch' || action.kind === 'search.run' || action.kind === 'results.view.patch';
|
|
478
|
-
}
|
|
479
|
-
function workspaceBoundaryMatches(a, b) {
|
|
480
|
-
return a.locale === b.locale && a.currency === b.currency && a.surface === b.surface && a.contextRef === b.contextRef && a.capabilities.surface === b.capabilities.surface && sameActions(a.capabilities.allowedActions, b.capabilities.allowedActions);
|
|
481
|
-
}
|
|
482
|
-
function workspaceHasOfferVersion(workspace, offerRef, offerVersionRef) {
|
|
483
|
-
return workspace.loadedOffers.some((offer)=>offer.offerRef === offerRef && offer.offerVersionRef === offerVersionRef);
|
|
484
|
-
}
|
|
485
|
-
function verifiedOfferMatches(workspace, input) {
|
|
486
|
-
return workspace.verifiedOffer?.offerRef === input.offerRef && workspace.verifiedOffer.offerVersionRef === input.offerVersionRef && workspace.verifiedOffer.verifiedOfferRef === input.verifiedOfferRef;
|
|
487
|
-
}
|
|
488
|
-
function verifiedOfferUnexpired(workspace, now) {
|
|
489
|
-
return Boolean(workspace.verifiedOffer && isBookingDateTimeV2(workspace.verifiedOffer.expiresAt) && Date.parse(workspace.verifiedOffer.expiresAt) > Date.parse(now));
|
|
490
|
-
}
|
|
491
|
-
function actionHitsCurrentOfferVersion(workspace, action, now) {
|
|
492
|
-
if (action.kind === 'offer.select' || action.kind === 'offer.check') return workspaceHasOfferVersion(workspace, action.input.offerRef, action.input.offerVersionRef);
|
|
493
|
-
if (action.kind === 'checkout.prepare') return workspaceHasOfferVersion(workspace, action.input.offerRef, action.input.offerVersionRef) && verifiedOfferMatches(workspace, action.input) && (now === undefined || verifiedOfferUnexpired(workspace, now));
|
|
494
|
-
return true;
|
|
495
|
-
}
|
|
496
|
-
function shortlistAfterCheckedOffer(previous, current, checkedOfferRef) {
|
|
497
|
-
if (sameActions(previous, current)) return true;
|
|
498
|
-
const removedChecked = previous.filter((ref)=>ref !== checkedOfferRef);
|
|
499
|
-
return removedChecked.length === previous.length - 1 && sameActions(removedChecked, current);
|
|
500
|
-
}
|
|
501
|
-
function loadedOffersUnchanged(previous, current) {
|
|
502
|
-
return sameActions(previous.loadedOffers.map((offer)=>bookingV2Digest(offer)), current.loadedOffers.map((offer)=>bookingV2Digest(offer)));
|
|
503
|
-
}
|
|
504
|
-
function changedFactRefsMatch(previousFactRefs, currentFactRefs, changedFactRefs) {
|
|
505
|
-
if (!changedFactRefs.length) return false;
|
|
506
|
-
const before = new Set(previousFactRefs);
|
|
507
|
-
const after = new Set(currentFactRefs);
|
|
508
|
-
const diff = [
|
|
509
|
-
...previousFactRefs.filter((ref)=>!after.has(ref)),
|
|
510
|
-
...currentFactRefs.filter((ref)=>!before.has(ref))
|
|
511
|
-
];
|
|
512
|
-
return sameActions(diff, changedFactRefs);
|
|
513
|
-
}
|
|
514
|
-
function loadedOffersChangedVersionOnly(previous, current, offerRef, currentOfferVersionRef, changedFactRefs) {
|
|
515
|
-
if (previous.loadedOffers.length !== current.loadedOffers.length) return false;
|
|
516
|
-
const previousChecked = previous.loadedOffers.find((offer)=>offer.offerRef === offerRef);
|
|
517
|
-
const currentChecked = current.loadedOffers.find((offer)=>offer.offerRef === offerRef);
|
|
518
|
-
if (!previousChecked || !currentChecked || previousChecked.hotelRef !== currentChecked.hotelRef || currentChecked.offerVersionRef !== currentOfferVersionRef || previousChecked.offerVersionRef === currentChecked.offerVersionRef) return false;
|
|
519
|
-
if (previousChecked.evidenceLevel !== currentChecked.evidenceLevel) return false;
|
|
520
|
-
if (!changedFactRefsMatch(previousChecked.factRefs, currentChecked.factRefs, changedFactRefs)) return false;
|
|
521
|
-
const previousOther = previous.loadedOffers.filter((offer)=>offer.offerRef !== offerRef).map((offer)=>bookingV2Digest(offer));
|
|
522
|
-
const currentOther = current.loadedOffers.filter((offer)=>offer.offerRef !== offerRef).map((offer)=>bookingV2Digest(offer));
|
|
523
|
-
return sameActions(previousOther, currentOther);
|
|
524
|
-
}
|
|
525
|
-
function availabilityReceiptIsComplete(receipt) {
|
|
526
|
-
return receipt.resultContract.outcome === 'complete' && receipt.resultContract.hardCriteriaMet && receipt.resultContract.gapCodes.length === 0 && receipt.resultContract.blockers.length === 0;
|
|
527
|
-
}
|
|
528
|
-
function offerCheckPostActionMatches(previous, current, action, receipt) {
|
|
529
|
-
const checkedOfferRef = action.input.offerRef;
|
|
530
|
-
const checkedOfferVersionRef = action.input.offerVersionRef;
|
|
531
|
-
const observation = receipt.observation.kind === 'offer.availability' ? receipt.observation : undefined;
|
|
532
|
-
const negative = receipt.status === 'unavailable' || receipt.status === 'no_match';
|
|
533
|
-
if ([
|
|
534
|
-
'applied',
|
|
535
|
-
'changed',
|
|
536
|
-
'unavailable',
|
|
537
|
-
'no_match'
|
|
538
|
-
].includes(receipt.status) && !observation) return false;
|
|
539
|
-
if (receipt.status === 'applied' && observation?.available && observation.verifiedOfferRef) {
|
|
540
|
-
if (!availabilityReceiptIsComplete(receipt) || observation.gapCodes?.length) return false;
|
|
541
|
-
if (!loadedOffersUnchanged(previous, current)) return false;
|
|
542
|
-
if (observation.checkedOfferVersionRef !== checkedOfferVersionRef || observation.currentOfferVersionRef !== checkedOfferVersionRef) return false;
|
|
543
|
-
if (current.selectedOfferRef !== checkedOfferRef) return false;
|
|
544
|
-
if (!sameActions(previous.shortlistedOfferRefs, current.shortlistedOfferRefs)) return false;
|
|
545
|
-
if (!current.verifiedOffer || current.verifiedOffer.offerRef !== checkedOfferRef || current.verifiedOffer.offerVersionRef !== checkedOfferVersionRef || current.verifiedOffer.verifiedOfferRef !== observation.verifiedOfferRef || Number.isNaN(Date.parse(current.verifiedOffer.expiresAt))) return false;
|
|
546
|
-
return true;
|
|
547
|
-
}
|
|
548
|
-
if (receipt.status === 'changed' && observation?.available && observation.currentOfferVersionRef) {
|
|
549
|
-
if (observation.checkedOfferVersionRef !== checkedOfferVersionRef || observation.currentOfferVersionRef === checkedOfferVersionRef || observation.verifiedOfferRef || !observation.changedFactRefs.length) return false;
|
|
550
|
-
if (!loadedOffersChangedVersionOnly(previous, current, checkedOfferRef, observation.currentOfferVersionRef, observation.changedFactRefs)) return false;
|
|
551
|
-
if (current.selectedOfferRef !== checkedOfferRef || current.verifiedOffer !== undefined) return false;
|
|
552
|
-
return sameActions(previous.shortlistedOfferRefs, current.shortlistedOfferRefs);
|
|
553
|
-
}
|
|
554
|
-
if (!loadedOffersUnchanged(previous, current)) return false;
|
|
555
|
-
if (negative) {
|
|
556
|
-
if (current.selectedOfferRef !== undefined || current.verifiedOffer !== undefined) return false;
|
|
557
|
-
if (!shortlistAfterCheckedOffer(previous.shortlistedOfferRefs, current.shortlistedOfferRefs, checkedOfferRef)) return false;
|
|
558
|
-
return !current.shortlistedOfferRefs.includes(checkedOfferRef);
|
|
559
|
-
}
|
|
560
|
-
if (!sameActions(previous.shortlistedOfferRefs, current.shortlistedOfferRefs)) return false;
|
|
561
|
-
if (previous.selectedOfferRef !== current.selectedOfferRef) return false;
|
|
562
|
-
if (bookingV2Digest(previous.verifiedOffer ?? null) !== bookingV2Digest(current.verifiedOffer ?? null)) return false;
|
|
563
|
-
return true;
|
|
564
|
-
}
|
|
565
|
-
function offerSelectPostActionMatches(previous, current, action, receipt) {
|
|
566
|
-
if (receipt.status !== 'applied') return current.selectedOfferRef === previous.selectedOfferRef && loadedOffersUnchanged(previous, current);
|
|
567
|
-
if (receipt.observation.kind !== 'offer.selection' || receipt.observation.offerRef !== action.input.offerRef || receipt.observation.offerVersionRef !== action.input.offerVersionRef) return false;
|
|
568
|
-
if (current.selectedOfferRef !== action.input.offerRef) return false;
|
|
569
|
-
return loadedOffersUnchanged(previous, current);
|
|
570
|
-
}
|
|
571
|
-
function workspacePostActionMatches(previous, current, action, receipt) {
|
|
572
|
-
if (!workspaceBoundaryMatches(previous, current)) return false;
|
|
573
|
-
const mutable = {
|
|
574
|
-
'search.patch': [
|
|
575
|
-
'searchDraft'
|
|
576
|
-
],
|
|
577
|
-
'search.run': [
|
|
578
|
-
'results',
|
|
579
|
-
'visibleHotels'
|
|
580
|
-
],
|
|
581
|
-
'results.view.patch': [
|
|
582
|
-
'results'
|
|
583
|
-
],
|
|
584
|
-
'hotel.focus': [
|
|
585
|
-
'focusedHotelRef'
|
|
586
|
-
],
|
|
587
|
-
'hotel.select': [
|
|
588
|
-
'focusedHotelRef'
|
|
589
|
-
],
|
|
590
|
-
'offers.query': [
|
|
591
|
-
'loadedOffers'
|
|
592
|
-
],
|
|
593
|
-
'offers.view.patch': [
|
|
594
|
-
'loadedOffers'
|
|
595
|
-
],
|
|
596
|
-
'offer.select': [
|
|
597
|
-
'selectedOfferRef'
|
|
598
|
-
],
|
|
599
|
-
'offer.check': [
|
|
600
|
-
'selectedOfferRef',
|
|
601
|
-
'shortlistedOfferRefs',
|
|
602
|
-
'verifiedOffer',
|
|
603
|
-
'loadedOffers'
|
|
604
|
-
]
|
|
605
|
-
};
|
|
606
|
-
if (action.kind === 'offer.select' && !offerSelectPostActionMatches(previous, current, {
|
|
607
|
-
kind: 'offer.select',
|
|
608
|
-
input: {
|
|
609
|
-
offerRef: action.input.offerRef,
|
|
610
|
-
offerVersionRef: action.input.offerVersionRef
|
|
611
|
-
}
|
|
612
|
-
}, receipt)) return false;
|
|
613
|
-
if (action.kind === 'offer.check' && !offerCheckPostActionMatches(previous, current, {
|
|
614
|
-
kind: 'offer.check',
|
|
615
|
-
input: {
|
|
616
|
-
offerRef: action.input.offerRef,
|
|
617
|
-
offerVersionRef: action.input.offerVersionRef
|
|
618
|
-
}
|
|
619
|
-
}, receipt)) return false;
|
|
620
|
-
const allowed = new Set([
|
|
621
|
-
'revision',
|
|
622
|
-
...mutable[action.kind] ?? []
|
|
623
|
-
]);
|
|
624
|
-
const keys = new Set([
|
|
625
|
-
...Object.keys(previous),
|
|
626
|
-
...Object.keys(current)
|
|
627
|
-
]);
|
|
628
|
-
for (const key of keys){
|
|
629
|
-
if (allowed.has(key)) continue;
|
|
630
|
-
if (bookingV2Digest(previous[key]) !== bookingV2Digest(current[key])) return false;
|
|
631
|
-
}
|
|
632
|
-
return true;
|
|
633
|
-
}
|
|
634
|
-
function approvalOption(taskId, contextRef, sourceTurnId, presentationRequestKey, blocker, to, deliveryNonce) {
|
|
635
|
-
const base = {
|
|
636
|
-
taskId,
|
|
637
|
-
contextRef,
|
|
638
|
-
sourceTurnId,
|
|
639
|
-
presentationRequestKey,
|
|
640
|
-
approvalId: `approval-${blocker.blockerId}-${to}`,
|
|
641
|
-
deliveryNonce,
|
|
642
|
-
blockerId: blocker.blockerId,
|
|
643
|
-
sourceActionId: blocker.sourceActionId,
|
|
644
|
-
sourceReceiptDigest: blocker.sourceReceiptDigest,
|
|
645
|
-
scope: blocker.scope,
|
|
646
|
-
code: blocker.code,
|
|
647
|
-
criterionPath: blocker.criterionPath,
|
|
648
|
-
valueDigest: blocker.valueDigest,
|
|
649
|
-
from: 'must',
|
|
650
|
-
to,
|
|
651
|
-
approved: true
|
|
652
|
-
};
|
|
653
|
-
return {
|
|
654
|
-
...base,
|
|
655
|
-
optionDigest: bookingV2Digest(base)
|
|
656
|
-
};
|
|
657
|
-
}
|
|
658
|
-
function approvalOptionDigest(approval) {
|
|
659
|
-
const { optionDigest: _optionDigest, ...base } = approval;
|
|
660
|
-
return bookingV2Digest(base);
|
|
661
|
-
}
|
|
662
|
-
function presentationKey(taskId, sourceTurnId, actionId, receiptDigest) {
|
|
663
|
-
return `approval:${taskId}:${sourceTurnId}:${actionId}:${receiptDigest}`;
|
|
664
|
-
}
|
|
665
|
-
function assertApprovalRef(ref, state, action) {
|
|
666
|
-
const approval = state.awaitingApproval?.approval;
|
|
667
|
-
const blocker = state.awaitingApproval?.blocker;
|
|
668
|
-
if (!approval || !blocker || ref.approvalId !== approval.approvalId || ref.blockerId !== blocker.blockerId || ref.contextRef !== state.contextRef || ref.sourceTurnId !== state.awaitingApproval?.sourceTurnId || ref.presentationRequestKey !== state.awaitingApproval?.presentationRequestKey || ref.sourceActionId !== blocker.sourceActionId || ref.targetActionId !== action.actionId || ref.sourceRevision !== action.expectedRevision || ref.targetActionKind !== action.kind || ref.to !== approval.to || ref.expiresAt !== state.awaitingApproval?.expiresAt || ref.nonce !== state.awaitingApproval?.nonce || ref.sourceReceiptDigest !== blocker.sourceReceiptDigest || ref.scope !== blocker.scope || ref.code !== blocker.code || ref.criterionPath !== blocker.criterionPath || ref.valueDigest !== blocker.valueDigest) throw new Error('ledger_corrupt:approval_ref');
|
|
669
|
-
}
|
|
670
|
-
export class BookingCopilotTaskRuntimeV2 {
|
|
671
|
-
ledger;
|
|
672
|
-
idFactory;
|
|
673
|
-
contextRefFactory;
|
|
674
|
-
now;
|
|
675
|
-
approvalTtlMs;
|
|
676
|
-
constructor(ledger, options = {}){
|
|
677
|
-
this.ledger = ledger;
|
|
678
|
-
this.idFactory = options.idFactory ?? ((prefix)=>`${prefix}-${randomUUID()}`);
|
|
679
|
-
this.contextRefFactory = options.contextRefFactory ?? (()=>this.idFactory('context'));
|
|
680
|
-
this.now = options.now ?? (()=>new Date().toISOString());
|
|
681
|
-
this.approvalTtlMs = options.approvalTtlMs ?? 120_000;
|
|
682
|
-
}
|
|
683
|
-
assertRequestBinding(requestKey, turn, input) {
|
|
684
|
-
assertRequestKey(requestKey);
|
|
685
|
-
assertPrincipal(input.principal);
|
|
686
|
-
if (input.requestKey !== requestKey) throw new Error('request_conflict');
|
|
687
|
-
const existing = this.requestBinding(requestKey);
|
|
688
|
-
if (!existing) return;
|
|
689
|
-
const candidate = this.requestBindingPayload(requestKey, turn, input);
|
|
690
|
-
if (existing.requestDigest !== candidate.requestDigest || existing.turnId !== candidate.turnId || existing.workspaceDigest !== candidate.workspaceDigest || existing.workspaceSemanticDigest !== candidate.workspaceSemanticDigest || existing.surface !== candidate.surface || existing.capabilityDigest !== candidate.capabilityDigest || existing.contextRef !== turn.workspace.contextRef || existing.principalDigest !== candidate.principalDigest || existing.scopeDigest !== candidate.scopeDigest || existing.taskHandle !== candidate.taskHandle) throw new Error('request_conflict');
|
|
691
|
-
}
|
|
692
|
-
assertTurnBinding(taskId, turn) {
|
|
693
|
-
assertTaskId(taskId);
|
|
694
|
-
const row = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ? ORDER BY seq DESC`).all(this.ledger.tenant, taskId, TURN);
|
|
695
|
-
const observed = row.map(({ payload })=>JSON.parse(payload)).find((candidate)=>candidate.turnId === turn.turnId);
|
|
696
|
-
if (!observed || observed.requestDigest !== bookingV2TurnDigest(turn) || observed.workspaceDigest !== bookingV2WorkspaceDigest(turn.workspace) || observed.workspaceSemanticDigest !== bookingV2WorkspaceSemanticDigest(turn.workspace) || observed.contextRef !== turn.workspace.contextRef) throw new Error('turn_conflict');
|
|
697
|
-
}
|
|
698
|
-
persistRequestBinding(requestKey, turn, input) {
|
|
699
|
-
assertRequestKey(requestKey);
|
|
700
|
-
assertPrincipal(input.principal);
|
|
701
|
-
if (input.requestKey !== requestKey) throw new Error('request_conflict');
|
|
702
|
-
const run = this.ledger.db.transaction(()=>{
|
|
703
|
-
const state = this.requireTask(turn.taskId);
|
|
704
|
-
if (state.phase === 'terminal' || state.phase === 'error') throw new Error('task_terminal');
|
|
705
|
-
assertReplayUpgradeReanchored(state);
|
|
706
|
-
this.appendRequestBindingInTransaction(requestKey, turn, input);
|
|
707
|
-
});
|
|
708
|
-
run.immediate();
|
|
709
|
-
}
|
|
710
|
-
bindIngressTurn(turn, task, turnId) {
|
|
711
|
-
assertSafeRef(turnId);
|
|
712
|
-
return {
|
|
713
|
-
schemaVersion: 'booking.surface.v2',
|
|
714
|
-
kind: 'user.turn',
|
|
715
|
-
taskId: task.taskId,
|
|
716
|
-
turnId,
|
|
717
|
-
workspace: {
|
|
718
|
-
...turn.workspace,
|
|
719
|
-
schemaVersion: 'booking.surface.v2',
|
|
720
|
-
contextRef: task.contextRef,
|
|
721
|
-
surface: task.surface,
|
|
722
|
-
capabilities: {
|
|
723
|
-
surface: task.surface,
|
|
724
|
-
allowedActions: [
|
|
725
|
-
...task.allowedActions
|
|
726
|
-
]
|
|
727
|
-
}
|
|
728
|
-
},
|
|
729
|
-
request: {
|
|
730
|
-
text: turn.request.text
|
|
731
|
-
}
|
|
732
|
-
};
|
|
733
|
-
}
|
|
734
|
-
startTask(turn, requestBinding) {
|
|
735
|
-
const validation = validateBookingSurfaceV2(turn);
|
|
736
|
-
if (!validation.ok) throw new Error(`invalid_planner_turn:${errorText(validation)}`);
|
|
737
|
-
if (turn.kind === 'user.turn.ingress') throw new Error('ingress_binding_required');
|
|
738
|
-
if (turn.kind === 'action.receipt.continuation') throw new Error('receipt_continuation_requires_continue');
|
|
739
|
-
const userTurn = turn;
|
|
740
|
-
if (!userTurn.taskId) throw new Error('invalid_planner_turn:task_id_required');
|
|
741
|
-
const taskId = userTurn.taskId;
|
|
742
|
-
assertTaskId(taskId);
|
|
743
|
-
const turnId = userTurn.turnId;
|
|
744
|
-
if (!turnId) throw new Error('invalid_planner_turn:turn_id_required');
|
|
745
|
-
assertSafeRef(turnId);
|
|
746
|
-
const contextRef = userTurn.workspace.contextRef;
|
|
747
|
-
const surface = userTurn.workspace.surface;
|
|
748
|
-
const revision = userTurn.workspace.revision;
|
|
749
|
-
const allowedActions = [
|
|
750
|
-
...userTurn.workspace.capabilities.allowedActions
|
|
751
|
-
];
|
|
752
|
-
const requestDigest = bookingV2TurnDigest(turn);
|
|
753
|
-
const boundWorkspace = userTurn.workspace;
|
|
754
|
-
assertWorkspaceLoadedOfferRefsUniqueV2(boundWorkspace);
|
|
755
|
-
const workspaceDigest = bookingV2WorkspaceDigest(boundWorkspace);
|
|
756
|
-
const workspaceSemanticDigest = bookingV2WorkspaceSemanticDigest(boundWorkspace);
|
|
757
|
-
const availability = createAvailabilityPolicyV2(boundWorkspace);
|
|
758
|
-
const run = this.ledger.db.transaction(()=>{
|
|
759
|
-
if (!this.resumeTask(taskId)) {
|
|
760
|
-
const foreign = this.ledger.db.prepare("SELECT 1 AS present FROM events WHERE tenant_id = ? AND run_id = ? AND kind LIKE 'booking.copilot.%' AND kind NOT LIKE 'booking.copilot.v2.%' LIMIT 1").get(this.ledger.tenant, taskId);
|
|
761
|
-
if (foreign) throw new Error('task_conflict:protocol_version');
|
|
762
|
-
}
|
|
763
|
-
const existing = this.resumeTask(taskId);
|
|
764
|
-
if (existing) {
|
|
765
|
-
if (existing.contextRef !== contextRef) throw new Error('task_conflict:context_mismatch');
|
|
766
|
-
if (existing.surface !== surface) throw new Error('task_conflict:surface_mismatch');
|
|
767
|
-
if (existing.revision !== revision && existing.phase !== 'waiting_receipt' && !existing.replayUpgradeRequired) throw new Error('task_conflict:revision_mismatch');
|
|
768
|
-
if (!sameActions(existing.allowedActions, allowedActions)) throw new Error('task_conflict:capability_mismatch');
|
|
769
|
-
if (existing.phase === 'terminal' || existing.phase === 'error') throw new Error('task_terminal');
|
|
770
|
-
if (turnId && existing.lastTurnId === turnId) {
|
|
771
|
-
this.assertTurnBinding(taskId, userTurn);
|
|
772
|
-
if (requestBinding) {
|
|
773
|
-
assertReplayUpgradeReanchored(existing);
|
|
774
|
-
this.appendRequestBindingInTransaction(requestBinding.requestKey, userTurn, requestBinding);
|
|
775
|
-
}
|
|
776
|
-
return existing;
|
|
777
|
-
}
|
|
778
|
-
if (existing.phase === 'waiting_receipt') throw new Error('receipt_required');
|
|
779
|
-
const approval = userTurn && 'approval' in userTurn.request ? userTurn.request.approval : undefined;
|
|
780
|
-
let approvalState;
|
|
781
|
-
if (approval) {
|
|
782
|
-
assertReplayUpgradeReanchored(existing);
|
|
783
|
-
const awaiting = existing.awaitingApproval;
|
|
784
|
-
if (!awaiting) throw new Error('approval_not_awaiting');
|
|
785
|
-
if (!awaiting.optionsEmitted) throw new Error('approval_not_presented');
|
|
786
|
-
if (Date.parse(awaiting.expiresAt) <= Date.parse(this.now())) throw new Error('approval_expired');
|
|
787
|
-
const checked = validateApprovalAgainstBlocker(approval, awaiting.blocker);
|
|
788
|
-
const option = awaiting.options.find((candidate)=>candidate.optionDigest === approval.optionDigest && bookingV2Digest(candidate) === bookingV2Digest(approval));
|
|
789
|
-
if (!checked.ok || !option || approval.taskId !== existing.taskId || approval.contextRef !== existing.contextRef || approval.sourceTurnId !== awaiting.sourceTurnId || approval.presentationRequestKey !== awaiting.presentationRequestKey || approval.optionDigest !== approvalOptionDigest(approval) || awaiting.approval && bookingV2Digest(approval) !== bookingV2Digest(awaiting.approval)) throw new Error('approval_mismatch');
|
|
790
|
-
if (awaiting.approval && bookingV2Digest(awaiting.approval) === bookingV2Digest(approval)) return existing;
|
|
791
|
-
approvalState = {
|
|
792
|
-
...awaiting,
|
|
793
|
-
approval
|
|
794
|
-
};
|
|
795
|
-
this.appendApproval(taskId, existing.contextRef, approvalState);
|
|
796
|
-
} else if (existing.awaitingApproval) {
|
|
797
|
-
throw new Error('approval_required');
|
|
798
|
-
}
|
|
799
|
-
this.appendTurn(taskId, existing.contextRef, requestDigest, workspaceDigest, workspaceSemanticDigest, existing.userTurnCount + 1, turnId, boundWorkspace);
|
|
800
|
-
if (requestBinding) this.appendRequestBindingInTransaction(requestBinding.requestKey, userTurn, requestBinding);
|
|
801
|
-
return this.requireTask(taskId);
|
|
802
|
-
}
|
|
803
|
-
if (userTurn?.request.approval) throw new Error('approval_not_awaiting');
|
|
804
|
-
const started = {
|
|
805
|
-
schema: LEDGER_SCHEMA,
|
|
806
|
-
taskId,
|
|
807
|
-
contextRef,
|
|
808
|
-
surface,
|
|
809
|
-
revision,
|
|
810
|
-
allowedActions,
|
|
811
|
-
workspaceDigest,
|
|
812
|
-
workspaceSemanticDigest,
|
|
813
|
-
workspace: boundWorkspace,
|
|
814
|
-
availability,
|
|
815
|
-
availabilityDigest: bookingV2Digest(availability)
|
|
816
|
-
};
|
|
817
|
-
this.append(STARTED, taskId, started, `booking-v2:task:${taskId}`);
|
|
818
|
-
this.appendTurn(taskId, contextRef, requestDigest, workspaceDigest, workspaceSemanticDigest, 1, turnId, boundWorkspace);
|
|
819
|
-
if (requestBinding) this.appendRequestBindingInTransaction(requestBinding.requestKey, userTurn, requestBinding);
|
|
820
|
-
return this.requireTask(taskId);
|
|
821
|
-
});
|
|
822
|
-
return run.immediate();
|
|
823
|
-
}
|
|
824
|
-
resumeTask(taskId) {
|
|
825
|
-
assertTaskId(taskId);
|
|
826
|
-
const rows = this.rows(taskId);
|
|
827
|
-
if (!rows.length) return null;
|
|
828
|
-
let state = null;
|
|
829
|
-
let skipLegacyUpgradeTail = false;
|
|
830
|
-
const replayWorkspaceDigests = new Map();
|
|
831
|
-
const consumed = {
|
|
832
|
-
events: new Map(),
|
|
833
|
-
actions: new Map(),
|
|
834
|
-
pendingBatchKeys: new Set(),
|
|
835
|
-
pendingBatchOpen: false
|
|
836
|
-
};
|
|
837
|
-
const suppressedDecisionRequestKeys = new Set();
|
|
838
|
-
const suppressedRequestBindingKeys = new Set();
|
|
839
|
-
const suppressedReceiptActionIds = new Set();
|
|
840
|
-
const suppressedApprovalTargetActionIds = new Set();
|
|
841
|
-
for (const row of rows){
|
|
842
|
-
const payload = JSON.parse(row.payload);
|
|
843
|
-
if (payload.schema !== LEDGER_SCHEMA || payload.taskId !== taskId) throw new Error(`ledger_corrupt:${taskId}:seq=${row.seq}`);
|
|
844
|
-
if (row.kind === STARTED) {
|
|
845
|
-
skipLegacyUpgradeTail = false;
|
|
846
|
-
if (state) throw new Error(`ledger_corrupt:${taskId}:duplicate_start`);
|
|
847
|
-
const started = payload;
|
|
848
|
-
let startedWorkspace;
|
|
849
|
-
try {
|
|
850
|
-
startedWorkspace = normalizeWorkspaceForReplay(started.workspace);
|
|
851
|
-
} catch {
|
|
852
|
-
throw new Error(`ledger_corrupt:${taskId}:start_workspace`);
|
|
853
|
-
}
|
|
854
|
-
let initialAvailability;
|
|
855
|
-
try {
|
|
856
|
-
initialAvailability = createAvailabilityPolicyV2(startedWorkspace);
|
|
857
|
-
} catch {
|
|
858
|
-
throw new Error(`ledger_corrupt:${taskId}:start_availability`);
|
|
859
|
-
}
|
|
860
|
-
try {
|
|
861
|
-
assertWorkspaceLoadedOfferRefsUniqueV2(startedWorkspace);
|
|
862
|
-
} catch {
|
|
863
|
-
throw new Error(`ledger_corrupt:${taskId}:start_workspace`);
|
|
864
|
-
}
|
|
865
|
-
rememberReplayWorkspaceDigest(replayWorkspaceDigests, started.workspaceDigest, started.workspace, startedWorkspace);
|
|
866
|
-
const startedAvailability = normalizeAvailabilityPolicyForReplay(started.availability, startedWorkspace, undefined, undefined, replayWorkspaceDigests);
|
|
867
|
-
if (!started.workspaceDigest || !started.workspaceSemanticDigest || !started.workspace || !started.availability || !started.availabilityDigest || !validateAvailabilityPolicyV2(startedAvailability) || !replayDigestMatches(started.availabilityDigest, started.availability, startedAvailability) || bookingV2Digest(initialAvailability) !== bookingV2Digest(startedAvailability) || !replayWorkspaceDigestMatches(started.workspaceDigest, started.workspace, startedWorkspace) || !replayWorkspaceSemanticDigestMatches(started.workspaceSemanticDigest, started.workspace, startedWorkspace)) throw new Error(`ledger_corrupt:${taskId}:start_workspace`);
|
|
868
|
-
state = {
|
|
869
|
-
schemaVersion: 'booking.surface.v2',
|
|
870
|
-
taskId,
|
|
871
|
-
contextRef: started.contextRef,
|
|
872
|
-
surface: started.surface,
|
|
873
|
-
revision: started.revision,
|
|
874
|
-
allowedActions: [
|
|
875
|
-
...started.allowedActions
|
|
876
|
-
],
|
|
877
|
-
userTurnCount: 0,
|
|
878
|
-
operationCount: 0,
|
|
879
|
-
phase: startedAvailability.terminal ? 'terminal' : 'planning',
|
|
880
|
-
lastSequence: 0,
|
|
881
|
-
workspaceDigest: bookingV2WorkspaceDigest(startedWorkspace),
|
|
882
|
-
workspaceSemanticDigest: bookingV2WorkspaceSemanticDigest(startedWorkspace),
|
|
883
|
-
workspaceSnapshot: startedWorkspace,
|
|
884
|
-
availability: startedAvailability
|
|
885
|
-
};
|
|
886
|
-
} else {
|
|
887
|
-
if (!state) throw new Error(`ledger_corrupt:${taskId}:event_before_start`);
|
|
888
|
-
if (payload.contextRef !== state.contextRef) throw new Error(`ledger_corrupt:${taskId}:context_drift`);
|
|
889
|
-
if (row.kind === REQUEST_BINDING) {
|
|
890
|
-
if (skipLegacyUpgradeTail) {
|
|
891
|
-
const binding = payload;
|
|
892
|
-
if (typeof binding.requestKey === 'string') suppressedRequestBindingKeys.add(binding.requestKey);
|
|
893
|
-
continue;
|
|
894
|
-
}
|
|
895
|
-
const binding = payload;
|
|
896
|
-
const turnRows = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ?`).all(this.ledger.tenant, taskId, TURN);
|
|
897
|
-
const rawBoundTurn = turnRows.map(({ payload })=>JSON.parse(payload)).find((candidate)=>candidate.turnId === binding.turnId);
|
|
898
|
-
let boundTurn;
|
|
899
|
-
try {
|
|
900
|
-
boundTurn = rawBoundTurn ? {
|
|
901
|
-
...rawBoundTurn,
|
|
902
|
-
workspace: normalizeWorkspaceForReplay(rawBoundTurn.workspace)
|
|
903
|
-
} : undefined;
|
|
904
|
-
} catch {
|
|
905
|
-
throw new Error(`ledger_corrupt:${taskId}:request_binding`);
|
|
906
|
-
}
|
|
907
|
-
if (!isSafeBookingRequestKeyV2(binding.requestKey) || !safeIdentity(binding.turnId) || !safeIdentity(binding.contextRef) || binding.taskHandle !== undefined && !safeIdentity(binding.taskHandle) || !/^[0-9a-f]{64}$/.test(binding.requestDigest) || !/^[0-9a-f]{64}$/.test(binding.workspaceDigest) || !/^[0-9a-f]{64}$/.test(binding.workspaceSemanticDigest) || !/^[0-9a-f]{64}$/.test(binding.capabilityDigest) || !/^[0-9a-f]{64}$/.test(binding.principalDigest) || !/^[0-9a-f]{64}$/.test(binding.scopeDigest) || ![
|
|
908
|
-
'tenant',
|
|
909
|
-
'customer_portal',
|
|
910
|
-
'storefront',
|
|
911
|
-
'payment_link'
|
|
912
|
-
].includes(binding.surface) || !boundTurn || boundTurn.requestDigest !== binding.requestDigest || boundTurn.workspaceDigest !== binding.workspaceDigest || boundTurn.workspaceSemanticDigest !== binding.workspaceSemanticDigest || bookingV2Digest(boundTurn.workspace.capabilities) !== binding.capabilityDigest || boundTurn.workspace.surface !== binding.surface) throw new Error(`ledger_corrupt:${taskId}:request_binding`);
|
|
913
|
-
} else if (row.kind === TURN) {
|
|
914
|
-
skipLegacyUpgradeTail = false;
|
|
915
|
-
const t = payload;
|
|
916
|
-
if (Object.prototype.hasOwnProperty.call(payload, 'approval')) throw new Error(`ledger_corrupt:${taskId}:turn_approval`);
|
|
917
|
-
let turnWorkspace;
|
|
918
|
-
try {
|
|
919
|
-
turnWorkspace = normalizeWorkspaceForReplay(t.workspace);
|
|
920
|
-
} catch {
|
|
921
|
-
throw new Error(`ledger_corrupt:${taskId}:turn_workspace`);
|
|
922
|
-
}
|
|
923
|
-
try {
|
|
924
|
-
assertWorkspaceLoadedOfferRefsUniqueV2(turnWorkspace);
|
|
925
|
-
} catch {
|
|
926
|
-
throw new Error(`ledger_corrupt:${taskId}:turn_workspace`);
|
|
927
|
-
}
|
|
928
|
-
if (!t.workspaceDigest || !t.workspaceSemanticDigest || !t.workspace || !replayWorkspaceDigestMatches(t.workspaceDigest, t.workspace, turnWorkspace) || !replayWorkspaceSemanticDigestMatches(t.workspaceSemanticDigest, t.workspace, turnWorkspace)) throw new Error(`ledger_corrupt:${taskId}:turn_workspace`);
|
|
929
|
-
rememberReplayWorkspaceDigest(replayWorkspaceDigests, t.workspaceDigest, t.workspace, turnWorkspace);
|
|
930
|
-
state.userTurnCount++;
|
|
931
|
-
state.lastTurnId = t.turnId;
|
|
932
|
-
state.workspaceDigest = bookingV2WorkspaceDigest(turnWorkspace);
|
|
933
|
-
state.workspaceSemanticDigest = bookingV2WorkspaceSemanticDigest(turnWorkspace);
|
|
934
|
-
state.workspaceSnapshot = turnWorkspace;
|
|
935
|
-
state.revision = turnWorkspace.revision;
|
|
936
|
-
delete state.replayUpgradeRequired;
|
|
937
|
-
} else if (row.kind === APPROVAL_GRANTED) {
|
|
938
|
-
if (skipLegacyUpgradeTail) continue;
|
|
939
|
-
const granted = payload;
|
|
940
|
-
if (!granted.approval || granted.approvalDigest !== bookingV2Digest(granted.approval) || !granted.approval.sourceTurnId || !granted.approval.presentationRequestKey || !validateCriterionBlockerV2(granted.approval.blocker).ok || !granted.approval.options?.length || granted.approval.options.some((option)=>!validateApprovalAgainstBlocker(option, granted.approval.blocker).ok || option.taskId !== taskId || option.contextRef !== state.contextRef || option.sourceTurnId !== granted.approval.sourceTurnId || option.presentationRequestKey !== granted.approval.presentationRequestKey || option.optionDigest !== approvalOptionDigest(option)) || granted.approval.approval && !granted.approval.options.some((option)=>bookingV2Digest(option) === bookingV2Digest(granted.approval.approval))) throw new Error(`ledger_corrupt:${taskId}:approval_granted`);
|
|
941
|
-
state.awaitingApproval = granted.approval;
|
|
942
|
-
state.phase = 'input_required';
|
|
943
|
-
} else if (row.kind === APPROVAL_OFFERED) {
|
|
944
|
-
if (skipLegacyUpgradeTail) continue;
|
|
945
|
-
const offered = payload;
|
|
946
|
-
if (!offered.approval || offered.approvalDigest !== bookingV2Digest(offered.approval) || !state.awaitingApproval || bookingV2Digest(offered.approval) !== bookingV2Digest(state.awaitingApproval)) throw new Error(`ledger_corrupt:${taskId}:approval_offered`);
|
|
947
|
-
state.phase = 'input_required';
|
|
948
|
-
} else if (row.kind === ACTION) {
|
|
949
|
-
const actionPayload = payload;
|
|
950
|
-
if (skipLegacyUpgradeTail) {
|
|
951
|
-
try {
|
|
952
|
-
consumeSkippedActionOrdinal(state, actionPayload, consumed);
|
|
953
|
-
} catch {
|
|
954
|
-
throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
955
|
-
}
|
|
956
|
-
continue;
|
|
957
|
-
}
|
|
958
|
-
const rawAction = actionPayload.action;
|
|
959
|
-
const operationCount = actionPayload.operationCount ?? state.operationCount + 1;
|
|
960
|
-
const { actionDigest: _rawActionDigest, ...rawActionBase } = rawAction;
|
|
961
|
-
if (rawAction.actionDigest !== checkpointDigest(rawActionBase) || rawAction.contextRef !== state.contextRef || !Number.isSafeInteger(operationCount) || operationCount !== state.operationCount + 1 || operationCount > BOOKING_COPILOT_MAX_OPERATIONS_V2 || !Number.isSafeInteger(rawAction.sequence) || rawAction.sequence <= state.lastSequence) throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
962
|
-
let a;
|
|
963
|
-
try {
|
|
964
|
-
a = normalizeActionCheckpointForReplay(rawAction, state.workspaceSnapshot);
|
|
965
|
-
} catch (error) {
|
|
966
|
-
if (error instanceof Error && error.message.startsWith('booking_v2_replan_required:')) {
|
|
967
|
-
state = replanAfterReplayUpgradeGap(state);
|
|
968
|
-
try {
|
|
969
|
-
consumeSkippedActionOrdinal(state, actionPayload, consumed);
|
|
970
|
-
} catch {
|
|
971
|
-
throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
972
|
-
}
|
|
973
|
-
skipLegacyUpgradeTail = true;
|
|
974
|
-
continue;
|
|
975
|
-
}
|
|
976
|
-
throw error;
|
|
977
|
-
}
|
|
978
|
-
const { actionDigest: _actionDigest, ...actionBase } = a;
|
|
979
|
-
if (!actionPayload.availability || actionPayload.availabilityDigest !== bookingV2Digest(actionPayload.availability)) throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
980
|
-
let actionAvailability;
|
|
981
|
-
try {
|
|
982
|
-
actionAvailability = normalizeAvailabilityPolicyForReplay(actionPayload.availability, state.workspaceSnapshot, a, state.availability, replayWorkspaceDigests);
|
|
983
|
-
} catch (error) {
|
|
984
|
-
if (error instanceof Error && error.message.startsWith('booking_v2_replan_required:')) {
|
|
985
|
-
state = replanAfterReplayUpgradeGap(state);
|
|
986
|
-
try {
|
|
987
|
-
consumeSkippedActionOrdinal(state, actionPayload, consumed);
|
|
988
|
-
} catch {
|
|
989
|
-
throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
990
|
-
}
|
|
991
|
-
skipLegacyUpgradeTail = true;
|
|
992
|
-
continue;
|
|
993
|
-
}
|
|
994
|
-
throw error;
|
|
995
|
-
}
|
|
996
|
-
if (!checkpointDigestMatchesForReplay(rawAction, a) || a.actionDigest !== checkpointDigest(actionBase) || !Number.isSafeInteger(operationCount) || operationCount !== state.operationCount + 1 || operationCount > BOOKING_COPILOT_MAX_OPERATIONS_V2 || !validateAvailabilityPolicyV2(actionAvailability) || !replayDigestMatches(actionPayload.availabilityDigest, actionPayload.availability, actionAvailability) || !state.workspaceSnapshot) throw new Error(`ledger_corrupt:${taskId}:action`);
|
|
997
|
-
if (a.relaxationApprovalRef) assertApprovalRef(a.relaxationApprovalRef, state, a);
|
|
998
|
-
if (state.pendingAction) throw new Error(`ledger_corrupt:${taskId}:parallel_actions`);
|
|
999
|
-
let expectedAvailability;
|
|
1000
|
-
try {
|
|
1001
|
-
expectedAvailability = reduceAvailabilityActionV2(state.availability, state.workspaceSnapshot, a);
|
|
1002
|
-
} catch {
|
|
1003
|
-
throw new Error(`ledger_corrupt:${taskId}:action_transition`);
|
|
1004
|
-
}
|
|
1005
|
-
if (bookingV2Digest(expectedAvailability) !== bookingV2Digest(actionAvailability)) throw new Error(`ledger_corrupt:${taskId}:action_transition`);
|
|
1006
|
-
state.operationCount = operationCount;
|
|
1007
|
-
state.availability = actionAvailability;
|
|
1008
|
-
state.pendingAction = a;
|
|
1009
|
-
state.phase = 'waiting_receipt';
|
|
1010
|
-
state.lastSequence = Math.max(state.lastSequence, a.sequence);
|
|
1011
|
-
{
|
|
1012
|
-
rememberConsumedActionIdentity(consumed, a);
|
|
1013
|
-
}
|
|
1014
|
-
delete state.awaitingApproval;
|
|
1015
|
-
} else if (row.kind === RECEIPT) {
|
|
1016
|
-
if (skipLegacyUpgradeTail) {
|
|
1017
|
-
const r = payload;
|
|
1018
|
-
if (typeof r.receipt?.actionId === 'string') suppressedReceiptActionIds.add(r.receipt.actionId);
|
|
1019
|
-
continue;
|
|
1020
|
-
}
|
|
1021
|
-
const r = payload;
|
|
1022
|
-
const operationCount = r.operationCount ?? state.operationCount;
|
|
1023
|
-
if (!state.pendingAction || state.pendingAction.actionId !== r.receipt.actionId) throw new Error(`ledger_corrupt:${taskId}:orphan_receipt`);
|
|
1024
|
-
let receiptWorkspace;
|
|
1025
|
-
try {
|
|
1026
|
-
receiptWorkspace = normalizeWorkspaceForReplay(r.workspace);
|
|
1027
|
-
} catch {
|
|
1028
|
-
throw new Error(`ledger_corrupt:${taskId}:receipt_workspace`);
|
|
1029
|
-
}
|
|
1030
|
-
try {
|
|
1031
|
-
assertWorkspaceLoadedOfferRefsUniqueV2(receiptWorkspace);
|
|
1032
|
-
} catch {
|
|
1033
|
-
throw new Error(`ledger_corrupt:${taskId}:receipt_workspace`);
|
|
1034
|
-
}
|
|
1035
|
-
if (!r.workspaceDigest || !r.workspaceSemanticDigest || !r.workspace || !replayWorkspaceDigestMatches(r.workspaceDigest, r.workspace, receiptWorkspace) || !replayWorkspaceSemanticDigestMatches(r.workspaceSemanticDigest, r.workspace, receiptWorkspace)) throw new Error(`ledger_corrupt:${taskId}:receipt_workspace`);
|
|
1036
|
-
rememberReplayWorkspaceDigest(replayWorkspaceDigests, r.workspaceDigest, r.workspace, receiptWorkspace);
|
|
1037
|
-
if (!replayDigestMatches(r.receiptDigest, r.receipt, r.receipt) || r.receipt.contextRef !== state.contextRef || r.receipt.actionId !== state.pendingAction.actionId || !Number.isSafeInteger(r.receipt.revision) || r.receipt.revision < state.pendingAction.expectedRevision || !Number.isSafeInteger(operationCount) || operationCount !== state.operationCount) throw new Error(`ledger_corrupt:${taskId}:receipt`);
|
|
1038
|
-
if (!r.availability || r.availabilityDigest !== bookingV2Digest(r.availability)) throw new Error(`ledger_corrupt:${taskId}:receipt`);
|
|
1039
|
-
let receipt;
|
|
1040
|
-
try {
|
|
1041
|
-
receipt = normalizeReceiptForReplay(r.receipt, state.pendingAction, receiptWorkspace);
|
|
1042
|
-
} catch (error) {
|
|
1043
|
-
if (error instanceof Error && error.message.startsWith('booking_v2_replan_required:')) {
|
|
1044
|
-
clearPendingBatch(consumed);
|
|
1045
|
-
state = replanAfterReplayUpgradeGap(state, receiptWorkspace, r.receipt.revision);
|
|
1046
|
-
skipLegacyUpgradeTail = true;
|
|
1047
|
-
continue;
|
|
1048
|
-
}
|
|
1049
|
-
throw error;
|
|
1050
|
-
}
|
|
1051
|
-
let receiptAvailability;
|
|
1052
|
-
try {
|
|
1053
|
-
receiptAvailability = normalizeAvailabilityPolicyForReplay(r.availability, receiptWorkspace, state.pendingAction, state.availability, replayWorkspaceDigests, receipt);
|
|
1054
|
-
} catch (error) {
|
|
1055
|
-
if (error instanceof Error && error.message.startsWith('booking_v2_replan_required:')) {
|
|
1056
|
-
clearPendingBatch(consumed);
|
|
1057
|
-
state = replanAfterReplayUpgradeGap(state, receiptWorkspace, r.receipt.revision);
|
|
1058
|
-
skipLegacyUpgradeTail = true;
|
|
1059
|
-
continue;
|
|
1060
|
-
}
|
|
1061
|
-
throw error;
|
|
1062
|
-
}
|
|
1063
|
-
if (!replayDigestMatches(r.receiptDigest, r.receipt, receipt) || !validateBookingSurfaceV2(receipt).ok || !r.availability || !r.availabilityDigest || !validateAvailabilityPolicyV2(receiptAvailability) || !replayDigestMatches(r.availabilityDigest, r.availability, receiptAvailability)) throw new Error(`ledger_corrupt:${taskId}:receipt`);
|
|
1064
|
-
if (Boolean(r.availabilityTerminal) !== Boolean(receiptAvailability.terminal) || r.availabilityTerminal && receiptAvailability.terminal && bookingV2Digest(r.availabilityTerminal) !== bookingV2Digest(receiptAvailability.terminal)) throw new Error(`ledger_corrupt:${taskId}:availability_terminal`);
|
|
1065
|
-
assertCanonicalReceipt(receipt);
|
|
1066
|
-
if (!state.workspaceSnapshot || !workspacePostActionMatches(state.workspaceSnapshot, receiptWorkspace, state.pendingAction, receipt) || !receiptObservationMatchesAction(receipt.observation.kind, state.pendingAction.kind) || !receiptTargetMatchesAction(receipt, state.pendingAction)) throw new Error(`ledger_corrupt:${taskId}:receipt_transition`);
|
|
1067
|
-
let expectedAvailability;
|
|
1068
|
-
try {
|
|
1069
|
-
expectedAvailability = reduceAvailabilityReceiptV2(state.availability, receiptWorkspace, receipt, state.pendingAction);
|
|
1070
|
-
} catch {
|
|
1071
|
-
throw new Error(`ledger_corrupt:${taskId}:receipt_transition`);
|
|
1072
|
-
}
|
|
1073
|
-
if (bookingV2Digest(expectedAvailability) !== bookingV2Digest(receiptAvailability)) throw new Error(`ledger_corrupt:${taskId}:receipt_transition`);
|
|
1074
|
-
state.lastReceipt = receipt;
|
|
1075
|
-
state.revision = receipt.revision;
|
|
1076
|
-
state.workspaceDigest = bookingV2WorkspaceDigest(receiptWorkspace);
|
|
1077
|
-
state.workspaceSemanticDigest = bookingV2WorkspaceSemanticDigest(receiptWorkspace);
|
|
1078
|
-
state.workspaceSnapshot = receiptWorkspace;
|
|
1079
|
-
state.availability = receiptAvailability;
|
|
1080
|
-
delete state.pendingAction;
|
|
1081
|
-
state.phase = receiptAvailability.terminal || state.operationCount >= BOOKING_COPILOT_MAX_OPERATIONS_V2 ? 'terminal' : 'planning';
|
|
1082
|
-
clearPendingBatch(consumed);
|
|
1083
|
-
delete state.awaitingApproval;
|
|
1084
|
-
} else if (row.kind === APPROVAL_CONSUMED) {
|
|
1085
|
-
if (skipLegacyUpgradeTail) {
|
|
1086
|
-
const consumed = payload;
|
|
1087
|
-
if (typeof consumed.ref?.targetActionId === 'string') suppressedApprovalTargetActionIds.add(consumed.ref.targetActionId);
|
|
1088
|
-
continue;
|
|
1089
|
-
}
|
|
1090
|
-
const consumed = payload;
|
|
1091
|
-
if (!consumed.ref || consumed.approvalDigest !== bookingV2Digest(consumed.ref) || !consumed.approval?.approval || !consumed.approval.options?.some((option)=>bookingV2Digest(option) === bookingV2Digest(consumed.approval.approval)) || !state.awaitingApproval || bookingV2Digest(consumed.approval) !== bookingV2Digest(state.awaitingApproval) || consumed.ref.approvalId !== consumed.approval.approval.approvalId || consumed.ref.blockerId !== consumed.approval.blocker.blockerId || consumed.ref.contextRef !== state.contextRef || consumed.ref.sourceTurnId !== consumed.approval.sourceTurnId || consumed.ref.presentationRequestKey !== consumed.approval.presentationRequestKey || consumed.ref.sourceActionId !== consumed.approval.blocker.sourceActionId || consumed.ref.targetActionId === '' || consumed.ref.sourceReceiptDigest !== consumed.approval.blocker.sourceReceiptDigest || consumed.ref.nonce !== consumed.approval.nonce || consumed.ref.nonce !== consumed.approval.approval.deliveryNonce || consumed.ref.to !== consumed.approval.approval.to || consumed.ref.scope !== consumed.approval.blocker.scope || consumed.ref.code !== consumed.approval.blocker.code || consumed.ref.criterionPath !== consumed.approval.blocker.criterionPath || consumed.ref.valueDigest !== consumed.approval.blocker.valueDigest) throw new Error(`ledger_corrupt:${taskId}:approval`);
|
|
1092
|
-
} else if (row.kind === DECISION_BATCH) {
|
|
1093
|
-
const batch = payload;
|
|
1094
|
-
if (skipLegacyUpgradeTail) {
|
|
1095
|
-
try {
|
|
1096
|
-
consumeSkippedEventSequence(state, batch, consumed);
|
|
1097
|
-
} catch {
|
|
1098
|
-
throw new Error(`ledger_corrupt:${taskId}:decision_batch`);
|
|
1099
|
-
}
|
|
1100
|
-
if (typeof batch.requestKey === 'string') suppressedDecisionRequestKeys.add(batch.requestKey);
|
|
1101
|
-
continue;
|
|
1102
|
-
}
|
|
1103
|
-
if (!batch.requestKey || !Array.isArray(batch.events) || batch.events.some((event)=>event.taskId !== taskId)) throw new Error(`ledger_corrupt:${taskId}:decision_batch`);
|
|
1104
|
-
let batchEvents;
|
|
1105
|
-
try {
|
|
1106
|
-
batchEvents = normalizeDecisionBatchEnvelopeForReplay(batch, consumed, true);
|
|
1107
|
-
} catch {
|
|
1108
|
-
throw new Error(`ledger_corrupt:${taskId}:decision_batch`);
|
|
1109
|
-
}
|
|
1110
|
-
for (const event of batchEvents){
|
|
1111
|
-
if (event.kind !== 'question') continue;
|
|
1112
|
-
const awaiting = state.awaitingApproval;
|
|
1113
|
-
if (!awaiting || bookingV2Digest(event.question.blocker) !== bookingV2Digest(awaiting.blocker) || event.question.approvalOptions.length !== awaiting.options.length || event.question.approvalOptions.some(({ approval })=>!awaiting.options.some((option)=>bookingV2Digest(option) === bookingV2Digest(approval)))) throw new Error(`ledger_corrupt:${taskId}:decision_batch_question`);
|
|
1114
|
-
awaiting.optionsEmitted = true;
|
|
1115
|
-
state.phase = 'input_required';
|
|
1116
|
-
}
|
|
1117
|
-
} else if (row.kind === EVENT) {
|
|
1118
|
-
const event = payload;
|
|
1119
|
-
if (skipLegacyUpgradeTail) {
|
|
1120
|
-
try {
|
|
1121
|
-
consumeSkippedEventSequence(state, event, consumed);
|
|
1122
|
-
} catch {
|
|
1123
|
-
throw new Error(`ledger_corrupt:${taskId}:event`);
|
|
1124
|
-
}
|
|
1125
|
-
continue;
|
|
1126
|
-
}
|
|
1127
|
-
state.lastSequence = Math.max(state.lastSequence, event.sequence);
|
|
1128
|
-
{
|
|
1129
|
-
rememberConsumedEventIdentity(consumed, event);
|
|
1130
|
-
}
|
|
1131
|
-
if (event.eventKind === 'status') state.phase = event.status === 'submitted' ? 'submitted' : event.status === 'working' ? 'working' : event.status === 'waiting_receipt' ? 'waiting_receipt' : 'input_required';
|
|
1132
|
-
else if (event.eventKind === 'question') state.phase = 'input_required';
|
|
1133
|
-
else if (event.eventKind === 'terminal') state.phase = 'terminal';
|
|
1134
|
-
else if (event.eventKind === 'error') state.phase = 'error';
|
|
1135
|
-
}
|
|
1136
|
-
}
|
|
1137
|
-
}
|
|
1138
|
-
if (state) {
|
|
1139
|
-
if (suppressedDecisionRequestKeys.size) state.legacySuppressedDecisionRequestKeys = [
|
|
1140
|
-
...suppressedDecisionRequestKeys
|
|
1141
|
-
];
|
|
1142
|
-
if (suppressedRequestBindingKeys.size) state.legacySuppressedRequestBindingKeys = [
|
|
1143
|
-
...suppressedRequestBindingKeys
|
|
1144
|
-
];
|
|
1145
|
-
if (suppressedReceiptActionIds.size) state.legacySuppressedReceiptActionIds = [
|
|
1146
|
-
...suppressedReceiptActionIds
|
|
1147
|
-
];
|
|
1148
|
-
if (suppressedApprovalTargetActionIds.size) state.legacySuppressedApprovalTargetActionIds = [
|
|
1149
|
-
...suppressedApprovalTargetActionIds
|
|
1150
|
-
];
|
|
1151
|
-
}
|
|
1152
|
-
return state;
|
|
1153
|
-
}
|
|
1154
|
-
withReceiptDigest(receipt) {
|
|
1155
|
-
const sourceDigest = receiptSourceDigest(receipt);
|
|
1156
|
-
return {
|
|
1157
|
-
...receipt,
|
|
1158
|
-
resultContract: {
|
|
1159
|
-
...receipt.resultContract,
|
|
1160
|
-
blockers: receipt.resultContract.blockers.map((b)=>({
|
|
1161
|
-
...b,
|
|
1162
|
-
sourceReceiptDigest: sourceDigest
|
|
1163
|
-
}))
|
|
1164
|
-
}
|
|
1165
|
-
};
|
|
1166
|
-
}
|
|
1167
|
-
receiptDigest(receipt) {
|
|
1168
|
-
return canonicalReceiptDigest(receipt);
|
|
1169
|
-
}
|
|
1170
|
-
approvalQuestion(taskId) {
|
|
1171
|
-
const task = this.requireTask(taskId);
|
|
1172
|
-
const awaiting = task.awaitingApproval;
|
|
1173
|
-
if (!awaiting) throw new Error('approval_not_awaiting');
|
|
1174
|
-
return {
|
|
1175
|
-
kind: 'question',
|
|
1176
|
-
question: {
|
|
1177
|
-
questionId: `question-${awaiting.blocker.blockerId}`,
|
|
1178
|
-
prompt: `Relax required criterion ${awaiting.blocker.criterionPath}?`,
|
|
1179
|
-
missingFields: [
|
|
1180
|
-
awaiting.blocker.criterionPath
|
|
1181
|
-
],
|
|
1182
|
-
type: 'relaxation_approval_required',
|
|
1183
|
-
blocker: awaiting.blocker,
|
|
1184
|
-
approvalOptions: awaiting.options.map((approval)=>({
|
|
1185
|
-
approval
|
|
1186
|
-
}))
|
|
1187
|
-
}
|
|
1188
|
-
};
|
|
1189
|
-
}
|
|
1190
|
-
approvalPresentationRequestKey(taskId) {
|
|
1191
|
-
const task = this.requireTask(taskId);
|
|
1192
|
-
const awaiting = task.awaitingApproval;
|
|
1193
|
-
if (!awaiting) throw new Error('approval_not_awaiting');
|
|
1194
|
-
return awaiting.presentationRequestKey;
|
|
1195
|
-
}
|
|
1196
|
-
commitDecisionBatch(taskId, requestKey, decisions) {
|
|
1197
|
-
return this.applyDecisionBatch(taskId, requestKey, decisions);
|
|
1198
|
-
}
|
|
1199
|
-
readDecisionBatch(taskId, requestKey) {
|
|
1200
|
-
const state = this.requireTask(taskId);
|
|
1201
|
-
if (state.legacySuppressedDecisionRequestKeys?.includes(requestKey)) throw new Error('request_key_invalidated');
|
|
1202
|
-
const rows = this.ledger.db.prepare('SELECT seq, payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ? ORDER BY seq DESC').all(this.ledger.tenant, taskId, DECISION_BATCH);
|
|
1203
|
-
for (const row of rows){
|
|
1204
|
-
const payload = JSON.parse(row.payload);
|
|
1205
|
-
if (payload.requestKey !== requestKey) continue;
|
|
1206
|
-
if (payload.schema !== LEDGER_SCHEMA || payload.taskId !== taskId || payload.contextRef !== state.contextRef || !Array.isArray(payload.events) || payload.events.some((event)=>event.taskId !== taskId || event.contextRef !== state.contextRef)) throw new Error(`ledger_corrupt:${taskId}:decision_batch`);
|
|
1207
|
-
const events = this.normalizeDecisionBatchFromDurableRows(taskId, payload.events, row.seq);
|
|
1208
|
-
if (!events) throw new Error(`ledger_corrupt:${taskId}:decision_batch`);
|
|
1209
|
-
for (const event of events){
|
|
1210
|
-
if (event.kind !== 'question') continue;
|
|
1211
|
-
const awaiting = state.awaitingApproval;
|
|
1212
|
-
if (!awaiting || requestKey !== awaiting.presentationRequestKey || bookingV2Digest(event.question.blocker) !== bookingV2Digest(awaiting.blocker) || event.question.approvalOptions.length !== awaiting.options.length || event.question.approvalOptions.some(({ approval })=>!awaiting.options.some((option)=>option.optionDigest === approval.optionDigest && bookingV2Digest(option) === bookingV2Digest(approval)))) throw new Error(`ledger_corrupt:${taskId}:decision_batch_question`);
|
|
1213
|
-
}
|
|
1214
|
-
return events;
|
|
1215
|
-
}
|
|
1216
|
-
return null;
|
|
1217
|
-
}
|
|
1218
|
-
terminalDecisionBatch(taskId, requestKey) {
|
|
1219
|
-
assertInternalDecisionKey(requestKey);
|
|
1220
|
-
const prior = this.readDecisionBatch(taskId, requestKey);
|
|
1221
|
-
if (prior) return prior;
|
|
1222
|
-
const state = this.requireTask(taskId);
|
|
1223
|
-
if (state.phase === 'terminal' || state.phase === 'error') throw new Error('task_terminal');
|
|
1224
|
-
assertReplayUpgradeReanchored(state);
|
|
1225
|
-
const run = this.ledger.db.transaction(()=>{
|
|
1226
|
-
const state = this.requireTask(taskId);
|
|
1227
|
-
if (!taskHasTerminalBudget(state) || state.phase !== 'terminal') throw new Error('task_not_terminal');
|
|
1228
|
-
assertReplayUpgradeReanchored(state);
|
|
1229
|
-
const event = this.terminalEvent(state);
|
|
1230
|
-
this.appendTerminalEvent(taskId, event);
|
|
1231
|
-
this.append(DECISION_BATCH, taskId, {
|
|
1232
|
-
schema: LEDGER_SCHEMA,
|
|
1233
|
-
taskId,
|
|
1234
|
-
contextRef: state.contextRef,
|
|
1235
|
-
requestKey,
|
|
1236
|
-
events: [
|
|
1237
|
-
event
|
|
1238
|
-
]
|
|
1239
|
-
}, `booking-v2:decision-batch:${taskId}:${requestKey}`);
|
|
1240
|
-
return [
|
|
1241
|
-
event
|
|
1242
|
-
];
|
|
1243
|
-
});
|
|
1244
|
-
return run.immediate();
|
|
1245
|
-
}
|
|
1246
|
-
applyDecisionBatch(taskId, requestKey, decisions, includeSubmitted = false) {
|
|
1247
|
-
assertInternalDecisionKey(requestKey);
|
|
1248
|
-
const prior = this.readDecisionBatch(taskId, requestKey);
|
|
1249
|
-
if (prior) return prior;
|
|
1250
|
-
const current = this.requireTask(taskId);
|
|
1251
|
-
if (current.phase === 'terminal' || current.phase === 'error') throw new Error('task_terminal');
|
|
1252
|
-
assertReplayUpgradeReanchored(current);
|
|
1253
|
-
assertDecisionBatchFinality(decisions);
|
|
1254
|
-
assertAvailabilityLiveness(current, decisions);
|
|
1255
|
-
if (current.availability.recoveryStarted && !current.availability.terminal && decisions.some((decision)=>decision.kind === 'terminal' || decision.kind === 'error')) throw new Error('availability_terminal_policy_owned');
|
|
1256
|
-
for (const decision of decisions){
|
|
1257
|
-
if (decision.kind === 'operation') {
|
|
1258
|
-
const checked = validateBookingReadActionV2(decision.action);
|
|
1259
|
-
if (!checked.ok) throw new Error(`invalid_action:${errorText(checked)}`);
|
|
1260
|
-
}
|
|
1261
|
-
}
|
|
1262
|
-
const run = this.ledger.db.transaction(()=>{
|
|
1263
|
-
const events = [];
|
|
1264
|
-
const before = this.requireTask(taskId);
|
|
1265
|
-
assertReplayUpgradeReanchored(before);
|
|
1266
|
-
assertAvailabilityLiveness(before, decisions);
|
|
1267
|
-
if (before.availability.recoveryStarted && !before.availability.terminal && decisions.some((decision)=>decision.kind === 'terminal' || decision.kind === 'error')) throw new Error('availability_terminal_policy_owned');
|
|
1268
|
-
for (const decision of decisions){
|
|
1269
|
-
if (decision.kind !== 'question') continue;
|
|
1270
|
-
const awaiting = before.awaitingApproval;
|
|
1271
|
-
if (!awaiting || requestKey !== awaiting.presentationRequestKey || bookingV2Digest(decision.question.blocker) !== bookingV2Digest(awaiting.blocker) || decision.question.approvalOptions.length !== awaiting.options.length || decision.question.approvalOptions.some(({ approval })=>!awaiting.options.some((option)=>option.optionDigest === approval.optionDigest && bookingV2Digest(option) === bookingV2Digest(approval)))) throw new Error('approval_presentation_key_mismatch');
|
|
1272
|
-
this.ensureApprovalOffered(taskId, before.contextRef, awaiting, requestKey);
|
|
1273
|
-
}
|
|
1274
|
-
if (includeSubmitted) events.push(this.emitEventInTransaction(taskId, {
|
|
1275
|
-
kind: 'status',
|
|
1276
|
-
status: 'submitted'
|
|
1277
|
-
}));
|
|
1278
|
-
events.push(this.emitEventInTransaction(taskId, {
|
|
1279
|
-
kind: 'status',
|
|
1280
|
-
status: 'working'
|
|
1281
|
-
}));
|
|
1282
|
-
for (const decision of decisions){
|
|
1283
|
-
if (decision.kind === 'operation') {
|
|
1284
|
-
events.push(this.issueOperationInTransaction(taskId, decision.action));
|
|
1285
|
-
events.push(this.emitEventInTransaction(taskId, {
|
|
1286
|
-
kind: 'status',
|
|
1287
|
-
status: 'waiting_receipt'
|
|
1288
|
-
}));
|
|
1289
|
-
} else events.push(this.emitEventInTransaction(taskId, decision));
|
|
1290
|
-
}
|
|
1291
|
-
const state = this.requireTask(taskId);
|
|
1292
|
-
this.append(DECISION_BATCH, taskId, {
|
|
1293
|
-
schema: LEDGER_SCHEMA,
|
|
1294
|
-
taskId,
|
|
1295
|
-
contextRef: state.contextRef,
|
|
1296
|
-
requestKey,
|
|
1297
|
-
events
|
|
1298
|
-
}, `booking-v2:decision-batch:${taskId}:${requestKey}`);
|
|
1299
|
-
return events;
|
|
1300
|
-
});
|
|
1301
|
-
return run.immediate();
|
|
1302
|
-
}
|
|
1303
|
-
issueOperation(taskId, candidate) {
|
|
1304
|
-
const validation = validateBookingReadActionV2(candidate);
|
|
1305
|
-
if (!validation.ok) throw new Error(`invalid_action:${errorText(validation)}`);
|
|
1306
|
-
assertTaskId(taskId);
|
|
1307
|
-
assertSafeRef(candidate.actionId);
|
|
1308
|
-
candidate.factRefs.forEach(assertSafeRef);
|
|
1309
|
-
return this.ledger.db.transaction(()=>this.issueOperationInTransaction(taskId, candidate)).immediate();
|
|
1310
|
-
}
|
|
1311
|
-
issueOperationInTransaction(taskId, candidate) {
|
|
1312
|
-
assertSafeRef(candidate.actionId);
|
|
1313
|
-
candidate.factRefs.forEach(assertSafeRef);
|
|
1314
|
-
const state = this.requireTask(taskId);
|
|
1315
|
-
if (state.phase === 'terminal' || state.phase === 'error') throw new Error('task_terminal');
|
|
1316
|
-
assertReplayUpgradeReanchored(state);
|
|
1317
|
-
if (state.pendingAction) {
|
|
1318
|
-
if (state.pendingAction.actionId !== candidate.actionId) throw new Error('receipt_required');
|
|
1319
|
-
if (!matchesCheckpoint(candidate, state.pendingAction)) throw new Error('action_conflict');
|
|
1320
|
-
return this.operationEvent(taskId, state.pendingAction, candidate);
|
|
1321
|
-
}
|
|
1322
|
-
if (candidate.contextRef !== state.contextRef) throw new Error('context_mismatch');
|
|
1323
|
-
if (!state.allowedActions.includes(candidate.kind)) throw new Error('unsupported_action');
|
|
1324
|
-
if (candidate.expectedRevision !== state.revision) throw new Error('stale_revision');
|
|
1325
|
-
if (state.operationCount >= BOOKING_COPILOT_MAX_OPERATIONS_V2) throw new Error('operation_limit_reached');
|
|
1326
|
-
if (candidate.relaxationApprovalRef) throw new Error('approval_ref_planner_owned_forbidden');
|
|
1327
|
-
if (!state.workspaceSnapshot) throw new Error(`ledger_corrupt:${taskId}:workspace_missing`);
|
|
1328
|
-
if (!actionHitsCurrentOfferVersion(state.workspaceSnapshot, candidate, this.now())) throw new Error('offer_version_not_loaded');
|
|
1329
|
-
let action = candidate;
|
|
1330
|
-
const availability = reduceAvailabilityActionV2(state.availability, state.workspaceSnapshot, candidate);
|
|
1331
|
-
if (state.awaitingApproval) {
|
|
1332
|
-
const approval = state.awaitingApproval;
|
|
1333
|
-
if (!approval.approval || Date.parse(approval.expiresAt) <= Date.parse(this.now())) throw new Error('approval_expired');
|
|
1334
|
-
const ref = {
|
|
1335
|
-
approvalId: approval.approval.approvalId,
|
|
1336
|
-
blockerId: approval.blocker.blockerId,
|
|
1337
|
-
contextRef: state.contextRef,
|
|
1338
|
-
sourceTurnId: approval.sourceTurnId,
|
|
1339
|
-
presentationRequestKey: approval.presentationRequestKey,
|
|
1340
|
-
sourceActionId: approval.blocker.sourceActionId,
|
|
1341
|
-
targetActionId: candidate.actionId,
|
|
1342
|
-
sourceRevision: candidate.expectedRevision,
|
|
1343
|
-
targetActionKind: candidate.kind,
|
|
1344
|
-
to: approval.approval.to,
|
|
1345
|
-
expiresAt: approval.expiresAt,
|
|
1346
|
-
nonce: approval.nonce,
|
|
1347
|
-
sourceReceiptDigest: approval.blocker.sourceReceiptDigest,
|
|
1348
|
-
scope: approval.blocker.scope,
|
|
1349
|
-
code: approval.blocker.code,
|
|
1350
|
-
criterionPath: approval.blocker.criterionPath,
|
|
1351
|
-
valueDigest: approval.blocker.valueDigest
|
|
1352
|
-
};
|
|
1353
|
-
action = {
|
|
1354
|
-
...candidate,
|
|
1355
|
-
relaxationApprovalRef: ref
|
|
1356
|
-
};
|
|
1357
|
-
this.append(APPROVAL_CONSUMED, taskId, {
|
|
1358
|
-
schema: LEDGER_SCHEMA,
|
|
1359
|
-
taskId,
|
|
1360
|
-
contextRef: state.contextRef,
|
|
1361
|
-
approval,
|
|
1362
|
-
ref,
|
|
1363
|
-
approvalDigest: bookingV2Digest(ref)
|
|
1364
|
-
}, `booking-v2:approval-consumed:${taskId}:${approval.approval.approvalId}:${approval.nonce}`);
|
|
1365
|
-
}
|
|
1366
|
-
const eventId = this.idFactory('event');
|
|
1367
|
-
const emittedAt = this.now();
|
|
1368
|
-
const sequence = state.lastSequence + 1;
|
|
1369
|
-
const event = {
|
|
1370
|
-
schemaVersion: 'booking.surface.v2',
|
|
1371
|
-
eventId,
|
|
1372
|
-
taskId,
|
|
1373
|
-
contextRef: state.contextRef,
|
|
1374
|
-
sequence,
|
|
1375
|
-
emittedAt,
|
|
1376
|
-
kind: 'operation',
|
|
1377
|
-
action
|
|
1378
|
-
};
|
|
1379
|
-
const eventValidation = validateBookingSurfaceEventV2(event);
|
|
1380
|
-
if (!eventValidation.ok) throw new Error(`invalid_operation_event:${errorText(eventValidation)}`);
|
|
1381
|
-
if (!state.lastTurnId) throw new Error(`ledger_corrupt:${taskId}:turn_id`);
|
|
1382
|
-
this.appendAction(taskId, state.contextRef, checkpointFor(action, eventId, sequence, emittedAt, state.lastTurnId), state.operationCount + 1, availability);
|
|
1383
|
-
return event;
|
|
1384
|
-
}
|
|
1385
|
-
continueWithReceipt(turn) {
|
|
1386
|
-
const validation = validateBookingSurfaceV2(turn);
|
|
1387
|
-
if (!validation.ok) throw new Error(`invalid_receipt_continuation:${errorText(validation)}`);
|
|
1388
|
-
assertWorkspaceLoadedOfferRefsUniqueV2(turn.workspace);
|
|
1389
|
-
assertCanonicalReceipt(turn.receipt);
|
|
1390
|
-
const run = this.ledger.db.transaction(()=>{
|
|
1391
|
-
const state = this.requireTask(turn.taskId);
|
|
1392
|
-
assertReplayUpgradeReanchored(state);
|
|
1393
|
-
if (turn.workspace.contextRef !== state.contextRef || turn.receipt.contextRef !== state.contextRef) throw new Error('context_mismatch');
|
|
1394
|
-
const receiptWorkspace = bookingV2WorkspaceDigest(turn.workspace);
|
|
1395
|
-
const receiptWorkspaceSemantic = bookingV2WorkspaceSemanticDigest(turn.workspace);
|
|
1396
|
-
if (!state.workspaceSnapshot || !workspaceBoundaryMatches(state.workspaceSnapshot, turn.workspace)) throw new Error('workspace_mismatch');
|
|
1397
|
-
const existing = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ? ORDER BY seq`).all(this.ledger.tenant, turn.taskId, RECEIPT);
|
|
1398
|
-
const receiptDigest = canonicalReceiptDigest(turn.receipt);
|
|
1399
|
-
if (state.legacySuppressedReceiptActionIds?.includes(turn.receipt.actionId)) throw new Error('request_key_invalidated');
|
|
1400
|
-
for (const row of existing){
|
|
1401
|
-
const prior = JSON.parse(row.payload);
|
|
1402
|
-
if (prior.receipt.actionId !== turn.receipt.actionId) continue;
|
|
1403
|
-
if (prior.receiptDigest !== receiptDigest) throw new Error('receipt_conflict');
|
|
1404
|
-
if (prior.workspaceDigest !== receiptWorkspace) throw new Error('workspace_mismatch');
|
|
1405
|
-
return state;
|
|
1406
|
-
}
|
|
1407
|
-
if (state.phase === 'terminal' || state.phase === 'error') throw new Error('task_terminal');
|
|
1408
|
-
if (!state.pendingAction) throw new Error('unexpected_receipt');
|
|
1409
|
-
if (state.pendingAction.actionId !== turn.receipt.actionId) throw new Error('receipt_action_mismatch');
|
|
1410
|
-
if (turn.receipt.revision < state.pendingAction.expectedRevision) throw new Error('revision_regression');
|
|
1411
|
-
if (turn.receipt.resultContract.blockers.some((blocker)=>blocker.sourceActionId !== state.pendingAction.actionId)) throw new Error('receipt_source_action_mismatch');
|
|
1412
|
-
if (!workspacePostActionMatches(state.workspaceSnapshot, turn.workspace, state.pendingAction, turn.receipt)) throw new Error('workspace_mismatch');
|
|
1413
|
-
if (!receiptObservationMatchesAction(turn.receipt.observation.kind, state.pendingAction.kind)) throw new Error('receipt_observation_action_mismatch');
|
|
1414
|
-
if (!receiptTargetMatchesAction(turn.receipt, state.pendingAction)) throw new Error('receipt_target_mismatch');
|
|
1415
|
-
if (state.pendingAction.kind === 'offer.check' && turn.receipt.status === 'applied' && !verifiedOfferUnexpired(turn.workspace, this.now())) throw new Error('receipt_verified_offer_expired');
|
|
1416
|
-
if (state.pendingAction.kind === 'offers.query' && turn.receipt.observation.kind === 'offers.state') validateOffersReceiptWorkspaceV2(turn.receipt, turn.workspace, state.pendingAction.input.hotelRefs);
|
|
1417
|
-
if (turn.receipt.resultContract.relaxationsApplied.some((approval)=>!this.approvalWasConsumed(turn.taskId, approval, state.pendingAction.actionId))) throw new Error('receipt_relaxation_unauthorized');
|
|
1418
|
-
const pending = state.pendingAction;
|
|
1419
|
-
if (turn.receipt.revision !== turn.workspace.revision) throw new Error('revision_mismatch');
|
|
1420
|
-
const availability = reduceAvailabilityReceiptV2(state.availability, turn.workspace, turn.receipt, pending);
|
|
1421
|
-
const availabilityTerminal = availabilityPolicyTerminal(availability);
|
|
1422
|
-
this.append(RECEIPT, turn.taskId, {
|
|
1423
|
-
schema: LEDGER_SCHEMA,
|
|
1424
|
-
taskId: turn.taskId,
|
|
1425
|
-
contextRef: state.contextRef,
|
|
1426
|
-
receipt: turn.receipt,
|
|
1427
|
-
receiptDigest,
|
|
1428
|
-
operationCount: state.operationCount,
|
|
1429
|
-
workspaceDigest: receiptWorkspace,
|
|
1430
|
-
workspaceSemanticDigest: receiptWorkspaceSemantic,
|
|
1431
|
-
workspace: turn.workspace,
|
|
1432
|
-
availability,
|
|
1433
|
-
availabilityDigest: bookingV2Digest(availability),
|
|
1434
|
-
...availabilityTerminal ? {
|
|
1435
|
-
availabilityTerminal
|
|
1436
|
-
} : {}
|
|
1437
|
-
}, `booking-v2:receipt:${turn.taskId}:${turn.receipt.actionId}`);
|
|
1438
|
-
if (availabilityTerminal || state.operationCount >= BOOKING_COPILOT_MAX_OPERATIONS_V2) {
|
|
1439
|
-
const terminalState = this.requireTask(turn.taskId);
|
|
1440
|
-
const terminalEvent = this.terminalEvent(terminalState);
|
|
1441
|
-
this.appendTerminalEvent(turn.taskId, terminalEvent);
|
|
1442
|
-
this.append(DECISION_BATCH, turn.taskId, {
|
|
1443
|
-
schema: LEDGER_SCHEMA,
|
|
1444
|
-
taskId: turn.taskId,
|
|
1445
|
-
contextRef: state.contextRef,
|
|
1446
|
-
requestKey: `receipt:${turn.receipt.actionId}:${receiptDigest}`,
|
|
1447
|
-
events: [
|
|
1448
|
-
terminalEvent
|
|
1449
|
-
]
|
|
1450
|
-
}, `booking-v2:decision-batch:${turn.taskId}:receipt:${turn.receipt.actionId}:${receiptDigest}`);
|
|
1451
|
-
return terminalState;
|
|
1452
|
-
}
|
|
1453
|
-
const blocker = turn.receipt.resultContract.blockers[0];
|
|
1454
|
-
if (blocker) {
|
|
1455
|
-
const nonce = randomUUID();
|
|
1456
|
-
const sourceTurnId = state.pendingAction?.sourceTurnId ?? state.lastTurnId ?? `ordinal:${state.userTurnCount}`;
|
|
1457
|
-
const requestKey = presentationKey(turn.taskId, sourceTurnId, turn.receipt.actionId, receiptDigest);
|
|
1458
|
-
const approval = {
|
|
1459
|
-
blocker,
|
|
1460
|
-
options: [
|
|
1461
|
-
approvalOption(turn.taskId, state.contextRef, sourceTurnId, requestKey, blocker, 'prefer', nonce),
|
|
1462
|
-
approvalOption(turn.taskId, state.contextRef, sourceTurnId, requestKey, blocker, 'drop', nonce)
|
|
1463
|
-
],
|
|
1464
|
-
optionsEmitted: false,
|
|
1465
|
-
approval: undefined,
|
|
1466
|
-
nonce,
|
|
1467
|
-
expiresAt: new Date(Date.parse(this.now()) + this.approvalTtlMs).toISOString(),
|
|
1468
|
-
sourceTurnId,
|
|
1469
|
-
presentationRequestKey: requestKey
|
|
1470
|
-
};
|
|
1471
|
-
this.append(APPROVAL_GRANTED, turn.taskId, {
|
|
1472
|
-
schema: LEDGER_SCHEMA,
|
|
1473
|
-
taskId: turn.taskId,
|
|
1474
|
-
contextRef: state.contextRef,
|
|
1475
|
-
approval,
|
|
1476
|
-
approvalDigest: bookingV2Digest(approval)
|
|
1477
|
-
}, `booking-v2:approval-awaiting:${turn.taskId}:${turn.receipt.actionId}`);
|
|
1478
|
-
}
|
|
1479
|
-
return this.requireTask(turn.taskId);
|
|
1480
|
-
});
|
|
1481
|
-
return run.immediate();
|
|
1482
|
-
}
|
|
1483
|
-
emitEvent(taskId, draft) {
|
|
1484
|
-
return this.ledger.db.transaction(()=>{
|
|
1485
|
-
const state = this.requireTask(taskId);
|
|
1486
|
-
if (state.phase === 'terminal' || state.phase === 'error') throw new Error('task_terminal');
|
|
1487
|
-
assertReplayUpgradeReanchored(state);
|
|
1488
|
-
return this.emitEventInTransaction(taskId, draft);
|
|
1489
|
-
}).immediate();
|
|
1490
|
-
}
|
|
1491
|
-
emitEventInTransaction(taskId, draft) {
|
|
1492
|
-
const state = this.requireTask(taskId);
|
|
1493
|
-
assertReplayUpgradeReanchored(state);
|
|
1494
|
-
const safeDraft = draft.kind === 'error' ? {
|
|
1495
|
-
...draft,
|
|
1496
|
-
error: {
|
|
1497
|
-
...draft.error,
|
|
1498
|
-
code: normalizeBookingErrorCode(draft.error.code),
|
|
1499
|
-
message: safeBookingErrorMessage(normalizeBookingErrorCode(draft.error.code))
|
|
1500
|
-
}
|
|
1501
|
-
} : draft;
|
|
1502
|
-
const event = {
|
|
1503
|
-
schemaVersion: 'booking.surface.v2',
|
|
1504
|
-
eventId: this.idFactory('event'),
|
|
1505
|
-
taskId,
|
|
1506
|
-
contextRef: state.contextRef,
|
|
1507
|
-
sequence: state.lastSequence + 1,
|
|
1508
|
-
emittedAt: this.now(),
|
|
1509
|
-
...safeDraft
|
|
1510
|
-
};
|
|
1511
|
-
const checked = validateBookingSurfaceEventV2(event);
|
|
1512
|
-
if (!checked.ok) throw new Error(`invalid_event:${errorText(checked)}`);
|
|
1513
|
-
this.append(EVENT, taskId, {
|
|
1514
|
-
schema: LEDGER_SCHEMA,
|
|
1515
|
-
taskId,
|
|
1516
|
-
contextRef: state.contextRef,
|
|
1517
|
-
eventId: event.eventId,
|
|
1518
|
-
sequence: event.sequence,
|
|
1519
|
-
emittedAt: event.emittedAt,
|
|
1520
|
-
eventKind: event.kind,
|
|
1521
|
-
...event.kind === 'status' ? {
|
|
1522
|
-
status: event.status
|
|
1523
|
-
} : {},
|
|
1524
|
-
contentDigest: bookingV2Digest(safeDraft)
|
|
1525
|
-
}, `booking-v2:event:${taskId}:${event.eventId}`);
|
|
1526
|
-
return event;
|
|
1527
|
-
}
|
|
1528
|
-
operationEvent(taskId, checkpoint, action) {
|
|
1529
|
-
const replayAction = action.relaxationApprovalRef || !checkpoint.relaxationApprovalRef ? action : {
|
|
1530
|
-
...action,
|
|
1531
|
-
relaxationApprovalRef: checkpoint.relaxationApprovalRef
|
|
1532
|
-
};
|
|
1533
|
-
return {
|
|
1534
|
-
schemaVersion: 'booking.surface.v2',
|
|
1535
|
-
eventId: checkpoint.eventId,
|
|
1536
|
-
taskId,
|
|
1537
|
-
contextRef: checkpoint.contextRef,
|
|
1538
|
-
sequence: checkpoint.sequence,
|
|
1539
|
-
emittedAt: checkpoint.emittedAt,
|
|
1540
|
-
kind: 'operation',
|
|
1541
|
-
action: replayAction
|
|
1542
|
-
};
|
|
1543
|
-
}
|
|
1544
|
-
terminalEvent(state) {
|
|
1545
|
-
if (!taskHasTerminalBudget(state)) throw new Error('task_not_terminal');
|
|
1546
|
-
const terminalCode = state.availability.terminal?.code ?? 'operation_limit_reached';
|
|
1547
|
-
const event = {
|
|
1548
|
-
schemaVersion: 'booking.surface.v2',
|
|
1549
|
-
eventId: `terminal-${state.taskId}-${state.operationCount}`,
|
|
1550
|
-
taskId: state.taskId,
|
|
1551
|
-
contextRef: state.contextRef,
|
|
1552
|
-
sequence: state.lastSequence + 1,
|
|
1553
|
-
emittedAt: this.now(),
|
|
1554
|
-
kind: 'terminal',
|
|
1555
|
-
terminal: {
|
|
1556
|
-
status: state.availability.terminal?.code === 'availability_confirmed' ? 'completed' : 'stopped',
|
|
1557
|
-
summary: terminalCode,
|
|
1558
|
-
factRefs: []
|
|
1559
|
-
}
|
|
1560
|
-
};
|
|
1561
|
-
const checked = validateBookingSurfaceEventV2(event);
|
|
1562
|
-
if (!checked.ok) throw new Error(`invalid_terminal_event:${errorText(checked)}`);
|
|
1563
|
-
return event;
|
|
1564
|
-
}
|
|
1565
|
-
requireTask(taskId) {
|
|
1566
|
-
const state = this.resumeTask(taskId);
|
|
1567
|
-
if (!state) throw new Error('task_not_found');
|
|
1568
|
-
return state;
|
|
1569
|
-
}
|
|
1570
|
-
requestBinding(requestKey) {
|
|
1571
|
-
const rows = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND kind = ? ORDER BY seq DESC`).all(this.ledger.tenant, REQUEST_BINDING);
|
|
1572
|
-
for (const row of rows){
|
|
1573
|
-
const binding = JSON.parse(row.payload);
|
|
1574
|
-
if (binding.requestKey === requestKey) {
|
|
1575
|
-
const state = this.resumeTask(binding.taskId);
|
|
1576
|
-
if (state?.legacySuppressedRequestBindingKeys?.includes(requestKey)) throw new Error('request_key_invalidated');
|
|
1577
|
-
return binding;
|
|
1578
|
-
}
|
|
1579
|
-
}
|
|
1580
|
-
return null;
|
|
1581
|
-
}
|
|
1582
|
-
requestBindingPayload(requestKey, turn, input) {
|
|
1583
|
-
assertPrincipal(input.principal);
|
|
1584
|
-
assertRequestKey(requestKey);
|
|
1585
|
-
if (input.taskHandle) assertSafeRef(input.taskHandle);
|
|
1586
|
-
return {
|
|
1587
|
-
requestKey,
|
|
1588
|
-
requestDigest: bookingV2TurnDigest(turn),
|
|
1589
|
-
turnId: turn.turnId,
|
|
1590
|
-
workspaceDigest: bookingV2WorkspaceDigest(turn.workspace),
|
|
1591
|
-
workspaceSemanticDigest: bookingV2WorkspaceSemanticDigest(turn.workspace),
|
|
1592
|
-
surface: turn.workspace.surface,
|
|
1593
|
-
capabilityDigest: bookingV2Digest(turn.workspace.capabilities),
|
|
1594
|
-
principalDigest: bookingV2Digest({
|
|
1595
|
-
subject: input.principal.subject
|
|
1596
|
-
}),
|
|
1597
|
-
scopeDigest: bookingV2Digest({
|
|
1598
|
-
scope: input.principal.scope
|
|
1599
|
-
}),
|
|
1600
|
-
...input.taskHandle ? {
|
|
1601
|
-
taskHandle: input.taskHandle
|
|
1602
|
-
} : {}
|
|
1603
|
-
};
|
|
1604
|
-
}
|
|
1605
|
-
appendRequestBindingInTransaction(requestKey, turn, input) {
|
|
1606
|
-
assertRequestKey(requestKey);
|
|
1607
|
-
assertPrincipal(input.principal);
|
|
1608
|
-
const payload = this.requestBindingPayload(requestKey, turn, input);
|
|
1609
|
-
if (input.taskHandle) {
|
|
1610
|
-
const prior = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND kind = ?`).all(this.ledger.tenant, REQUEST_BINDING);
|
|
1611
|
-
for (const row of prior){
|
|
1612
|
-
const binding = JSON.parse(row.payload);
|
|
1613
|
-
if (binding.taskHandle !== input.taskHandle) continue;
|
|
1614
|
-
if (binding.principalDigest !== payload.principalDigest || binding.scopeDigest !== payload.scopeDigest) throw new Error('principal_conflict');
|
|
1615
|
-
if (binding.taskId !== turn.taskId || binding.contextRef !== turn.workspace.contextRef) throw new Error('task_handle_conflict');
|
|
1616
|
-
}
|
|
1617
|
-
}
|
|
1618
|
-
const existing = this.requestBinding(requestKey);
|
|
1619
|
-
if (existing) {
|
|
1620
|
-
if (existing.taskId !== turn.taskId || existing.contextRef !== turn.workspace.contextRef || existing.requestDigest !== payload.requestDigest || existing.turnId !== payload.turnId || existing.workspaceDigest !== payload.workspaceDigest || existing.workspaceSemanticDigest !== payload.workspaceSemanticDigest || existing.surface !== payload.surface || existing.capabilityDigest !== payload.capabilityDigest || existing.principalDigest !== payload.principalDigest || existing.scopeDigest !== payload.scopeDigest || existing.taskHandle !== payload.taskHandle) throw new Error('request_conflict');
|
|
1621
|
-
return;
|
|
1622
|
-
}
|
|
1623
|
-
this.append(REQUEST_BINDING, turn.taskId, {
|
|
1624
|
-
schema: LEDGER_SCHEMA,
|
|
1625
|
-
taskId: turn.taskId,
|
|
1626
|
-
contextRef: turn.workspace.contextRef,
|
|
1627
|
-
...payload
|
|
1628
|
-
}, `booking-v2:request-binding:${requestKey}`);
|
|
1629
|
-
}
|
|
1630
|
-
normalizeDecisionBatchFromDurableRows(taskId, batchEvents, batchSeq) {
|
|
1631
|
-
const individualRows = this.ledger.db.prepare(`SELECT kind, payload FROM events WHERE tenant_id = ? AND run_id = ? AND seq < ? AND kind IN (?, ?) ORDER BY seq`).all(this.ledger.tenant, taskId, batchSeq, EVENT, ACTION);
|
|
1632
|
-
const turnRows = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ? AND seq < ?`).all(this.ledger.tenant, taskId, TURN, batchSeq);
|
|
1633
|
-
const sourceWorkspaces = new Map();
|
|
1634
|
-
for (const row of turnRows){
|
|
1635
|
-
try {
|
|
1636
|
-
const turn = JSON.parse(row.payload);
|
|
1637
|
-
sourceWorkspaces.set(turn.turnId, normalizeWorkspaceForReplay(turn.workspace));
|
|
1638
|
-
} catch {
|
|
1639
|
-
return null;
|
|
1640
|
-
}
|
|
1641
|
-
}
|
|
1642
|
-
const recordedEvents = new Map();
|
|
1643
|
-
const recordedActions = new Map();
|
|
1644
|
-
for (const row of individualRows){
|
|
1645
|
-
if (row.kind === EVENT) {
|
|
1646
|
-
const payload = JSON.parse(row.payload);
|
|
1647
|
-
const key = consumedIdentityKey(payload.eventId, payload.sequence);
|
|
1648
|
-
if (recordedEvents.has(key) || recordedActions.has(key)) return null;
|
|
1649
|
-
recordedEvents.set(key, payload);
|
|
1650
|
-
} else if (row.kind === ACTION) {
|
|
1651
|
-
const payload = JSON.parse(row.payload);
|
|
1652
|
-
let action = payload.action;
|
|
1653
|
-
try {
|
|
1654
|
-
action = normalizeActionCheckpointForReplay(action, sourceWorkspaces.get(action.sourceTurnId));
|
|
1655
|
-
} catch {
|
|
1656
|
-
return null;
|
|
1657
|
-
}
|
|
1658
|
-
const key = consumedIdentityKey(action.eventId, action.sequence);
|
|
1659
|
-
if (recordedEvents.has(key) || recordedActions.has(key)) return null;
|
|
1660
|
-
recordedActions.set(key, action);
|
|
1661
|
-
}
|
|
1662
|
-
}
|
|
1663
|
-
let lastBatchSequence = -1;
|
|
1664
|
-
const seen = new Set();
|
|
1665
|
-
const normalizedEvents = [];
|
|
1666
|
-
for (const event of batchEvents){
|
|
1667
|
-
if (!Number.isSafeInteger(event.sequence) || event.sequence <= lastBatchSequence) return null;
|
|
1668
|
-
lastBatchSequence = event.sequence;
|
|
1669
|
-
const key = consumedIdentityKey(event.eventId, event.sequence);
|
|
1670
|
-
if (seen.has(key)) return null;
|
|
1671
|
-
seen.add(key);
|
|
1672
|
-
if (event.kind === 'operation') {
|
|
1673
|
-
const checkpoint = recordedActions.get(key);
|
|
1674
|
-
if (!checkpoint || !operationEventMatchesAction(event, checkpoint)) return null;
|
|
1675
|
-
const normalized = {
|
|
1676
|
-
...event,
|
|
1677
|
-
action: actionFromOperationEventForReplay(event, checkpoint)
|
|
1678
|
-
};
|
|
1679
|
-
if (!validateBookingSurfaceEventV2(normalized).ok) return null;
|
|
1680
|
-
normalizedEvents.push(normalized);
|
|
1681
|
-
} else {
|
|
1682
|
-
const recorded = recordedEvents.get(key);
|
|
1683
|
-
if (!recorded || !validateBookingSurfaceEventV2(event).ok || !eventPayloadMatchesEvent(recorded, event)) return null;
|
|
1684
|
-
normalizedEvents.push(event);
|
|
1685
|
-
}
|
|
1686
|
-
}
|
|
1687
|
-
return normalizedEvents;
|
|
1688
|
-
}
|
|
1689
|
-
rows(taskId) {
|
|
1690
|
-
return this.ledger.db.prepare(`SELECT seq, kind, payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind IN (?, ?, ?, ?, ?, ?, ?, ?, ?, ?) ORDER BY seq`).all(this.ledger.tenant, taskId, STARTED, TURN, ACTION, RECEIPT, EVENT, APPROVAL_GRANTED, APPROVAL_OFFERED, APPROVAL_CONSUMED, DECISION_BATCH, REQUEST_BINDING);
|
|
1691
|
-
}
|
|
1692
|
-
append(kind, taskId, payload, idemKey) {
|
|
1693
|
-
const result = this.ledger.db.prepare(`INSERT OR IGNORE INTO events (tenant_id, ts, actor, kind, subject_id, payload, idem_key, run_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(this.ledger.tenant, this.now(), ACTOR, kind, taskId, JSON.stringify(payload), idemKey, taskId);
|
|
1694
|
-
if (result.changes === 0) throw new Error(`ledger_write_failed:${kind}`);
|
|
1695
|
-
}
|
|
1696
|
-
appendTurn(taskId, contextRef, requestDigest, workspaceDigest, workspaceSemanticDigest, ordinal, turnId, workspace) {
|
|
1697
|
-
if (!workspace) throw new Error('ledger_write_failed:turn_workspace');
|
|
1698
|
-
this.append(TURN, taskId, {
|
|
1699
|
-
schema: LEDGER_SCHEMA,
|
|
1700
|
-
taskId,
|
|
1701
|
-
contextRef,
|
|
1702
|
-
requestDigest,
|
|
1703
|
-
workspaceDigest,
|
|
1704
|
-
workspaceSemanticDigest,
|
|
1705
|
-
workspace,
|
|
1706
|
-
turnId
|
|
1707
|
-
}, `booking-v2:turn:${taskId}:${turnId}`);
|
|
1708
|
-
}
|
|
1709
|
-
appendApproval(taskId, contextRef, approval) {
|
|
1710
|
-
this.append(APPROVAL_GRANTED, taskId, {
|
|
1711
|
-
schema: LEDGER_SCHEMA,
|
|
1712
|
-
taskId,
|
|
1713
|
-
contextRef,
|
|
1714
|
-
approval,
|
|
1715
|
-
approvalDigest: bookingV2Digest(approval)
|
|
1716
|
-
}, `booking-v2:approval-granted:${taskId}:${approval.approval?.approvalId ?? 'pending'}:${approval.nonce}`);
|
|
1717
|
-
}
|
|
1718
|
-
appendAction(taskId, contextRef, action, operationCount, availability) {
|
|
1719
|
-
this.append(ACTION, taskId, {
|
|
1720
|
-
schema: LEDGER_SCHEMA,
|
|
1721
|
-
taskId,
|
|
1722
|
-
contextRef,
|
|
1723
|
-
action,
|
|
1724
|
-
operationCount,
|
|
1725
|
-
availability,
|
|
1726
|
-
availabilityDigest: bookingV2Digest(availability)
|
|
1727
|
-
}, `booking-v2:action:${taskId}:${action.actionId}`);
|
|
1728
|
-
}
|
|
1729
|
-
appendTerminalEvent(taskId, event) {
|
|
1730
|
-
const payload = {
|
|
1731
|
-
schema: LEDGER_SCHEMA,
|
|
1732
|
-
taskId,
|
|
1733
|
-
contextRef: event.contextRef,
|
|
1734
|
-
eventId: event.eventId,
|
|
1735
|
-
sequence: event.sequence,
|
|
1736
|
-
emittedAt: event.emittedAt,
|
|
1737
|
-
eventKind: 'terminal',
|
|
1738
|
-
contentDigest: bookingV2Digest(event.terminal)
|
|
1739
|
-
};
|
|
1740
|
-
const idemKey = `booking-v2:terminal-event:${taskId}`;
|
|
1741
|
-
const result = this.ledger.db.prepare(`INSERT OR IGNORE INTO events (tenant_id, ts, actor, kind, subject_id, payload, idem_key, run_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`).run(this.ledger.tenant, this.now(), ACTOR, EVENT, taskId, JSON.stringify(payload), idemKey, taskId);
|
|
1742
|
-
if (result.changes === 0) {
|
|
1743
|
-
const existing = this.ledger.db.prepare('SELECT payload FROM events WHERE tenant_id = ? AND idem_key = ?').get(this.ledger.tenant, idemKey);
|
|
1744
|
-
if (!existing || JSON.parse(existing.payload).contentDigest !== payload.contentDigest) throw new Error('ledger_write_failed:terminal_event');
|
|
1745
|
-
}
|
|
1746
|
-
}
|
|
1747
|
-
ensureApprovalOffered(taskId, contextRef, approval, requestKey) {
|
|
1748
|
-
if (requestKey !== approval.presentationRequestKey) throw new Error('approval_presentation_key_mismatch');
|
|
1749
|
-
const idemKey = `booking-v2:approval-offered:${taskId}:${requestKey}`;
|
|
1750
|
-
const exists = this.ledger.db.prepare('SELECT 1 AS present FROM events WHERE tenant_id = ? AND idem_key = ?').get(this.ledger.tenant, idemKey);
|
|
1751
|
-
if (!exists) this.append(APPROVAL_OFFERED, taskId, {
|
|
1752
|
-
schema: LEDGER_SCHEMA,
|
|
1753
|
-
taskId,
|
|
1754
|
-
contextRef,
|
|
1755
|
-
approval,
|
|
1756
|
-
approvalDigest: bookingV2Digest(approval)
|
|
1757
|
-
}, idemKey);
|
|
1758
|
-
}
|
|
1759
|
-
approvalWasConsumed(taskId, approval, targetActionId) {
|
|
1760
|
-
const state = this.resumeTask(taskId);
|
|
1761
|
-
if (state?.legacySuppressedApprovalTargetActionIds?.includes(targetActionId)) return false;
|
|
1762
|
-
const rows = this.ledger.db.prepare(`SELECT payload FROM events WHERE tenant_id = ? AND run_id = ? AND kind = ?`).all(this.ledger.tenant, taskId, APPROVAL_CONSUMED);
|
|
1763
|
-
return rows.some(({ payload })=>{
|
|
1764
|
-
const consumed = JSON.parse(payload);
|
|
1765
|
-
return consumed.ref?.targetActionId === targetActionId && consumed.approval?.approval && bookingV2Digest(consumed.approval.approval) === bookingV2Digest(approval);
|
|
1766
|
-
});
|
|
1767
|
-
}
|
|
1768
|
-
}
|
|
1769
|
-
|
|
1770
|
-
|
|
1771
|
-
//# sourceURL=ts/src/booking-surface/runtime-v2.ts
|