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
docs/cargo-fleet.mdadded+218-0
Changes to docs/cargo-fleet.md
@@ -0,0 +1,218 @@
1# Two-carrier modeled cargo handover
2
3`simulateCargoFleet()` in `resources/functions/drone/cargo/fleet.ts` runs two actual
4retained vehicle sessions on the same 4 ms clock. One source point parcel falls onto
5a station, follows a finite powered rail, enters an initially empty receiving body,
6and then flies the receiver's own delivery and return route.
7
8This is a bounded fictional simulation, with physical outputs inhibited. It does not
9qualify an aircraft, station, recipient identity, electrical endurance or BVLOS service.
10The [single-carrier guide](cargo-delivery.md) retains the wider operations evidence case.
11
12## Native command and exit status
13
14```sh
15./buddy cargo:fleet
16./buddy cargo:fleet --scenario receiver-primary-link-loss
17./buddy cargo:fleet --scenario receiver-both-links-loss
18./buddy cargo:fleet --scenario receiver-host-loss-before-intake
19./buddy cargo:fleet --scenario intake-receipt-loss
20./buddy cargo:fleet --scenario receiver-joint-shift-before-intake
21./buddy cargo:fleet --scenario receiver-navigation-loss-during-rail
22./buddy cargo:fleet --scenario source-kill-after-station-receipt
23./buddy cargo:fleet --scenario receiver-kill-after-intake
24./buddy cargo:fleet --scenario receiver-pad-motion-during-rail
25./buddy cargo:fleet --scenario receiver-containment-breach-after-intake-receipt
26```
27
28The command emits one JSON line, at most 16 KiB. Exit 0 means the modeled routes and
29captured custody completed. Exit 2 retains an incomplete modeled outcome. Exit 1 means
30invalid input, execution or output failure. The standalone `drone cargo:fleet` command
31uses the same native Stacks definition. `cargoFleetSummary(run)` projects observed
32results without serializing the full runtime journals.
33
34The library accepts only an optional own-data `scenario` declaration from this finite
35set. It does not yet accept arbitrary fleet geometry, vehicle count or hardware transports.
36
37## One world, two authority owners
38
39Carrier A uses raw boot 101 and authority session 201. Carrier B uses raw boot 102 and
40session 202. Both use the fixed synthetic WGS84 origin 0, 0, 100 and LOCAL_NED, with down
41positive. These are distinct model identities, not authenticated identities or distributed
42clock qualification. Each retains its own raw IMU/GNSS pipeline, estimator, mission,
43controller, output watchdog and primary/backup radio observer.
44
45A begins at [0, 0, -0.1] m with a 0.1 kg body-forward point at 0.08 m. B begins at
46[3, 2, -0.1] m with a declared empty joint. The first site is [3, 0, 0] m and the final
47recipient site is [6, 2, 0] m, each with a 0.35 m horizontal acceptance disc. Both bodies
48use the declared flat -0.1 m ground datum; the parcel capture plane is down 0. No landing
49gear, collision/contact geometry, wind/weather envelope or surveyed field is inferred.
50
51The receiving task holds its declared pad with neutral motor commands from its first
52frame. It does not preload mass. Flight policy consumes the owned estimator and modeled
53sensor captures. Physical joint geometry is used only inside the modeled mechanism's
54contact operation; it is not supplied as a flight-controller positioning oracle.
55
56## Transfer and custody
57
581. A's existing release coordinator requires current observed site/recipient/load evidence
59 and its own mission scope. The world checks actual same-epoch host availability,
60 supervisor boot/session, current lease, recent policy and pending command before separation.
612. The actual separation event supplies the point to the [station actor](cargo-station.md).
62 Free fall retains the within-step impact epoch, impulse and mechanical loss. Only after
63 A confirms station custody does the rail start toward B's declared current joint.
643. B's intake coordinator requires 26 distinct qualified captures spanning at least 500 ms,
65 its boot/reference, healthy estimator/gyro, conservative pad uncertainty, contact, stopped
66 motors, a clear site and the captured ready-station parcel/source event. It issues one
67 modeled grant, valid for at most 40 ms and within the pending task deadline.
684. On a later 4 ms epoch the mechanism independently checks B's actual host availability,
69 current supervisor boot/session/lease, recent policy, exact pending command and neutral
70 outputs. It consumes the station's departure once and calls actual `attachParcel` at
71 B's current joint. A refused point enters the world's separate loose-parcel actor and continues
72 ballistic motion to the declared capture plane. It is not copied back, repositioned
73 onto the joint or silently retried.
745. A later B sensor capture must report that actual intake event, source event, mass and
75 mechanism epoch. Its capture pose and command scope produce the receipt ACK. Requesting
76 or granting intake is not confirmation. Only then does B take off with changed mass/CG,
77 release the point at the final site and complete captured recipient custody and landing.
78
79The grant's session declaration alone cannot establish authority. The physical-world
80check uses the live retained runtime at the actual operation epoch. Host loss can leave
81an old supervisor snapshot saying `autonomous`; it still blocks the intake mechanism.
82
83Physical ownership and captured custody are separate records. The world mass ledger reads
84the actual body/actor masses after transitions and at 20 ms intervals. It retains one
850.1 kg point and 3.1 kg total mass, with reported maximum numerical error. Historical
86separation/departure records are evidence copies, not additional physical owners. The
87station reports mechanical work; each vehicle's reserve remains the shared longest-path
88**declared power budget**, not measured Wh or an electrical model.
89
90## Bounded model cases
91
92| Scenario | Expected result | Parcel and authority outcome |
93| --- | --- | --- |
94| `nominal` | Completed | A to station to B to final parcel, with three separate captured custody stages |
95| `receiver-primary-link-loss` | Completed | Receiver primary stops during station handling; its independently captured backup preserves authority |
96| `receiver-both-links-loss` | Incomplete | Receiver link freshness expires and authority fails; finite station braking retains the parcel while A continues |
97| `receiver-host-loss-before-intake` | Incomplete | Host stops 4 ms after the actual grant; no physical intake, independent board expiry and station retention |
98| `receiver-joint-shift-before-intake` | Incomplete | A 0.4 N force for one 4 ms step shifts the actual joint before intake; strict coincidence refuses it, the loose point falls, and B lands its counted alternate empty |
99| `intake-receipt-loss` | Incomplete | Actual intake occurs but its receipt fields are withheld; B retains the mass and lands its counted alternate without claiming custody or making a second delivery |
100| `receiver-navigation-loss-during-rail` | Incomplete | GNSS capture stops 4 ms after actual rail start; receiver navigation expires, station brakes and retains the point, and A continues |
101| `source-kill-after-station-receipt` | Incomplete | Source kill follows its captured station receipt; A inhibits while B completes intake, final delivery and return. B's success does not make the whole fleet complete |
102| `receiver-kill-after-intake` | Incomplete | Kill follows actual intake by 4 ms, before receipt capture; B retains the attached mass with uncertain custody and no final release |
103| `receiver-pad-motion-during-rail` | Incomplete | A declared constant 4 N northward force moves B; native receiving interlocks stop its mission before fence breach or intake, and the station brakes |
104| `receiver-containment-breach-after-intake-receipt` | Incomplete | After captured intake, an 8 N northward force ramps over 2 s. B's qualified estimated position breaches its 12 m fence; authority fails and outputs neutral while attached mass and received custody remain |
105
106The loaded containment case explicitly opts into the existing `fixture-imu` position
107prediction model, including its assumed initial north heading and synthetic uncertainty.
108It uses the actual raw IMU/GNSS feed and the native estimator/fence checks, with no
109substitution of plant position into policy. The receiver force is a declared world-NED
110model input, retained as `forceN` and `forceRampMs` in the fault report. It continues
111through the independent neutral tail. A neutral command cannot stop momentum or an
112ongoing external force; this case demonstrates fence-breach detection and inhibition,
113not guaranteed physical containment. The pad-motion case uses the same real body-force
114path and is stopped earlier by receiving contact/speed/anchor interlocks.
115
116Radio observations retain capture, receipt, sequence and scope, with 1 ms clock uncertainty
117and 20/40 ms primary/backup delays. Failure stops new packets rather than restamping a
118connected fixture. Link loss takes effect through the declared freshness contract.
119Vehicle host termination retains a 1,000 ms independent board/plant tail. The other peer
120continues its own mission. Both routes and their failure alternatives count toward the
121native finite graph/reserve budget; the world is bounded by the 180 s host limit and tails.
122
123## Retained world and explicit transport decisions
124
125`createCargoFleetSession()` exposes `step`, `snapshot`, `decide`, `result` and
126idempotent `close`. The one-shot `simulateCargoFleet()` uses that same world. Each
127step requires exactly the next 4 ms epoch, starting at zero. Both retained vehicle
128sessions, station and single physical point advance together. Snapshots are detached;
129`result()` requires a terminal world and returns a detached complete report, including
130initial loads, fault anchors and transfer history. Mutating a returned report cannot
131rewrite later reads. Closing early revokes both actual board models
132and reports their current neutral outputs without advancing the plant, changing the
133last policy/measurement epochs or claiming that the moving parcel instantly stopped.
134A closed world cannot resume. Closing is not a durable checkpoint or physical settling
135procedure.
136
137The exported `CargoFleetOperatorDecision` is a strict, data-only declaration:
138
139```ts
140const state = world.snapshot()
141if (state.atMs === null || !state.receiver || !state.stationSourceEventId)
142 throw new Error('Wait for an active receiver and station event')
143const outcome = world.decide({
144 version: 1,
145 evidence: 'modeled-cargo-transport-decision-v1',
146 contextId: state.operator.contextId,
147 bootId: 102n,
148 sessionId: 202n,
149 sequence: 1,
150 issuedAtMs: state.atMs,
151 reference: state.receiver.reference,
152 sourceEventId: state.stationSourceEventId,
153 action: 'cancel',
154})
155```
156
157Call after observing an active receiving task and the actual station source event.
158The fresh context UUID separates two otherwise identical worlds; it does not
159authenticate an operator. Admission requires the exact world epoch, receiving
160boot/session/reference and source event, and the next sequence from 1 through 32.
161Accessors, extra fields and extra arguments are rejected. Wrong scope, old clock or
162replayed sequence cannot touch the parcel or consume a sequence. A valid scoped
163operational refusal does consume its sequence and records its reason. Closure during
164declaration capture cannot admit later work. Decision history is bounded to 32 events.
165
166`cancel` consumes any queued physical intake request and asks the station to stop.
167Actual finite braking retains position, velocity, mass and work. The receiving mission
168keeps its existing task/event deadline; the other carrier continues independently.
169Cancellation does not reset an estimator, replace a body or renew a failed lease.
170
171A later fresh `resume` needs the same pending receive task, current native authority,
172captured source custody, a fully stopped station and no prior intake grant. The same
173point resumes from its actual stopped position, with a new bounded rail duration and
174cumulative mechanical accounting. At most eight station resumptions fit within the
175original 180 s lifetime. An attempted intake remains uncertain even if cancellation
176prevents its queued mechanism from executing; `intake-already-attempted` prevents a
177second attempt. No inferred custody repair is performed.
178
179Native Buddy and the copied standalone CLI expose four explicit fictional decision cases:
180
181```sh
182./buddy cargo:fleet-control --case cancel
183./buddy cargo:fleet-control --case cancel-resume
184./buddy cargo:fleet-control --case cancel-after-grant
185./buddy cargo:fleet-control --case resume-after-navigation-loss
186```
187
188The default `cancel-resume` waits for actual moving transport, cancels it, waits at
189least 1 s after its physical stop, then resumes the same receiver session and parcel.
190It completes captured intake, final delivery and return. `cancel` retains the parcel
191and lets the original receive deadline lead to an alternate. `cancel-after-grant`
192withholds physical intake but retains attempted-intake uncertainty and refuses recovery.
193`resume-after-navigation-loss` refuses recovery after native navigation authority fails.
194These three cases exit 2. The completed case exits 0; invalid input, execution and output
195failures exit 1. Each emits one JSON line within 16 KiB, including explicit decision
196outcomes, source/receiver scopes and physical ownership. Identity authentication and
197physical outputs remain disabled. These are fixed simulation declarations, not an
198interactive control server or an arbitrary fleet mission interface.
199
200## Evidence and remaining work
201
202`tests/unit/cargo-fleet.test.ts` exercises actual two-session physics, intake mass changes,
203source/receiver scopes, same-epoch admission, captured receipt ordering, retained mass,
204backup continuation, both-link braking, the host/grant gap and uncertain loaded diversion.
205`tests/unit/cargo-fleet-cli.test.ts` executes the native Buddy command and its bounded wire.
206`tests/unit/cargo-fleet-operator.test.ts` exercises same-session recovery, braking,
207foreign/stale/replayed decisions, close reentry, retained output observations and the
208grant/execution gap. `tests/unit/cargo-fleet-control-cli.test.ts` exercises native command
209exits and bounded reports. `scripts/qualify-cargo-fleet-cli.ts` exercises all eleven
210fault cases and four operator cases through a copied standalone binary outside the
211checkout and retains output hashes and factual outcomes.
212
213These cases do not cover a complete fleet fault envelope. Receiver/source kill or manual
214intervention at every phase, broader navigation degradation and containment campaigns,
215wider late/foreign/replayed receipt campaigns, general vehicle abort/replan and
216uncertain-intake reconciliation, durable whole-world checkpoints, general rendezvous, collision avoidance and richer fleet planning
217remain open under [#25](https://github.com/stacksjs/drone/issues/25) and its dependencies.
218The wider measured hardware, endurance and operational evidence requirements remain open.