also looking at this
feat: coordinate modeled two-carrier cargo handover
#103
25 files
+1654
-13
| @@ -0,0 +1,237 @@ | ||
| 1 | import type { SensorVector } from '../sensors/types' | |
| 2 | import type { PointLoadAttachment } from '../controls/physics' | |
| 3 | import type { VehiclePayloadCommand, VehiclePayloadPort, VehiclePlant, VehicleMissionPlan, VehicleSession } from '../vehicles/types' | |
| 4 | import type { ModeledCargoIntakeGrant } from './intake' | |
| 5 | import { createRigidBody, createReceivingRigidBody } from '../controls/physics' | |
| 6 | import { createMultirotorPlant, createMultirotorProfile } from '../vehicles/multirotor/profile' | |
| 7 | import { createRedundantVehicleLinks } from '../vehicles/links' | |
| 8 | import type { VehicleLinkScope, VehicleLinkSource } from '../vehicles/links' | |
| 9 | import { createVehicleSimulationSession } from '../vehicles/runtime' | |
| 10 | import { createCargoStationHandler } from './station' | |
| 11 | import { createCargoDeliveryCoordinator } from './coordinator' | |
| 12 | import { createCargoIntakeCoordinator } from './intake' | |
| 13 | import { planCargoDelivery } from './plan' | |
| 14 | ||
| 15 | type Progress = ReturnType<ReturnType<typeof createVehicleSimulationSession>['step']> | |
| 16 | type Station = ReturnType<typeof createCargoStationHandler> | |
| 17 | type Release = ReturnType<ReturnType<typeof createReceivingRigidBody>['separateCarriedLoad']> | |
| 18 | type Departure = Extract<ReturnType<Station['takeReadyParcel']>, { outcome: 'departed' }> | |
| 19 | type Owner = 'source-body' | 'station-actor' | 'receiver-body' | 'final-parcel-actor' | 'loose-parcel' | |
| 20 | export const cargoFleetScenarios = ['nominal', 'receiver-host-loss-before-intake', 'intake-receipt-loss', 'receiver-primary-link-loss', 'receiver-both-links-loss', 'receiver-joint-shift-before-intake'] as const | |
| 21 | export type CargoFleetScenario = typeof cargoFleetScenarios[number] | |
| 22 | function captureScenario(input: unknown): CargoFleetScenario { | |
| 23 | try { | |
| 24 | if (!input || typeof input !== 'object' || Object.getPrototypeOf(input) !== Object.prototype || Reflect.ownKeys(input).some(key => key !== 'scenario')) throw new TypeError() | |
| 25 | const d = Object.getOwnPropertyDescriptor(input, 'scenario') | |
| 26 | if (d && (!d.enumerable || !Object.hasOwn(d, 'value') || !cargoFleetScenarios.some(name => name === d.value))) throw new TypeError() | |
| 27 | return (d?.value ?? 'nominal') as CargoFleetScenario | |
| 28 | } | |
| 29 | catch { throw new TypeError('cargo-fleet-arguments') } | |
| 30 | } | |
| 31 | const origin = { latitudeDeg: 0, longitudeDeg: 0, ellipsoidHeightM: 100 } | |
| 32 | const point = { id: 'parcel-a', massKg: .1, forwardM: .08 } | |
| 33 | const receiverPadM: SensorVector = [3, 2, -.1] | |
| 34 | const stationSite = { id: 'handover-station', recipientId: 'station-operator', containerId: point.id, positionM: [3, 0, 0] as SensorVector, radiusM: .35 } | |
| 35 | const finalSite = { id: 'final-site', recipientId: 'final-recipient', containerId: point.id, positionM: [6, 2, 0] as SensorVector, radiusM: .35 } | |
| 36 | function receiverMission(): VehicleMissionPlan { | |
| 37 | const spatial = { acceptanceM: .18, maxArrivalSpeedMps: .15, settleMs: 300, timeoutMs: 20000 } | |
| 38 | 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: [ | |
| 39 | { id: 'start', kind: 'start', next: 'intake' }, | |
| 40 | { id: 'intake', kind: 'payload', operation: 'material-receive', containerId: point.id, positionM: [...receiverPadM], timeoutMs: 60000, next: 'depart', onFailure: 'alternate-approach' }, | |
| 41 | { id: 'depart', kind: 'takeoff', positionM: [3, 2, -1], ...spatial, next: 'site' }, | |
| 42 | { id: 'site', kind: 'waypoint', positionM: [6, 2, -1], ...spatial, settleMs: 800, next: 'release' }, | |
| 43 | { id: 'release', kind: 'payload', operation: 'material-drop', containerId: point.id, timeoutMs: 1500, next: 'home', onFailure: 'alternate-approach' }, | |
| 44 | { id: 'home', kind: 'return', ...spatial, next: 'land' }, | |
| 45 | { id: 'land', kind: 'land', positionM: [3, 2, 0], ...spatial }, | |
| 46 | { id: 'alternate-approach', kind: 'waypoint', positionM: [5, 3, -1], ...spatial, next: 'alternate-land' }, | |
| 47 | { id: 'alternate-land', kind: 'land', positionM: [5, 3, 0], ...spatial }, | |
| 48 | ] } | |
| 49 | } | |
| 50 | function hasAuthority(p: Progress | null, command: VehiclePayloadCommand, nowMs: number, bootId: bigint, sessionId: bigint) { | |
| 51 | return !!p && p.atMs === nowMs && p.hostAvailable && !p.terminal && p.phase === 'host' && p.policyAtMs !== null && p.policyAtMs <= nowMs && nowMs - p.policyAtMs < 20 | |
| 52 | && p.reference === command.reference && p.authority.bootId === bootId && p.authority.sessionId === sessionId && p.authority.state === 'autonomous' | |
| 53 | && p.authority.lastCheckedAtMs !== null && nowMs - p.authority.lastCheckedAtMs < 20 && p.authority.leaseUntilMs !== null && p.authority.leaseUntilMs > nowMs && p.board.fault === null | |
| 54 | && p.mission.state === 'running' && p.mission.payload?.eventId === command.eventId && JSON.stringify(p.mission.payload) === JSON.stringify(command) && command.expiresAtMs > nowMs | |
| 55 | } | |
| 56 | ||
| 57 | /** One modeled parcel, two retained raw-sensor/estimator/authority runtimes, and finite station physics. */ | |
| 58 | export function simulateCargoFleet(input: unknown = {}, ...extra: unknown[]) { | |
| 59 | if (extra.length) throw new TypeError('cargo-fleet-arguments') | |
| 60 | const scenario = captureScenario(input) | |
| 61 | const faultInjection: { scenario: Exclude<CargoFleetScenario, 'nominal'>, anchoredAtMs: number | null, triggeredAtMs: number | null } | null = scenario === 'nominal' ? null : { scenario, anchoredAtMs: null, triggeredAtMs: null } | |
| 62 | const bodyA = createRigidBody({ positionM: [0, 0, -.1], groundDownM: -.1, carriedPointLoad: point }) | |
| 63 | const bodyB = createReceivingRigidBody({ positionM: [...receiverPadM], groundDownM: -.1, expectedPointLoad: point }) | |
| 64 | const initialA = bodyA.loadSnapshot(), initialB = bodyB.loadSnapshot() | |
| 65 | let station: Station | null = null, recipient: Station | null = null, loose: Station | null = null | |
| 66 | const physical: { owner: Owner } = { owner: 'source-body' } | |
| 67 | let maximumMassErrorKg = 0, massSamples = 0 | |
| 68 | const transitions: { atMs: number, from: Owner, to: Owner }[] = [] | |
| 69 | let sourceRelease: { atMs: number, eventId: string, event: Release } | null = null, finalRelease: { atMs: number, eventId: string, event: Release } | null = null | |
| 70 | let stationDeparture: Departure | null = null | |
| 71 | let intake: { atMs: number, grant: ModeledCargoIntakeGrant, attachment: PointLoadAttachment, source: Progress, receiver: Progress } | null = null | |
| 72 | let intakeEvidence: { atMs: number, eventId: string, sourceEventId: string, outcome: string, massKg: number } | null = null | |
| 73 | const commands: { source: VehiclePayloadCommand | null, receiver: VehiclePayloadCommand | null, intake: ModeledCargoIntakeGrant | null } = { source: null, receiver: null, intake: null } | |
| 74 | let progressA: Progress | null = null, progressB: Progress | null = null | |
| 75 | const sourceCoordinator = createCargoDeliveryCoordinator({ origin, site: stationSite, releaseHeightM: 1 }, { | |
| 76 | evidence: 'modeled-cargo-mechanism', request(command) { commands.source = structuredClone(command) }, cancel(eventId) { if (commands.source?.eventId === eventId) commands.source = null }, | |
| 77 | }) | |
| 78 | const deliveryCoordinator = createCargoDeliveryCoordinator({ origin, site: finalSite, releaseHeightM: 1 }, { | |
| 79 | evidence: 'modeled-cargo-mechanism', request(command) { commands.receiver = structuredClone(command) }, cancel(eventId) { if (commands.receiver?.eventId === eventId) commands.receiver = null }, | |
| 80 | }) | |
| 81 | const intakeCoordinator = createCargoIntakeCoordinator({ origin, padM: receiverPadM, receiverId: 'carrier-b', containerId: point.id, massKg: point.massKg, bootId: 102n, sessionId: 202n }, { | |
| 82 | 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 }, | |
| 83 | }) | |
| 84 | let activeBPort: VehiclePayloadPort | null = null | |
| 85 | const receiverPort: VehiclePayloadPort = { | |
| 86 | observe(c) { intakeCoordinator.port.observe!(c); deliveryCoordinator.port.observe!(c) }, | |
| 87 | request(command) { activeBPort = command.operation === 'material-receive' ? intakeCoordinator.port : deliveryCoordinator.port; activeBPort.request(command) }, | |
| 88 | poll(nowMs) { const ack = activeBPort?.poll(nowMs) ?? null; if (ack) activeBPort = null; return ack }, | |
| 89 | close() { activeBPort = null; intakeCoordinator.port.close(); deliveryCoordinator.port.close() }, | |
| 90 | } | |
| 91 | function linksFor(scope: VehicleLinkScope, receiver: boolean) { | |
| 92 | const monitor = createRedundantVehicleLinks(scope), queue: { sourceId: VehicleLinkSource, sequence: number, capturedAtMs: number, receivedAtMs: number }[] = [] | |
| 93 | let sequence = 0, last = monitor.snapshot(0) | |
| 94 | const events: typeof last[] = [] | |
| 95 | return { | |
| 96 | observe(nowMs: number) { | |
| 97 | sequence++ | |
| 98 | if (receiver && faultInjection && ['receiver-primary-link-loss', 'receiver-both-links-loss'].includes(faultInjection.scenario) && faultInjection.anchoredAtMs === null && station?.snapshot().phase === 'held') faultInjection.anchoredAtMs = nowMs | |
| 99 | for (const sourceId of ['primary', 'backup'] as const) { | |
| 100 | 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 } | |
| 101 | if (queue.length >= 8) throw new RangeError('cargo-fleet-link-queue') | |
| 102 | queue.push({ sourceId, sequence, capturedAtMs: nowMs, receivedAtMs: nowMs + (sourceId === 'primary' ? 20 : 40) }) | |
| 103 | } | |
| 104 | queue.sort((a, b) => a.receivedAtMs - b.receivedAtMs) | |
| 105 | while (queue[0] && queue[0].receivedAtMs <= nowMs) monitor.ingest({ ...scope, ...queue.shift()!, clockUncertaintyMs: 1, connected: true }, nowMs) | |
| 106 | last = monitor.snapshot(nowMs) | |
| 107 | const previous = events.at(-1) | |
| 108 | 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)) } | |
| 109 | return { ...last.authority } | |
| 110 | }, | |
| 111 | snapshot: () => structuredClone(last), events: () => structuredClone(events), | |
| 112 | } | |
| 113 | } | |
| 114 | const linksA = linksFor({ vehicleId: 'carrier-a', bootId: 101, sessionId: 201 }, false), linksB = linksFor({ vehicleId: 'carrier-b', bootId: 102, sessionId: 202 }, true) | |
| 115 | const profileA = createMultirotorProfile(), profileB = createMultirotorProfile(), createA = profileA.createSession, createB = profileB.createSession | |
| 116 | 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 | |
| 117 | profileB.mission = receiverMission() | |
| 118 | const baseFaultsB = profileB.faults | |
| 119 | profileB.scenario = scenario; profileB.scenarios = [scenario] | |
| 120 | profileB.faults = (selected, atMs, phase) => { | |
| 121 | if (selected !== scenario) throw new TypeError('cargo-fleet-scenario-changed') | |
| 122 | const active = faultInjection?.scenario === 'receiver-host-loss-before-intake' && faultInjection.anchoredAtMs !== null && atMs >= faultInjection.anchoredAtMs + 4 | |
| 123 | if (active && phase === 'host') faultInjection!.triggeredAtMs ??= atMs | |
| 124 | return { ...baseFaultsB('nominal', atMs, phase), hostLost: active } | |
| 125 | } | |
| 126 | const plantA = createMultirotorPlant(bodyA), adaptedB = createMultirotorPlant(bodyB) | |
| 127 | let receiverPhysicalAtMs = 600 | |
| 128 | const plantB: VehiclePlant = { snapshot: adaptedB.snapshot, step(actuators, dtS, environment) { | |
| 129 | if (dtS !== .004) throw new RangeError('cargo-fleet-receiver-step') | |
| 130 | receiverPhysicalAtMs += 4 | |
| 131 | const shift = faultInjection?.scenario === 'receiver-joint-shift-before-intake' && faultInjection.anchoredAtMs !== null && receiverPhysicalAtMs === faultInjection.anchoredAtMs + 4 | |
| 132 | if (shift) faultInjection!.triggeredAtMs = receiverPhysicalAtMs | |
| 133 | bodyB.step(actuators as [number, number, number, number], dtS, { windMps: environment.windMps, ...(shift ? { forceN: [.4, 0, 0] as SensorVector } : {}) }) | |
| 134 | return adaptedB.snapshot() | |
| 135 | } } | |
| 136 | function releaseValues(which: 'source' | 'receiver') { | |
| 137 | const released = which === 'source' ? sourceRelease : finalRelease, target = which === 'source' ? station : recipient, site = which === 'source' ? stationSite : finalSite | |
| 138 | const impact = target?.snapshot().impact | |
| 139 | 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 | |
| 140 | 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 } | |
| 141 | } | |
| 142 | profileA.createSession = (): VehicleSession => { | |
| 143 | const base = createA() | |
| 144 | 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') } } } } | |
| 145 | } | |
| 146 | profileB.createSession = (): VehicleSession => { | |
| 147 | const base = createB() | |
| 148 | return { ...base, linkObservation: linksB.observe, createPlant: () => plantB, createPayload: () => receiverPort, renderMeasurement(state, atMs, reference) { | |
| 149 | const packet = base.renderMeasurement(state, atMs, reference) | |
| 150 | const suppressReceipt = faultInjection?.scenario === 'intake-receipt-loss' && intakeEvidence !== null | |
| 151 | if (suppressReceipt) faultInjection!.triggeredAtMs ??= atMs | |
| 152 | const evidence = suppressReceipt ? null : intakeEvidence | |
| 153 | return { ...packet, values: { ...packet.values, ...releaseValues('receiver'), receiverId: 'carrier-b', stationReady: station?.snapshot().phase === 'ready', stationContainerId: point.id, stationSourceEventId: sourceRelease?.eventId ?? '', | |
| 154 | intakeAtMs: evidence?.atMs ?? -1, intakeEventId: evidence?.eventId ?? '', intakeSourceEventId: evidence?.sourceEventId ?? '', intakeOutcome: evidence?.outcome ?? '', intakeMassKg: evidence?.massKg ?? 0 } } | |
| 155 | } } | |
| 156 | } | |
| 157 | const a = createVehicleSimulationSession(profileA, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 101n, sessionId: 201n } }) | |
| 158 | const b = createVehicleSimulationSession(profileB, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 102n, sessionId: 202n } }) | |
| 159 | function changeOwner(next: Owner, nowMs: number) { transitions.push({ atMs: nowMs, from: physical.owner, to: next }); physical.owner = next } | |
| 160 | function totalMass() { return bodyA.loadSnapshot().properties.totalMassKg + bodyB.loadSnapshot().properties.totalMassKg + (station?.snapshot().ownedMassKg ?? 0) + (recipient?.snapshot().ownedMassKg ?? 0) + (loose?.snapshot().ownedMassKg ?? 0) } | |
| 161 | function sampleMass() { maximumMassErrorKg = Math.max(maximumMassErrorKg, Math.abs(totalMass() - 3.1)); massSamples++ } | |
| 162 | sampleMass() | |
| 163 | try { | |
| 164 | for (let nowMs = 0; nowMs <= 181000; nowMs += 4) { | |
| 165 | if (!progressA?.terminal) progressA = a.step(nowMs) | |
| 166 | if (!progressB?.terminal) progressB = b.step(nowMs) | |
| 167 | if (station && station.snapshot().atMs < nowMs) station.step(nowMs) | |
| 168 | if (recipient && recipient.snapshot().atMs < nowMs) recipient.step(nowMs) | |
| 169 | if (loose && loose.snapshot().atMs < nowMs) loose.step(nowMs) | |
| 170 | if (commands.source && nowMs > commands.source.issuedAtMs) { | |
| 171 | const command = commands.source; commands.source = null | |
| 172 | if (physical.owner === 'source-body' && hasAuthority(progressA, command, nowMs, 101n, 201n)) { | |
| 173 | const event = bodyA.separateCarriedLoad(); sourceRelease = { atMs: nowMs, eventId: command.eventId, event } | |
| 174 | if (event.outcome === 'separated') { | |
| 175 | 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 }) | |
| 176 | changeOwner('station-actor', nowMs); sampleMass() | |
| 177 | } | |
| 178 | } | |
| 179 | } | |
| 180 | if (station?.snapshot().phase === 'held' && sourceCoordinator.snapshot().delivery.outcome === 'received' && progressB?.mission.payload?.operation === 'material-receive' && hasAuthority(progressB, progressB.mission.payload, nowMs, 102n, 202n)) station.start() | |
| 181 | if (station && ['falling', 'held', 'moving', 'ready'].includes(station.snapshot().phase) && progressB && (!progressB.hostAvailable || progressB.authority.state !== 'autonomous')) station.cancel() | |
| 182 | if (commands.intake && nowMs > commands.intake.issuedAtMs) { | |
| 183 | const grant = commands.intake; commands.intake = null | |
| 184 | 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 | |
| 185 | && hasAuthority(progressB, grant.command, nowMs, grant.bootId, grant.sessionId) && progressB!.board.actuators.every(n => n === 0) && bodyB.snapshot().motorsN.every(n => n < .01)) { | |
| 186 | const departure = station.takeReadyParcel() | |
| 187 | if (departure.outcome === 'departed') { | |
| 188 | stationDeparture = departure | |
| 189 | const attachment = bodyB.attachParcel(departure.parcel) | |
| 190 | intake = { atMs: nowMs, grant, attachment, source: structuredClone(progressA!), receiver: structuredClone(progressB!) } | |
| 191 | intakeEvidence = { atMs: nowMs, eventId: grant.command.eventId, sourceEventId: grant.sourceEventId, outcome: attachment.outcome, massKg: attachment.outcome === 'attached' ? attachment.parcel.massKg : 0 } | |
| 192 | if (attachment.outcome === 'attached') { loose = null; changeOwner('receiver-body', nowMs); if (faultInjection?.scenario === 'intake-receipt-loss') faultInjection.anchoredAtMs = nowMs } | |
| 193 | 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) } | |
| 194 | sampleMass() | |
| 195 | } | |
| 196 | } | |
| 197 | } | |
| 198 | if (commands.receiver && nowMs > commands.receiver.issuedAtMs) { | |
| 199 | const command = commands.receiver; commands.receiver = null | |
| 200 | if (physical.owner === 'receiver-body' && hasAuthority(progressB, command, nowMs, 102n, 202n)) { | |
| 201 | const event = bodyB.separateCarriedLoad(); finalRelease = { atMs: nowMs, eventId: command.eventId, event } | |
| 202 | if (event.outcome === 'separated') { | |
| 203 | recipient = createCargoStationHandler({ atMs: nowMs, parcel: { id: point.id, ...event.parcel }, pickup: { centerM: finalSite.positionM, radiusM: finalSite.radiusM }, destinationM: finalSite.positionM, maxSpeedMps: .5, maxAccelerationMps2: 1 }) | |
| 204 | changeOwner('final-parcel-actor', nowMs); sampleMass() | |
| 205 | } | |
| 206 | } | |
| 207 | } | |
| 208 | if (nowMs % 20 === 0) sampleMass() | |
| 209 | if (progressA?.terminal && progressB?.terminal) break | |
| 210 | } | |
| 211 | const sourceRun = a.result(), receiverRun = b.result(), sourceDelivery = sourceCoordinator.snapshot().delivery, receiverDelivery = deliveryCoordinator.snapshot().delivery, receiverIntake = intakeCoordinator.snapshot() | |
| 212 | 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 | |
| 213 | return { 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, | |
| 214 | 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 }, | |
| 215 | 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 } } | |
| 216 | } | |
| 217 | finally { a.close(); b.close() } | |
| 218 | } | |
| 219 | ||
| 220 | /** Compact actual observations for Buddy/standalone output; never serialize the full runtime journal. */ | |
| 221 | export function cargoFleetSummary(run: ReturnType<typeof simulateCargoFleet>) { | |
| 222 | function vehicle(runtime: typeof run.source.runtime) { | |
| 223 | const power = runtime.trace.plan.power, usableWh = power.availableWh * (1 - power.reservePercent / 100) | |
| 224 | 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, | |
| 225 | finalPositionM: runtime.finalTruthPositionM, sensors: runtime.navigationEvidence.observedSensors, board: { physicalActuationEnabled: runtime.board.physicalActuationEnabled, actuators: runtime.board.actuators, fault: runtime.board.fault, expiresAtMs: runtime.board.expiresAtMs }, | |
| 226 | 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 } } | |
| 227 | } | |
| 228 | const capturedIntake = run.transfer.intake, attachment = capturedIntake?.attachment | |
| 229 | const release = (event: typeof run.transfer.sourceRelease) => event ? { atMs: event.atMs, eventId: event.eventId, outcome: event.event.outcome } : null | |
| 230 | return { version: run.version, evidence: run.evidence, scenario: run.scenario, status: run.status, physicalFlightEnabled: run.physicalFlightEnabled, boardOutputsInhibited: run.boardOutputsInhibited, identityAuthenticated: run.identityAuthenticated, | |
| 231 | 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 }, | |
| 232 | 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 }, | |
| 233 | 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, | |
| 234 | 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 }, | |
| 235 | massBeforeKg: attachment!.outcome === 'attached' ? attachment!.before.properties.totalMassKg : null, massAfterKg: attachment!.outcome === 'attached' ? attachment!.after.properties.totalMassKg : null } : null, finalRelease: release(run.transfer.finalRelease) }, | |
| 236 | station: run.station, recipient: run.recipient, loose: run.loose, ownership: run.ownership } | |
| 237 | } | |