ReviewOS

also looking at this

stacks/drone

feat: add retained cargo fleet cancellation and recovery

#105
Merged chris wants to merge codex/cargo-fleet-operator-recovery into main
32 files +2496 -27
resources/functions/drone/cargo/fleet.tsadded+361-0
Changes to resources/functions/drone/cargo/fleet.ts
@@ -0,0 +1,361 @@
1import type { SensorVector } from '../sensors/types'
2import type { PointLoadAttachment } from '../controls/physics'
3import type { VehiclePayloadCommand, VehiclePayloadPort, VehiclePlant, VehicleMissionPlan, VehicleSession } from '../vehicles/types'
4import type { ModeledCargoIntakeGrant } from './intake'
5import { createRigidBody, createReceivingRigidBody } from '../controls/physics'
6import { createMultirotorPlant, createMultirotorProfile } from '../vehicles/multirotor/profile'
7import { createRedundantVehicleLinks } from '../vehicles/links'
8import type { VehicleLinkScope, VehicleLinkSource } from '../vehicles/links'
9import { createVehicleSimulationSession } from '../vehicles/runtime'
10import { createCargoStationHandler } from './station'
11import { createCargoDeliveryCoordinator } from './coordinator'
12import { createCargoIntakeCoordinator } from './intake'
13import { planCargoDelivery } from './plan'
14
15type Progress = ReturnType<ReturnType<typeof createVehicleSimulationSession>['step']>
16type Station = ReturnType<typeof createCargoStationHandler>
17type Release = ReturnType<ReturnType<typeof createReceivingRigidBody>['separateCarriedLoad']>
18type Departure = Extract<ReturnType<Station['takeReadyParcel']>, { outcome: 'departed' }>
19type Owner = 'source-body' | 'station-actor' | 'receiver-body' | 'final-parcel-actor' | 'loose-parcel'
20export interface CargoFleetOperatorDecision {
21 version: 1
22 evidence: 'modeled-cargo-transport-decision-v1'
23 contextId: string
24 bootId: bigint
25 sessionId: bigint
26 sequence: number
27 issuedAtMs: number
28 reference: string
29 sourceEventId: string
30 action: 'cancel' | 'resume'
31}
32export const cargoFleetScenarios = ['nominal', 'receiver-host-loss-before-intake', 'intake-receipt-loss', 'receiver-primary-link-loss', 'receiver-both-links-loss', 'receiver-joint-shift-before-intake', 'receiver-navigation-loss-during-rail', 'source-kill-after-station-receipt', 'receiver-kill-after-intake', 'receiver-pad-motion-during-rail', 'receiver-containment-breach-after-intake-receipt'] as const
33export type CargoFleetScenario = typeof cargoFleetScenarios[number]
34function captureScenario(input: unknown): CargoFleetScenario {
35 try {
36 if (!input || typeof input !== 'object' || Object.getPrototypeOf(input) !== Object.prototype || Reflect.ownKeys(input).some(key => key !== 'scenario')) throw new TypeError()
37 const d = Object.getOwnPropertyDescriptor(input, 'scenario')
38 if (d && (!d.enumerable || !Object.hasOwn(d, 'value') || !cargoFleetScenarios.some(name => name === d.value))) throw new TypeError()
39 return (d?.value ?? 'nominal') as CargoFleetScenario
40 }
41 catch { throw new TypeError('cargo-fleet-arguments') }
42}
43const origin = { latitudeDeg: 0, longitudeDeg: 0, ellipsoidHeightM: 100 }
44const point = { id: 'parcel-a', massKg: .1, forwardM: .08 }
45const receiverPadM: SensorVector = [3, 2, -.1]
46const stationSite = { id: 'handover-station', recipientId: 'station-operator', containerId: point.id, positionM: [3, 0, 0] as SensorVector, radiusM: .35 }
47const finalSite = { id: 'final-site', recipientId: 'final-recipient', containerId: point.id, positionM: [6, 2, 0] as SensorVector, radiusM: .35 }
48function receiverMission(): VehicleMissionPlan {
49 const spatial = { acceptanceM: .18, maxArrivalSpeedMps: .15, settleMs: 300, timeoutMs: 20000 }
50 return { version: 2, vehicle: 'quadcopter', id: 'cargo-fleet-receiver', frame: 'LOCAL_NED', altitude: 'ORIGIN_RELATIVE_DOWN', terrain: 'DECLARED_MODEL_SURFACE', origin, fence: { radiusM: 12, minDownM: -5, maxDownM: 0 }, rallyM: [3, 2, -1], power: { availableWh: 40, maxW: 600, reservePercent: 30 }, start: 'start', tasks: [
51 { id: 'start', kind: 'start', next: 'intake' },
52 { id: 'intake', kind: 'payload', operation: 'material-receive', containerId: point.id, positionM: [...receiverPadM], timeoutMs: 60000, next: 'depart', onFailure: 'alternate-approach' },
53 { id: 'depart', kind: 'takeoff', positionM: [3, 2, -1], ...spatial, next: 'site' },
54 { id: 'site', kind: 'waypoint', positionM: [6, 2, -1], ...spatial, settleMs: 800, next: 'release' },
55 { id: 'release', kind: 'payload', operation: 'material-drop', containerId: point.id, timeoutMs: 1500, next: 'home', onFailure: 'alternate-approach' },
56 { id: 'home', kind: 'return', ...spatial, next: 'land' },
57 { id: 'land', kind: 'land', positionM: [3, 2, 0], ...spatial },
58 { id: 'alternate-approach', kind: 'waypoint', positionM: [5, 3, -1], ...spatial, next: 'alternate-land' },
59 { id: 'alternate-land', kind: 'land', positionM: [5, 3, 0], ...spatial },
60 ] }
61}
62function hasAuthority(p: Progress | null, command: VehiclePayloadCommand, nowMs: number, bootId: bigint, sessionId: bigint) {
63 return !!p && p.atMs === nowMs && p.hostAvailable && !p.terminal && p.phase === 'host' && p.policyAtMs !== null && p.policyAtMs <= nowMs && nowMs - p.policyAtMs < 20
64 && p.reference === command.reference && p.authority.bootId === bootId && p.authority.sessionId === sessionId && p.authority.state === 'autonomous'
65 && p.authority.lastCheckedAtMs !== null && nowMs - p.authority.lastCheckedAtMs < 20 && p.authority.leaseUntilMs !== null && p.authority.leaseUntilMs > nowMs && p.board.fault === null
66 && p.mission.state === 'running' && p.mission.payload?.eventId === command.eventId && JSON.stringify(p.mission.payload) === JSON.stringify(command) && command.expiresAtMs > nowMs
67}
68
69/** One modeled parcel, two retained raw-sensor/estimator/authority runtimes, and finite station physics. */
70export function createCargoFleetSession(input: unknown = {}, ...extra: unknown[]) {
71 if (extra.length) throw new TypeError('cargo-fleet-arguments')
72 const scenario = captureScenario(input)
73 const faultInjection: { scenario: Exclude<CargoFleetScenario, 'nominal'>, anchoredAtMs: number | null, triggeredAtMs: number | null, forceN?: SensorVector, forceRampMs?: number } | null = scenario === 'nominal' ? null : { scenario, anchoredAtMs: null, triggeredAtMs: null, ...(['receiver-pad-motion-during-rail', 'receiver-containment-breach-after-intake-receipt'].includes(scenario) ? { forceN: [scenario === 'receiver-pad-motion-during-rail' ? 4 : 8, 0, 0] as SensorVector, ...(scenario === 'receiver-containment-breach-after-intake-receipt' ? { forceRampMs: 2000 } : {}) } : {}) }
74 const bodyA = createRigidBody({ positionM: [0, 0, -.1], groundDownM: -.1, carriedPointLoad: point })
75 const bodyB = createReceivingRigidBody({ positionM: [...receiverPadM], groundDownM: -.1, expectedPointLoad: point })
76 const initialA = bodyA.loadSnapshot(), initialB = bodyB.loadSnapshot()
77 let station: Station | null = null, recipient: Station | null = null, loose: Station | null = null
78 const physical: { owner: Owner } = { owner: 'source-body' }
79 const operatorContextId = crypto.randomUUID()
80 const operatorEvents: { atMs: number, sequence: number, action: 'cancel' | 'resume', outcome: 'accepted' | 'refused', reason: string }[] = []
81 let operatorSequence = 0, operatorHold = false, currentAtMs: number | null = null, nextAtMs = 0, terminal = false, closed = false, stepping = false
82 let maximumMassErrorKg = 0, massSamples = 0
83 const transitions: { atMs: number, from: Owner, to: Owner }[] = []
84 let sourceRelease: { atMs: number, eventId: string, event: Release } | null = null, finalRelease: { atMs: number, eventId: string, event: Release } | null = null
85 let stationDeparture: Departure | null = null
86 let intake: { atMs: number, grant: ModeledCargoIntakeGrant, attachment: PointLoadAttachment, source: Progress, receiver: Progress } | null = null
87 let intakeEvidence: { atMs: number, eventId: string, sourceEventId: string, outcome: string, massKg: number } | null = null
88 const commands: { source: VehiclePayloadCommand | null, receiver: VehiclePayloadCommand | null, intake: ModeledCargoIntakeGrant | null } = { source: null, receiver: null, intake: null }
89 let progressA: Progress | null = null, progressB: Progress | null = null
90 const sourceCoordinator = createCargoDeliveryCoordinator({ origin, site: stationSite, releaseHeightM: 1 }, {
91 evidence: 'modeled-cargo-mechanism', request(command) { commands.source = structuredClone(command) }, cancel(eventId) { if (commands.source?.eventId === eventId) commands.source = null },
92 })
93 const deliveryCoordinator = createCargoDeliveryCoordinator({ origin, site: finalSite, releaseHeightM: 1 }, {
94 evidence: 'modeled-cargo-mechanism', request(command) { commands.receiver = structuredClone(command) }, cancel(eventId) { if (commands.receiver?.eventId === eventId) commands.receiver = null },
95 })
96 const intakeCoordinator = createCargoIntakeCoordinator({ origin, padM: receiverPadM, receiverId: 'carrier-b', containerId: point.id, massKg: point.massKg, bootId: 102n, sessionId: 202n }, {
97 evidence: 'modeled-cargo-intake-mechanism', request(grant) { commands.intake = structuredClone(grant); if (faultInjection && ['receiver-host-loss-before-intake', 'receiver-joint-shift-before-intake'].includes(faultInjection.scenario)) faultInjection.anchoredAtMs = grant.issuedAtMs }, cancel(eventId) { if (commands.intake?.command.eventId === eventId) commands.intake = null },
98 })
99 let activeBPort: VehiclePayloadPort | null = null
100 const receiverPort: VehiclePayloadPort = {
101 observe(c) { intakeCoordinator.port.observe!(c); deliveryCoordinator.port.observe!(c) },
102 request(command) { activeBPort = command.operation === 'material-receive' ? intakeCoordinator.port : deliveryCoordinator.port; activeBPort.request(command) },
103 poll(nowMs) { const ack = activeBPort?.poll(nowMs) ?? null; if (ack) activeBPort = null; return ack },
104 close() { activeBPort = null; intakeCoordinator.port.close(); deliveryCoordinator.port.close() },
105 }
106 function linksFor(scope: VehicleLinkScope, receiver: boolean) {
107 const monitor = createRedundantVehicleLinks(scope), queue: { sourceId: VehicleLinkSource, sequence: number, capturedAtMs: number, receivedAtMs: number }[] = []
108 let sequence = 0, last = monitor.snapshot(0)
109 const events: typeof last[] = []
110 return {
111 observe(nowMs: number) {
112 sequence++
113 if (receiver && faultInjection && ['receiver-primary-link-loss', 'receiver-both-links-loss'].includes(faultInjection.scenario) && faultInjection.anchoredAtMs === null && station?.snapshot().phase === 'held') faultInjection.anchoredAtMs = nowMs
114 for (const sourceId of ['primary', 'backup'] as const) {
115 if (receiver && faultInjection && ['receiver-primary-link-loss', 'receiver-both-links-loss'].includes(faultInjection.scenario) && (sourceId === 'primary' || faultInjection.scenario === 'receiver-both-links-loss') && faultInjection.anchoredAtMs !== null && nowMs >= faultInjection.anchoredAtMs) { faultInjection.triggeredAtMs ??= nowMs; continue }
116 if (queue.length >= 8) throw new RangeError('cargo-fleet-link-queue')
117 queue.push({ sourceId, sequence, capturedAtMs: nowMs, receivedAtMs: nowMs + (sourceId === 'primary' ? 20 : 40) })
118 }
119 queue.sort((a, b) => a.receivedAtMs - b.receivedAtMs)
120 while (queue[0] && queue[0].receivedAtMs <= nowMs) monitor.ingest({ ...scope, ...queue.shift()!, clockUncertaintyMs: 1, connected: true }, nowMs)
121 last = monitor.snapshot(nowMs)
122 const previous = events.at(-1)
123 if (!previous || last.selectedSource !== previous.selectedSource || last.latchedLoss !== previous.latchedLoss) { if (events.length >= 16) throw new RangeError('cargo-fleet-link-events'); events.push(structuredClone(last)) }
124 return { ...last.authority }
125 },
126 snapshot: () => structuredClone(last), events: () => structuredClone(events),
127 }
128 }
129 const linksA = linksFor({ vehicleId: 'carrier-a', bootId: 101, sessionId: 201 }, false), linksB = linksFor({ vehicleId: 'carrier-b', bootId: 102, sessionId: 202 }, true)
130 const profileA = createMultirotorProfile(), profileB = createMultirotorProfile(), createA = profileA.createSession, createB = profileB.createSession
131 profileA.mission = planCargoDelivery({ version: 1, id: 'cargo-fleet-source', delivery: { origin, site: stationSite, releaseHeightM: 1 }, load: { massKg: point.massKg, forwardM: point.forwardM }, alternateM: [1.5, -2, 0], power: { availableWh: 40, maxW: 600, reservePercent: 30 } }).mission
132 profileB.mission = receiverMission()
133 if (scenario === 'receiver-containment-breach-after-intake-receipt') profileB.positionPrediction = 'fixture-imu'
134 const baseFaultsA = profileA.faults
135 if (scenario === 'source-kill-after-station-receipt') {
136 profileA.scenario = scenario; profileA.scenarios = [scenario]
137 profileA.faults = (selected, atMs, phase) => {
138 if (selected !== scenario) throw new TypeError('cargo-fleet-scenario-changed')
139 const killed = faultInjection!.anchoredAtMs !== null && atMs > faultInjection!.anchoredAtMs
140 if (killed && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
141 return { ...baseFaultsA('nominal', atMs, phase), kill: killed }
142 }
143 }
144 const baseFaultsB = profileB.faults
145 profileB.scenario = scenario; profileB.scenarios = [scenario]
146 profileB.faults = (selected, atMs, phase) => {
147 if (selected !== scenario) throw new TypeError('cargo-fleet-scenario-changed')
148 const active = faultInjection?.scenario === 'receiver-host-loss-before-intake' && faultInjection.anchoredAtMs !== null && atMs >= faultInjection.anchoredAtMs + 4
149 if (active && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
150 const navigationLost = faultInjection?.scenario === 'receiver-navigation-loss-during-rail' && faultInjection.anchoredAtMs !== null && atMs > faultInjection.anchoredAtMs
151 if (navigationLost && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
152 const killed = faultInjection?.scenario === 'receiver-kill-after-intake' && faultInjection.anchoredAtMs !== null && atMs > faultInjection.anchoredAtMs
153 if (killed && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
154 return { ...baseFaultsB('nominal', atMs, phase), hostLost: active, dropPosition: navigationLost, kill: killed }
155 }
156 const plantA = createMultirotorPlant(bodyA), adaptedB = createMultirotorPlant(bodyB)
157 let receiverPhysicalAtMs = 600
158 const plantB: VehiclePlant = { snapshot: adaptedB.snapshot, step(actuators, dtS, environment) {
159 if (dtS !== .004) throw new RangeError('cargo-fleet-receiver-step')
160 receiverPhysicalAtMs += 4
161 const shift = faultInjection?.scenario === 'receiver-joint-shift-before-intake' && faultInjection.anchoredAtMs !== null && receiverPhysicalAtMs === faultInjection.anchoredAtMs + 4
162 if (shift) faultInjection!.triggeredAtMs = receiverPhysicalAtMs
163 const containment = faultInjection && ['receiver-pad-motion-during-rail', 'receiver-containment-breach-after-intake-receipt'].includes(faultInjection.scenario) && faultInjection.anchoredAtMs !== null && receiverPhysicalAtMs > faultInjection.anchoredAtMs
164 if (containment) faultInjection!.triggeredAtMs ??= receiverPhysicalAtMs
165 bodyB.step(actuators as [number, number, number, number], dtS, { windMps: environment.windMps, ...(shift || containment ? { forceN: shift ? [.4, 0, 0] as SensorVector : faultInjection!.forceN!.map(n => n * Math.min(1, (receiverPhysicalAtMs - faultInjection!.anchoredAtMs!) / (faultInjection!.forceRampMs ?? 4))) as SensorVector } : {}) })
166 return adaptedB.snapshot()
167 } }
168 function releaseValues(which: 'source' | 'receiver') {
169 const released = which === 'source' ? sourceRelease : finalRelease, target = which === 'source' ? station : recipient, site = which === 'source' ? stationSite : finalSite
170 const impact = target?.snapshot().impact
171 const captured = !!impact && impact.positionM[2] === site.positionM[2] && Math.hypot(impact.positionM[0] - site.positionM[0], impact.positionM[1] - site.positionM[1]) <= site.radiusM
172 return { siteId: site.id, recipientId: site.recipientId, siteClear: true, recipientPresent: true, loadAttached: which === 'source' ? bodyA.loadSnapshot().properties.phase === 'attached' : bodyB.loadSnapshot().properties.phase === 'attached', mechanismOpen: released?.event.outcome === 'separated', mechanismJammed: false, mechanismEventId: released?.eventId ?? '', receiptEventId: captured ? released?.eventId ?? '' : '', receiptContainerId: point.id }
173 }
174 profileA.createSession = (): VehicleSession => {
175 const base = createA()
176 return { ...base, linkObservation: linksA.observe, createPlant: () => plantA, createPayload: () => sourceCoordinator.port, renderMeasurement(state, atMs, reference) { const packet = base.renderMeasurement(state, atMs, reference); return { ...packet, values: { ...packet.values, ...releaseValues('source') } } } }
177 }
178 profileB.createSession = (): VehicleSession => {
179 const base = createB()
180 return { ...base, linkObservation: linksB.observe, createPlant: () => plantB, createPayload: () => receiverPort, renderMeasurement(state, atMs, reference) {
181 const packet = base.renderMeasurement(state, atMs, reference)
182 const suppressReceipt = faultInjection?.scenario === 'intake-receipt-loss' && intakeEvidence !== null
183 if (suppressReceipt) faultInjection!.triggeredAtMs ??= atMs
184 const evidence = suppressReceipt ? null : intakeEvidence
185 return { ...packet, values: { ...packet.values, ...releaseValues('receiver'), receiverId: 'carrier-b', stationReady: station?.snapshot().phase === 'ready', stationContainerId: point.id, stationSourceEventId: sourceRelease?.eventId ?? '',
186 intakeAtMs: evidence?.atMs ?? -1, intakeEventId: evidence?.eventId ?? '', intakeSourceEventId: evidence?.sourceEventId ?? '', intakeOutcome: evidence?.outcome ?? '', intakeMassKg: evidence?.massKg ?? 0 } }
187 } }
188 }
189 const a = createVehicleSimulationSession(profileA, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 101n, sessionId: 201n } })
190 const b = createVehicleSimulationSession(profileB, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 102n, sessionId: 202n } })
191 function changeOwner(next: Owner, nowMs: number) { transitions.push({ atMs: nowMs, from: physical.owner, to: next }); physical.owner = next }
192 function totalMass() { return bodyA.loadSnapshot().properties.totalMassKg + bodyB.loadSnapshot().properties.totalMassKg + (station?.snapshot().ownedMassKg ?? 0) + (recipient?.snapshot().ownedMassKg ?? 0) + (loose?.snapshot().ownedMassKg ?? 0) }
193 function sampleMass() { maximumMassErrorKg = Math.max(maximumMassErrorKg, Math.abs(totalMass() - 3.1)); massSamples++ }
194 sampleMass()
195 function advance(nowMs: number) {
196 if (!progressA?.terminal) progressA = a.step(nowMs)
197 if (!progressB?.terminal) progressB = b.step(nowMs)
198 if (faultInjection?.scenario === 'source-kill-after-station-receipt' && faultInjection.anchoredAtMs === null) {
199 const receipt = sourceCoordinator.snapshot().delivery
200 if (receipt.outcome === 'received') faultInjection.anchoredAtMs = receipt.acknowledgedAtMs
201 }
202 if (faultInjection?.scenario === 'receiver-containment-breach-after-intake-receipt' && faultInjection.anchoredAtMs === null) {
203 const receipt = intakeCoordinator.snapshot().custody
204 if (receipt.outcome === 'received') faultInjection.anchoredAtMs = receipt.acknowledgedAtMs
205 }
206 if (station && station.snapshot().atMs < nowMs) station.step(nowMs)
207 if (recipient && recipient.snapshot().atMs < nowMs) recipient.step(nowMs)
208 if (loose && loose.snapshot().atMs < nowMs) loose.step(nowMs)
209 if (commands.source && nowMs > commands.source.issuedAtMs) {
210 const command = commands.source; commands.source = null
211 if (physical.owner === 'source-body' && hasAuthority(progressA, command, nowMs, 101n, 201n)) {
212 const event = bodyA.separateCarriedLoad(); sourceRelease = { atMs: nowMs, eventId: command.eventId, event }
213 if (event.outcome === 'separated') {
214 station = createCargoStationHandler({ atMs: nowMs, parcel: { id: point.id, ...event.parcel }, pickup: { centerM: stationSite.positionM, radiusM: stationSite.radiusM }, destinationM: bodyB.intakePoint().positionM, maxSpeedMps: .5, maxAccelerationMps2: 1 })
215 changeOwner('station-actor', nowMs); sampleMass()
216 }
217 }
218 }
219 if (!operatorHold && station?.snapshot().phase === 'held' && sourceCoordinator.snapshot().delivery.outcome === 'received' && progressB?.mission.payload?.operation === 'material-receive' && hasAuthority(progressB, progressB.mission.payload, nowMs, 102n, 202n)) {
220 station.start()
221 if (faultInjection && ['receiver-navigation-loss-during-rail', 'receiver-pad-motion-during-rail'].includes(faultInjection.scenario)) faultInjection.anchoredAtMs ??= nowMs
222 }
223 if (station && ['falling', 'held', 'moving', 'ready'].includes(station.snapshot().phase) && progressB && (!progressB.hostAvailable || progressB.authority.state !== 'autonomous')) station.cancel()
224 if (commands.intake && nowMs > commands.intake.issuedAtMs) {
225 const grant = commands.intake; commands.intake = null
226 if (physical.owner === 'station-actor' && station?.snapshot().phase === 'ready' && sourceRelease?.eventId === grant.sourceEventId && grant.receiverId === 'carrier-b' && grant.bootId === 102n && grant.sessionId === 202n && nowMs < grant.expiresAtMs
227 && hasAuthority(progressB, grant.command, nowMs, grant.bootId, grant.sessionId) && progressB!.board.actuators.every(n => n === 0) && bodyB.snapshot().motorsN.every(n => n < .01)) {
228 const departure = station.takeReadyParcel()
229 if (departure.outcome === 'departed') {
230 stationDeparture = departure
231 const attachment = bodyB.attachParcel(departure.parcel)
232 intake = { atMs: nowMs, grant, attachment, source: structuredClone(progressA!), receiver: structuredClone(progressB!) }
233 intakeEvidence = { atMs: nowMs, eventId: grant.command.eventId, sourceEventId: grant.sourceEventId, outcome: attachment.outcome, massKg: attachment.outcome === 'attached' ? attachment.parcel.massKg : 0 }
234 if (attachment.outcome === 'attached') { loose = null; changeOwner('receiver-body', nowMs); if (faultInjection && ['intake-receipt-loss', 'receiver-kill-after-intake'].includes(faultInjection.scenario)) faultInjection.anchoredAtMs = nowMs }
235 else { loose = createCargoStationHandler({ atMs: nowMs, parcel: departure.parcel, pickup: { centerM: [3, 2, 0], radiusM: 2 }, destinationM: [3, 2, 0], maxSpeedMps: .5, maxAccelerationMps2: 1 }); changeOwner('loose-parcel', nowMs) }
236 sampleMass()
237 }
238 }
239 }
240 if (commands.receiver && nowMs > commands.receiver.issuedAtMs) {
241 const command = commands.receiver; commands.receiver = null
242 if (physical.owner === 'receiver-body' && hasAuthority(progressB, command, nowMs, 102n, 202n)) {
243 const event = bodyB.separateCarriedLoad(); finalRelease = { atMs: nowMs, eventId: command.eventId, event }
244 if (event.outcome === 'separated') {
245 recipient = createCargoStationHandler({ atMs: nowMs, parcel: { id: point.id, ...event.parcel }, pickup: { centerM: finalSite.positionM, radiusM: finalSite.radiusM }, destinationM: finalSite.positionM, maxSpeedMps: .5, maxAccelerationMps2: 1 })
246 changeOwner('final-parcel-actor', nowMs); sampleMass()
247 }
248 }
249 }
250 if (nowMs % 20 === 0) sampleMass()
251 }
252 function close() {
253 if (closed) return
254 const interrupted = !terminal
255 closed = true
256 if (interrupted) { terminal = true; station?.cancel(); commands.intake = null }
257 try { a.close() }
258 finally {
259 try { b.close() }
260 finally {
261 // Closing revokes the boards now. Keep the last observation/policy clocks
262 // and physical point, but do not expose their previously powered output.
263 if (interrupted) {
264 const source = a.result(), receiver = b.result()
265 if (progressA) progressA = { ...progressA, hostAvailable: false, terminal: true, board: source.board, authority: source.authority, mission: source.mission }
266 if (progressB) progressB = { ...progressB, hostAvailable: false, terminal: true, board: receiver.board, authority: receiver.authority, mission: receiver.mission }
267 }
268 }
269 }
270 }
271 function step(nowMs: number, ...extra: unknown[]) {
272 if (closed || terminal) throw new Error('Cargo fleet session is closed')
273 if (stepping) throw new Error('Cargo fleet session is already stepping')
274 if (extra.length || !Number.isSafeInteger(nowMs) || nowMs !== nextAtMs || nowMs > 181000) throw new RangeError('cargo-fleet-clock')
275 stepping = true
276 try {
277 currentAtMs = nowMs; advance(nowMs); nextAtMs += 4
278 terminal = !!progressA?.terminal && !!progressB?.terminal
279 return { atMs: nowMs, terminal }
280 }
281 catch (error) { close(); throw error }
282 finally { stepping = false }
283 }
284 function snapshot() {
285 return structuredClone({ atMs: currentAtMs, terminal, closed, source: progressA, receiver: progressB, station: station?.snapshot() ?? null, stationSourceEventId: sourceRelease?.eventId ?? null, intake: intakeCoordinator.snapshot(),
286 ownership: { owner: physical.owner, totalMassKg: totalMass() }, operator: { contextId: operatorContextId, identityAuthenticated: false as const, lastSequence: operatorSequence, hold: operatorHold, events: operatorEvents } })
287 }
288 function decide(input: unknown, ...extra: unknown[]): { outcome: 'accepted' | 'refused', reason: string } {
289 if (closed || terminal || stepping) return { outcome: 'refused', reason: 'session-unavailable' }
290 let decision: Record<string, unknown>
291 try {
292 const fields = ['version', 'evidence', 'contextId', 'bootId', 'sessionId', 'sequence', 'issuedAtMs', 'reference', 'sourceEventId', 'action']
293 if (extra.length || !input || typeof input !== 'object' || Object.getPrototypeOf(input) !== Object.prototype || Reflect.ownKeys(input).length !== fields.length) throw new TypeError()
294 decision = {}
295 for (const key of fields) { const d = Object.getOwnPropertyDescriptor(input, key); if (!d?.enumerable || !Object.hasOwn(d, 'value')) throw new TypeError(); decision[key] = d.value }
296 if (decision.version !== 1 || decision.evidence !== 'modeled-cargo-transport-decision-v1' || typeof decision.contextId !== 'string' || decision.contextId.length > 80
297 || typeof decision.bootId !== 'bigint' || typeof decision.sessionId !== 'bigint' || !Number.isSafeInteger(decision.sequence) || (decision.sequence as number) < 1 || (decision.sequence as number) > 32
298 || !Number.isSafeInteger(decision.issuedAtMs) || (decision.issuedAtMs as number) < 0 || typeof decision.reference !== 'string' || decision.reference.length > 120
299 || typeof decision.sourceEventId !== 'string' || decision.sourceEventId.length > 160 || !['cancel', 'resume'].includes(decision.action as string)) throw new TypeError()
300 }
301 catch { throw new TypeError('cargo-fleet-operator-declaration') }
302 if (closed || terminal || stepping) return { outcome: 'refused', reason: 'session-unavailable' }
303 if (decision.contextId !== operatorContextId || decision.bootId !== 102n || decision.sessionId !== 202n || decision.reference !== progressB?.reference || decision.sourceEventId !== sourceRelease?.eventId) return { outcome: 'refused', reason: 'operator-scope' }
304 if (decision.issuedAtMs !== currentAtMs) return { outcome: 'refused', reason: 'operator-clock' }
305 if (decision.sequence !== operatorSequence + 1 || operatorEvents.length >= 32) return { outcome: 'refused', reason: 'operator-sequence' }
306 operatorSequence = decision.sequence as number
307 const action = decision.action as 'cancel' | 'resume'
308 const record = (outcome: 'accepted' | 'refused', reason: string) => { operatorEvents.push({ atMs: currentAtMs!, sequence: operatorSequence, action, outcome, reason }); return { outcome, reason } }
309 if (physical.owner !== 'station-actor' || !station) return record('refused', 'parcel-not-at-station')
310 if (action === 'cancel') {
311 const result = station.cancel()
312 if (result.outcome === 'refused') return record('refused', 'station-' + result.reason)
313 commands.intake = null; operatorHold = true
314 return record('accepted', 'transport-cancellation-requested')
315 }
316 const command = progressB?.mission.payload
317 if (!operatorHold || !command || command.operation !== 'material-receive' || !hasAuthority(progressB, command, currentAtMs!, 102n, 202n) || sourceCoordinator.snapshot().delivery.outcome !== 'received') return record('refused', 'recovery-authority-unavailable')
318 if (intakeCoordinator.snapshot().custody.grantedAtMs !== null) return record('refused', 'intake-already-attempted')
319 const result = station.resume()
320 if (result.outcome === 'refused') return record('refused', 'station-' + result.reason)
321 operatorHold = false
322 return record('accepted', 'transport-resumed')
323 }
324 function result() {
325 if (!terminal) throw new Error('Cargo fleet session is still active')
326 const sourceRun = a.result(), receiverRun = b.result(), sourceDelivery = sourceCoordinator.snapshot().delivery, receiverDelivery = deliveryCoordinator.snapshot().delivery, receiverIntake = intakeCoordinator.snapshot()
327 const completed = sourceRun.status === 'completed' && receiverRun.status === 'completed' && sourceDelivery.outcome === 'received' && receiverIntake.custody.outcome === 'received' && receiverDelivery.outcome === 'received' && physical.owner === 'final-parcel-actor' && recipient?.snapshot().phase === 'held' && maximumMassErrorKg < 1e-12
328 return structuredClone({ version: 1, evidence: 'owned-cargo-fleet-simulation' as const, scenario, faultInjection, physicalFlightEnabled: false as const, boardOutputsInhibited: true as const, identityAuthenticated: false as const, status: completed ? 'completed' as const : 'unqualified' as const,
329 source: { links: linksA.snapshot(), linkEvents: linksA.events(), initialLoad: initialA, finalLoad: bodyA.loadSnapshot(), runtime: sourceRun, delivery: sourceDelivery }, receiver: { links: linksB.snapshot(), linkEvents: linksB.events(), initialLoad: initialB, finalLoad: bodyB.loadSnapshot(), runtime: receiverRun, intake: receiverIntake, delivery: receiverDelivery },
330 transfer: { sourceRelease, stationDeparture, intake, finalRelease }, station: station?.snapshot() ?? null, recipient: recipient?.snapshot() ?? null, loose: loose?.snapshot() ?? null, ownership: { owner: physical.owner, initialMassKg: 3.1, finalMassKg: totalMass(), maximumMassErrorKg, samples: massSamples, transitions }, ...(operatorEvents.length ? { operator: { contextId: operatorContextId, identityAuthenticated: false as const, events: operatorEvents } } : {}) })
331 }
332 return { step, snapshot, decide, result, close }
333}
334
335/** Finite one-shot facade over the same retained shared world. */
336export function simulateCargoFleet(input: unknown = {}, ...extra: unknown[]) {
337 const world = createCargoFleetSession(input, ...extra)
338 try {
339 for (let nowMs = 0; ; nowMs += 4) if (world.step(nowMs).terminal) return world.result()
340 }
341 finally { world.close() }
342}
343
344/** Compact actual observations for Buddy/standalone output; never serialize the full runtime journal. */
345export function cargoFleetSummary(run: ReturnType<typeof simulateCargoFleet>) {
346 function vehicle(runtime: typeof run.source.runtime) {
347 const power = runtime.trace.plan.power, usableWh = power.availableWh * (1 - power.reservePercent / 100)
348 return { scope: { bootId: String(runtime.board.bootId), sessionId: String(runtime.authority.sessionId) }, status: runtime.status, fault: runtime.fault, missionState: runtime.mission.state, missionReason: runtime.mission.reason, payloadFailure: runtime.mission.payloadFailure ?? null,
349 finalPositionM: runtime.finalTruthPositionM, sensors: runtime.navigationEvidence.observedSensors, board: { physicalActuationEnabled: runtime.board.physicalActuationEnabled, actuators: runtime.board.actuators, fault: runtime.board.fault, expiresAtMs: runtime.board.expiresAtMs },
350 energy: { evidence: 'declared-mission-power-budget', measured: false, electricalModel: false, availableWh: power.availableWh, maxW: power.maxW, reservePercent: power.reservePercent, worstCaseMs: runtime.budget.worstCaseMs, requiredWh: runtime.budget.requiredWh, marginAboveReserveWh: usableWh - runtime.budget.requiredWh } }
351 }
352 const capturedIntake = run.transfer.intake, attachment = capturedIntake?.attachment
353 const release = (event: typeof run.transfer.sourceRelease) => event ? { atMs: event.atMs, eventId: event.eventId, outcome: event.event.outcome } : null
354 return { version: run.version, evidence: run.evidence, scenario: run.scenario, status: run.status, physicalFlightEnabled: run.physicalFlightEnabled, boardOutputsInhibited: run.boardOutputsInhibited, identityAuthenticated: run.identityAuthenticated,
355 faultInjection: run.faultInjection, source: { links: run.source.links, linkEvents: run.source.linkEvents, ...vehicle(run.source.runtime), initialLoad: run.source.initialLoad.properties, finalLoad: run.source.finalLoad.properties, delivery: run.source.delivery },
356 receiver: { links: run.receiver.links, linkEvents: run.receiver.linkEvents, ...vehicle(run.receiver.runtime), initialLoad: run.receiver.initialLoad.properties, finalLoad: run.receiver.finalLoad.properties, intake: run.receiver.intake.custody, delivery: run.receiver.delivery },
357 transfer: { sourceRelease: release(run.transfer.sourceRelease), stationDeparture: run.transfer.stationDeparture, intake: capturedIntake ? { atMs: capturedIntake.atMs, outcome: attachment!.outcome, eventId: capturedIntake.grant.command.eventId, sourceEventId: capturedIntake.grant.sourceEventId,
358 receiverScope: { bootId: String(capturedIntake.receiver.authority.bootId), sessionId: String(capturedIntake.receiver.authority.sessionId), epoch: capturedIntake.receiver.authority.epoch, reference: capturedIntake.receiver.reference, policyAtMs: capturedIntake.receiver.policyAtMs },
359 massBeforeKg: attachment!.outcome === 'attached' ? attachment!.before.properties.totalMassKg : null, massAfterKg: attachment!.outcome === 'attached' ? attachment!.after.properties.totalMassKg : null } : null, finalRelease: release(run.transfer.finalRelease) },
360 station: run.station, recipient: run.recipient, loose: run.loose, ownership: run.ownership, ...(run.operator ? { operator: run.operator } : {}) }
361}