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
tests/unit/cargo-fleet-operator.test.tsadded+210-0
Changes to tests/unit/cargo-fleet-operator.test.ts
@@ -0,0 +1,210 @@
1import { expect, test } from 'bun:test'
2import { createCargoFleetSession } from '../../resources/functions/drone/cargo/fleet'
3import { simulateCargoFleetControl } from '../../resources/functions/drone/cargo/fleet-control'
4
5type World = ReturnType<typeof createCargoFleetSession>
6function decision(world: World, action: 'cancel' | 'resume', sequence: number) {
7 const state = world.snapshot()
8 return { version: 1, evidence: 'modeled-cargo-transport-decision-v1', contextId: state.operator.contextId, bootId: 102n, sessionId: 202n, reference: state.receiver!.reference, sourceEventId: state.stationSourceEventId!, sequence, issuedAtMs: state.atMs!, action }
9}
10
11// Public retained world seam. Both real runtime sessions and the same point/rail
12// keep advancing; operator transport decisions do not replace a body or estimator.
13test('scoped operator cancellation and later recovery finish the same parcel on the same receiving session', () => {
14 const world = createCargoFleetSession()
15 try {
16 let nowMs = 0
17 for (; nowMs <= 60000; nowMs += 4) {
18 world.step(nowMs)
19 const station = world.snapshot().station
20 if (station?.phase === 'moving' && Math.hypot(...station.parcel!.velocityMps) > .1) break
21 }
22 expect(nowMs).toBeLessThan(60000)
23 const before = world.snapshot(), pendingId = before.receiver!.mission.payload!.eventId, epoch = before.receiver!.authority.epoch
24 expect(world.decide(decision(world, 'cancel', 1)).outcome).toBe('accepted')
25 expect(world.snapshot().station!.phase).toBe('braking')
26 expect(Math.hypot(...world.snapshot().station!.parcel!.velocityMps)).toBeGreaterThan(0)
27 while (world.snapshot().station!.phase === 'braking') { nowMs += 4; world.step(nowMs) }
28 const stopped = world.snapshot()
29 expect(stopped.ownership.owner).toBe('station-actor')
30 expect(stopped.ownership.totalMassKg).toBe(3.1)
31 expect(Math.hypot(...stopped.station!.parcel!.velocityMps)).toBe(0)
32 const waitUntil = nowMs + 1000
33 for (nowMs += 4; nowMs <= waitUntil; nowMs += 4) {
34 world.step(nowMs)
35 expect(world.snapshot().receiver!.board.actuators).toEqual([0, 0, 0, 0])
36 expect(world.snapshot().receiver!.mission.payload!.eventId).toBe(pendingId)
37 }
38 nowMs -= 4
39 expect(world.decide(decision(world, 'resume', 2)).outcome).toBe('accepted')
40 expect(world.snapshot().station!.parcel).toEqual(stopped.station!.parcel)
41 expect(world.snapshot().receiver!.authority.epoch).toBe(epoch)
42 while (!world.snapshot().terminal) { nowMs += 4; world.step(nowMs) }
43 const run = world.result()
44 expect(run.status).toBe('completed')
45 expect(run.receiver.runtime.authority.sessionId).toBe(202n)
46 expect(run.receiver.runtime.board.bootId).toBe(102n)
47 expect(run.receiver.intake.custody.outcome).toBe('received')
48 expect(run.receiver.delivery.outcome).toBe('received')
49 expect(run.station!.resumptions).toHaveLength(1)
50 expect(run.operator!.events.map(e => [e.action, e.outcome])).toEqual([['cancel', 'accepted'], ['resume', 'accepted']])
51 expect(run.ownership.transitions.map(e => [e.from, e.to])).toEqual([['source-body', 'station-actor'], ['station-actor', 'receiver-body'], ['receiver-body', 'final-parcel-actor']])
52 expect(run.ownership.finalMassKg).toBe(3.1)
53 expect(run.ownership.maximumMassErrorKg).toBeLessThan(1e-12)
54 }
55 finally { world.close() }
56})
57
58function advanceUntil(world: World, predicate: (state: ReturnType<World['snapshot']>) => boolean, ceiling = 60000) {
59 for (let nowMs = (world.snapshot().atMs ?? -4) + 4; nowMs <= ceiling; nowMs += 4) {
60 const progress = world.step(nowMs), state = world.snapshot()
61 if (predicate(state)) return nowMs
62 if (progress.terminal) break
63 }
64 throw new Error('Expected bounded world phase')
65}
66const moving = (state: ReturnType<World['snapshot']>) => state.station?.phase === 'moving' && Math.hypot(...state.station.parcel!.velocityMps) > .1
67
68test('operator scope, exact clock and sequence reject stale or foreign decisions before touching the parcel', () => {
69 const world = createCargoFleetSession(), other = createCargoFleetSession()
70 try {
71 const nowMs = advanceUntil(world, moving)
72 advanceUntil(other, moving)
73 const packet = decision(world, 'cancel', 1), before = world.snapshot(), otherBefore = other.snapshot()
74 expect(other.decide(packet)).toEqual({ outcome: 'refused', reason: 'operator-scope' })
75 expect(other.snapshot()).toEqual(otherBefore)
76 for (const patch of [{ bootId: 103n }, { sessionId: 203n }, { reference: '102:1,0,0,0,0' }, { sourceEventId: 'foreign-source-event' }]) expect(world.decide({ ...packet, ...patch }).reason).toBe('operator-scope')
77 expect(world.decide({ ...packet, issuedAtMs: nowMs - 4 }).reason).toBe('operator-clock')
78 expect(world.snapshot()).toEqual(before)
79 let invoked = 0
80 const unsafe = { ...packet, get action() { invoked++; return 'cancel' } }
81 expect(() => world.decide(unsafe)).toThrow('cargo-fleet-operator-declaration')
82 expect(invoked).toBe(0)
83 expect(() => world.decide(packet, 'extra')).toThrow('cargo-fleet-operator-declaration')
84 expect(() => world.step(nowMs + 8)).toThrow('cargo-fleet-clock')
85 expect(world.snapshot()).toEqual(before)
86 expect(world.decide(packet).outcome).toBe('accepted')
87 expect(world.decide(packet).reason).toBe('operator-sequence')
88 expect(world.snapshot().operator.events).toHaveLength(1)
89 }
90 finally { world.close(); other.close() }
91 expect(world.decide({}).reason).toBe('session-unavailable')
92 expect(() => world.step(0)).toThrow('Cargo fleet session is closed')
93 expect(world.result().status).toBe('unqualified')
94 expect(world.result().source.runtime.board.actuators).toEqual([0, 0, 0, 0])
95 expect(world.result().receiver.runtime.board.actuators).toEqual([0, 0, 0, 0])
96})
97
98test('a recovery requested while the parcel still brakes is refused without jumping to the old rail endpoint', () => {
99 const world = createCargoFleetSession()
100 try {
101 advanceUntil(world, moving)
102 world.decide(decision(world, 'cancel', 1))
103 const braking = world.snapshot().station!
104 expect(world.decide(decision(world, 'resume', 2))).toEqual({ outcome: 'refused', reason: 'station-not-stopped' })
105 expect(world.snapshot().station).toEqual(braking)
106 advanceUntil(world, state => state.station?.phase === 'cancelled')
107 expect(world.decide(decision(world, 'resume', 3)).outcome).toBe('accepted')
108 const detached = world.snapshot(); detached.operator.events[0]!.reason = 'changed'
109 expect(world.snapshot().operator.events[0]!.reason).toBe('transport-cancellation-requested')
110 }
111 finally { world.close() }
112})
113
114test('cancellation between intake grant and mechanism consumes the grant and cannot be recovered into a second attempt', () => {
115 const world = createCargoFleetSession()
116 try {
117 let nowMs = advanceUntil(world, state => state.intake.custody.grantedAtMs !== null)
118 expect(world.snapshot().ownership.owner).toBe('station-actor')
119 expect(world.decide(decision(world, 'cancel', 1)).outcome).toBe('accepted')
120 expect(world.decide(decision(world, 'resume', 2))).toEqual({ outcome: 'refused', reason: 'intake-already-attempted' })
121 while (!world.snapshot().terminal) { nowMs += 4; world.step(nowMs) }
122 const run = world.result()
123 expect(run.status).toBe('unqualified')
124 expect(run.transfer.intake).toBeNull()
125 expect(run.transfer.stationDeparture).toBeNull()
126 expect(run.receiver.finalLoad.properties.totalMassKg).toBe(1.5)
127 expect(run.receiver.intake.custody.outcome).toBe('uncertain')
128 expect(run.receiver.runtime.mission.reason).toBe('payload-diversion-landed')
129 expect(run.station!.phase).toBe('cancelled')
130 expect(run.station!.ownedMassKg).toBe(.1)
131 expect(run.ownership.finalMassKg).toBe(3.1)
132 }
133 finally { world.close() }
134})
135
136test('a current operator declaration cannot recover transport after receiver navigation authority expires', () => {
137 const world = createCargoFleetSession({ scenario: 'receiver-navigation-loss-during-rail' })
138 try {
139 advanceUntil(world, state => state.station?.phase === 'moving')
140 world.decide(decision(world, 'cancel', 1))
141 advanceUntil(world, state => state.receiver?.authority.state === 'failsafe')
142 const before = world.snapshot().station
143 expect(world.decide(decision(world, 'resume', 2))).toEqual({ outcome: 'refused', reason: 'recovery-authority-unavailable' })
144 expect(world.snapshot().station).toEqual(before)
145 expect(world.snapshot().ownership.owner).toBe('station-actor')
146 }
147 finally { world.close() }
148})
149
150test('closing the retained world reports revoked current board output without pretending the parcel instantly stopped', () => {
151 const world = createCargoFleetSession()
152 advanceUntil(world, moving)
153 const before = world.snapshot(), movingPoint = before.station!.parcel!
154 world.close(); world.close()
155 const closed = world.snapshot()
156 expect(closed.closed).toBe(true)
157 expect(closed.terminal).toBe(true)
158 expect(closed.source!.hostAvailable).toBe(false)
159 expect(closed.receiver!.hostAvailable).toBe(false)
160 expect(closed.source!.board.actuators).toEqual([0, 0, 0, 0])
161 expect(closed.receiver!.board.actuators).toEqual([0, 0, 0, 0])
162 expect(closed.atMs).toBe(before.atMs)
163 expect(closed.source!.policyAtMs).toBe(before.source!.policyAtMs)
164 expect(closed.receiver!.policyAtMs).toBe(before.receiver!.policyAtMs)
165 expect(closed.receiver!.reference).toBe(before.receiver!.reference)
166 expect(closed.station!.phase).toBe('braking')
167 expect(closed.station!.parcel).toEqual(movingPoint)
168 expect(closed.ownership.totalMassKg).toBe(3.1)
169 expect(world.decide({}).reason).toBe('session-unavailable')
170})
171
172test('a declaration capture that closes the world cannot resume or consume an operator sequence', () => {
173 const world = createCargoFleetSession()
174 advanceUntil(world, moving)
175 const packet = decision(world, 'cancel', 1)
176 const proxy = new Proxy(packet, { getOwnPropertyDescriptor(target, key) { world.close(); return Reflect.getOwnPropertyDescriptor(target, key) } })
177 expect(world.decide(proxy)).toEqual({ outcome: 'refused', reason: 'session-unavailable' })
178 expect(world.snapshot().operator.lastSequence).toBe(0)
179 expect(world.snapshot().operator.events).toHaveLength(0)
180 expect(world.snapshot().closed).toBe(true)
181})
182
183test('operator case admission rejects extra fields, accessors and extra arguments before creating a world', () => {
184 let calls = 0
185 for (const declaration of [null, { case: 'unknown' }, { case: 'cancel', extra: true }, { get case() { calls++; return 'cancel' } }]) expect(() => simulateCargoFleetControl(declaration)).toThrow('cargo-fleet-control-arguments')
186 expect(() => simulateCargoFleetControl({}, true)).toThrow('cargo-fleet-control-arguments')
187 expect(calls).toBe(0)
188})
189
190for (const completion of ['early-close', 'natural'] as const) {
191 test(`fleet terminal results remain detached after ${completion}`, () => {
192 const world = createCargoFleetSession({ scenario: completion === 'early-close' ? 'receiver-kill-after-intake' : 'nominal' })
193 try {
194 if (completion === 'early-close') world.close()
195 else for (let nowMs = 0; !world.step(nowMs).terminal; nowMs += 4) { /* Same finite native world. */ }
196 const result = world.result(), expected = structuredClone(result)
197 result.source.initialLoad.properties.totalMassKg = 0
198 result.receiver.initialLoad.properties.totalMassKg = 0
199 result.source.linkEvents.length = 0
200 result.ownership.transitions.length = 0
201 if (result.faultInjection) result.faultInjection.triggeredAtMs = 999
202 if (result.transfer.sourceRelease) result.transfer.sourceRelease.eventId = 'rewritten'
203 if (result.transfer.intake) result.transfer.intake.receiver.board.actuators[0] = 77
204 expect(world.result()).toEqual(expected)
205 world.close()
206 expect(world.result()).toEqual(expected)
207 }
208 finally { world.close() }
209 })
210}