ReviewOS

also looking at this

stacks/drone

feat: model phase-bound cargo fleet failures

#104
Merged chris wants to merge codex/cargo-fleet-phase-faults into main
25 files +1844 -13
resources/functions/drone/cargo/fleet.tsadded+265-0
Changes to resources/functions/drone/cargo/fleet.ts
@@ -0,0 +1,265 @@
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 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
21export type CargoFleetScenario = typeof cargoFleetScenarios[number]
22function 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}
31const origin = { latitudeDeg: 0, longitudeDeg: 0, ellipsoidHeightM: 100 }
32const point = { id: 'parcel-a', massKg: .1, forwardM: .08 }
33const receiverPadM: SensorVector = [3, 2, -.1]
34const stationSite = { id: 'handover-station', recipientId: 'station-operator', containerId: point.id, positionM: [3, 0, 0] as SensorVector, radiusM: .35 }
35const finalSite = { id: 'final-site', recipientId: 'final-recipient', containerId: point.id, positionM: [6, 2, 0] as SensorVector, radiusM: .35 }
36function 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}
50function 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. */
58export 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, 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 } : {}) } : {}) }
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 if (scenario === 'receiver-containment-breach-after-intake-receipt') profileB.positionPrediction = 'fixture-imu'
119 const baseFaultsA = profileA.faults
120 if (scenario === 'source-kill-after-station-receipt') {
121 profileA.scenario = scenario; profileA.scenarios = [scenario]
122 profileA.faults = (selected, atMs, phase) => {
123 if (selected !== scenario) throw new TypeError('cargo-fleet-scenario-changed')
124 const killed = faultInjection!.anchoredAtMs !== null && atMs > faultInjection!.anchoredAtMs
125 if (killed && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
126 return { ...baseFaultsA('nominal', atMs, phase), kill: killed }
127 }
128 }
129 const baseFaultsB = profileB.faults
130 profileB.scenario = scenario; profileB.scenarios = [scenario]
131 profileB.faults = (selected, atMs, phase) => {
132 if (selected !== scenario) throw new TypeError('cargo-fleet-scenario-changed')
133 const active = faultInjection?.scenario === 'receiver-host-loss-before-intake' && faultInjection.anchoredAtMs !== null && atMs >= faultInjection.anchoredAtMs + 4
134 if (active && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
135 const navigationLost = faultInjection?.scenario === 'receiver-navigation-loss-during-rail' && faultInjection.anchoredAtMs !== null && atMs > faultInjection.anchoredAtMs
136 if (navigationLost && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
137 const killed = faultInjection?.scenario === 'receiver-kill-after-intake' && faultInjection.anchoredAtMs !== null && atMs > faultInjection.anchoredAtMs
138 if (killed && phase === 'host') faultInjection!.triggeredAtMs ??= atMs
139 return { ...baseFaultsB('nominal', atMs, phase), hostLost: active, dropPosition: navigationLost, kill: killed }
140 }
141 const plantA = createMultirotorPlant(bodyA), adaptedB = createMultirotorPlant(bodyB)
142 let receiverPhysicalAtMs = 600
143 const plantB: VehiclePlant = { snapshot: adaptedB.snapshot, step(actuators, dtS, environment) {
144 if (dtS !== .004) throw new RangeError('cargo-fleet-receiver-step')
145 receiverPhysicalAtMs += 4
146 const shift = faultInjection?.scenario === 'receiver-joint-shift-before-intake' && faultInjection.anchoredAtMs !== null && receiverPhysicalAtMs === faultInjection.anchoredAtMs + 4
147 if (shift) faultInjection!.triggeredAtMs = receiverPhysicalAtMs
148 const containment = faultInjection && ['receiver-pad-motion-during-rail', 'receiver-containment-breach-after-intake-receipt'].includes(faultInjection.scenario) && faultInjection.anchoredAtMs !== null && receiverPhysicalAtMs > faultInjection.anchoredAtMs
149 if (containment) faultInjection!.triggeredAtMs ??= receiverPhysicalAtMs
150 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 } : {}) })
151 return adaptedB.snapshot()
152 } }
153 function releaseValues(which: 'source' | 'receiver') {
154 const released = which === 'source' ? sourceRelease : finalRelease, target = which === 'source' ? station : recipient, site = which === 'source' ? stationSite : finalSite
155 const impact = target?.snapshot().impact
156 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
157 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 }
158 }
159 profileA.createSession = (): VehicleSession => {
160 const base = createA()
161 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') } } } }
162 }
163 profileB.createSession = (): VehicleSession => {
164 const base = createB()
165 return { ...base, linkObservation: linksB.observe, createPlant: () => plantB, createPayload: () => receiverPort, renderMeasurement(state, atMs, reference) {
166 const packet = base.renderMeasurement(state, atMs, reference)
167 const suppressReceipt = faultInjection?.scenario === 'intake-receipt-loss' && intakeEvidence !== null
168 if (suppressReceipt) faultInjection!.triggeredAtMs ??= atMs
169 const evidence = suppressReceipt ? null : intakeEvidence
170 return { ...packet, values: { ...packet.values, ...releaseValues('receiver'), receiverId: 'carrier-b', stationReady: station?.snapshot().phase === 'ready', stationContainerId: point.id, stationSourceEventId: sourceRelease?.eventId ?? '',
171 intakeAtMs: evidence?.atMs ?? -1, intakeEventId: evidence?.eventId ?? '', intakeSourceEventId: evidence?.sourceEventId ?? '', intakeOutcome: evidence?.outcome ?? '', intakeMassKg: evidence?.massKg ?? 0 } }
172 } }
173 }
174 const a = createVehicleSimulationSession(profileA, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 101n, sessionId: 201n } })
175 const b = createVehicleSimulationSession(profileB, { seconds: 180, neutralTailMs: 1000, scope: { bootId: 102n, sessionId: 202n } })
176 function changeOwner(next: Owner, nowMs: number) { transitions.push({ atMs: nowMs, from: physical.owner, to: next }); physical.owner = next }
177 function totalMass() { return bodyA.loadSnapshot().properties.totalMassKg + bodyB.loadSnapshot().properties.totalMassKg + (station?.snapshot().ownedMassKg ?? 0) + (recipient?.snapshot().ownedMassKg ?? 0) + (loose?.snapshot().ownedMassKg ?? 0) }
178 function sampleMass() { maximumMassErrorKg = Math.max(maximumMassErrorKg, Math.abs(totalMass() - 3.1)); massSamples++ }
179 sampleMass()
180 try {
181 for (let nowMs = 0; nowMs <= 181000; nowMs += 4) {
182 if (!progressA?.terminal) progressA = a.step(nowMs)
183 if (!progressB?.terminal) progressB = b.step(nowMs)
184 if (faultInjection?.scenario === 'source-kill-after-station-receipt' && faultInjection.anchoredAtMs === null) {
185 const receipt = sourceCoordinator.snapshot().delivery
186 if (receipt.outcome === 'received') faultInjection.anchoredAtMs = receipt.acknowledgedAtMs
187 }
188 if (faultInjection?.scenario === 'receiver-containment-breach-after-intake-receipt' && faultInjection.anchoredAtMs === null) {
189 const receipt = intakeCoordinator.snapshot().custody
190 if (receipt.outcome === 'received') faultInjection.anchoredAtMs = receipt.acknowledgedAtMs
191 }
192 if (station && station.snapshot().atMs < nowMs) station.step(nowMs)
193 if (recipient && recipient.snapshot().atMs < nowMs) recipient.step(nowMs)
194 if (loose && loose.snapshot().atMs < nowMs) loose.step(nowMs)
195 if (commands.source && nowMs > commands.source.issuedAtMs) {
196 const command = commands.source; commands.source = null
197 if (physical.owner === 'source-body' && hasAuthority(progressA, command, nowMs, 101n, 201n)) {
198 const event = bodyA.separateCarriedLoad(); sourceRelease = { atMs: nowMs, eventId: command.eventId, event }
199 if (event.outcome === 'separated') {
200 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 })
201 changeOwner('station-actor', nowMs); sampleMass()
202 }
203 }
204 }
205 if (station?.snapshot().phase === 'held' && sourceCoordinator.snapshot().delivery.outcome === 'received' && progressB?.mission.payload?.operation === 'material-receive' && hasAuthority(progressB, progressB.mission.payload, nowMs, 102n, 202n)) {
206 station.start()
207 if (faultInjection && ['receiver-navigation-loss-during-rail', 'receiver-pad-motion-during-rail'].includes(faultInjection.scenario)) faultInjection.anchoredAtMs ??= nowMs
208 }
209 if (station && ['falling', 'held', 'moving', 'ready'].includes(station.snapshot().phase) && progressB && (!progressB.hostAvailable || progressB.authority.state !== 'autonomous')) station.cancel()
210 if (commands.intake && nowMs > commands.intake.issuedAtMs) {
211 const grant = commands.intake; commands.intake = null
212 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
213 && hasAuthority(progressB, grant.command, nowMs, grant.bootId, grant.sessionId) && progressB!.board.actuators.every(n => n === 0) && bodyB.snapshot().motorsN.every(n => n < .01)) {
214 const departure = station.takeReadyParcel()
215 if (departure.outcome === 'departed') {
216 stationDeparture = departure
217 const attachment = bodyB.attachParcel(departure.parcel)
218 intake = { atMs: nowMs, grant, attachment, source: structuredClone(progressA!), receiver: structuredClone(progressB!) }
219 intakeEvidence = { atMs: nowMs, eventId: grant.command.eventId, sourceEventId: grant.sourceEventId, outcome: attachment.outcome, massKg: attachment.outcome === 'attached' ? attachment.parcel.massKg : 0 }
220 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 }
221 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) }
222 sampleMass()
223 }
224 }
225 }
226 if (commands.receiver && nowMs > commands.receiver.issuedAtMs) {
227 const command = commands.receiver; commands.receiver = null
228 if (physical.owner === 'receiver-body' && hasAuthority(progressB, command, nowMs, 102n, 202n)) {
229 const event = bodyB.separateCarriedLoad(); finalRelease = { atMs: nowMs, eventId: command.eventId, event }
230 if (event.outcome === 'separated') {
231 recipient = createCargoStationHandler({ atMs: nowMs, parcel: { id: point.id, ...event.parcel }, pickup: { centerM: finalSite.positionM, radiusM: finalSite.radiusM }, destinationM: finalSite.positionM, maxSpeedMps: .5, maxAccelerationMps2: 1 })
232 changeOwner('final-parcel-actor', nowMs); sampleMass()
233 }
234 }
235 }
236 if (nowMs % 20 === 0) sampleMass()
237 if (progressA?.terminal && progressB?.terminal) break
238 }
239 const sourceRun = a.result(), receiverRun = b.result(), sourceDelivery = sourceCoordinator.snapshot().delivery, receiverDelivery = deliveryCoordinator.snapshot().delivery, receiverIntake = intakeCoordinator.snapshot()
240 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
241 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,
242 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 },
243 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 } }
244 }
245 finally { a.close(); b.close() }
246}
247
248/** Compact actual observations for Buddy/standalone output; never serialize the full runtime journal. */
249export function cargoFleetSummary(run: ReturnType<typeof simulateCargoFleet>) {
250 function vehicle(runtime: typeof run.source.runtime) {
251 const power = runtime.trace.plan.power, usableWh = power.availableWh * (1 - power.reservePercent / 100)
252 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,
253 finalPositionM: runtime.finalTruthPositionM, sensors: runtime.navigationEvidence.observedSensors, board: { physicalActuationEnabled: runtime.board.physicalActuationEnabled, actuators: runtime.board.actuators, fault: runtime.board.fault, expiresAtMs: runtime.board.expiresAtMs },
254 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 } }
255 }
256 const capturedIntake = run.transfer.intake, attachment = capturedIntake?.attachment
257 const release = (event: typeof run.transfer.sourceRelease) => event ? { atMs: event.atMs, eventId: event.eventId, outcome: event.event.outcome } : null
258 return { version: run.version, evidence: run.evidence, scenario: run.scenario, status: run.status, physicalFlightEnabled: run.physicalFlightEnabled, boardOutputsInhibited: run.boardOutputsInhibited, identityAuthenticated: run.identityAuthenticated,
259 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 },
260 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 },
261 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,
262 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 },
263 massBeforeKg: attachment!.outcome === 'attached' ? attachment!.before.properties.totalMassKg : null, massAfterKg: attachment!.outcome === 'attached' ? attachment!.after.properties.totalMassKg : null } : null, finalRelease: release(run.transfer.finalRelease) },
264 station: run.station, recipient: run.recipient, loose: run.loose, ownership: run.ownership }
265}