Compare commits

..

282 commits
v0.6.3 ... main

Author SHA1 Message Date
acamilo
291620f5d5 Merge nobs/feed-sigpipe2 (nobs MiniMax M3; Claude review: the test did not reproduce the bug and printf still printed its error; fixed on top)
Some checks failed
ci / node 22 (test + typecheck) (push) Has been cancelled
ci / rust stable (cargo test --workspace --release) (push) Has been cancelled
ci / infra/tests/lint.sh (push) Has been cancelled
ci / playwright apps/stage (allowed to fail) (push) Has been cancelled
2026-10-02 13:16:49 +00:00
acamilo
f21bd45077 fly-feed: silence the failed write itself; the test reproduces pct exec (SIGPIPE ignored, a reader that leaves)
The previous test sent stdout to /dev/null before the pipe, so head never
closed it, and printf still printed its write error. With SIGPIPE ignored
and a slow systemctl stub the old fly-feed prints the live error
('echo: write error: Broken pipe'); the fix prints nothing.
2026-10-02 13:16:49 +00:00
acamilo
75e231c707 fly-feed: status exits quietly on a closed stdout (no broken-pipe error on stderr)
When stdout is closed early (e.g. `fly-feed status | head -1`), the second and later
status_report writes fail with EPIPE; bash's builtins report "write error: Broken pipe"
to stderr even with `trap '' PIPE`, because the failed write is reported by the
runtime, not the signal handler. Route every status_report write through a `say`
helper that checks printf's exit status and exits 0 on the first EPIPE: the reader
is gone, nothing useful is left to do, and `set -e` must not trip on the failing
write.

The change is scoped to status_report: bus/direct's stderr log/record writes are
unaffected, the output text is unchanged, and the switching behaviour and exit
codes are untouched. A test in infra/tests/lint.sh runs `fly-feed status` with
the existing stubbed state into `| head -1` and asserts nothing is written to
stderr.
2026-10-02 13:04:20 +00:00
acamilo
02afc659a4 Merge nobs/gpu-devbox-doc (nobs MiniMax M3; Claude review: fixed the checksum file name, --target and the bench command; re-authored) 2026-10-02 12:48:29 +00:00
acamilo
d501db689c docs: GPU on a build box (dev and benchmarks) section 2026-10-02 12:48:29 +00:00
acamilo
6759555744 docs: v0.7.8 status 2026-10-02 12:27:21 +00:00
acamilo
e4d9d7c9ff Merge port/bus-02 (reviewed: APPROVE-WITH-NOTES; N1-N7 fixed with tests, live speakers soaked): cheaper bus round trips (seal-on-reply, recycled zero-filled staging writers, encode once); session bus transport still off 2026-10-02 12:25:09 +00:00
acamilo
e1f594425e Merge port/gpu-02 (reviewed: APPROVE-WITH-NOTES; N1/N2 fixed: a dead GPU makes the process CPU-only and the replacement restores on the CPU): the GPU brain steps a whole frame per call with state resident on the card (cuda feature, off by default) 2026-10-02 11:51:47 +00:00
acamilo
9a4542de5f flybus: zero-fill a recycled staging file in place instead of truncating and reserving it again
Freeing the blocks and faulting them back in on the producer's next write cost about 36 us a
92,160-byte reply on tmpfs; writing zeros over the blocks already there costs about 10 (rtt,
process mode, interleaved against the branch before the review round). Same guarantee: a
reissued writer reads as zeros, as a fresh allocation does.
2026-10-02 10:59:47 +00:00
acamilo
7d2650ae5e gpu-02 notes: a GPU failure falls back to the CPU for the process lifetime
A CUDA failure (a failed batch or read-back, or an attach that fails at a restart) now marks the
GPU unusable for the process: the replacement agent worker is created on the CPU and restores the
last checkpoint, so a lost device no longer leaves the session unable to restore and a flaky one is
never re-attached in a loop. Worker processes share the record through a marker file the launcher
owns and empties when it starts. Exposed as the LIF_GPU_FALLBACK log line,
fly_brain_backend{backend}, fly_brain_backend_wanted and fly_brain_backend_fallbacks_total, and
fly-watchdog check 11 (report only).

Adds a committed fault-injection hook for the cuda feature (FLY_LIF_CUDA_FAULT or the inject
setters), the recovery harness in legacy_parity, and the cuda_fallback test: init failure, transient
(host current) and permanent (in-process and process) faults, each equal to the CPU reference.
Corrects the runbook, documents the stale host arrays on LifNetwork, and has cuda_session assert
that no fallback hid a CPU pass.
2026-10-02 10:15:03 +00:00
acamilo
da8fa2a927 Merge main (v0.7.7: row 73 + notes, feed and control over flybus, integration feed-rate, BUS-01 notes) into port/bus-02 2026-10-02 10:14:26 +00:00
acamilo
6a92a1902b BUS-02 review notes: recycled writers zero-filled, replays wait for the sealing reply, typed seal failures
The feed and the control API run over flybus in production, so these notes are treated as
live-path correctness.

- N3: the router empties and re-reserves a recycled writer's staging file before reissuing it,
  so no artifact sealed from it (by prefix or whole) carries the previous artifact's bytes;
  ArtifactWriter::seal's doc now holds for every writer. contractDigest text says so.
- N2: a sealing reply is sent with the worker's result cache held, so a duplicate replays the
  sealed artifacts instead of attaching the still-unsealed writer.
- N1: a refused sealing reply is answered as the handler's own seal failure was before BUS-02
  (BACKEND_FAILURE, mutation applied), cached the same way, worker marked failed, and logged.
- N5: a failed staging rename unlinks the writer's own staging file.
- N4: recycle without a sealing attachment is refused even when false; one writer named by two
  attachments is refused as INVALID_ENVELOPE; the SDK checks writers on rpc.call and publish
  replies too.
- N6: the store-directory cache is per client connection; bus-v1 notes the residual case.
- N7: the fly-edge stall test waits for the feed topic; SERVE-01 parity accepts a refused
  /stimulate drained one frame late (retryAfterMs one frame apart, nothing else).
- tests: the review's adversarial lifecycle suite (sealing_lifecycle.rs); recycled-writer content,
  rename failure and recycle edges (sealing.rs); replay-vs-sealing and typed refusal in the worker
  shell; smaller-after-larger artifacts through fly-edge and fly-control-edge.
2026-10-02 10:14:23 +00:00
acamilo
37b3195b0b docs: v0.7.7 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-02 09:43:02 +00:00
acamilo
4b29f08c21 Merge fix/loop-row73-notes (coordinator review of the round; N5 cleared: no live watchdog rule fires): bad hidden-object entries skipped, room ledger forgotten on leaving, blocked one-sided targets release the exits 2026-10-02 09:42:53 +00:00
acamilo
49e48a5075 macros: row 73 review notes -- an errand room's talked entries are forgotten when the fly leaves it, a one-sided target with no standable tile is not waited for, an off-map hidden-event entry is skipped
N3: the talked ledger never forgot within a session, but the cartridge re-shows Bill after the fly
leaves and a Bill whose bag was full never hands over the ticket. While the objective is an errand in
a room the palette notes the room, and on the first frame the fly stands elsewhere with that errand
still the objective it forgets that room's talked entries (Talked::forget_map).

N4: a hidden event pressed from one side whose only stand tile is pushed had no aim, earned no
blocked entry and kept the exits withheld. It now leaves the errand's list at once (palette::servable).

N1: state::hidden_events skipped nothing; one entry off its own map voided the whole map's list. It
now skips that entry and keeps the others.

N2: the item-use dispatch doc comment is back on mod items.
2026-10-02 09:40:49 +00:00
acamilo
bbbfe4b68a docs: control runs over flybus 2026-10-02 07:56:18 +00:00
acamilo
5dad5b3cd7 Merge main into port/gpu-02 2026-10-02 07:49:17 +00:00
acamilo
7d817d8cee GPU-02: the session steps a frame per call, the CUDA backend keeps its state on the device
LifNetwork::step_frame runs a game frame's ticks in one call and ORs every
tick's spikes into the transition's bitset. On the CPU it is exactly the
one-tick loop the session ran; on the GPU it is one batch, with membrane
and refractory left on the device (device-owned state): per frame only the
noise draws, visual drive and plastic gains go up and the spike lists come
down, instead of 1.4 MB per tick (about 24 MB per frame) with the old
step(1) loop and per-batch host sync.

- LifBackend (cpu / cuda:<ordinal>) from FLY_LIF_CUDA / FLY_LIF_CUDA_DEVICE,
  set_backend, configure_sweep (set_sweep_plan without the test hook),
  sync_host, host_state_current, try_step, take_backend_fault.
- export_state downloads the device arrays itself while the host copy is
  stale, so no capture can read old values; the session syncs before
  State.Capture.
- A CUDA failure detaches the backend: if the host state was current the
  frame continues bit-exactly on the CPU, otherwise the agent fails and a
  restore in that worker runs on the CPU. Warm-up no longer panics.
- The legacy agent worker picks its backend explicitly and refuses a GPU it
  cannot have (no feature, no device) at Agent.Initialize instead of
  running the CPU under a GPU label. The FLY_LIF_CUDA hook in
  set_sweep_plan stays for the golden suite and the legacy loop.
- cuda passthrough features on fly-session and fly-legacy-session, so
  FLY_CARGO_FEATURES=cuda reaches flysim-session, fly-shadow, fly-session.
- Tests: step_frame vs the one-tick loop (state and bitset, 1 and 3
  threads), the backend switch; cuda_exact frame mode; a cuda-feature
  session test (FAFB, rollback, restore, checkpoints) against the CPU
  reference.
2026-10-02 07:49:17 +00:00
acamilo
0004ffaf36 Merge fix/loop-row73 (reviewed: APPROVE-WITH-NOTES): rung 16 is Bill's errand inside his house; hidden objects read from the cartridge's table are targets only as the errand's next step; Cerulean graph 2026-10-02 07:43:20 +00:00
acamilo
8b696f8f1c docs: the feed runs over flybus 2026-10-02 07:34:50 +00:00
acamilo
6a063d32b4 Merge fix/integration-feed-rate (ported from a stray archive worktree; 8/8 under load): the integration test asserts the feed's structure, not a wall-clock rate 2026-10-02 07:03:50 +00:00
acamilo
48aedd25ff Merge fix/bus-01-notes (coordinator review): bus shadow check refuses on the session runtime; worker children die with their parent (PDEATHSIG, spawned from async worker threads, never spawn_blocking); digest-mismatch test 2026-10-02 07:03:35 +00:00
acamilo
91d0214cbc flysim integration test: assert the feed's structure, not a wall-clock rate
The publish cadence is a 30 Hz wall-clock timer, so the 25..31 Hz bound failed on a
loaded box (22.5 Hz in the v0.7.6 gate). Log the rate, bound it only against the 2 Hz
idle path, and assert what is deterministic: contiguous seq, at least one frame per
snapshot, brain time advancing 16-17 ticks per frame.

Two more load-dependent races in the same test: /status read the boot header (a 1-rung
ladder) right after /healthz, and the first feed message after the restart could be the
frame-0 boot header. Wait for a running snapshot in both.
2026-10-02 06:20:46 +00:00
acamilo
9d5dd398ca Cargo.lock: the fly-edge dependency the EDGE-02/CTRL-01 merge resolution left out
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-02 06:06:08 +00:00
acamilo
29b51ff336 docs: implementation guide BUS-02 (port slice) entry 2026-10-02 05:30:31 +00:00
acamilo
6bc447a5bd docs: flybus README and bus conformance rows for sealing sends (BUS-02) 2026-10-02 05:23:08 +00:00
acamilo
4935dcc045 BUS-01 review notes: clippy fixes in the new tests 2026-10-02 05:15:45 +00:00
acamilo
210296a0ff docs: v0.7.6 status 2026-10-02 05:00:24 +00:00
acamilo
fc5a579027 Merge port/edge-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE): the video feed over flybus (off by default), fly-feed switch, aux cpus for the bus threads 2026-10-02 04:57:52 +00:00
acamilo
ef48a6aed9 Merge feat/scorecard (reviewed: BLOCK; B1/B2 fixed with the review's proofs): multi-seed play regression harness, per-checkpoint trap rule, v0.7.5 baseline 2026-10-02 04:56:04 +00:00
acamilo
a2449488a5 scorecard: the lockfile gains libc for the crate; docs for the trap rule, Holm and the throws metric 2026-10-02 04:40:14 +00:00
acamilo
0a35b393aa flybus: sealing sends, encode-once router, cheaper client hot path (BUS-02)
- bus-v1 section 12 amendment 2026-10-02: an rpc.call/rpc.reply/publish attachment may name the
  sender's own unsealed writer; the router seals its declared prefix on admission (copy outside
  the state lock), the writer becomes the sender's hold, and with recycle:true the staging
  allocation comes back as a new writer in the reply. A refused sealing send releases every
  writer it named. contractDigest changes.
- SDK: ArtifactWriter::into_unsealed, Responder::reply_sealing; no rpc.responder.release after an
  admitted reply; delivery payloads moved, not cloned; Fields without hashing.
- Router: every frame encoded once (id spliced at selection); admitted payloads forwarded as
  pre-encoded JSON instead of deep copies; seal copies via copy_file_range with a sized buffer;
  client location resolution caches the store directories.
- fly-session: result attachments kept as delivered (no artifact.retain round trip per
  attachment); reply artifacts sealed by the reply that carries them, writers recycled into a
  capacity-bucketed pool.
- tests: sealing.rs; artifacts.rs updated to the amendment. examples/rtt.rs measures a round trip.
2026-10-02 04:28:05 +00:00
acamilo
2bae8a7b6a macros-traps: row 73, with the multi-seed hunt before and after 2026-10-02 04:26:09 +00:00
acamilo
eaae6fd82a EDGE-02 notes: bus threads on an aux cpu (FLY_SESSION_AUX_CPUS, SESSION_AUX_CPUS in the deploy), fly-feed direct never rolled back, watchdog falls back to direct at the 4th failure and never reboots for the edge; runbook cost corrected 2026-10-02 04:22:39 +00:00
acamilo
49309a83bd scorecard: per-checkpoint trap rule, Holm over the metric family, throws count throws, children die with the suite, LegacyConfig fields
The compare could not fail a trap confined to one checkpoint: add a rule per checkpoint
(B trapped on two or more runs and two more than A, or a blocked-macro storm A lacks).
Holm-adjust the sign-flip p-values over the judged metrics (the unadjusted family false-failed
about 15% of releases). throws_per_hour counts THROW BALL done, not starts; blocked throws are
their own reported metric. run-one children get PR_SET_PDEATHSIG. runner.rs sets transport and
placements (main's LegacyConfig); overlay.sh drops those lines for trees without the fields.
2026-10-02 03:50:50 +00:00
acamilo
397a589fae Merge branch 'main' into feat/scorecard 2026-10-02 03:42:45 +00:00
acamilo
d5b576a2c1 Merge main into port/edge-02 (CTRL-01, BUS-01, row 72, parity flake fix) 2026-10-02 03:19:30 +00:00
acamilo
076a6bcbbf BUS-01 review notes: shadow check refuses on the session runtime (N1), workers die with their parent via PR_SET_PDEATHSIG (N2), test for the Hello digest refusal (N3) 2026-10-02 03:04:49 +00:00
acamilo
c6ab8247d9 Merge port/bus-01 (reviewed: APPROVE-WITH-NOTES): the session can run its agent and world over the flybus router on Unix sockets (off by default); per-frame work metric 2026-10-02 02:53:23 +00:00
acamilo
7dc744fe63 scorecard: the lockfile gains the crate 2026-10-02 02:29:15 +00:00
acamilo
ae05221495 scorecard: the v0.7.5 reference card and what it shows; the hunt's windows are reported, not judged 2026-10-02 02:28:16 +00:00
acamilo
3181c5ef7b scorecard: one thread per run and eight runs at a time, and --resume 2026-10-02 02:28:16 +00:00
acamilo
d7547085e5 scorecard: ten brain minutes, four threads, two jobs: the cost the box can bear 2026-10-02 02:28:16 +00:00
acamilo
ae5db47801 scorecard: the overlay can be run from a copy outside a checkout 2026-10-02 02:28:15 +00:00
acamilo
49bae21a4d scorecard: a multi-seed good-play regression harness (fly-scorecard)
A fixed checkpoint set x seeds x brain minutes on the real connectome, on the session runtime or the legacy loop, reduced to JSON: rungs per hour, empty pad, watchdog check 10 rules, ladder-worthy traps, the shop-to-catch funnel, heals, whiteouts, battles, blocked macros. Compare mode pairs two cards by (checkpoint, seed) and judges each metric with a sign-flip permutation test and a tolerance. PokeredTask gains a read-only with_reader for the harness.
2026-10-02 02:28:15 +00:00
acamilo
872dcfc214 docs: macros.md 12.35 and macros-wram.md 17 (row 73); the hidden-event list bound covers the Game Corner's 48 entries, checked on the cartridge 2026-10-02 02:18:22 +00:00
acamilo
24753db620 Merge fix/service-parity-flake (coordinator review: test-only): the parity test waits for the pause's idle header instead of racing it 2026-10-02 02:16:43 +00:00
acamilo
1ebf35d845 Merge main (v0.7.5 + loop-row72 + ctrl-01) into port/bus-01
service_parity: the control-bus runtime runs on SessionArm::LOCAL.
2026-10-02 02:05:33 +00:00
acamilo
0caade6b20 macros: rung 16 is an errand in Bill's house, its PC is a hidden event, and Cerulean's south is behind the trashed house (row 73)
Rung 16's place was at(ROUTE_25), so inside Bill's house GO OBJECTIVE and GO OUT were both the
door: the live Route 25 <-> Bill's house ring. It is now errand(BILLS_HOUSE): the room's people
first, then its things, where the things include the cartridge's own hidden events, read from
HiddenEventMaps/HiddenEventPointers ($11:$6A40/$6A96, pinned from CheckForHiddenEvent's operands
and shape-checked on every read). A hidden event is only ever the errand's next step: GO ITEM,
GO NPC and TALK elsewhere are unchanged. One with a SPRITE_FACING argument (Bill's PC) is
approached and faced from that side only.

Cerulean is split a third time: the town's ground ends at row 28, and Route 5 and Route 9 are on
the ground behind the trashed house ($3e), in by its front door and out by the hole in its back
wall. The house is on the map graph, so the objective toward rung 17 walks through it.

ROM tests from the scout checkpoints (door ring, PC step, live row-71 Route 25, Cerulean
south-half and trashed house) fail on main and pass here. No button, readout, catalog or adapter
change; the compatibility string is unchanged.
2026-10-02 02:05:33 +00:00
acamilo
7d98fbf8ba Merge port/ctrl-01 (reviewed: APPROVE-WITH-NOTES; N1 edge follows flysim, N2 large bodies as artifacts): control API as flybus RPC with per-agent grants, off by default 2026-10-02 01:44:56 +00:00
acamilo
d50914e4c7 control edge follows flysim's stops and starts; large request bodies match direct
N1: flysim.service Wants= flycontrol-edge.service and the edge gets an ExecCondition on FLY_CONTROL_VIA
(no [Install]), the pattern flyedge uses, so fly-loop-reset's stop and start brings :7401 back in bus
mode and the edge stays skipped in direct mode. lint.sh checks the wiring and runs the condition;
runbook and flybus.md updated (no enable step).

N2: a request body over 48 KiB of JSON travels as a sealed request artifact, so the edge answers
what direct answers instead of 503 INVALID_ENVELOPE. parity test covers 49 KB to 300 KB bodies on
/chat, /stimulate and /reward plus an unparseable large body.
2026-10-02 01:43:34 +00:00
acamilo
3ea56ef3f8 tests: service_parity waits for the idle header instead of racing the pause
The idle-headers check failed 8 of 12 runs on a loaded build box (main
46e25ef: 3 of 4). The script paused and resumed 2 ms apart, so whether the
loop published a header-only idle snapshot in that window (due at 2 Hz) was
wall-clock luck, and legacy and session often disagreed. Not a product race:
the cadence is the protocol's.

The recorder now holds the resume until the first idle header has been seen
(bounded wait, 30 s), and the compare requires BOTH runtimes to have published
one, rather than merely agreeing on whether any did. The first idle header is
compared as before except for its `events` list: which publish carries the
pause's events is wall clock, and the events are compared in the running
snapshots and the event log.

Also fixed, found once the first was gone (1 in 20 under load): the two
sugars sent at one frame must be drained together; when the loop publishes
a snapshot while they are being sent the run is flagged incomplete and
repeated, like a missed frame.

What it proves, unchanged: a pause makes each runtime publish header-only
idle snapshots (status paused, no attachments) whose fields match the legacy
loop, and the script's responses, feed, event log, journal and final
checkpoint are identical between runtimes.

Under load (build box, load ~25 on 6 cores), toy_raw_service_contracts:
before 4/12 pass, after 40/40.
2026-10-02 01:12:56 +00:00
acamilo
74a3c12857 Merge fix/loop-row72 (coordinator review: test-only, both tests stale): the GO SHOP and GO HEAL ROM tests start where the macro is dealt 2026-10-02 00:44:35 +00:00
acamilo
1382f94cf3 runbook: what the rehearsal measured 2026-10-02 00:43:32 +00:00
acamilo
021c92c66f docs: BUS-01 (port slice) in the implementation guide
The live session's participants on the router: how to select it, what it
took, parity in every arm, and the measurement -- about 8 ms a frame over
the lane on the release CPU model, so the lane stays live.
2026-10-02 00:33:25 +00:00
acamilo
b2fd148f52 session: the live composition's participants on the router (BUS-01)
FLY_SESSION_TRANSPORT=bus (flysim-session --transport bus) runs the
agent and the world as socket clients of the session's router, one
process each by default (FLY_SESSION_MODE=thread and in-process too);
local, the PERF-01 lane, stays the default. Results, traces, checkpoints
and the compatibility string are the same in every arm (SessionArm:
local, bus/in-process, bus/thread, bus/process; FLY_PARITY_ARMS picks
them for the parity suites).

- process-mode placement: the service splits its cpuset as PERF-02 does
  and hands each process its CPUs (--host-cpus, --sweep-cpus;
  Launcher::place_process; pool::apply_placement); FLY_SESSION_AUX_CPUS
  moves the service and the world
- the launcher's own clients in memory in thread and process modes
- participants on a one-worker runtime; long handlers under
  block_in_place, which fixes a process-mode boot that failed when
  Agent.Initialize outlived the 2 s probe on a loaded box
- writers allocated ahead (WriterPool); a worker's own seals cached by
  clone, not a second hold
- over the bus the agent's Commit attaches its feed status, which the
  host reads instead of calling Legacy.FeedStatus at every publish
- fly-shadow --mode / FLY_SHADOW_MODE names the topology, forwarded to a
  remote box; the verdict records candidate.transport; fly-shadow check
  --require-arm

legacy-gameboy-v1 section 12 and 18 carry the dated amendments.
2026-10-02 00:09:41 +00:00
acamilo
8b6d69e13c infra: fly-runtime session --bus; shadow of the bus topology
fly-runtime session --bus (session-bus) writes FLY_SESSION_TRANSPORT=bus
into the runtime drop-in and needs the release's fly-session worker;
session --local takes it out; a flag-less session (05-deploy's refresh)
keeps it. status prints the transport. 05-deploy refuses a release
without fly-session while the drop-in says bus.

fly-shadow-run start --bus runs the shadow's session on the bus
(FLY_SHADOW_MODE=bus/process, forwarded to a remote box by the relay);
check --bus requires a verdict that ran it. start refuses while the live
fly runs the session runtime, which writes no trace to follow. Runbook
and lint cover both.
2026-10-01 23:57:34 +00:00
acamilo
673eec54d5 flysim: per-frame compute time on /metrics
fly_frame_work_mean_ms, _p99_ms, _max_ms and _frames: the loop's work per
frame without its pacing sleep, over the last 3,600 frames, so the
headroom a paced realtime factor of 1.0 hides is visible. The legacy loop
records it here; the session runtime's host records it the same way.
2026-10-01 23:57:29 +00:00
acamilo
49f5496d2a flybus: deliveries carry read locations; small store I/O in place; no body copies
A delivery's attachments now name the read location their ownership
grants (bus-v1 section 12, amendment 2026-10-01; contractDigest changes),
so a delivered artifact is read without an artifact.open round trip. A
client attachment that carries one is refused as an unknown field.

SDK and router only, no wire change: staging allocation, seals and
read_all up to 256 KiB run in place instead of on the blocking pool;
Artifact::is_hold tells an explicit hold from a delivery's handle; an
envelope is encoded from borrowed parts and decoded without copying its
body.
2026-10-01 23:57:29 +00:00
acamilo
39efc4af5c docs: control over the bus (CTRL-01)
Services and methods, the grant table as the no-button guarantee, scoping
per session, agent and controller port, and what in control-api.md is
single-fly.
2026-10-01 23:33:59 +00:00
acamilo
8474d93eb0 infra: flycontrol-edge.service and the FLY_CONTROL_VIA switch
Off by default. 05-deploy validates and writes FLY_CONTROL_VIA; the build
and package ship fly-control-edge; the edge gets the page's cpus. With the
control API on the bus, watchdog check 1 reads flysim's own /healthz and
check 1b restarts only the edge. Runbook: the live switch and rollback.
2026-10-01 23:33:59 +00:00
acamilo
29f9b7da3b flysim: the control API as flybus services with per-client grants (FLY_CONTROL_VIA=bus)
The control semantics move to flysim::control, one ControlRequest per
docs/control-api.md endpoint; flysim::api becomes the HTTP layer over a
ControlBackend. flysim::controlbus registers them as services scoped per
session and per agent (fly), with a closed grant table per client role;
flysim::bus composes the feed and control on one embedded router.
fly-control-edge serves :7401 from the services with flysim's own router.

Tests: every endpoint through the edge equals direct (status, headers,
body, and raw HTTP over TCP); grants refuse what they should, including
an input service on a shared router and per-agent/per-port player grants;
backpressure, cancel, deadlines and the edge's unbind/rebind; serve() in
control-bus mode; the session runtime's service contracts over the bus.
2026-10-01 23:33:59 +00:00
acamilo
6851d6f5a3 rom_macros_mode: GO SHOP test from a state where it is dealt (rung-11 Pewter), GO HEAL test forced hot from the first frame
Both tests passed vacuously until the Viridian stall checkpoint was mapped. GO SHOP is dealt for
a service need since rows 62/66 and the parcel errand is GO OBJECTIVE's, so the Viridian
checkpoint (parcel in the bag) rightly has no GO SHOP. In the GO HEAL test the first hold was the
rotation's GO OBJECTIVE, which walked to Oak's lab and left the area.
2026-10-01 23:26:24 +00:00
acamilo
5ca3488c1f runbook, flybus and tour: the feed over the bus in production 2026-10-01 23:17:58 +00:00
acamilo
6612f9ae9c feed bus in production: fly-feed switch, flysim wants the edge, watchdog checks the edge and falls back, deploy refuses a release without fly-edge 2026-10-01 22:10:44 +00:00
acamilo
12321bb513 fly-edge: healthz fails when the bus goes silent; snapshot age gauge 2026-10-01 21:56:34 +00:00
acamilo
23cc217221 flysim-session serves the feed over the bus: a test of the real binary against direct, and a restart under the edge 2026-10-01 21:55:12 +00:00
acamilo
46e25ef3fc docs: cutover to the session runtime
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 20:47:16 +00:00
acamilo
49bb69e5da docs: v0.7.5 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 15:58:22 +00:00
acamilo
2c1b51695a Merge port/perf-02 (reviewed: r1 APPROVE-WITH-NOTES, r2 APPROVE-WITH-NOTES; R1-R3 addressed): the session pins its sweep workers, and the sim's cpus are its own 2026-10-01 15:58:22 +00:00
acamilo
ac7be4a204 infra: fly-cpu-confine also confines /.lxc, check ignores its own chain (PERF-02 review R1-R3)
apply/release/status now cover the cgroup pct exec lands in (/.lxc, only when
it already exists, warn-only when unwritable). check no longer counts its own
process or its parents. Runbook: rollback via an older 05-deploy needs
fly-cpu-confine release; the exact post-first-deploy status/check commands.
2026-10-01 15:57:46 +00:00
acamilo
ab537d1045 infra: the sim's cpus are exclusive to the sim (PERF-02 review N1)
A pinned sweep worker cannot leave its cpu, so any sustained cpu-bound process allowed there
collapsed the session runtime to 0.14x real time. flysim and flysim-session now run in
flysim.slice (AllowedCPUs = the sim's set) and bin/fly-cpu-confine, run by their ExecStartPre,
confines system.slice, user.slice and init.scope to the other cpus. It refuses while a sim unit
still sits outside the slice (shrinking system.slice under it would make it float). Without a
partition the deploy writes FLY_SESSION_PIN=0. fly-recap and fly-retention run at SCHED_IDLE.
The drop-in plan is one function (cpuset_dropin_plan) shared by the deploy and lint; lint covers the
plan, the units, the deploy wiring and fly-cpu-confine against a stub systemctl and a fake /proc.
Runbook and README updated.
2026-10-01 15:01:47 +00:00
acamilo
80104f0d98 docs: v0.7.4 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 14:47:23 +00:00
acamilo
15ab7ee002 Merge fix/loop-row71 (reviewed: APPROVE both): the bag and mart cursors count the list's scroll offset 2026-10-01 14:47:23 +00:00
acamilo
ecff9bcff4 docs: macros-traps row 71 trap hunt before/after 2026-10-01 13:49:20 +00:00
acamilo
2ca0853c9a docs: macros-traps row 71 2026-10-01 13:18:49 +00:00
acamilo
a6632b4acf macros: the mart's list cursor is the entry too; the catch test pins its first-window ball (row 71)
state::shop reports the buy and sell lists' cursor as row plus
wListScrollOffset, only while the list is on screen. MART_CURSOR_ROWS
stays. The catch ROM test now asserts its ball sits in the bag window's
first rows, so it covers the unscrolled throw beside row 71's scrolled
one.
2026-10-01 13:10:05 +00:00
acamilo
2dcce9452a docs: row 71, the battle bag's scroll offset (macros.md 12.34, macros-wram.md 16) 2026-10-01 12:57:03 +00:00
acamilo
85d2da363a macros: the battle bag's cursor is the entry, not the window's row (row 71)
The battle bag is a DisplayListMenuID list: the arrow walks rows 0..2 and
the window scrolls under it. state::battle reported wCurrentMenuItem alone
as the bag cursor, so THROW BALL and ITEM could never reach a bag entry
past the third. Live on rung 15 a wild Oddish sat at low HP with the
Poke Ball fifth in the bag; row 69 left THROW BALL alone on the pad and
every start blocked.

The cursor is now wCurrentMenuItem + wListScrollOffset, the sum the
cartridge makes on A. wListScrollOffset ($CC36) is pinned from the operand
of DisplayListMenuIDLoop's read and checked by a ROM test. The ROM test
from the live trap checkpoint (FLY_ROW71_CHECKPOINT) blocks on main and
throws and catches on this branch.
2026-10-01 12:57:03 +00:00
acamilo
8fa98b0b03 session: pin the sweep workers one per cpu in flysim-session (PERF-02)
CUT-01's speed probation fell back at a median realtime factor of 0.959.
With exactly as many cpus as sweep threads, the session's host threads
(dispatching tokio worker, coordinator, listeners) sleep and wake around
every transition, the sweep workers park and wake with them, and the
scheduler often stacks two workers on one cpu: the session's ticks ran
about 35% slower than the legacy loop's on the same frames (equal with a
spare cpu).

flybrain_core::pool::place_workers gives each spawned sweep worker a cpu
of its own and confines every other thread to the rest of the cpuset;
flysim-session calls it before spawning anything (in-process and thread
modes; FLY_SESSION_PIN=0 turns it off). Placement chooses cpus only, so
no result, trace or checkpoint changes; the legacy loop, process mode and
the shadow binary never call it. The compatibility string is unchanged.

On the release cpu model, 4 cpus, 4 threads, same frames: session 16.16
-> 12.98 ms/frame (legacy 10.53). The service's profile line prints the
measurement spans and the brain's phase split when FLY_SESSION_PROFILE is
set. Docs: legacy-gameboy-v1 section 12 amendment, implementation entry.
2026-10-01 12:16:59 +00:00
acamilo
390d118460 infra: fly-shadow-run check reads fly.env as KEY=VALUE lines, never sources it
fly.env is systemd EnvironmentFile syntax; GAME_TITLE=Pokemon Red is valid
there and a shell error when sourced. The v0.7.3 cutover's check died on it
(exit 127) after a passing verdict. Parse it as fly-runtime does; lint
refuses any infra/bin script that sources fly.env.
2026-10-01 09:54:11 +00:00
acamilo
16cb3b754b infra: the box set-up's ingest probe tolerates the usage exit
fly-shadow ingest without --root exits 2; piped into grep under pipefail the
probe failed even when the message matched, so the set-up refused every
release. Found on its first run as root on a real box.
2026-10-01 05:56:11 +00:00
acamilo
519503a523 docs: v0.7.3 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 05:10:22 +00:00
acamilo
e8d8584647 Merge port/shadow-02 (reviewed: r1 BLOCK, r2 BLOCK, r3 APPROVE-WITH-NOTES, final APPROVE): the shadow runs on a build box; the release container relays the trace and keeps the guard and the verdict 2026-10-01 05:10:22 +00:00
acamilo
01fae60e37 shadow: r3 notes: a reward skip still reads on for a stop; the relay flags a byte-cap stop; a window end takes back a pass; runbook: a new run after a long outage
N5: after an operator reward pulse the shadow reads the rest of the trace for its stop line, which ends the window. N4: the relay treats a byte-cap stop exactly like a no-consumer stop. N3: end_window turns a pass back into running and clears passedAt and reason. N2: the runbook says plainly that a long outage costs the run and gives the command to start a new one.
2026-10-01 04:42:02 +00:00
acamilo
ff67e6cdd6 shadow: a trace stop ends the verdict's window; a pass counts only brain time after the last coverage gap (SHADOW-02 review B2)
A stopped trace (no consumer, byte cap) is no longer an allowed skip: the shadow drops the brain time and saves compared before it, so a restarted box shadow that replays a stopped trace cannot count pre-gap time. The relay closes coverageLost only when the verdict's window.lastStopTrace is the lost trace or later, persists coverageLost (fsync) before forwarding the stop, and check refuses a verdict without a window. Runbook: a mid-run relay restart costs the run.
2026-10-01 03:49:18 +00:00
acamilo
239a86f793 infra: fly-shadow-run's check reads FLY_ENV_FILE and FLY_CURRENT_DIR when set (the two-box run); shellcheck 2026-10-01 00:45:54 +00:00
acamilo
b39ee8e805 shadow: a lost coverage is never forgotten (SHADOW-02 review B1) and the review notes
B1: after an outage of more than ten minutes flysim stops its trace for want of a
consumer and the live fly runs untraced. When the link heals the relay reported healthy
and, counted in trace lines, the box's lag fell under the catch-up bound before its
shadow reached the stop, so `check` could pass for about a minute. The relay now scans
the trace bytes it forwards for that stop and sets a sticky coverageLost in relay.json
(kept across a relay restart of the run; cleared only by a new shadow window, which
takes the stop as history) and reports itself not healthy. `check` refuses on
coverageLost, on a live trace not written for 90 s, and on a run id that is not the
drop-in's (also for a verdict that carries one without a remote drop-in).

Notes: the divergence files the box may send are bounded (after a diverged verdict, at
most three, capped in size); the saves queue holds twelve minutes and the relay unit
gets 1G; fly-shadow-remote-setup keeps authorized_keys in a root-owned home apart from
the mirror, never follows a symlink there as root and requires --from; the runbook
documents the clock-skew refusal, the recovered-stop rule and the first-hour RTF watch.
Also: the ingest lists the mirror's traces under its ledger lock (a file created between
the listing and the lock was marked finished).
2026-10-01 00:45:54 +00:00
acamilo
32df851c16 shadow: saves read by the relay survive a broken connection
A save is pending from the moment the relay reads it until the box's byte
count shows it arrived; a new connection sends again every pending save the
box does not hold, before any trace. In the two-box rehearsal an 11-minute
stall that ended in a broken connection lost the saves queued on it.
2026-10-01 00:45:54 +00:00
acamilo
c418a9b352 docs, infra: SHADOW-02 measurements; box setup --threads
implementation.md gains the SHADOW-02 entry (tests, the two-box rehearsal,
per-box cost, the trace's own cost on the live loop and why a writer thread
was rejected). The runbook's resources and box choice carry the measured
numbers; fly-shadow-remote-setup takes --threads (default 4) with --cpus in
one drop-in.
2026-10-01 00:45:54 +00:00
acamilo
b03ddc957d shadow: the relay never blocks on a stalled link
A writer thread owns the ssh pipe. The relay keeps ticking through a stall,
reports itself unhealthy and stops the heartbeat; new saves are still read the
moment they appear and held in memory (256 MiB, about 8 minutes of hot saves:
the container keeps a hot save about ten seconds, and a 3-minute stall in the
two-box rehearsal lost 33 of them); trace bytes wait on disk (16 MiB queued at
most), and a newer trace file and the journal wait until every older file is
complete on its way. A reconnect resends what the box does not hold.
2026-10-01 00:45:54 +00:00
acamilo
ac7762eb00 shadow: ingest unit tests (release refusal, offsets, names, run reset, env allowlist) 2026-10-01 00:45:54 +00:00
acamilo
56a315eda1 shadow: SHADOW-02, the shadow run on a build box
The on-container shadow cost the live fly real time (RTF 0.9998 -> 0.93-0.98,
27 ms/frame on shared CPUs, falling behind every hour). fly-shadow gains:

- relay (release container, as flyshadow.service): streams new saves, the
  trace bytes of this run and the sugar journal over one ssh connection;
  writes the box shadow's verdict back (runId-bound, lagTransitions plus the
  unsynced tail, a relay member) and keeps flysim's consumer heartbeat fresh
  only while connected, the box shadow of this run is alive and the box has
  everything that was on disk a minute ago; exits 3 on a remote divergence.
- ingest (build box, the relay key's forced command): checks the release
  directory and binary hashes against its own, resets the mirror for a new
  run, writes the mirror and reports acks, liveness, verdict, divergence.
- run --run-id-file: the verdict carries runId; a new id exits 4.
- coverage: a no-consumer trace stop while following is a coverage
  divergence (a stop that predates the shadow stays a trace-cap skip); the
  journal is read before the trace directory is listed.

tests/shadow_remote.rs runs a real flysim, the relay, the real ingest binary
and a remote shadow through a restart, a remote shadow death and a sync
stall (coverage divergence relayed back).

infra: fly-shadow-run start runs remote with /etc/fly/shadow-remote.env
(a flyshadow.service drop-in running the relay; --local keeps the old
placement), check also needs relay.json healthy; infra/box/ holds the build
box's flyshadow-remote.service/.path and fly-shadow-remote-setup (release at
the same path, root-owned restrict,command= authorized_keys); 02-base adds
openssh-client. Runbook, lint and a dated legacy-gameboy-v1 section 18
amendment.
2026-10-01 00:45:54 +00:00
acamilo
ce6dcfeb65 docs: v0.7.2 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-10-01 00:45:36 +00:00
acamilo
2e92381296 Merge fix/loop-row70 ladder (reviewed: r3 APPROVE, independent read APPROVE-WITH-NOTES): resets keep a catch for 2 h and count only unseen rewards as progress 2026-10-01 00:05:49 +00:00
acamilo
e4272ba00d infra: a reset's replay is not progress; the ladder measures progress and catches against the reward names it has seen (row 70 review r3)
The watchdog names each lasting reward in window.progress.keys (kind:label).
fly-loop-recover keeps progressSeen (last 2000 names): only a new name starts
the ladder over (and only after a clear probe past SETTLE), and only a new
species opens the 2 h protection. Restarts stay HOLD apart after a start-over;
a failed reset does not mark its archive. Only-rung-11-escapes trap: 2.1 h
(3.3 h after a catch), was 5.6 h / 6.8 h; v0.7.0 2.1 h.
2026-09-30 23:58:13 +00:00
acamilo
18bef06cef infra: catch protection in the recovery ladder is 2 hours, not 6 (operator decision) 2026-09-30 23:28:44 +00:00
acamilo
e35858e96e infra: only a catch-protected reset is held; a step skipped for the archive just used climbs, so the rung below is reached promptly (row 70 review r2) 2026-09-30 20:59:58 +00:00
acamilo
a84e617fc9 infra: a held reset does not climb the ladder and the last-archive marker expires, so a restart-proof trap is reset in bounded time (row 70 review) 2026-09-30 20:57:52 +00:00
acamilo
d7f5ef5ff7 infra: the recovery ladder starts over after real progress, keeps a recent catch, and never replays one archive twice (row 70)
Check 10 now reports window.progress (a milestone, and pokedex/area/trainer/badge rewards; the
species alone), read by no rule. fly-loop-recover returns to level 0 when lasting progress
follows the last step by more than SETTLE, demotes a milestone reset to a restart within six
hours of a species owned, and never restores the archive the last reset restored (a restore is
deterministic: the live rung-11 replay matched the first one event for event and walked into the
same trap). Ladder tests, lint check 10 case 9, loop-recovery.md, macros-traps row 70b-e.
2026-09-30 20:57:52 +00:00
acamilo
539d73bc36 tests: the shadow test waits for the verdict status to settle before asserting it
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
The compared count and the status are recomputed on different verdict
writes; on a loaded box the v0.7.1 release gate read the new count with
the status still 'running'. Bounded wait (120 s); assertions unchanged.
2026-09-30 20:57:27 +00:00
acamilo
7420541df6 docs: v0.7.1 status 2026-09-30 20:21:19 +00:00
acamilo
59ac004b76 Merge fix/loop-row70 hotfix (6eeff4a, reviewed: APPROVE): the SHIFT-style change-Pokémon offer is not a forced switch 2026-09-30 20:21:19 +00:00
acamilo
6eeff4a735 macros: the SHIFT offer's party list is the fly's turn, not a forced switch (row 70)
EnemySendOut opens the party list with BATTLE_PARTY_MENU when the fly answers YES to
"Will <mon> change POKeMON?", the value ChooseNextMon uses after a faint. Read as a forced
switch its pad was SWITCH, NEXT with no B: live in Mt. Moon after the first catch, NEXT on the
Pokemon already out for 58 brain minutes. A forced switch now also needs the active battler at
0 HP; the offer's pad is the party list's SWITCH and BACK.

Unit tests for both lists; ROM tests from the live trap (FLY_ROW70_CHECKPOINT) and from a real
forced switch after a faint (FLY_ROW70_FORCED_CHECKPOINT); macros.md 12.33, macros-traps row 70.
2026-09-30 19:27:08 +00:00
acamilo
4200a99e7e docs: v0.7.0 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-09-30 14:15:14 +00:00
acamilo
c0be101c5f Merge release/v0.7.0-rc: the flybus session runtime ships beside legacy (installed, not selected), with the shadow run and the guarded cutover 2026-09-30 14:15:14 +00:00
acamilo
6c0cc2b717 infra: session stops the shadow and guard; shadow start verifies its cpuset
fly-runtime session now stops a running shadow and its guard (fly-shadow-run stop,
no flysim restart) once flysim is healthy on the session runtime, so the guard
cannot judge the session against the legacy baseline during the probation. The
runbook cutover drops the restart in step 5.

fly-shadow-run start refuses, starting nothing, unless flyshadow's cpuset drop-in
exists and its AllowedCPUs is non-empty and disjoint from flysim.service's.

Tests in infra/tests/lint.sh cover both.
2026-09-30 13:36:12 +00:00
acamilo
a3a0d957e2 Merge feat/cut-01-probation: the switch to the session runtime is a 30-minute speed probation 2026-09-30 12:59:57 +00:00
acamilo
c1f0dde9e9 infra: CUT-01 speed probation after fly-runtime session
fly-runtime session now starts fly-runtime-probation (timer every 60 s, 30 minutes):
after a 300 s warm-up, a sustained median realtime factor below 0.97 or lag growth
over 30 s in a 10-minute window runs fly-runtime fallback with reason speed. A pass
writes /run/fly/runtime-probation.json and stops the timer; fly-runtime legacy and
every fallback cancel it; state on disk resumes it after a reboot. Lint drives it over
synthetic traces; runbook gets the end-to-end cutover procedure.
2026-09-30 12:58:05 +00:00
acamilo
416c73941a lint: the build and package checks name flysim-session, fly-shadow and fly-session together 2026-09-30 10:19:32 +00:00
acamilo
b3f6d6fbba Merge port/shadow-01 (SHADOW-01) into v0.7.0 release candidate
Conflicts: deploy/build/package scripts (flysim-session, fly-shadow and fly-session all
built, packaged and given cpuset drop-ins; fly-runtime and fly-shadow-run both converged),
fly-legacy-session Cargo.toml and lib.rs (service and shadow both kept, tokio gains signal),
runbook and implementation guide (both sections kept).
2026-09-30 10:09:01 +00:00
acamilo
b996695f0a Merge port/serve-01 (SERVE-01) into v0.7.0 release candidate
Conflicts in fly-legacy-session task.rs (feed record next to PERF-01 profile spans) and
fly-session coordinator.rs (media_bytes doc, read_agent_extension and trim_records kept
alongside PERF-01 spans, publish span and publish metric both kept).
2026-09-30 10:06:03 +00:00
acamilo
7f5f5d0e5d Merge port/perf-01 (PERF-01) into v0.7.0 release candidate 2026-09-30 10:05:07 +00:00
acamilo
6b77b87991 Merge port/task-01 (TASK-01) into v0.7.0 release candidate 2026-09-30 10:05:06 +00:00
acamilo
0b56e03ae3 shadow: a live process that leaves no trace fails the verdict; the test builds the flysim it runs
tests/shadow.rs failed with 'one trace file per process' (0 vs 2) on a
build box because it ran a flysim binary that was not built from the
tree under test: cargo test -p fly-legacy-session does not build
flysim's binary, and the box's bx target directory was shared by name
with other trees, so the binary beside the test predated FLY_TRACE_DIR
and wrote no trace. Reproduced by running that test binary against its
stale flysim; not a timing or segment-handling bug. The test now builds
the flysim binary itself (cargo build -p flysim --bin flysim, same
target directory and profile), proved on a target another tree had
populated.

Production could miss a whole process the same way (a trace that
cannot be created, a failed consumer check), so the shadow now holds
every flysim boot header in the live sugar journal since it started to
a trace file created during that boot; an untraced process is a
coverage divergence and fails the verdict. In FLY_TRACE_DIR mode a trace
that cannot be created no longer stops flysim from starting (it runs
untraced and the shadow fails), and a heartbeat dated ahead of the
clock counts as fresh. The test adds an untraced third process and
expects the coverage divergence.
2026-09-30 04:57:50 +00:00
acamilo
e04b0c76b0 session_trace: boot parity accepts the adapter migrations v0.6.7 deploys with
The live checkpoints the boot parity starts from are pokered-unique8-v7 files;
since row 68 (v8) a boot takes them only with FLY_ACCEPT_ADAPTERS, as the
v0.6.7 deploy sets it. The test sets the adapter's own MIGRATES_FROM when the
environment names none; both runtimes read the same list.
2026-09-30 04:11:06 +00:00
acamilo
f7ca35ba2c infra: the shadow guard survives the shadow's crash-restart delay; check needs a live guard and a baseline; refuse a verdict dated in the future
Review round 3, G1-a: the guard stops only when flyshadow's ActiveState is inactive or failed
(systemctl show), not while it is activating/auto-restart. check also requires the guard timer
active and baseline.json. allows_cutover refuses an updatedAt more than 60 s ahead of the clock.
Lint drives the guard and check with a fake systemctl; a real systemd 257 user manager run is
kept in the review notes.
2026-09-30 04:06:38 +00:00
acamilo
c56e04cdf8 docs: PERF-01 in legacy-gameboy-v1 (release configuration) and the implementation guide 2026-09-30 03:57:05 +00:00
acamilo
d2d65a4a60 tests: recorded live-fly RTF traces for the shadow guard; docs: review round 2 (SHADOW-01)
Four recordings from a real flysim at real time, with and without a real
fly-shadow (infra/tests/fixtures/shadow-guard): alone and with an idle
shadow on other cpus the guard does not trip; with a shadow on the fly's
own cpu (0.66 -> 0.44-0.60) it trips at check 7. Section 18 and the
implementation guide record R3, G1 (both guards), N3, the rebase onto
port/task-01 eaf588d and the merge of main v0.6.7 (adapter v8).
2026-09-30 03:47:37 +00:00
acamilo
5a7747210f Merge main (v0.6.7: row 68 damage reward, adapter pokered-unique8-v8) into port/shadow-01 2026-09-30 03:16:36 +00:00
acamilo
6634b33e80 infra: the guard's baseline is robust to a step in its window (median, MAD)
A real recording (a flysim whose box load stepped 1.0 -> 0.66 inside the
10-minute window) widened the old mean/sd margin to 0.25 and hid a
genuine shadow-induced drop to 0.44-0.60. The baseline RTF is now the
median of the window, its spread 1.4826 x the median absolute deviation,
and the lag rate is taken over the most recent half. The recording now
trips at check 7; over 800 synthetic 3-hour runs shaped on the release
CT (flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per second and per sample)
there is no false trip, and all 400 degradations (to 0.55-0.75, and
0.66 -> 0.58) trip.
2026-09-30 03:16:36 +00:00
acamilo
2058fff54a Merge main (606e386, row 68: pokered-unique8-v8) into port/perf-01 2026-09-30 03:09:59 +00:00
acamilo
606e386e86 docs: v0.6.7 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-09-30 03:06:09 +00:00
acamilo
790347af7d Merge feat/damage-reward (reviewed: APPROVE-WITH-NOTES): pay the fly for damage its own attacks deal, adapter pokered-unique8-v8 2026-09-30 03:06:05 +00:00
acamilo
8618e38a5f fly-session: clippy (box the bus request), race test starts from its torn state
The admission race test (TASK-01 R2-3) spawned its hammer before the first
iteration set the queue up; on a loaded build box the hammer could admit into
the empty initial queue, which is a legitimate admission, and fail the test.
2026-09-30 02:55:51 +00:00
acamilo
9a2d7c0286 PERF-01: the local lane carries every endpoint method but Worker.*; contract amendments
- worker: local_lane_carries is every method but Worker.*, so an endpoint's
  read-only extension (SERVE-01's Legacy.FeedStatus) no longer crosses the bus.
- ipc-v1 section 1, bus-v1 section 12, step-v1 and the framework README: the
  in-process local lane and in-memory artifacts, dated 2026-09-30.
2026-09-30 02:42:17 +00:00
acamilo
be73014bf5 docs: the stage folds a battle's damage hits into one ticker row 2026-09-30 02:41:58 +00:00
acamilo
fa8c9305a7 PERF-01: spikes gathered per tick, 1 Hz session snapshots, fewer copies
- flybrain-core: LifNetwork::tick_spikes, the last CPU tick's spike list
  (None under the GPU backend); a test proves it is exactly the neurons the
  tick stamped and that window unions equal the last_spike_ms scan.
- legacy agent: Prepare runs its ticks one at a time and ORs each tick's list
  into the transition's bitset; Commit uses it instead of scanning 139,255
  last-spike times (falls back to the scan when no list is kept).
- legacy composition: a service session publishes its committed snapshot
  every 60th boundary (plus every boundary with events or boundary actions);
  nothing in the release subscribes, and each publication seals copies of
  the frame and the audio.
- coordinator: a single dispatch job is called in place; worker shell moves
  the reply result instead of cloning it; publication promotions begin when
  Advance answers whatever the cadence.
- profile: record() for a sample from another clock; finer spans (shell,
  local lane, handlers, advance parse/build, the brain's phase clock).
2026-09-30 02:15:25 +00:00
acamilo
d10aa09afa stage: the ticker folds a battle's hits into one damage row, with two ticker mockups 2026-09-30 02:14:41 +00:00
acamilo
9462c2e28a docs: row 68, the damage reward survey, and a status line
macros-traps: row 68, the catalog's answer to row 67. Three starts x 120 brain
minutes from the row 67 checkpoint, v7 against v8 (the palette seed does not
diversify a run; the starts are the checkpoint and the game run 7 and 19 frames
ahead of the brain). v8 beat the Jr. Trainer in 2 of 3 (one also took the
Boulder Badge), v7 in 0 of 3; the move choice did not shift more under v8 than
under v7 (BUBBLE about 15% -> 20% in both), so no learned preference is shown
inside two brain hours. stream-mvp-plan: an unreleased status line.
2026-09-30 02:11:56 +00:00
acamilo
e9d8f1a753 docs: the damage reward, and the v7 migration in deploy examples
rewards-learning: the catalog row, "Damage rewards" (what counts as the fly's
attack, the magnitudes against the catalog, what cannot be farmed, why `damage`
has no feed counter, the measured press-to-payout delay against the 5 s trace,
the migration) and an honesty paragraph. flysim.md: v7 -> v8 under "Restoring
across an adapter version", with the exact compatibility-string change.
macros-wram: hWhoseTurn, wPlayerMoveNum, wEnemyMonPartyPos and the stale
wEnemyMon. Deploy examples name pokered-unique8-v7 (example.env: add v6 to keep
the pre-v0.6.0 milestone archives restorable).
2026-09-30 02:11:45 +00:00
acamilo
3914f824ce rewards: rom_damage reports how long after the MOVE press each hit is paid 2026-09-30 02:11:45 +00:00
acamilo
17c4c88423 session types: the legacy composition names pokered-unique8-v8
The example composition's adapter and FLYSIM01 string move to v8 with the live
adapter, and the fixtures are regenerated by update_fixtures (composition digest
44916db0... -> d37ccb40...); invalid.json's hand-written cases follow, with the
one deliberately mismatched string moving from v6 to v7 so it is still the
previous adapter. Branches that carry these fixtures (the port stack) regenerate
them the same way on rebase.
2026-09-30 02:11:45 +00:00
acamilo
dfc9a2d227 rewards: damage, adapter v8 with a v7 migration
The operator's decision of 2026-09-29, chosen over a pad rule that would have
withheld a stat move once used: pay the fly for the HP its own attack removes
from the Pokemon it is fighting, so the move that deals damage is worth more
than the one that does not. Row 67: the live fly lost the Pewter Gym's Jr.
Trainer 29 times running with TAIL WHIP 155, BUBBLE 23, TACKLE 0, and nothing in
the catalog paid for anything inside a battle it did not win.

`damage`, the twelfth kind, 80 ms. 0.20 per whole enemy Pokemon's max HP, paid
in proportion on the sample the HP drops; +0.05 when the fly's hit knocks out a
trainer's Pokemon; at most 0.50 a battle (the trainer rule's own value, which
two Pokemon reach exactly). A wild battle pays at the wild-KO rule's scale, 1,
1/2, 1/3, for its first three battles per (map, species, level) that paid any
damage, then nothing, and a rollback blocks every key that has paid
(damageCounts, replay-blocked damage:<key>). Trainer battles keep no lifetime
ledger: a trainer is fought again only after losing to it.

The fly's attack is a drop in wEnemyMonHP on a sample where hWhoseTurn ($FFF3,
counted from the hJoyLast anchor to the end of HRAM) reads 0 and wPlayerMoveNum
is not STRUGGLE. ApplyDamageToEnemyPokemon runs in ExecutePlayerMove with it 0;
the enemy's poison, burn and Leech Seed ticks (HandlePoisonBurnLeechSeed picks
the enemy's HP because it is 1), its recoil, confusion self-hit, Explosion and
Substitute all land with it 1. Every drop moves the target's mark, so a tick is
never paid later as part of a hit. A target is (wEnemyMonPartyPos, species,
level) and keeps its lowest HP for the battle, so a heal is never paid twice and
a switch back keeps its mark; it is marked when it first reads full HP, because
InitBattleVariables leaves the last battle's wEnemyMon in place -- in the row 67
ring that is the same trainer's Diglett at the HP it won with.

v7 -> v8. STATE_VERSION stays 4: damageCounts and battle.damage are optional and
absent in a v7 state, which restores with no wild key paid and a battle in flight
marked where it stands, so nothing lost before the restore is paid.
MIGRATES_FROM is [v7, v6]: the chain composes, since v7's own migration (the
item seed) still runs in this build on the first sample without items:seeded.

Feed: `damage` has no counter (RewardKind::from_adapter -> None). On `wildwin`
the stage would fold every hit into "N wild wins", false of a trainer battle and
of one the fly goes on to lose. A hit reaches the page as a reward event with
its own label, HIT #<species> FOR <n> HP[ KO]; the feed's closed kind set does
not move.

The compatibility string differs from main's in exactly one segment:
pokered-unique8-v7 -> pokered-unique8-v8.

Tests: the rule (fly's turn vs the enemy's, Struggle, heal, switch, twin slots,
stale enemy, restored battle, cap, knockout, wild scale, round trip); the adapter
(proportional pay, TAIL WHIP nothing, poison then hit, the ring's second battle,
wild scale and rollback, one read per address, checkpoint round trip, a v7 state
mid-battle); compat_migration (v7 and v6 FLYSIM01 envelopes refused without
their own opt-in and restored with it; the v7 one mid-battle pays only what
follows); rom_damage (FLY_ROW67_CHECKPOINT: the live v7 string and ledger
migrate; from the live state BUBBLE and TACKLE are paid on every drop they cause
and TAIL WHIP never, the fly's hits land with hWhoseTurn 0 and the enemy's with 1).
2026-09-30 02:11:45 +00:00
acamilo
c433316179 symbols: wPlayerMoveNum and wEnemyMonPartyPos for the damage reward
resolve_wram.py --emit resolved both from ram/wram.asm at the pinned commit,
each bracketed by pinned anchors (wWalkCounter/wEnemyMonSpecies and
wEnemyMonHP/wEnemyMonStatus): $cfd2 and $cfe8. 77 of 81 pinned addresses
re-derived, no disagreement. wEnemyMonPartyPos is battle_struct's third field
(macros/ram.asm: Species db, HP dw, PartyPos). gen_symbols.py's EXTRA_RAM
carries both so a regeneration keeps them.
2026-09-30 02:11:45 +00:00
acamilo
d4b448f14c Merge port/task-01 (eaf588d, TASK-01 round-2 notes) into port/perf-01 2026-09-30 01:46:10 +00:00
acamilo
9aa7b92d04 fly-legacy-session: in-process sessions over the local lane; speed_ab arms
LegacySession starts in-process participants with Via::Local
(FLY_SESSION_LOCAL_LANE=0 keeps the bus path, a measurement knob). speed_ab
takes FLY_PERF_ARMS (local, bus, process), FLY_PERF_SERVICE (the service
host's per-frame reads), FLY_PERF_WORKERS (1 or 2 Tokio workers) and prints
the legacy brain's own tick time beside the session's.
2026-09-30 01:46:07 +00:00
acamilo
aaf660d48e fly-session: the in-process local lane, and the per-frame costs it leaves
- worker: one Shell per worker serves its bus loop and a LocalLane. A local
  request goes through the same admission (classification, body digest,
  result cache, arrival-order ticket, endpoint lock) and answers the same
  SessionRpcOutcome, without a bus message. Worker.* stays on the bus.
  HandlerCtx::seal keeps a local request's reply media in memory.
- rpc: a WorkerRef carrying a lane sends endpoint methods over it; sealed reply
  handles reach the caller in memory under the same reference; a bus call
  carries sealed copies of in-memory attachments (promote).
- launcher: Via::Local offers in-process participants over their lane.
- coordinator: publication attaches sealed copies of in-memory media, begun
  when Environment.Advance answers; defer_snapshots (publish without waiting
  for admission, settled at the next snapshot); digest_views and media_bytes
  as SERVE-01 has them.
- legacy env/agent: frame, memory image, audio and spike bitset sealed via
  HandlerCtx::seal; the spike bitset is built eight neurons a byte.
- profile: span maxima, enabled(); the agent runs the brain's phase clock
  when profiling.
- tests: every synthetic transport test also runs over the local lane; the
  two publication-identity checks state the sealed copy there.
2026-09-30 01:46:07 +00:00
acamilo
35d5a1f38d flybus: in-memory artifacts that never cross a router
Artifact::in_memory holds an immutable buffer in the caller's address space
(store id 'in-memory', no digest): it reads, clones and retains like any other
handle without a router round trip, and a bus call, reply or publish refuses it
as an attachment before anything is sent. Artifact::to_memory reads a sealed
handle into one under the same reference. PERF-01's local lane hands these
between participants of one process.
2026-09-30 01:46:07 +00:00
acamilo
504e4bb116 docs: implementation guide, a blank line before SHADOW-01 2026-09-30 01:41:19 +00:00
acamilo
19d84de387 infra: the guard judges the live fly against its own baseline (SHADOW-01 review round 2, G1)
fly-shadow-run start measures a 10-minute baseline before the shadow
exists (sixty 10-s realtime-factor means: mean, spread; the lag growth
rate). The guard trips only on a sustained degradation against it: 3
checks in a row where the last 5 samples of the same process fall below
the baseline realtime factor or grow lag faster than the baseline rate,
by more than max(0.05, 4 x spread / sqrt 5). It stops itself when
flyshadow.service is not running; check refuses after a guard trip or
with the shadow down. lint drives the rule over RTF traces shaped on the
release CT (a flat 0.66, 0.77-0.99 noisy, real time with hiccups) which
must not trip, and degradations which must. Section 18 and the runbook
follow.
2026-09-30 01:39:52 +00:00
acamilo
a472adcaf4 fly-shadow: review round 2, R3, G1 (in-shadow back-off), N3 (SHADOW-01)
R3: allows_cutover floors the window at REQUIRED_BRAIN_SECONDS (10,800):
a verdict run with a shorter --required-brain-seconds never passes
check. G1: the in-shadow back-off (LagJudge) judges the live lag growth
rate against fly-shadow-run's pre-start baseline (baseline.json lagRate
and margin, re-read every poll) instead of any growth, and lifts itself
for 10 minutes when a pause did not help (the shadow is not the cause);
--lag-guard-margin replaces --max-live-lag-seconds. N3: lagTransitions
is refreshed at every verdict write, backed off or not, over the rest of
the current file and every newer one.
2026-09-30 01:39:52 +00:00
acamilo
37c7befc11 docs: SHADOW-01 review fix round (legacy-gameboy-v1 section 18, implementation guide)
Section 18: skips are the live side's own kinds only, every session-side
failure is a divergence, the live fly never pays for the shadow
(heartbeat, directory cap, guard), and the cutover rule requires the
release /opt/fly/current resolves to, compared saves and a caught-up
shadow. host-fields' reason updated. The guide records the fix round and
the cost re-measured on the rebased tip.
2026-09-30 01:39:52 +00:00
acamilo
2d8b529f42 infra: the shadow's live-impact guard (SHADOW-01 review N2, N1)
fly-shadow-run start records the live fly's baseline (fly_realtime_factor
over 10 s, fly_lag_seconds, uptime), waits for the shadow's heartbeat and
starts flyshadow-guard.timer. fly-shadow-run guard (every 60 s, root)
stops the shadow and the guard, removes the trace drop-in and restarts
flysim without the trace when fly_lag_seconds grew 1 s in the same
process or the mean realtime factor fell below min(0.97, baseline-0.03);
a paused fly is not judged, a restarted one rebaselines. check passes
--current /opt/fly/current --binary flysim-session. lint drives the
guard's rule on six cases. Runbook rewritten: the trace cannot outlive
the shadow (heartbeat, 8 GiB directory cap), not the old claim.
2026-09-30 01:39:52 +00:00
acamilo
e085876d79 fly-shadow: review fixes R1, R2, N3 (SHADOW-01)
R1: the verdict hashes flysim-session (SERVE-01's service) with the
other release binaries; check takes --current (default /opt/fly/current)
and --binary (default flysim-session) and requires the verdict's release
to be the directory the link resolves to, every shadowed binary
unchanged there. R2: a session that does not start, a restore-gate
refusal, a capture with no agent, an unrecorded transition and an
unbuildable trace line are divergences; skips carry a kind and only the
live side's own kinds (startup-save-gone, operator-reward-pulse,
trace-cap, no-transition) allow a cutover. N3: pass and the cutover rule
require one live save compared per 600 brain seconds and at most 10 %
unavailable, and the cutover rule a shadow at most 3,600 transitions
behind. N1: the shadow writes the consumer heartbeat, removes it when it
stops, and prunes history files. The coordinator's history is bounded
per segment. The test adds a gate refusal (a boot divergence) and waits
for the heartbeat; so does the rehearsal script.
2026-09-30 01:39:52 +00:00
acamilo
4bf664ee22 flysim: the trace needs a live consumer and a bounded directory (SHADOW-01 review N1)
In FLY_TRACE_DIR mode a process starts no trace unless the shadow's
heartbeat (<dir>/consumer) is fresh (FLY_TRACE_CONSUMER_STALE_SECONDS,
600), and a running trace stops within a minute of frames once it is
stale ({"truncated":true,"reason":"no-consumer"}). Before a
process creates its file the oldest trace files are deleted to keep the
directory under FLY_TRACE_DIR_MAX_BYTES (8 GiB). A dead or diverged
shadow can no longer leave the live service tracing.
2026-09-30 01:39:52 +00:00
acamilo
9a3a4f5a9c docs: SHADOW-01 final rehearsal (final binary, lag guard on) 2026-09-30 01:39:52 +00:00
acamilo
c09ac100ce docs: SHADOW-01 (legacy-gameboy-v1 section 18, implementation guide) and the rehearsal script
Section 18 fixes what the 3-hour zero-divergence gate means: the inputs,
the architecture (the live legacy fly stays primary; the shadow follows
its trace), what is compared, the declared differences, the window and
the verdict contract. tools/shadow-rehearsal.sh runs the real service and
the real shadow side by side from one checkpoint.
2026-09-30 01:39:52 +00:00
acamilo
095cf7b1da infra: flyshadow.service and fly-shadow-run (SHADOW-01)
Report-only unit, off by default, not bound to flysim, SCHED_IDLE on the
page and encoder CPUs, stays stopped after a divergence (exit 3).
fly-shadow-run start|stop|status|check installs the flysim trace drop-in,
restarts flysim once and reads the verdict. Deploy, build and packaging
ship fly-shadow and fly-session; lint holds the unit to its rules; the
runbook has a Shadow run section.
2026-09-30 01:39:42 +00:00
acamilo
12f361436f fly-legacy-session: the shadow run, its comparator and verdict (SHADOW-01)
shadow::run follows the live service's per-process trace files: each
segment boots a session from that process's startup save (a fresh start
powers on instead), replays the transition's admissions, runs it, takes
the live captures in the live order around a deferred rollback, and
compares its own trace line field by field, the ledger digest, and the
FLYSIM01 bytes of every live save (host-fields and archive-order
substituted). The first difference stops it with a diverged verdict and
divergence.json. A spool copies live generations as they appear; a lag
guard backs off while the live fly loses real time.

verdict.json is fly-shadow-verdict-v1, the contract CUT-01 reads;
fly-shadow check applies the cutover rule. trace::compare_line is shared
with trace::compare. tests/shadow.rs runs the real service through a
restart under a shadow and plants four differences, each caught with the
right kind, field and step.
2026-09-30 01:39:42 +00:00
acamilo
105f526200 flysim: trace switches for the shadow run (SHADOW-01)
FLY_TRACE_DIR writes one FLY_TRACE file per process (a restart truncated
the single path), FLY_TRACE_MAX_BYTES caps a file (4 GiB in directory
mode: a trace nobody consumes cannot fill the disk), FLY_TRACE_LEDGERS=<n>
adds ledgersDigest every n transitions. frame::ledgers_string is now the
one definition of the ledger string both runtimes digest. Recording only:
no behaviour field and nothing the fly does changes; compatibility string
unchanged.
2026-09-30 01:39:42 +00:00
acamilo
68bde25493 Merge port/task-01 (TASK-01 round-2 fixes) into port/serve-01; hand begun captures to the writer on pause 2026-09-30 01:37:12 +00:00
acamilo
6c7c58b35a infra: RestartMode=direct so OnFailure= fires only at the start limit; one lock for fly-runtime rollback and fallback
Verified on systemd 257: with the default RestartMode=normal the unit passes through failed
before every auto-restart, so OnFailure= ran on the first crash. The session drop-in now sets
RestartMode=direct. session, legacy, fallback and the trap rollback share one flock; a switch
holds it only until its restart is queued (restart --no-block, health checked against the new
invocation), and the rollback skips restoring an older drop-in once a fallback has completed.
lint.sh covers the drop-in key, the interleaving and the shared lock; runbook corrected.
2026-09-30 01:36:23 +00:00
acamilo
eaf588d2e2 TASK-01 round-2 notes: saves reach the writer on a failed step and on pause, every save outcome reported, sugar admission atomic with the commit
R2-1: a failed step hands the begun captures to the writer before it reports the error, and LegacySession::flush_captures hands them over while the loop idles.
R2-2: completed_saves reports every queued save's outcome instead of stopping at the first error.
R2-3: the commit ends the in-flight admissions and records the pulses under one lock, and a sugar's reads and queueing take that same lock.
2026-09-30 01:30:56 +00:00
acamilo
405cf11498 flysim: read adapter.progress() once per publish
feed_game and feed_milestone each called adapter.progress() (a pure read), so every publish
computed it twice. Both now take the snapshot as an argument; publish and the session service
read it once. The header bytes are unchanged (service_parity and journal_replay pass).
2026-09-30 00:11:25 +00:00
acamilo
1d29ab1ff8 infra: persistent session-to-legacy fallback, signal-safe fly-runtime, MALLOC_ARENA_MAX=2
The fallback used to live only inside one 'fly-runtime session' invocation. The session
drop-in now carries OnFailure=fly-runtime-fallback.service and a 3-starts-in-10-minutes
start limit, so a session binary that will not stay up puts flysim.service back on legacy
after a reboot, a watchdog or loop-recover restart or a deploy. 'fly-runtime fallback'
removes the drop-in, daemon-reloads, restarts on legacy, writes /run/fly/runtime-fellback.json
and a journal line; it is locked, idempotent and keeps the drop-in if legacy cannot start.
fly-runtime traps INT/TERM/HUP and any failure during a switch and rolls back to the
previous state. Session drop-in and flysim-session.service set MALLOC_ARENA_MAX=2.
05-deploy keeps the chosen runtime (operator decision: session stays, trust gates),
refreshes the drop-in in place, and says so; the runbook documents all of it.
lint.sh drives the fallback, the interrupts and the deploy policy against a fake systemctl.
2026-09-30 00:11:25 +00:00
acamilo
7ec9a3c9ef docs: TASK-01 review fix round in the implementation guide 2026-09-29 23:43:17 +00:00
acamilo
12940a5215 tests: speed_ab, the session against the legacy loop interleaved in chunks on one box 2026-09-29 23:08:12 +00:00
acamilo
d35eda399b N5: captures off the loop; wanted and cached artifacts held concurrently
- worker: a handler may finish its reply outside the endpoint's lock
  (HandlerReply::deferred); admitted mutations take the lock in arrival
  order (LockOrder), so a request sent before another is handled first;
  a reply's cache holds are taken concurrently.
- legacy agent: State.Capture copies the state under the lock and
  encodes, digests and seals it off the lock, so the next Prepare ticks
  while the payload is written.
- rpc: send/finish split (SentCall); the caller's holds on wanted
  attachments are taken concurrently.
- coordinator: begin_capture sends every State.Capture and returns;
  finish_capture collects them. LegacySession begins a boundary's saves
  and collects them after the next transition, then queues them to the
  writer thread.
2026-09-29 23:03:37 +00:00
acamilo
1bfaf923b2 N5: publication at the feed's rate, in-memory transport in-process, capture spans; docs for the fix round
- Coordinator::snapshot_every(n): a snapshot every n-th boundary plus
  every boundary with events or boundary actions; a service session
  publishes every other boundary, the legacy feed's 30 Hz from 60 Hz.
- In-process participants reach the router in memory (a separate process
  still uses its socket).
- Spans on the agent's and the coordinator's capture path; tests/speed.rs
  times the legacy frame's phases, its agent export, and a session save.
- legacy-gameboy-v1: the artifact-backed ledger, the palette seed and the
  pending pulse (amendments of 2026-09-29).
2026-09-29 22:20:39 +00:00
acamilo
d3c61286bf docs: SERVE-01 results and what is open for CUT-01 2026-09-29 22:13:51 +00:00
acamilo
2fc9fd7247 tests: the reward segments include row 64 and the row 65 yard 2026-09-29 21:58:23 +00:00
acamilo
42f3c91c29 journal_replay: compare the adapter ledger as numbers
The session's ledger crosses the task's canonical JSON, which writes an
integral f64 as 7580031 where the legacy export writes 7580031.0; the
values are equal and the legacy import reads both alike.
2026-09-29 21:54:41 +00:00
acamilo
5cf40c3148 Merge port/task-01 (TASK-01 review fixes) into port/serve-01
Takes the artifact-backed task ledger (B1), the pending pulse (N1), the
palette seed (N3), queue_save/completed_saves (N4) and the bounded history
and concurrent seals (N5). The service host now queues its saves through
TASK-01's queue_save; SERVE-01's save_queued is gone.
2026-09-29 21:29:31 +00:00
acamilo
46d07260e9 TASK-01 review N5: the per-boundary costs measured, the world's seals concurrent, bounded history
- fly-session::profile: switchable per-phase spans (FLY_SESSION_PROFILE),
  in the coordinator's phases, the world's advance and the agent's
  prepare and commit.
- The world seals the view, the image and the audio chunk concurrently.
- Coordinator::bound_history: a service session keeps the newest 4096
  transitions of trace, phase and audit logs and latency samples (it
  grew without bound).
- tests/speed.rs: legacy loop against the session on one box, unpaced
  and paced at 1x, in-process and process, with the span breakdown.
2026-09-29 21:06:32 +00:00
acamilo
0776fab225 service_parity: two sugars in one drain; repeat a run whose recorder fell behind
The TASK-01 review's N1: a second sugar before the next commit is refused
with the first one's pulse as the retry, legacy and session alike. A run
whose recorder misses a frame on a loaded box is repeated rather than
failed (it cannot be compared, and it says nothing about either runtime).
2026-09-29 20:48:37 +00:00
acamilo
7a61877e78 TASK-01 review fixes: an artifact-backed task ledger, the pending pulse, the palette seed, queued saves
- B1: the pokered ledger's adapter state travels as an attachment
  ('reward', its JSON) beside a small typed value {reward: {digest,
  byteLength}, ratchet, slotFilled}; Task gains capture_attachments /
  validate_restore_with / install_restore_with, and the coordinator files
  them as task-ledger-<name> payloads in captures and imports. Every
  failure is an IncompatibleState error, so boot falls to the next
  candidate. Tests: ledger_size (past 64 KB, and malformed ones).
- N1: a sugar admitted and not yet reported on by a commit is an active
  pulse (AdmissionQueue::pending_stimulus_ms): two sugars between two
  commits are one admission and one PulseActive, as the legacy drain.
- N3: a restore seeds the palette with the restored brain's RNG state,
  as Sim::boot does; palette_seed holds on the cartridge that two seeds
  press the same buttons (a fresh start's constant is therefore exact).
- N4: interval, milestone and after-rollback saves are queued to the
  checkpointer's writer thread; startup and shutdown saves block.
- Boot parity adds row64 and the row65 yard (the largest ledgers); the
  segments add them too. tests/speed.rs measures N5.
2026-09-29 20:47:19 +00:00
acamilo
002fcbe26c docs, tools: SERVE-01 implementation entry and the runtime soak client
tools/runtime-soak.ts drives a running flysim or flysim-session with the
stage's own feed decoder and the bridge's HttpSimClient for a wall-clock
soak and samples the store cadence.
2026-09-29 20:31:20 +00:00
acamilo
0012759ace infra: flysim-session.service, fly-runtime, and shipping the session runtime
fly-runtime session|legacy|status switches which binary flysim.service runs
with one drop-in (flysim.service.d/10-runtime.conf), so fly.target, flyedge's
Requires=, the watchdog, fly-loop-recover and its sudoers line,
fly-loop-reset, fly-reset-to-milestone and the unstick rule keep naming
flysim.service, and the choice survives reboots and deploys. It refuses a
release without flysim-session or with a different compatibility string,
waits for /healthz and an advancing frame, and falls back to legacy by
itself when the session runtime does not come up.

flysim-session.service: the standalone unit (flysim's limits, cpuset and
environment, Conflicts=flysim.service, no [Install]). build-flysim.sh and
package-release.sh ship flysim-session and fly-session; 05-deploy.sh
installs fly-runtime, writes the standalone unit's cpuset drop-in and
refuses a release without flysim-session while the drop-in is present;
tmpfiles creates /run/fly/session. lint.sh checks all of it and drives
fly-runtime against stubs. Runbook: Switch the runtime.
2026-09-29 20:31:20 +00:00
acamilo
98f29e47c6 fly-legacy-session: flysim-session, the session runtime as the live service
The service host (service.rs, bin flysim-session) runs the legacy composition
behind flysim::serve with flysim's own Config and keeps Sim's order and
bookkeeping: TASK-01's boot (legacy candidate order and gate), boot events,
chat sidecar, sugar journal (runtime fly-session), startup/shutdown durable
saves, queued hot/durable/milestone/after-rollback saves on the wall clock,
macro/reward/milestone/recovery/sugar/checkpoint events, the recovering
status, flysim's Pacer, sd_notify ready/watchdog, and the 30 Hz feed built
by flysim's feed_* functions from the committed view, the step's audio
through the legacy DC blocker, the OR of the commits' spike bitsets, the
task's adapter/ratchet/macro layer and the agent's Legacy.FeedStatus.

Task: FeedRecord (executed/rewards/abandoned/rollback events), the applied
mask (0 after a rollback, the checkpoint's after an import), inspect().
Composition: boot_unsaved, save_queued, the event-log watermark setter.

Tests: service_parity (legacy Sim vs session host behind flysim's router,
one scripted request set, every header/attachment/response/event/journal
line and the final checkpoint compared), journal_replay (a killed session
run's journal replayed from the seed in the legacy loop onto its last hot
checkpoint), unit tests for the audio path and the feed status;
examples/seed_store.
2026-09-29 20:31:13 +00:00
acamilo
4fcd9233c7 fly-session: what a service host needs from the session
- Legacy.FeedStatus (capability legacy-feed-status-v1): the legacy agent's
  read-only feed status at a committed boundary -- rates, pulse, the whole
  plasticity statistics and the decoder's baselines/scores -- which no
  session message carries and the legacy header and /status report.
- Coordinator::read_agent_extension (never fences), media_bytes (the
  committed view/audio chunk), digest_views (off for a host that reads the
  details only for commit attachments), trim_records (the trace, phase log,
  audit and injection log grew with every transition: ~120 KB/s on the live
  fly), and timings for the feed status and the per-step publication.
2026-09-29 20:31:13 +00:00
acamilo
95614122a9 flysim: serve() shell and shared feed-header builders for a second runtime
flysim::run is now serve(config, Sim::boot + Sim::run): serve binds the feed
(or the feed bus), the control API and the metrics listener, handles the
signals and runs any runtime on the calling thread with the shared state,
the snapshot slot and the command queue. The fly-derived pieces of a feed
header (feed_rates/learning/game/milestone/sugar) and the chat admission
(admit_chat) are free functions both runtimes call; DcBlocker gains an f32
entry point for audio already converted with v/255. No behaviour change:
the legacy frame, header bytes and compatibility string are unchanged.
2026-09-29 20:31:13 +00:00
acamilo
f34b236f12 tests: the service test waits for the first snapshot before reading /status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
/healthz goes green before the first snapshot is published, and until
then /status carries the placeholder header (a one-rung BOOT ladder). A
loaded box read that window and failed 'the ladder length is in
/status'. Bounded wait (30 s); every assertion unchanged.
2026-09-29 20:15:04 +00:00
acamilo
452525dc38 docs: v0.6.6 status 2026-09-29 19:34:29 +00:00
acamilo
1700bd58e9 Merge feat/row69-throw-name (reviewed: APPROVE-WITH-NOTES): throw on low HP only, the fly names its catch
# Conflicts:
#	infra/docs/macros-traps.md
2026-09-29 19:34:10 +00:00
acamilo
3c72967a5b docs: row 69, throw on low HP only and the fly names its catch
macros.md 12.32 and the 13.1 table rows; macros-wram.md 15 (the two
naming bytes); feed-protocol: padEmptyMs is 0 on the keyboard;
macros-traps row 69 with the ROM tests and the connectome survey.
2026-09-29 18:54:57 +00:00
acamilo
70aa740b37 reset: a sugar journal that cannot be cleared is a warning once the reset is complete
review-state-02 N3: the error made fly-reset-to-milestone exit non-zero
after a finished reset, so fly-loop-reset reported it failed and the
stream's splash said so.
2026-09-29 18:45:05 +00:00
acamilo
5a05b1667a Merge fix/loop-row67 (reviewed: APPROVE-WITH-NOTES)
# Conflicts:
#	docs/design/macros.md
#	infra/docs/macros-traps.md
#	services/flysim/crates/flysim/tests/rom_macros_mode.rs
2026-09-29 18:43:50 +00:00
acamilo
494477e1f2 Merge test/row66-shop-catch (reviewed: APPROVE-WITH-NOTES) 2026-09-29 18:43:19 +00:00
acamilo
70e5ad6134 Merge port/integration (reviewed: APPROVE-WITH-NOTES) 2026-09-29 18:43:19 +00:00
acamilo
7ef16be317 docs: TASK-01 on STATE-02 (the store, the boot, the task ledger) 2026-09-29 18:23:11 +00:00
acamilo
e561c81295 TASK-01 on STATE-02: the store, the boot and the task ledger
- The task ledger is STATE-02's TaskHalf ledger {reward, ratchet,
  slotFilled} (pokered-task-ledger-v1); the task exposes its half, rank
  and brain time for the host.
- The FLYSIM01 import uses legacy_checkpoint's halves, agent_payload
  (the file's framebuffer as the next input, its reinforcement count)
  and world_payload, with ids from the file; ImportSpec carries the
  source scope.
- The coordinator can defer a rollback so the host captures first
  (apply_pending_rollback) and takes a participant-coherent capture
  for the legacy store (capture_payloads).
- LegacySession: attach_store (LegacyCheckpointer), save, advance in the
  declared boundary order (slot save, milestone archive on a climb,
  rollback, durable save after it, interval saves), shutdown_save; boot()
  restores from the live stores in the legacy order and gate, one
  session per attempt, fresh when the stores are empty.
- tests: fafb_boot_run_save_restore, the SHADOW-01 entry gate.
2026-09-29 18:16:55 +00:00
acamilo
e6fa92613a Merge port/integration (STATE-02) into port/task-01 2026-09-29 18:11:33 +00:00
acamilo
1a6e064e4f docs: TASK-01 in the implementation guide; dated amendments (2026-09-29) to legacy-gameboy-v1 sections 10, 11, 14 and 15, step-v1 sections 2 and 3, workers-v1 sections 4 and 5 2026-09-29 18:11:30 +00:00
acamilo
851b4f85c4 fly-session: clippy (slice from_ref) 2026-09-29 18:11:30 +00:00
acamilo
9cc3a54dc9 Merge port/state-02 (unreviewed, integration base) 2026-09-29 18:11:26 +00:00
acamilo
0d444bb00f tests: row 69 ROM tests; trap_hunt counts the throw's pad and the keyboard
rom_catch: the low-HP pad is the ball (FLY_ROW69_CHECKPOINT), the
keyboard after a catch is the fly's own buttons and closes, a fly that
types nothing is ended by the bound, and the two naming bytes are where
the cartridge stores them. The row 66 catch drive passes the readout's
own buttons and leans on A and B on the keyboard.

rom_macros_mode: the keyboard is drawn, so its CONFIRM is not an
Unknown pad on nothing.
2026-09-29 18:07:15 +00:00
acamilo
e006db3742 macros: a ball at low HP is the only attack, and the fly types its catch's name
Two operator decisions (2026-09-29, row 69).

Throw on low HP only: in a wild battle with THROW BALL dealt and the
wild Pokemon at the HP where ItemUseBall's HP factor saturates
(W = (MaxHP*255/BallFactor)/max(HP/4,1) >= 255: about a third for a
Poke Ball, a half for a Great Ball), MOVE 1-4, SWITCH, RUN and the bag's
BACK are withheld. ITEM stays for a hurt thrower. Every precondition of
THROW BALL still gates it, so no ball, a caught species or a trainer
gives the ordinary pad back.

Let the fly name it: the naming screen is read (menu bytes, the
keyboard's box, the underscores; wNamingScreenNameLength and
wNamingScreenSubmitName pinned from the cartridge's own stores) before
the battle test and reads Unknown. Its pad is the fly's own D-pad, A, B
and START, passed through Observed::raw while nothing is bound. Once
the name is full or sixty brain seconds have run, CONFIRM alone is
dealt and presses START until the keyboard closes.

Also moves two doc comments row 66 split from their items (review N3).
2026-09-29 18:07:15 +00:00
acamilo
7c8d5a33dc fly-legacy-session: pokered-macros-v1 on the session framework (TASK-01)
The live fly's composition under one coordinator: AGENT-01's agent,
ENV-01's world, and the Pokemon Red task and executor as one object
running the unchanged legacy engine (flysim's MacroLayer, flybrain-gb's
palette, executor, PokeState, reward adapter and ratchet) over MEM-01's
ImageReader of each boundary's memory image.

- task: Phase B decide over O[k], Phase C sample/observe/ratchet over
  O[k+1], rollback clear_transient/cancel/observe over O'[k]; slot save
  and rollback requests; legacy-transient-reset on restore; a reward
  with no stimulation is a Reward alone; uncaptured reads are recorded.
- import: a FLYSIM01 checkpoint as the start (world, agent, task halves
  in each participant's own format, the context from the checkpoint's
  image), onto a replacement world.
- admission: sugar by flysim's RateLimiter against the last commit's
  pulse; the operator reward pulse is refused.
- trace: the session's own FLY_TRACE lines and the comparison;
  driver: the ROM tests' rotation stub readout for reward-bearing runs.
- tests: session_trace (toy raw from power-on; FAFB from the service
  traces' checkpoints and from stream checkpoints, brain and driver
  arms; in-process and process) and rollback_sequence (ROM-free).
2026-09-29 18:03:59 +00:00
acamilo
817318f014 fly-session: the coordinator runs the legacy composition's boundary (TASK-01)
- A task declares the inspection attachments it reads; the coordinator
  holds them (O[k] until its transition is evaluated) and hands the task
  and the executor their bytes (task::Inspection).
- The executor's clock is the agent's brain time after Prepare.
- Evaluation.slot_saves: Environment.SaveSlot at the boundary reached.
- A declared rollback policy runs itself: Ready(e,k) -> RollingBack(k)
  -> Ready(e',k) with RestoreSlot, Task::rollback, Agent.Rollback; a
  composition that declares it needs agents that advertise it.
- AdmissionQueue: admitted stimuli cut into each Prepare, ended applied
  or aborted; the last commit's stimulusRemainingMs for the edge.
- Coordinator::import: a checkpoint of another format as a session's
  start, through the ordinary group restore (Ready(0) -> Restoring(k));
  Task::restored re-observes the restored world and must agree with the
  recorded contexts. capture_participant, import_scope.
- Composition setters: environment config, media, decision schema,
  world state format, per-agent model versions; StepDetails for parity.
- ENV-01's interim 'declared rollback pauses' test now states the rule:
  a declared policy needs participants that apply it.
2026-09-29 18:03:59 +00:00
acamilo
0d41cc2003 docs: STATE-02, the reinforcement count in FLYSIM01 and the import's ids 2026-09-29 17:18:10 +00:00
acamilo
f0981825a0 FLYSIM01 carries the reinforcement count; the import takes its ids from the file; StageRestore refuses conflicts before building a network
AGENT-01 review: learning.updates fell back to plasticity.updates on every FLYSIM01 round trip.
Both runtimes now count reinforcement calls the same way (one per commit while the rule is
enabled) and write the count as the optional manifest member reinforcements, which old readers
ignore and old files lack (a reader then starts from plasticity.updates, once). The import's
checkpoint id is the file's generation (flysim01-g<N>), and the agent worker checks for a
staged or activated restore before it builds the replacement network.
2026-09-29 17:17:56 +00:00
acamilo
d034a26be5 legacy_env: MEM-01's bulk read behind the image seam (ENV-01 review R1)
The environment's memory image is now Emulator::read_memory_image: the
register windows read $FF (legacy-gameboy-v1 section 8, MEM-01 amendment)
and the read is neutral by construction, so the export/import guard is
gone. The toy golden's image digests are regenerated (only 'memory'
changes), the neutrality test states MEM-01's rule, and the ENV-01 guard
amendment is struck in legacy-gameboy-v1 and implementation.md. The
service traces still match in all three modes (rollback 3,199, climb
3,156, r58 11,043).
2026-09-29 17:07:48 +00:00
acamilo
bb70a3b5d7 Merge chore/pii-guard: private names out of the public tree, a scan in lint, tag-release and pre-push 2026-09-29 16:57:02 +00:00
acamilo
2c8596eaa2 pii-scan: refuse an invalid pattern instead of scanning clean, and read '+++' as a header only after '---'
review-pii-guard N2 (a broken private regex made grep exit 2 and the scan
report clean) and N3 (an added line starting '++ ' was taken for a file
header). Tests for both; the env README names BRIDGE_ID_KEY and
BRIDGE_SECRET_KEY.
2026-09-29 16:56:56 +00:00
acamilo
d211e53fab docs: STATE-02 in the implementation guide and the legacy-gameboy-v1 section 16 amendment (2026-09-29) 2026-09-29 16:26:07 +00:00
acamilo
1faccd2908 flysim: STATE-02 proofs: real-checkpoint round trips, restore-then-continue against FLY_TRACE, and the reset tools both ways 2026-09-29 16:26:07 +00:00
acamilo
9c98281f4a fly-session: legacy_checkpoint, the session runtime's FLYSIM01 export, import, store policy and restore selection (STATE-02)
The export assembles a FLYSIM01 file from the agent's FLYAGT01 and the world's FLYENV01 capture
payloads, the task's {reward, ratchet} and the host's fields, through flysim-store's encoder.
The import reads a file back into those halves. The agent payload is the shipped form of
AGENT-01's prototype: learning.updates starts at plasticity.updates, and the file's framebuffer
goes in an inputFrame chunk that StageRestore installs, as the legacy restore does.
LegacyCheckpointer keeps the legacy loop's generations, hot and durable intervals, per-process
milestone archives and writer thread. restore_from_store walks the legacy candidate order and
takes the next candidate on any refusal. The agent worker's payload encoder is now one shared
function, and legacy_parity seeds through the shipped import.
2026-09-29 16:26:07 +00:00
acamilo
32631e2d02 flysim-store: the FLYSIM01 store and the sugar journal in one crate; journal boot header, rotation and reset clearing
store.rs and journal.rs move unchanged from flysim into the new flysim-store crate, which flysim
re-exports, so the session runtime can write and read the same store (STATE-02). The journal gains
a per-process boot header, rotation at 4 MiB with three kept files, and clear(), which
flysim --reset-to-milestone now calls after copying the stores aside.
2026-09-29 16:25:42 +00:00
acamilo
ae878ede41 Merge port/env-01 (unreviewed, integration base)
Both slices add a worker to the same launcher and CLI; the resolution keeps
both: the legacy-agent and legacy-environment subcommands, launch structs,
flags, flag round-trip rows and the flybrain-core/flybrain-gb/flate2
dependencies. Cargo.lock regenerated by cargo.
2026-09-29 16:25:10 +00:00
acamilo
2defc4947a Merge port/mem-01 (unreviewed, integration base) 2026-09-29 15:59:32 +00:00
acamilo
0d6bce8838 flybrain-gb README: the image module 2026-09-29 15:54:57 +00:00
acamilo
f666b404dd docs: MEM-01 status and the section 8 memory-image amendment (2026-09-29) 2026-09-29 15:54:57 +00:00
acamilo
a23e587c96 flysim: image-backed shadow executor equals the live one (MEM-01)
tests/rom_memory_image.rs runs a live arm and a shadow task+executor that
reads only per-boundary images and the cartridge, from nine rom-env
checkpoints: every MacroState answer, deal, pad, decision, reward, ledger and
rollback compared frame by frame, and every shadow read inside the captured
ranges. Plus the gameboy-memory-inspection-v1 encoding against the session
types.
2026-09-29 15:54:57 +00:00
acamilo
3d1a81a679 flybrain-gb: the boundary memory image (MEM-01)
One read-only bulk read in the shim, fly_gb_read_memory_image: the address
space's memory in address order, the register windows (VRAM, OAM, I/O) read
$FF because binjgb's catch-up on a register read moves the exported state.
MemoryImage, Cartridge and ImageReader put an image and the ROM behind
MemoryReader, so the same macro engine and adapter run over it; the
emulator's bank reads go through the same Cartridge. ROM tests prove the read
leaves the state byte-identical, equals the single and cached reads, changes
nothing downstream, and measure its cost.
2026-09-29 15:54:57 +00:00
acamilo
05324293ee tools: pii-scan guard with a private pattern list, tag-release gate and pre-push hook
tools/pii-scan.sh scans the tree, a commit range (added lines and messages) or a push
(pre-push protocol, incl. annotated tag messages). Generic shapes stay in the script; the
proper nouns move to the operator's private list ($FLY_PII_PATTERNS), which can also name
env files whose values are matched as literals and never printed. lint.sh section 5 now
runs it (a missing list is a note, so public CI still passes) and no longer spells the
names with one bracketed character. tag-release.sh fails closed without the list and scans
the tree and every line since the previous tag. tools/install-hooks.sh installs a pre-push
hook that scans pushes to github. Tests in infra/tests/pii-scan-test.sh.
2026-09-29 15:52:35 +00:00
acamilo
49a00bc84a infra: pass entry names out of the public tree
The Twitch app id/secret entry names were spelled in 06-secrets.sh defaults and four docs.
06-secrets.sh now takes BRIDGE_ID_KEY and BRIDGE_SECRET_KEY from the env file (placeholders
in example.env) and skips twitch-app with a warning when they are unset; the docs use
twitch/<app>-client-{id,secret}, twitch/<bot>-token and twitch/<channel>-key.
2026-09-29 15:52:35 +00:00
acamilo
a69a258edd macros: no floor BUY BALL in Viridian before Oak has the parcel; docs for row 66
On the first visit the Viridian clerk's script hands the parcel over, and
his counter sells nothing until Oak has it. MacroState::parcel_delivered
reads EVENT_OAK_GOT_PARCEL (defaulted true).

docs/design/macros.md 12.30 and infra/docs/macros-traps.md row 66: the
GO SHOP ring, the one-button purchase, the bag after a catch, and the
measured choices with the connectome.
2026-09-29 15:38:51 +00:00
acamilo
df08d2eb51 docs: row 67, the Pewter Gym trainer lost on repeat (12.31, audit) 2026-09-29 15:34:01 +00:00
acamilo
7f56feac46 test: the no-PP turn's honest pad is FIGHT alone
The no-PP checkpoint is a trainer battle with a party of one and no Potion:
RUN, THROW BALL, ITEM and SWITCH have nothing behind them, and spent moves
are off the pad since 12.23/12.27, so MOVE 1 (FIGHT, then Struggle) is the
one button and the battle ends in 1,487 frames. The assertion demanded a
second button; it was red on main whenever FLY_NOPP_CHECKPOINT was set.
2026-09-29 15:34:00 +00:00
acamilo
e137260475 test: the Pewter Gym trainer is beaten from what the pad deals (row 67)
From the live checkpoint: on every own-turn frame the pad deals every move
with PP and an effect, and a uniform choice beats the Jr. Trainer the live
readout lost to 29 times. FLY_ROW67_CHECKPOINT.
2026-09-29 15:34:00 +00:00
acamilo
b6a4098992 infra: check 10 flags battles lost on repeat (row 67)
A whiteout ring in the Pewter Gym ran for an hour and a half without a
flag: every macro completed, and a stray tile reward on a walk back reset
the unrewarded rule. Reward lines now carry their rewardKind, and
unwon-battles flags 24+ MOVE n decisions with no wildwin/trainer/badge
reward in the window, on two probes, with no new ground. Report only, as
every check-10 rule; lint case 8 fails on main and passes here.
2026-09-29 15:34:00 +00:00
acamilo
6e090b0be5 Merge feat/agent-legacy-worker (unreviewed, integration base) 2026-09-29 15:13:47 +00:00
acamilo
dc403e8cdf docs: AGENT-01 rebased onto v0.6.5 and checked against FLY_TRACE; FLYSIM01 import seeds learning.updates 2026-09-29 14:26:07 +00:00
acamilo
563afb18f0 tests: the legacy agent worker checked against FND-01's FLY_TRACE of the running legacy frame
FLY_TRACE carries digests, not the frames or the {boot, bound, location} context, so it checks
a worker rather than drives one. legacy_parity gains read_frame_trace and check_against_trace
(ticks, clock, exact remainder, rates digest, spike-set digest, decision; the script held to the
trace's sugar, frames, rewards and rollback), RestoredSource, and
AgentDriver::seed_from_legacy_state for a worker started from a FLYSIM01 agent state.

flysim/tests/agent_trace_parity.rs runs LegacyFrame on the ROM with the trace on, records the
missing inputs, and checks the direct reference and the worker in-process, on a thread and as a
process: toy raw from power-on (FLY_ROM), and gameboy-legacy-fafb-v783-v1 macros mode from a
stream checkpoint with sugar and a ratchet rollback (FLY_AGENT01_FAFB=1). fly-session is a
flysim dev-dependency only.

A FLYSIM01 import starts learning.updates at the legacy plasticity.updates
(legacy_reinforcements): starting at zero broke changed <= updates on the live checkpoint.
2026-09-29 14:26:07 +00:00
acamilo
5da77454c3 macros: BUY BALL is one button from a mart's floor, like HEAL
Operator decision on row 66. Measured with the connectome, the fly walked
to the Viridian clerk again and again and never chose TALK, so the four
choices a purchase took at the counter never happened. BUY BALL is now also
offered on the overworld pad inside a mart whose first stock row is a Poke
Ball (Viridian, Pewter, Cerulean), while service_needed holds (no ball,
money for one, no Oak's parcel) and the clerk is not in the blocked window.
One press walks to the clerk, talks, advances the greeting to BUY/SELL/QUIT
(checking the first row is a Poke Ball), buys one, answers the price box
and is done when the wallet drops. The open-counter BUY BALL is unchanged.

Unit test for each offer condition; ROM row66 floor purchase from
FLY_ROW66_MART_CHECKPOINT: base never dealt on the floor, no ball; branch
dealt, started, done, one ball, 200 paid.
2026-09-29 14:09:02 +00:00
acamilo
96e3ffeeb1 examples: row 66 survey counters
trap_hunt: a shop/ball/catch tally (pad frames, starts, outcomes, balls,
party+box, Pokedex owned, mart entries) and FLY_TRAP_LOG_MACROS=1.
scene_probe offers: catch, party and Pokedex counts, FLY_PROBE_SCREEN_*
screen dumps, FLY_PROBE_SAVE_MART to save a mart entrance.
2026-09-29 13:55:23 +00:00
acamilo
36325d82dd palette: a counter the fly walked away from is not walked back to for the window
Row 62 re-deals GO SHOP/GO HEAL whenever the service is needed, with no
window. Live on v0.6.5 from the rung-8 archive that was a ring: GO SHOP to
the Viridian clerk, GO OUT/GO OBJECTIVE back out without TALK, GO SHOP again
(33 in 35 minutes). A completed GO SHOP/GO HEAL facing the counter person now
records TargetKey::Counter on the building's map; the service walk toward it
is withheld for the reached window, from the street and inside. TALK at the
counter is unchanged.

ROM row66 test (FLY_ROW66_MART_CHECKPOINT): base 31 street GO SHOPs in 10,000
frames, branch 0.
2026-09-29 13:55:23 +00:00
acamilo
5269c2f142 state: the battle bag is open only while its box is on screen
wListMenuID keeps ITEMLISTMENU after the list closes, so from a catch to the
end of the battle (caught text, Pokedex page, nickname offer, naming screen)
the pad read as the bag: BACK and THROW BALL, whose A presses typed the name.
The bag now also needs its TextBoxBorder at (4,2)-(19,12).

rom_catch: row66 test (THROW BALL dealt after the catch: base 666 frames,
branch 0), and both tests retry from idle offsets because one ball misses
about two throws in three and frame timing decides which.
2026-09-29 13:55:23 +00:00
acamilo
931fa01a8c docs: ENV-01 status and the 2026-09-29 amendments (guarded image read, FLYSIM01 boundary, names) 2026-09-29 13:16:22 +00:00
acamilo
d07653cc41 tests: legacy environment goldens and parity in every execution mode, the refusals, and the service trace replay 2026-09-29 13:16:22 +00:00
acamilo
d130a5ffe0 fly-session: a rollback request without a declared rollback policy fails the epoch 2026-09-29 13:16:22 +00:00
acamilo
4819f6ccd9 fly-session: the launcher starts the legacy Game Boy environment in-process, on a thread or as a process 2026-09-29 13:16:22 +00:00
acamilo
e28b0d8999 fly-session: LegacyGameboyEnvironment, the ENV-01 Game Boy environment worker
The emulator half of flysim's LegacyFrame behind the environment methods:
the one-frame setup scaffold, one joypad batch per Advance, f32le audio
(sample/255, unfiltered), the per-boundary memory image behind the MEM-01
seam (read between an export and an import, because emulator_read_mem syncs
OAM/VRAM/timer/STAT/LY), gameboy-slots-v1 SaveSlot/RestoreSlot, capture and
staged restore, and the world's half of FLYSIM01. SaveSlot, RestoreSlot and
Agent.Rollback are step mutations under the ipc-v1 operation key. The parity
harness (toy cartridge, direct reference in LegacyFrame order, bus driver,
FLY_TRACE replay) is in legacy_env_parity.
2026-09-29 13:16:22 +00:00
acamilo
ae503aa7a0 docs: legacy-gameboy-v1 amendments, the rate-role mapping and what the legacy agent reports 2026-09-29 12:21:06 +00:00
acamilo
8f058a402b tests: the gated FAFB run, recorded inputs through the worker against NeuralAgent driven directly 2026-09-29 12:21:06 +00:00
acamilo
625bcb6403 tests: the toy rollback lands in a world that stands still past a blocked window 2026-09-29 12:21:06 +00:00
acamilo
bd57b73b72 tests: legacy agent goldens in every execution mode, two flies, and the refusals 2026-09-29 12:21:06 +00:00
acamilo
214755f2b9 fly-session: the AGENT-01 parity harness, a direct NeuralAgent reference and a toy connectome 2026-09-29 12:21:06 +00:00
acamilo
fbf7c1e486 fly-session: the launcher starts a legacy agent in-process, on a thread or as a process 2026-09-29 12:21:06 +00:00
acamilo
9bdfb079e5 fly-session: LegacyAgentWorker, the legacy Game Boy agent over the neural core
Agent.Initialize checks the profile against the dataset fingerprint and
warms up as the legacy fresh start does; Prepare applies sugar, ticks the
548625/32768 ms frame on the rational clock and decodes with
gameboy-readout-context-v1; Commit installs the frame, stimulates, then
reinforces once; Agent.Rollback is legacy-ratchet-rollback-v1's agent
half; capture is agent_to_chunks in an envelope and a restore resets the
readout transient as a fresh legacy process has it.
2026-09-29 12:21:06 +00:00
acamilo
72cefb773b session-types: legacy-rate-role-id-v1, the identity on the Id grammar, pinned in both languages 2026-09-29 12:21:06 +00:00
acamilo
9f2345dba7 docs: v0.6.5 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-09-29 04:47:16 +00:00
acamilo
05ff68773c Merge fix/loop-row65: the Mt. Moon mouth ring and the Cerulean yard, on the 62+63+64 tree 2026-09-29 04:47:05 +00:00
acamilo
b720db9a42 docs: row 65, the Mt. Moon door ring on the release merge and the Cerulean yard (12.29, audit) 2026-09-29 04:01:16 +00:00
acamilo
ceaf55ad48 macros: a yard's one door is taken, and a split map's exits are the fly's own piece's
Cerulean's badge house back door leaves the fly on (9, 9), the door tile of a
closed yard; the pad was empty for the rest of the survey.

- The exit walks fall back on a step-fired warp underfoot once every listed
  goal has failed the route search (goals_of set it aside while any other exit
  was listed, reachable or not).
- The decoded grid marks warp carpets (warp_carpet_tile_ids.asm) on the maps
  whose ExtraWarpCheck reads them; a walk whose goal is a warp underfoot bumps
  toward one (CheckWarpsCollision) instead of row 64's sideways step-off, which
  fires nothing on a tile that is no door.
- The badge house is on the map graph and the yard is a piece of Cerulean, so
  GO OUT in the house takes the front door.
- path::exits keeps the fly's own piece on a split map: refusals from the yard
  no longer rest the town's exits for the whole map.
- The 12.28 guarantee reads where the fly stands: a same-map teleport moved it.

ROM test row65_the_fly_leaves_the_cerulean_badge_houses_back_yard
(FLY_ROW65_YARD_CHECKPOINT); scene_probe's route survey can save its caught
frame (FLY_PROBE_SAVE without FLY_PROBE_SAVE_RANK).
2026-09-29 04:01:16 +00:00
acamilo
2f869fd4bc macros: a floor whose way on is a passage deals no GO OUT fallback
GO OUT's "a room has to be leavable" tier dealt Mt. Moon 1F's mouth back onto
Route 4 (visited, away from the rung) one step from the tile the fly arrives
on, and Route 4's GO ROUTE / GO OBJECTIVE walked it straight back in. With row
62's GO HEAL bringing a hurt fly back to that tile, rows 62+63+64 crossed
Route 4's west doors 34 times in row 59's ROM test (bound 25).

While an unrested passage leads toward the objective, the way out has no
fallback: GO WARP's rule the other way round. The blocked window is the escape
hatch; tiers one and two (somewhere new, toward the objective or an errand)
are untouched, and a hurt party keeps GO HEAL.
2026-09-29 04:01:16 +00:00
acamilo
310282540b Merge fix/tag-release-rom 2026-09-29 02:49:03 +00:00
acamilo
abacebf6b9 tag-release: refuse a gate that would pass the ROM suites without running them
The ROM suites return early and count as passed when FLY_ROM or their
checkpoint variable is unset; v0.6.4's gate ran that way and the merge
of rows 62-64 looked green while row 59's ROM test failed. Require
FLY_ROM and log every checkpoint suite left unset.
2026-09-29 02:49:03 +00:00
acamilo
19d295d111 tests: close row 62's last test, whose brace the row 64 merge took as shared context
Both branches appended tests at the end of the file; resolving the
conflict as both sides left row 62's final test without its closing
brace.
2026-09-29 01:47:23 +00:00
acamilo
56ed48b0b9 Merge fix/bridge-refresh-on-load 2026-09-29 01:31:26 +00:00
acamilo
4a37527c76 Merge fix/deploy-bridge-env 2026-09-29 01:31:26 +00:00
acamilo
d7238a935b Merge feat/recovery-copy 2026-09-29 01:31:26 +00:00
acamilo
ccba5d75a2 tests: row 64's ledge test sees Route 4's centre, which row 62 made an errand
review-row62-r2: merged, the Mt. Moon centre is the errand ahead of the
test's goal on Route 4's west side; the behaviour is right, the fixture
predates row 62.
2026-09-29 01:31:22 +00:00
acamilo
ce12a1d7a5 Merge fix/loop-row64
# Conflicts:
#	docs/design/macros.md
#	infra/docs/macros-traps.md
#	services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs
#	services/flysim/crates/flysim/tests/rom_macros_mode.rs
2026-09-29 01:31:22 +00:00
acamilo
e2e830076e Merge fix/loop-row62
# Conflicts:
#	docs/design/macros.md
#	infra/docs/macros-traps.md
#	services/flysim/crates/flybrain-gb/src/pokemon_red/macros/tests.rs
#	services/flysim/crates/flysim/tests/rom_macros_mode.rs
2026-09-29 01:30:32 +00:00
acamilo
6d11e437e5 Merge fix/loop-row63 2026-09-29 01:29:42 +00:00
acamilo
b6e552ace2 tests: the row 62 east test's first sighting as a plain tuple 2026-09-29 00:18:27 +00:00
acamilo
c8f35b4fce docs: row 64, a ladder underfoot, Route 4's ledges and the way out that goes nowhere (12.28, audit) 2026-09-29 00:11:14 +00:00
acamilo
d06e1cf809 bridge: refresh stored tokens on load before giving up, persist both roles
A stored access token that has expired (obtainmentTimestamp + expiresIn) or
that validate rejects with 401 is now refreshed once through its role's
RefreshingAuthProvider before startup fails, for the bot and broadcaster
roles alike. Refreshes are persisted under the role whose provider made
them (no more scope-set guessing), through one serialized writer, so both
roles reach tokens.json even when they are one account; writes stay
tmp + rename, 0600.

Only a refresh Twitch refuses (4xx, e.g. 400 Invalid refresh token) is
fatal, with one line naming the role and the runbook's re-authorize step.
Twitch errors are logged by status and message only: twurple's
HttpStatusCodeError message carries the refresh grant URL, client secret
and refresh token included, so the entrypoint and EventSub log lines now
redact it.

Tests mock Twitch's validate and token endpoints. Runbook and B1 updated.
2026-09-28 23:47:48 +00:00
acamilo
83e842aee2 macros: a way out that does not take the fly anywhere is not done
The general half of row 64: section 12.2's rule ("a macro that completes
without moving because its precondition is already satisfied is a trap")
held by the executor for every way out, instead of by each macro.

A way out's promise is another map. A Settle arrival on an exit key that
leaves the fly on the same map now ends Blocked, so the exit rests in the
blocked ledger for the window. When the fly never left the tile it pressed
from, row 57's refused-from-here ledger also keeps that button off this
tile for the window, because the last resort ignores the blocked ledger
and would otherwise re-deal the same dead exit once per hold. Nothing is
pressed, ranked or chosen: two ledgers that already exist get one more
honest writer. A pad with nothing left that can run is empty and waits.

On base with only this commit, from the live row-64 checkpoint (72k
frames, GO OBJECTIVE/GO WARP preferred): GO OBJECTIVE done in place 1,500
-> 0; the fly leaves the ladder tile and moves on (still not to Cerulean,
which needs the ledge knowledge). The test fixture's settle now drains the
refused ledger after every finish, as PokemonPalette::record_talk does.
2026-09-28 23:38:06 +00:00
acamilo
f4946ce744 tests, docs: row 62 round 2, GO HEAL east of Mt. Moon on the cartridge and the two limits in 12.26 2026-09-28 23:37:40 +00:00
acamilo
b2c5944a02 05-deploy: a release with a channel refuses an empty GAME_TITLE
The generated fly.env writes GAME_TITLE whether or not the env file
sets it, and flybridge refuses to start on an empty one. It reads the
file only at start, so the gap surfaced as dead chat at the next reboot
(2026-09-28), a day after the deploy that caused it.
2026-09-28 23:35:33 +00:00
acamilo
e10f48e1c7 macros: a ledge is a hop the route search takes the one way the cartridge does
Row 64, the source of the Mt. Moon ring. Off the ladder, the road reaches
Route 4 east of the mountain, where Cerulean is three ledges down. The
collision list calls a ledge tile a wall, so the route search had no road
from the cave's exit to Cerulean at all: GO OBJECTIVE refused no route, the
east edge rested in the blocked ledger, and the other walks took the fly
back into the cave, onto B1F's exit (27, 3) or down B1F's ladder to B2F
(5, 7), where the ladder ring took over.

- The decoded grid marks LedgeTiles hops (data/tilesets/ledge_tiles.asm,
  OVERWORLD tileset only, the lower-left anchor tiles HandleLedges reads).
- The route search takes a hop from above as one press that lands two
  tiles on; from below a ledge stays a wall; the flood the map's pieces
  are measured with is unchanged.
- The walk holds while the cartridge carries the fly over (scene Unknown,
  scripted, on the hop's own line), so a hop it asked for is not written
  as a push-back.

ROM test from the live checkpoint (FLY_ROW64_CHECKPOINT): base stays on
(5, 7) with 167 done-in-place and never leaves B2F; branch takes the
ladder on the first GO OBJECTIVE, hops Route 4's ledges and reaches
Cerulean City at frame 1,972 with the pushed ledger empty.
2026-09-28 22:50:34 +00:00
acamilo
014d869e14 macros: a walk that starts on its own ladder steps off and back on to take it
Row 64, Mt. Moon B2F (5, 7), two days live. A warp whose exit has no press
fires at the end of a step onto it (CheckWarpsNoCollision) and at no other
time; a bump into the wall beside it warps only at a map edge off the
overworld (ExtraWarpCheck). The fly came down the exit ladder and stood on
it, and GO OBJECTIVE and GO WARP both aimed at the tile underfoot, settled
there and reported done without a press, 27 frames each, ~750 per ten brain
minutes. No ledger was involved, so restarts restored the ring.

A walk whose goal is a step-fired warp the fly already stands on now steps
onto free ground beside it (never another warp) and back, which is what
fires it. Nothing else changes: the pad, the ledgers and every other
arrival are as they were.
2026-09-28 22:49:17 +00:00
acamilo
3ea8da346c recovery splash: the operator's copy, and STUCK from the last progress
A reset to the rung the fly is on reads 'the start of MT. MOON'; a rung
that is not a place reads 'the BOULDER BADGE milestone'; failed says
what happens next ('Trying something else next') instead of promising
a human. The helper keeps the last probe that saw new places or a higher
rung, across restarts and reboots, so STUCK counts the whole trap rather
than the current streak (live: 15 MIN shown for a two-day trap).
Mockups re-shot with the real next target (12 -> 11).
2026-09-28 22:43:41 +00:00
acamilo
64148848e5 loop recovery: check every minute, not every five
The live timer's phase sat one second before each watchdog loop probe,
so every confirmation waited almost a whole extra period. A run is a
JSON read unless a step is due, and the ladder already ignores a probe
it has seen, so a one-minute cadence costs nothing.
2026-09-28 22:19:53 +00:00
acamilo
f2d8a2d491 palette: a centre is the area's from ground the route to it stays on, and no service leaves the rung's room
Review round 2 of row 62. Route 4's east side and Mt. Moon B1F's exit chamber are in
Route 4's area, but the only road to its centre runs through B2F, which is in none:
GO HEAL (and the errand under GO OBJECTIVE) walked into B2F and dropped there, opposite
the road to Cerulean. A building is the area's errand or service only where
geography::route_within holds. And a service is not wanted while the rung's own target
stands in the room (row 29's rule, row 58's gym bounces).
2026-09-28 22:12:09 +00:00
acamilo
aba63beb77 docs: macros.md 12.26 and the row 62 audit, the shop, the balls and the nurse withheld
What the pad dealt against what the fly chose, the five places the pad
withheld a counter with a job to do, the purchase that ended before its
price box, THROW BALL measured as not a trap, and the before/after
surveys (ten per arm) and ROM runs.
2026-09-28 22:08:17 +00:00
acamilo
2fb5e37ab4 scene_probe: FLY_PROBE_CATCH=offers, what the pad deals frame by frame
Twenty brain minutes of the service's frame behind a uniform stub,
counting per decidable frame which shop, centre and ball buttons are on
the pad and what comes of the ones pressed, beside the cartridge's own
heals, purchases, throws, catches, whiteouts and wLastBlackoutMap. With
FLY_PROBE_PREFER, FLY_PROBE_PADS and FLY_PROBE_TRACE_MACRO for the
mechanism (loop review row 62).
2026-09-28 22:08:17 +00:00
acamilo
d188a59495 tests: row 62's ROM proofs, HEAL in the Mt. Moon centre and a ball bought in Pewter
From the Mt. Moon centre with the party at 10/70 (FLY_ROW62_CENTER_CHECKPOINT):
HEAL is dealt, heals, and wLastBlackoutMap becomes Route 4. From the
rung-11 Pewter checkpoint with the errands paid, 1,606 and no ball
(FLY_ROW62_MART_CHECKPOINT): GO SHOP is on the pad, walks into the mart,
and BUY BALL reports done only with the ball in the bag and 200 paid.
Both fail on main 862e343 (HEAL never dealt in 3,000 frames; GO SHOP not
on Pewter's pad).
2026-09-28 22:08:17 +00:00
acamilo
87d31bcade palette: a centre or a mart with a job to do is dealt again, and its counter person is found from the door
The errand is paid by the first visit, including one on which the counter
could do nothing (the Viridian clerk handing over Oak's parcel, a centre
entered with a full party), and GO SHOP / GO HEAL never came back; a
counter person this session had talked to or reached was retired for it
too. Live: eleven hours, GO SHOP twice (the parcel), no BUY, no HEAL, no
throw, wLastBlackoutMap still Pallet Town.

service_needed reads the cartridge each time: a centre while the party
needs rest, a mart while the bag has no ball, the wallet covers one and
the bag holds no Oak's parcel. It satisfies itself (a heal leaves the
party full, a purchase leaves a ball). GO SHOP / GO HEAL aim at the
area's building while it holds; inside, the counter walk and TALK at it
ignore the talked and reached ledgers (blocked is kept). HEAL's goals
keep the tile that already faces the nurse, where GO HEAL leaves the fly.
The counter person is read from the drawn and the off-screen sprites
(row 58's reading): from a centre's door the nurse is six rows up and
off the screen, so HEAL, GO HEAL and the counter's suppression were all
off on arrival (loop review row 62).
2026-09-28 22:08:17 +00:00
acamilo
9ad2feff5c executor: a purchase answers the price box the cartridge drew, and is done when paid
After the quantity the mart prints "That will be" and waits for a press
(a cont), then prints the price and only then draws its YES/NO box. The
script's one blind A after a settle was that press, so BUY BALL reported
done before the box existed: 55 starts, 55 done, the wallet unchanged,
from the rung-11 Pewter checkpoint. Step::Prompt pulses A until the box
is drawn (yes_no_prompt, row 56's reading), Step::Paid waits for the
wallet to drop; either running out is blocked. The fake mart now prints
its price, draws the box and charges for a YES (loop review row 62).
2026-09-28 22:08:17 +00:00
acamilo
019bd02dfe geography: Route 4's Pokécenter is a centre on the map graph
MT_MOON_POKECENTER ($44, Route 4's warp at (11, 5)) joins LINKS, Route
4's west piece and AMENITIES as Route 4's centre. It was on no table,
so HEAL was never dealt in it and no errand could walk to it: the last
centre before Mt. Moon, where the live run spent 3.5 hours whiting out
(loop review row 62).
2026-09-28 22:08:17 +00:00
acamilo
eecd5744e0 docs: v0.6.4 status
Some checks are pending
ci / node 22 (test + typecheck) (push) Waiting to run
ci / rust stable (cargo test --workspace --release) (push) Waiting to run
ci / infra/tests/lint.sh (push) Waiting to run
ci / playwright apps/stage (allowed to fail) (push) Waiting to run
2026-09-28 21:38:07 +00:00
acamilo
dc64ffb4ea Merge feat/recovery-splash: an on-stream splash while recovery acts 2026-09-28 21:37:56 +00:00
acamilo
3922b82762 Merge feat/loop-recover-ladder: automatic loop recovery climbs restart, rung reset, rung below 2026-09-28 21:37:50 +00:00
acamilo
26892d8530 loop recovery: wait on the watchdog's ActiveState, and only a root flysim that is the running build
review-ladder r2: a oneshot probe mid-run is 'activating', which
is-active does not count, so the wait never waited. The root copy must
also be byte-identical to /opt/fly/current/flysim, so a manual rollback
cannot approve an archive the running build refuses. Docs: the hold
after an unrestorable rung, the post-deploy --list check, and never
stopping the unit mid-step.
2026-09-28 21:37:40 +00:00
acamilo
865d6f6b55 stage mockups: recovery splash, four phases by two actions 2026-09-28 21:34:37 +00:00
acamilo
c574e7b973 docs: recovery splash and the stream notice contract 2026-09-28 21:34:37 +00:00
acamilo
15f2e6dbae stage: auto-recovery splash over the game, polled from flystage-web
The loop-recovery helper's notice (/run/fly/wd/recovery-notice.json,
FLY_RECOVERY_NOTICE) is served by serve.mjs at /recovery-notice.json and
polled once a second by the page, independent of flysim. Countdown shows a
Game Boy text box over the bottom of the game; acting covers the game while
flysim is down; done/failed show briefly. Stale, malformed or oversized
notices are ignored and helper strings are clipped to a closed charset.
Adds ?recovery=, __stage.recovery(), the recovery-notice dev tool, unit
tests (model, poller, serve.mjs route) and an e2e spec.
2026-09-28 21:34:37 +00:00
acamilo
f205d95e5e loop recovery: review-ladder fixes, root never runs a fly-writable binary
B1: fly-loop-reset runs only /opt/fly/sbin/flysim, a root-owned copy
05-deploy installs from the release tarball after checking it against
the tarball's MANIFEST; fixed paths, fly.env parsed as data, env -i.
B2: the wrapper pauses fly-watchdog.timer (and waits out a running
probe) for the reset, and starts flysim and the timer on every exit.
H1: a step that raises or times out is a failed step; the ladder state
is saved before the step runs. H2: one --list call computes the build's
compatibility once; TimeoutStartSec 25 min. H3: level 2+ resets to the
rung below the best or restarts, never lower.
Tests run the wrapper against a fake flysim, systemctl and archives.
2026-09-28 21:34:32 +00:00
acamilo
9c9cec49a9 loop recovery: reset only to an archive the running build can restore
fly-reset-to-milestone does not check compatibility and a flysim that
refuses every checkpoint does not start. fly-loop-reset --check applies
05-deploy's rule (identical, or an adapter-only difference named in
FLY_ACCEPT_ADAPTERS); the ladder picks the highest restorable rung and
falls back to a restart when there is none.
2026-09-28 21:25:58 +00:00
acamilo
63ecc32b2f loop recovery: an escalation ladder that unsticks a trap on its own
Restart flysim, then reset to the current rung's milestone, then to the
archive below the best rung (never lower), one step per confirmed trap
that outlives the previous one. Two resets a day, three-hour restarts
once they are spent; the ladder starts over at a new best rung or after
six quiet hours. State and history live in the unit's StateDirectory so
a reboot does not forget where the ladder stood.

A router model list confirms each step; a 'not stuck' answer delays it
at most three probes and no answer leaves the watchdog to decide alone.
Each step is announced 60 s ahead in /run/fly/wd/recovery-notice.json
for the stage's recovery splash.

fly-loop-reset is the one new root surface (a sudoers line); 05-deploy
now converges config/fly-sudoers so a release can add it.
2026-09-28 21:23:33 +00:00
acamilo
f6e3013708 tests: the own-turn pad measure skips a menu the cartridge still holds an A on 2026-09-24 05:29:03 +00:00
acamilo
1acd20eb23 docs: macros.md 12.27 and the row 63 audit, an A the cartridge has not let go of 2026-09-24 05:29:03 +00:00
acamilo
e170812e7c palette: a battle menu the cartridge still holds an A on deals no pad
RUN's A is taken and the menu's box stays up while the game stops asking the joypad; a
macro dealt on those frames pressed at a menu already gone and held the pad for its cursor
wait. Empty until the cartridge asks again, 12.13's reading.
2026-09-24 05:29:03 +00:00
acamilo
68b756d824 tests: row 63's ROM proofs, the Potion used from the Mt. Moon checkpoint and the two pinned addresses read back 2026-09-24 05:29:03 +00:00
acamilo
4178a20529 palette: MOVE 1 is FIGHT's backstop only while nothing else is a move, and ITEM asks the cartridge about its Potion 2026-09-24 04:49:40 +00:00
acamilo
86149dca9b executor: a confirming A waits for the cartridge to have let go of the last one
The Potion's party list reads open before the game asks the joypad again, and until it asks
the A that opened it is still in hJoyLast: an A pressed there is no edge. ITEM confirmed on
that frame, reported done over a list still waiting, and the fly backed out with BACK, BACK.
2026-09-24 04:49:40 +00:00
acamilo
944c9204e0 scene_probe: FLY_PROBE_CATCH=bag and =potion, row 63's battle survey and the party list's A window 2026-09-24 04:49:40 +00:00
acamilo
113970f4e1 state: what the cartridge does with an item from the battle bag, and whether it still holds an A
item_routine reads ItemUsePtrTable ($03:$55E1) by id and checks it by its own shape;
battle_item_use answers each routine's refusal on bytes already in WRAM. a_latched reads
hJoyLast, the reading the joypad edge is made against. MacroState gains item_refused and
a_latched, both off by default.
2026-09-24 04:04:08 +00:00
335 changed files with 76367 additions and 2632 deletions

View file

@ -32,6 +32,8 @@ Read `docs/architecture-tour.md` first. Then `docs/stream-mvp-plan.md` for decis
LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass` LAN addresses, container ids, host paths, account ids, channel names, people's names, `pass`
entry names or forge URLs. Say "the host", "the release container", "the dev container", "the entry names or forge URLs. Say "the host", "the release container", "the dev container", "the
channel", "the operator"; put the real values in the operator's infra repo. Real values belong channel", "the operator"; put the real values in the operator's infra repo. Real values belong
in an env file outside the checkout — see `infra/env/README.md`. `infra/tests/lint.sh` refuses in an env file outside the checkout — see `infra/env/README.md`. `tools/pii-scan.sh` refuses
the patterns; the rules live in the operator's infra repo and the patterns (run by `infra/tests/lint.sh`, `infra/build/tag-release.sh` and the pre-push hook
`infra/tests/de-pii-allow.txt` the few legitimate mentions. from `tools/install-hooks.sh`); the proper nouns it looks for live in the operator's private
pattern list (`$FLY_PII_PATTERNS`), never here, and `infra/tests/de-pii-allow.txt` lists the few
legitimate mentions. Run `tools/install-hooks.sh` once per clone.

View file

@ -47,12 +47,15 @@ are a `chromium --kiosk` line in a systemd unit and a Playwright test.
| `feed` | ws URL | Feed override for `mode=live`. Default `ws://127.0.0.1:7400/feed`. | | `feed` | ws URL | Feed override for `mode=live`. Default `ws://127.0.0.1:7400/feed`. |
| `gain`, `gamegain`, `sfxgain` | 0..1 | Master / game / SFX gain. Defaults 0.9 / 0.8 / 0.5. | | `gain`, `gamegain`, `sfxgain` | 0..1 | Master / game / SFX gain. Defaults 0.9 / 0.8 / 0.5. |
| `audio` | `0` | Do not create an AudioContext at all. | | `audio` | `0` | Do not create an AudioContext at all. |
| `recovery` | `1`, `0` | Poll `/recovery-notice.json` for the auto-recovery splash. Defaults to on in `live` mode and off in `player` mode, so a fixture screenshot never picks up a stray notice file. |
`window.__stage` exposes the operator surface: `metrics()` (per-stage paint timings), `audio()` `window.__stage` exposes the operator surface: `metrics()` (per-stage paint timings), `audio()`
(context state, ring fill, underruns, drops), `health()` (accepted snapshots, feed gaps, decode (context state, ring fill, underruns, drops), `health()` (accepted snapshots, feed gaps, decode
errors), `manifest()`, `seek(seconds)`, `stopFeed()`, `gameScale()`, `fly()` (renderer mode, gait errors), `manifest()`, `seek(seconds)`, `stopFeed()`, `gameScale()`, `fly()` (renderer mode, gait
phase, leg tips, proboscis extension), `motion()` (which tab and why, the moment on stage and its phase, leg tips, proboscis extension), `motion()` (which tab and why, the moment on stage and its
phase, the queue depth, live particles), `pam()` (the PAM centroid the flare spreads from), and phase, the queue depth, live particles), `pam()` (the PAM centroid the flare spreads from), and
`recovery(notice, nowS?)` (put a recovery notice on the splash by hand, validated like a polled
one, with its clock optionally pinned; `null` clears it), and
`fire(type, label, detail)` — the one deliberate way to drive the moment catalogue by hand, which `fire(type, label, detail)` — the one deliberate way to drive the moment catalogue by hand, which
is what the moment mockups and the moment assertions use instead of waiting for a fixture to is what the moment mockups and the moment assertions use instead of waiting for a fixture to
contain one of each. contain one of each.
@ -95,7 +98,8 @@ Builds, serves, and writes sixteen PNGs to `mockups/`, at 1920x1080 and DPR 1:
`steady-t1-{senses,connectome,ladder}` and `describe` for the four tabs, `big-moment-t1` 2.5 s into that `steady-t1-{senses,connectome,ladder}` and `describe` for the four tabs, `big-moment-t1` 2.5 s into that
fixture's milestone, `moment-{milestone,badge,sugar,rollback}` shot 300 ms after the trigger (the fixture's milestone, `moment-{milestone,badge,sugar,rollback}` shot 300 ms after the trigger (the
middle of every arrival in the catalogue), `macros-{overworld,running,outcome,battle,indoors}` for middle of every arrival in the catalogue), `macros-{overworld,running,outcome,battle,indoors}` for
the macro strip's five states, and the two `fly-*` review crops at 2x. `--only <substring>` shoots the macro strip's five states, `recovery-<phase>-<action>` for the auto-recovery splash, and the
two `fly-*` review crops at 2x. `--only <substring>` shoots
just the ones whose name contains it, which is how one panel gets re-reviewed without rewriting just the ones whose name contains it, which is how one panel gets re-reviewed without rewriting
every committed PNG. every committed PNG.
@ -194,6 +198,7 @@ Four rail panels instead of layout v1's five, on a 12 px gutter; the left column
| CHAT | 1012x244 | The last seven chat lines, or nothing at all | `panels/ChatPanel.tsx` | | CHAT | 1012x244 | The last seven chat lines, or nothing at all | `panels/ChatPanel.tsx` |
| Moment layer | — | Caption band, rail flash, particles, day slide | `panels/MomentLayer.tsx` | | Moment layer | — | Caption band, rail flash, particles, day slide | `panels/MomentLayer.tsx` |
| Stale feed banner | 1824x40 | Over the title strip after 2 s of silence | `panels/StaleBanner.tsx` | | Stale feed banner | 1824x40 | Over the title strip after 2 s of silence | `panels/StaleBanner.tsx` |
| Recovery splash | over the game | The auto-recovery notice: a text box, or the whole game while flysim restarts | `panels/RecoverySplash.tsx` |
### The progress cluster ### The progress cluster
@ -264,6 +269,52 @@ Bot lines green, names amber, text ink: a viewer has to be able to tell the brid
replies from a person at a glance, because the bridge is the only thing on this stream that can be replies from a person at a glance, because the bridge is the only thing on this stream that can be
made to say something by accident. made to say something by accident.
### Recovery splash
`infra/bin/fly-loop-recover` (`infra/docs/loop-recovery.md`) unsticks a confirmed macro loop by
restarting flysim or resetting the run to an earlier rung. Without a word on screen, viewers see
the game freeze and jump. The splash says what is happening, in the Game Boy's own four greens so
it reads as the cartridge's text box, not as a rail panel or an alarm:
| Phase | Layout | Reset copy | Restart copy |
|---|---|---|---|
| `countdown` | Text box over the bottom ~40% of the game, big `M:SS` to `executeAt`, the loop and how long it was stuck. The stuck loop stays visible above it | The fly is stuck in a loop! / Rewinding to the BOULDER BADGE milestone in 0:42 | … / Shaking it off in 0:42 |
| `acting` | Covers the whole 800x720 game panel, which is frozen or blank while flysim is down; a stepped progress bar | Rewinding… / Back to the BOULDER BADGE milestone | Shaking it off… / Same place, fresh start |
| `done` | Text box, 8 s after the helper's `updatedAt` | Back at the BOULDER BADGE milestone! | All shaken off! |
| `failed` | Text box, 20 s | That didn't work / Trying something else next | same |
A reset names its target by the ladder label: a place as is (`PEWTER CITY`), any other rung as
`the BOULDER BADGE milestone`, and the rung the fly is already on as `the start of MT. MOON` (the
ladder's first reset goes back to where it first reached that rung).
**Where the notice comes from.** Not the feed: flysim is the thing being restarted. The helper
writes `/run/fly/wd/recovery-notice.json` atomically (tmp + rename); `flystage-web`
(`infra/config/serve.mjs`, the page's own static server, User=fly, same container, independent of
flysim) serves it at `/recovery-notice.json` — 200 with the bytes, or 204 when there is no file
— and the page polls that once a second (`src/lib/recovery-poll.ts`). `FLY_RECOVERY_NOTICE`
overrides the path, for `serve.mjs` and for the Vite dev and preview servers alike, which serve
the same route.
**It can never break the stream.** `src/lib/recovery.ts` is pure and stateless: a missing,
malformed, oversized (> 16 KiB) or wrong-version file is no splash; a notice whose `updatedAt` is
more than 15 minutes old is ignored; `acting` stops covering the game 10 minutes after its last
write even if the helper never follows up, so a dead helper cannot hide the game; and every
string the helper wrote is clipped to letters, digits, spaces and `.,'&:#/-` at a fixed length
before it can reach the screen. Because the view is a function of the file and the wall clock
alone, a page that reloads mid-recovery shows exactly what one that watched it all would.
To look at it by hand:
```sh
export FLY_RECOVERY_NOTICE=$PWD/.recovery-notice.json # any writable path
npm run dev -w @flybrain/stage # http://127.0.0.1:5273/?recovery=1
npm run recovery-notice -w @flybrain/stage -- --phase countdown --action reset --in 45
npm run recovery-notice -w @flybrain/stage -- --demo restart # 20 s countdown, 15 s acting, done
npm run recovery-notice -w @flybrain/stage -- --clear
```
`npm run mockups -- --only recovery` writes the eight `mockups/recovery-<phase>-<action>.png`.
### Moments ### Moments
`docs/design/animation.md`'s catalogue, wired. The engine (`src/motion/`, landed separately) owns `docs/design/animation.md`'s catalogue, wired. The engine (`src/motion/`, landed separately) owns

Binary file not shown.

After

Width:  |  Height:  |  Size: 64 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 62 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 65 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 61 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 56 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

View file

@ -14,7 +14,8 @@
"test:e2e": "playwright test", "test:e2e": "playwright test",
"mockups": "tsx tools/mockup.mts", "mockups": "tsx tools/mockup.mts",
"fonts": "tsx tools/font-compare.mts", "fonts": "tsx tools/font-compare.mts",
"record": "tsx tools/record-fixture.mts" "record": "tsx tools/record-fixture.mts",
"recovery-notice": "tsx tools/recovery-notice.mts"
}, },
"dependencies": { "dependencies": {
"@flybrain/brain": "*", "@flybrain/brain": "*",

View file

@ -50,6 +50,8 @@ import {
boxStyle, boxStyle,
} from '@/lib/geometry'; } from '@/lib/geometry';
import { stageOptions } from '@/lib/query'; import { stageOptions } from '@/lib/query';
import { parseRecoveryNotice, recoveryView, type RecoveryView } from '@/lib/recovery';
import { RecoveryPoller } from '@/lib/recovery-poll';
import { Director, FLY_HEAD_ANCHOR } from '@/motion/director'; import { Director, FLY_HEAD_ANCHOR } from '@/motion/director';
import { MotionEngine } from '@/motion/engine'; import { MotionEngine } from '@/motion/engine';
import type { MomentType } from '@/motion/moments'; import type { MomentType } from '@/motion/moments';
@ -68,6 +70,7 @@ import { FlyStrip } from '@/panels/FlyStrip';
import { GamePanel } from '@/panels/GamePanel'; import { GamePanel } from '@/panels/GamePanel';
import { MomentLayer } from '@/panels/MomentLayer'; import { MomentLayer } from '@/panels/MomentLayer';
import { ProgressCluster } from '@/panels/ProgressCluster'; import { ProgressCluster } from '@/panels/ProgressCluster';
import { RecoverySplash, nowSeconds, useRecovery } from '@/panels/RecoverySplash';
import { StaleBanner } from '@/panels/StaleBanner'; import { StaleBanner } from '@/panels/StaleBanner';
import { TabSlot } from '@/panels/TabSlot'; import { TabSlot } from '@/panels/TabSlot';
import { TitleStrip } from '@/panels/TitleStrip'; import { TitleStrip } from '@/panels/TitleStrip';
@ -632,6 +635,14 @@ export function App() {
loop.start(); loop.start();
// -- The auto-recovery splash's notice ----------------------------------------------------
// Polled from `flystage-web`, not the feed: flysim is what the helper restarts
// (`src/lib/recovery-poll.ts`). Off in player mode unless `?recovery=1`.
const recoveryPoller = options.recovery
? new RecoveryPoller({ onChange: (notice) => useRecovery.setState({ notice }) })
: null;
recoveryPoller?.start();
// -- Test and operator surface ------------------------------------------------------------ // -- Test and operator surface ------------------------------------------------------------
window.__stage = { window.__stage = {
options, options,
@ -687,6 +698,37 @@ export function App() {
ingest.commit(hot.lastSnapshotMs, true); ingest.commit(hot.lastSnapshotMs, true);
return useStage.getState().chat.length; return useStage.getState().chat.length;
}, },
/**
* Feed reward events into the ticker by hand, `stepMs` of feed time apart, for the ticker
* mockups (a battle's hits, a KO), and settle the dwell gate five seconds after the last.
* The events go through the same `TickerQueue.push` a snapshot's do.
*/
ticker: (events, stepMs = 7000) => {
let at = hot.lastSnapshotMs;
for (const [index, item] of events.entries()) {
at = hot.lastSnapshotMs + index * stepMs;
ingest.queue().push(
{ id: 900_000 + index, wallMs: 0, brainMs: 0, kind: 'reward', label: item.label, value: item.value },
at,
);
}
at += 5000;
ingest.commit(at, true);
return useStage.getState().ticker.map((row) => `${row.label} ${String(row.amount ?? '')}`);
},
/**
* Put a notice on the recovery splash by hand, the same way `fire` drives a moment: for the
* splash mockups and e2e assertions. The raw object goes through the same validation as a
* polled file, the poller stops so it cannot overwrite it, and `nowS` pins the splash's clock
* so a countdown screenshot is reproducible. `null` clears it. Returns what the splash shows.
*/
recovery: (raw, nowS) => {
recoveryPoller?.stop();
const notice = raw === null ? null : parseRecoveryNotice(raw);
const pinnedNowS = nowS ?? null;
useRecovery.setState({ notice, pinnedNowS });
return recoveryView(notice, nowSeconds(pinnedNowS));
},
fly: () => ({ fly: () => ({
// The renderer that is actually drawing, which is not always the one that was asked for: // The renderer that is actually drawing, which is not always the one that was asked for:
// `webgl` falls back to `paper` on a host with no usable GL context (`src/fly/index.ts`). // `webgl` falls back to `paper` on a host with no usable GL context (`src/fly/index.ts`).
@ -714,6 +756,7 @@ export function App() {
if (readyTimer !== null) clearTimeout(readyTimer); if (readyTimer !== null) clearTimeout(readyTimer);
loop.stop(); loop.stop();
source?.stop(); source?.stop();
recoveryPoller?.stop();
fly?.dispose(); fly?.dispose();
worker.terminate(); worker.terminate();
void engine?.stop(); void engine?.stop();
@ -739,6 +782,7 @@ export function App() {
<ChatPanel source={options.chat} /> <ChatPanel source={options.chat} />
<MomentLayer particleRef={particleCanvas} /> <MomentLayer particleRef={particleCanvas} />
<RecoverySplash />
<StaleBanner /> <StaleBanner />
</div> </div>
); );
@ -764,6 +808,10 @@ declare global {
fire: (type: MomentType, label?: string, detail?: string) => number | null; fire: (type: MomentType, label?: string, detail?: string) => number | null;
/** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */ /** Replace the held feed's chat ring by hand; returns how many lines the panel accepted. */
chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number; chat: (lines: readonly { by: string; text: string; bot?: boolean }[]) => number;
/** Push reward events into the ticker by hand; returns the rows shown. */
ticker: (events: readonly { label: string; value: number }[], stepMs?: number) => string[];
/** Show a recovery notice by hand (validated like a polled one); null clears it. */
recovery: (notice: unknown, nowS?: number) => RecoveryView | null;
fly: () => { fly: () => {
mode: string; mode: string;
requested: string; requested: string;

View file

@ -89,6 +89,11 @@ export const pokemonRed: GameConfig = {
badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 }, badge: { label: 'gym badge', tier: 'moment', dedupeMs: 0 },
}, },
// The fly's own hits (adapter `damage`): several a battle, no protocol kind, so one row per
// battle that counts up. 45 s covers the slowest turn seen (about 7 s from press to payout)
// several times over and is far shorter than the gap between two battles.
hitCopy: { label: 'damage dealt', gapMs: 45_000, tier: 'quiet', koTier: 'notable' },
counters: [ counters: [
{ field: 'badges', label: 'badges', outOf: 8 }, { field: 'badges', label: 'badges', outOf: 8 },
{ field: 'uniqueLocations', label: 'places' }, { field: 'uniqueLocations', label: 'places' },

View file

@ -29,6 +29,21 @@ export interface RewardCopy {
collapsedNoun?: string; collapsedNoun?: string;
} }
/**
* Copy and window for the adapter's per-hit reward, which the protocol has no `rewardKind` for
* (Pokémon Red's `damage`, `HIT #<species> FOR <n> HP[ KO]`). Hits are folded stage-side into one
* row per battle instead of one row per hit.
*/
export interface HitCopy {
/** Row text. Constant; the feed's label is only read for the KO suffix. */
label: string;
/** A row is joined by a hit up to this long after the previous hit folded into it. */
gapMs: number;
/** Tier of the row; a KO raises it to `koTier`. */
tier: RewardTier;
koTier: RewardTier;
}
/** A counter shown in the progress row beside the milestone ladder. */ /** A counter shown in the progress row beside the milestone ladder. */
export interface GameCounter { export interface GameCounter {
/** Which `FeedGame` field to read. */ /** Which `FeedGame` field to read. */
@ -64,6 +79,8 @@ export interface GameConfig {
modeLabels: Record<GameMode, string>; modeLabels: Record<GameMode, string>;
/** Human copy and presentation tier for each reward kind. */ /** Human copy and presentation tier for each reward kind. */
rewardCopy: Record<RewardKind, RewardCopy>; rewardCopy: Record<RewardKind, RewardCopy>;
/** How a reward event with no `rewardKind` that reads as a hit is rolled up. Absent: never. */
hitCopy?: HitCopy;
/** /**
* Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g. * Counters shown on the progress cluster's footer line (`ProgressCluster`), e.g.
* "3/8 badges · 214 places". Per-game *data*, not copy: the values come * "3/8 badges · 214 places". Per-game *data*, not copy: the values come

View file

@ -3,6 +3,7 @@
@import './theme/panels.css'; @import './theme/panels.css';
@import './theme/rail.css'; @import './theme/rail.css';
@import './theme/motion.css'; @import './theme/motion.css';
@import './theme/recovery.css';
/** /**
* Self-hosted OFL faces. `font-display: block` with the default 3 s block period is deliberate: * Self-hosted OFL faces. `font-display: block` with the default 3 s block period is deliberate:

View file

@ -57,6 +57,12 @@ export interface StageOptions {
audio: boolean; audio: boolean;
/** `?metrics=1` keeps the paint-stage histogram and prints it on demand. */ /** `?metrics=1` keeps the paint-stage histogram and prints it on demand. */
metrics: boolean; metrics: boolean;
/**
* Poll `flystage-web` for the auto-recovery notice (`src/lib/recovery.ts`). On by default in
* `live` mode and off in `player` mode, so a fixture screenshot can never pick up a notice file
* that happens to exist on the machine; `?recovery=1` / `?recovery=0` force it either way.
*/
recovery: boolean;
} }
const THEMES: readonly StageTheme[] = ['t1', 't2', 't3']; const THEMES: readonly StageTheme[] = ['t1', 't2', 't3'];
@ -114,6 +120,7 @@ export function parseStageOptions(search: string, defaultFeedUrl = 'ws://127.0.0
}, },
audio: flag(params, 'audio', true), audio: flag(params, 'audio', true),
metrics: flag(params, 'metrics', false), metrics: flag(params, 'metrics', false),
recovery: flag(params, 'recovery', mode === 'live'),
}; };
} }

View file

@ -0,0 +1,88 @@
/**
* Polls `flystage-web` for the recovery notice (`src/lib/recovery.ts`).
*
* Deliberately not the feed: flysim is the thing being restarted, so during `acting` there is no
* feed and no control API to ask. `flystage-web` is the page's own static server, in the same
* container and independent of flysim, and serves the helper's file at
* {@link RECOVERY_NOTICE_ROUTE} (`infra/config/serve.mjs`).
*
* Once a second, with a short timeout, and every failure — no server, a 404 from an older
* `serve.mjs`, a 204 for "no file", a half-written body, a hung request — is "no notice". The
* poller never throws into the page and never retries faster than its interval.
*/
import { RECOVERY_NOTICE_ROUTE, parseRecoveryBody, type RecoveryNotice } from './recovery';
export const RECOVERY_POLL_MS = 1000;
const TIMEOUT_MS = 2500;
type Fetch = (input: string, init?: RequestInit) => Promise<Response>;
export interface RecoveryPollerOptions {
url?: string;
intervalMs?: number;
fetch?: Fetch;
onChange: (notice: RecoveryNotice | null) => void;
}
export class RecoveryPoller {
private readonly url: string;
private readonly intervalMs: number;
private readonly fetchFn: Fetch;
private readonly onChange: (notice: RecoveryNotice | null) => void;
private timer: ReturnType<typeof setTimeout> | null = null;
private stopped = true;
/** The last body seen, so an unchanged file does not re-render the panel. */
private lastKey = '\u0000';
constructor(options: RecoveryPollerOptions) {
this.url = options.url ?? RECOVERY_NOTICE_ROUTE;
this.intervalMs = options.intervalMs ?? RECOVERY_POLL_MS;
this.fetchFn = options.fetch ?? ((input, init) => fetch(input, init));
this.onChange = options.onChange;
}
start(): void {
if (!this.stopped) return;
this.stopped = false;
void this.tick();
}
stop(): void {
this.stopped = true;
if (this.timer !== null) clearTimeout(this.timer);
this.timer = null;
}
/** One poll. Public so the unit tests can drive it without timers. */
async poll(): Promise<RecoveryNotice | null> {
let body = '';
const abort = new AbortController();
const timeout = setTimeout(() => abort.abort(), TIMEOUT_MS);
try {
const response = await this.fetchFn(this.url, { cache: 'no-store', signal: abort.signal });
if (response.status === 200) body = await response.text();
} catch {
body = '';
} finally {
clearTimeout(timeout);
}
const notice = parseRecoveryBody(body);
const key = notice === null ? '' : JSON.stringify(notice);
if (key !== this.lastKey) {
this.lastKey = key;
try {
this.onChange(notice);
} catch (error) {
console.warn(`recovery splash: ${(error as Error).message}`);
}
}
return notice;
}
private async tick(): Promise<void> {
if (this.stopped) return;
await this.poll();
if (this.stopped) return;
this.timer = setTimeout(() => void this.tick(), this.intervalMs);
}
}

View file

@ -0,0 +1,309 @@
/**
* The recovery splash's model: the notice file's contract, its validation, and what the splash
* shows at a given wall-clock second.
*
* `infra/bin/fly-loop-recover` (the auto-unstick helper) writes one small JSON file while it acts
* on a confirmed macro loop — restarting flysim, or resetting the run to an earlier rung — and
* `flystage-web` serves it to this page at {@link RECOVERY_NOTICE_ROUTE}. Viewers otherwise see
* the game freeze or jump for no reason; the splash says what is happening.
*
* Everything here is pure: the poller (`src/lib/recovery-poll.ts`) fetches, the panel
* (`src/panels/RecoverySplash.tsx`) renders, and this file decides. The one rule it exists to
* keep is that **the notice can never break the stream**: a missing, malformed, oversized, future
* or stale file is no notice at all, and every string the helper wrote is clipped to a closed
* character set before it can reach the screen.
*/
/** Where `flystage-web` (and the Vite dev/preview servers) serve the notice file. */
export const RECOVERY_NOTICE_ROUTE = '/recovery-notice.json';
/** Ignore a notice whose `updatedAt` is older than this (the contract: 15 minutes). */
export const RECOVERY_STALE_S = 15 * 60;
/** How long `done` stays up after the helper wrote it. */
export const RECOVERY_DONE_S = 8;
/** How long `failed` stays up after the helper wrote it. */
export const RECOVERY_FAILED_S = 20;
/**
* Stop covering the game this long after an `acting` write, even if the helper never follows up.
* A helper that died mid-recovery must not leave the game hidden behind a splash; with the game
* uncovered again the page's own STALE FEED banner is the honest state.
*/
export const RECOVERY_ACTING_MAX_S = 10 * 60;
/** Tolerated clock skew between the helper's `updatedAt` and the page's clock. */
const FUTURE_SKEW_S = 120;
export type RecoveryPhase = 'countdown' | 'acting' | 'done' | 'failed';
export type RecoveryAction = 'restart' | 'reset';
/** A validated notice. Field names are the file's own; see `infra/docs/loop-recovery.md`. */
export interface RecoveryNotice {
id: string;
phase: RecoveryPhase;
action: RecoveryAction;
fromRung: number | null;
fromLabel: string;
/** Only for `reset`; null otherwise. */
toRung: number | null;
toLabel: string;
reason: string;
loop: string[];
stuckSeconds: number | null;
announcedAt: number;
executeAt: number;
updatedAt: number;
}
const PHASES: readonly RecoveryPhase[] = ['countdown', 'acting', 'done', 'failed'];
const ACTIONS: readonly RecoveryAction[] = ['restart', 'reset'];
/** Longest place name kept (the ladder's longest is 15 characters). */
const LABEL_MAX = 24;
/** Longest macro name kept (the pad's are at most 12, e.g. `GO OBJECTIVE`). */
const MACRO_MAX = 16;
/** At most this many macros of the loop are shown. */
const LOOP_MAX = 4;
/**
* Clip a helper-written string to what the splash may draw: printable ASCII letters, digits,
* spaces and a little punctuation (place names like `MT. MOON` or `S.S. ANNE`, `ROUTE 22`), with
* runs of whitespace collapsed, capped at `max` characters. Anything else is dropped, so a notice
* cannot put markup, control characters or an unbounded line on air.
*/
export function cleanText(value: unknown, max: number): string {
if (typeof value !== 'string') return '';
return value
.replace(/\s+/g, ' ')
.replace(/[^A-Za-z0-9 .,'&:#/-]/g, '')
.replace(/ {2,}/g, ' ')
.trim()
.slice(0, max)
.trim();
}
function finite(value: unknown): number | null {
return typeof value === 'number' && Number.isFinite(value) ? value : null;
}
function rung(value: unknown): number | null {
const n = finite(value);
return n !== null && Number.isInteger(n) && n >= 0 && n < 1000 ? n : null;
}
/**
* Validate a parsed JSON value as a v1 notice, or return null.
*
* Required: `v === 1`, `id`, a known `phase` and `action`, and finite `announcedAt`, `executeAt`,
* `updatedAt`. Everything else is optional and degrades the copy rather than the notice: a reset
* without a `toLabel` still says it is rewinding, just not to where.
*/
export function parseRecoveryNotice(raw: unknown): RecoveryNotice | null {
if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) return null;
const o = raw as Record<string, unknown>;
if (o.v !== 1) return null;
const id = typeof o.id === 'string' ? o.id.slice(0, 64) : '';
if (id === '') return null;
if (!PHASES.includes(o.phase as RecoveryPhase)) return null;
if (!ACTIONS.includes(o.action as RecoveryAction)) return null;
const announcedAt = finite(o.announcedAt);
const executeAt = finite(o.executeAt);
const updatedAt = finite(o.updatedAt);
if (announcedAt === null || executeAt === null || updatedAt === null) return null;
const action = o.action as RecoveryAction;
const loop = Array.isArray(o.loop)
? o.loop
.map((step) => cleanText(step, MACRO_MAX).toUpperCase())
.filter((step) => step !== '')
.slice(0, LOOP_MAX)
: [];
const stuck = finite(o.stuckSeconds);
return {
id,
phase: o.phase as RecoveryPhase,
action,
fromRung: rung(o.fromRung),
fromLabel: cleanText(o.fromLabel, LABEL_MAX).toUpperCase(),
toRung: action === 'reset' ? rung(o.toRung) : null,
toLabel: action === 'reset' ? cleanText(o.toLabel, LABEL_MAX).toUpperCase() : '',
reason: cleanText(o.reason, 32),
loop,
stuckSeconds: stuck !== null && stuck >= 0 ? stuck : null,
announcedAt,
executeAt,
updatedAt,
};
}
/** Parse the body the server returned. Never throws. */
export function parseRecoveryBody(body: string): RecoveryNotice | null {
if (body.length === 0 || body.length > 16_384) return null;
try {
return parseRecoveryNotice(JSON.parse(body));
} catch {
return null;
}
}
/**
* How the splash sits on the stage: `box` is the Pokémon-style text box along the bottom of the
* game, leaving the stuck loop visible above it; `cover` fills the game panel, which is frozen or
* blank while flysim restarts.
*/
export type RecoveryLayout = 'box' | 'cover';
/** What the splash draws. Every string is already final copy. */
export interface RecoveryView {
id: string;
phase: RecoveryPhase;
action: RecoveryAction;
layout: RecoveryLayout;
/** The small chip in the frame's top edge. */
chip: string;
/** The first line, Pokémon-dialogue style. */
headline: string;
/** The second line. */
body: string;
/** `M:SS` during the countdown, otherwise empty. */
countdown: string;
/** `GO OBJECTIVE > GO WARP`, or empty. */
loop: string;
/** `STUCK 30 MIN`, or empty. */
stuck: string;
/** Whether to animate the trailing dots / blinking arrow. */
busy: boolean;
}
/** `0:42`, `1:00`, `12:05`. Negative clamps to `0:00`. */
export function formatCountdown(seconds: number): string {
const s = Math.max(0, Math.ceil(seconds));
const m = Math.floor(s / 60);
return `${m}:${String(s % 60).padStart(2, '0')}`;
}
/** `STUCK 30 MIN`, `STUCK 2 H`, `STUCK 1 H 5 MIN`; empty under a minute or when unknown. */
export function formatStuck(seconds: number | null): string {
if (seconds === null || seconds < 60) return '';
const minutes = Math.round(seconds / 60);
if (minutes < 60) return `STUCK ${minutes} MIN`;
const h = Math.floor(minutes / 60);
const m = minutes % 60;
return m === 0 ? `STUCK ${h} H` : `STUCK ${h} H ${m} MIN`;
}
/**
* Whether the notice is showing at `nowS` (epoch seconds), per the contract's lifetimes.
*
* Stateless on purpose: a page that reloads mid-recovery, or a Chromium the watchdog restarted,
* draws exactly what a page that watched the whole thing would, from the file alone.
*/
export function recoveryVisible(notice: RecoveryNotice, nowS: number): boolean {
const age = nowS - notice.updatedAt;
if (age > RECOVERY_STALE_S) return false;
if (age < -FUTURE_SKEW_S) return false;
switch (notice.phase) {
case 'countdown':
return true;
case 'acting':
return age <= RECOVERY_ACTING_MAX_S;
case 'done':
return age <= RECOVERY_DONE_S;
case 'failed':
return age <= RECOVERY_FAILED_S;
}
}
/**
* Ladder rungs (`docs/design/ladder.md`) whose label is a place the fly can be "back at". The rest
* are events (BOULDER BADGE, GOT A STARTER, HM CUT) and read as "the BOULDER BADGE milestone".
*/
const PLACE_RUNGS: ReadonlySet<string> = new Set([
'PALLET TOWN', "OAK'S LAB", 'VIRIDIAN CITY', 'VIRIDIAN FOREST', 'PEWTER CITY', 'MT. MOON',
'CERULEAN CITY', 'NUGGET BRIDGE', 'VERMILION CITY', 'ROCK TUNNEL', 'LAVENDER TOWN',
'CELADON CITY', 'FUCHSIA CITY', 'CINNABAR ISLAND', 'INDIGO PLATEAU',
]);
/**
* Where a reset goes, in words: `PEWTER CITY`, `the BOULDER BADGE milestone`, and `the start of
* MT. MOON` when the target is the rung the fly is already on (the ladder's first reset: it goes
* back to where it first reached that rung). Empty without a label.
*/
export function resetTarget(notice: RecoveryNotice): string {
const label = notice.toLabel;
if (label === '') return '';
const named = PLACE_RUNGS.has(label) ? label : `the ${label} milestone`;
const same = notice.toRung !== null && notice.toRung === notice.fromRung;
return same ? `the start of ${named}` : named;
}
/** The splash at `nowS`, or null when nothing should be on screen. */
export function recoveryView(notice: RecoveryNotice | null, nowS: number): RecoveryView | null {
if (notice === null || !recoveryVisible(notice, nowS)) return null;
const reset = notice.action === 'reset';
const to = resetTarget(notice);
const base = {
id: notice.id,
phase: notice.phase,
action: notice.action,
loop: notice.loop.join(' > '),
stuck: formatStuck(notice.stuckSeconds),
};
switch (notice.phase) {
case 'countdown': {
const remaining = notice.executeAt - nowS;
const now = remaining <= 0;
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: 'The fly is stuck in a loop!',
body: reset
? now
? to !== '' ? `Rewinding to ${to} now` : 'Rewinding now'
: to !== '' ? `Rewinding to ${to} in` : 'Rewinding to the last milestone in'
: now
? 'Shaking it off now'
: 'Shaking it off in',
countdown: formatCountdown(remaining),
busy: now,
};
}
case 'acting':
return {
...base,
layout: 'cover',
chip: 'AUTO RECOVERY',
headline: reset ? 'Rewinding' : 'Shaking it off',
body: reset
? to !== '' ? `Back to ${to}` : 'Back to the last milestone'
: 'Same place, fresh start',
countdown: '',
busy: true,
};
case 'done':
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: reset ? (to !== '' ? `Back at ${to}!` : 'Rewound!') : 'All shaken off!',
body: "Go get 'em, little fly",
countdown: '',
loop: '',
stuck: '',
busy: false,
};
case 'failed':
return {
...base,
layout: 'box',
chip: 'AUTO RECOVERY',
headline: "That didn't work",
body: 'Trying something else next',
countdown: '',
loop: '',
stuck: '',
busy: false,
};
}
}

View file

@ -68,6 +68,9 @@ export const DEFAULT_TICKER_OPTIONS = {
*/ */
const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']); const HIDDEN_KINDS: ReadonlySet<FeedEventKind> = new Set<FeedEventKind>(['checkpoint', 'viewer']);
/** The adapter's hit label: `HIT #<species> FOR <n> HP` with ` KO` when the hit felled a trainer's Pokémon. */
const HIT_LABEL = /^HIT #\d+ FOR \d+ HP( KO)?$/;
export class TickerQueue { export class TickerQueue {
private readonly visibleRows: number; private readonly visibleRows: number;
private readonly minDwellMs: number; private readonly minDwellMs: number;
@ -77,6 +80,8 @@ export class TickerQueue {
private visible: TickerItem[] = []; private visible: TickerItem[] = [];
private pending: TickerItem[] = []; private pending: TickerItem[] = [];
private lastPromotionMs = Number.NEGATIVE_INFINITY; private lastPromotionMs = Number.NEGATIVE_INFINITY;
/** Feed time of the last hit folded into each hit row, by the row. */
private readonly lastHitMs = new WeakMap<TickerItem, number>();
/** Bumped whenever the visible list changes, so the store can push to React on change only. */ /** Bumped whenever the visible list changes, so the store can push to React on change only. */
private revision = 0; private revision = 0;
@ -106,10 +111,11 @@ export class TickerQueue {
push(event: FeedEvent, nowMs: number): boolean { push(event: FeedEvent, nowMs: number): boolean {
if (HIDDEN_KINDS.has(event.kind)) return false; if (HIDDEN_KINDS.has(event.kind)) return false;
const tier = this.tierOf(event); const hit = this.hitOf(event);
const label = this.labelOf(event); const tier = hit ? this.hitTier(hit.ko) : this.tierOf(event);
const label = hit ? `${this.game.hitCopy?.label ?? event.label}${hit.ko ? ' KO' : ''}` : this.labelOf(event);
const folded = this.fold(event, nowMs); const folded = hit ? this.foldHit(event, hit.ko, nowMs) : this.fold(event, nowMs);
if (folded) return true; if (folded) return true;
const item: TickerItem = { const item: TickerItem = {
@ -125,6 +131,8 @@ export class TickerQueue {
...(event.by === undefined ? {} : { by: event.by }), ...(event.by === undefined ? {} : { by: event.by }),
}; };
if (hit) this.lastHitMs.set(item, nowMs);
if (tier === 'moment') { if (tier === 'moment') {
// Jump the gate: the badge is the reason anyone is watching. // Jump the gate: the badge is the reason anyone is watching.
this.promote(item, nowMs); this.promote(item, nowMs);
@ -176,6 +184,42 @@ export class TickerQueue {
return false; return false;
} }
/** Is this a hit the game rolls up? Only a reward with no `rewardKind` and the adapter's own label. */
private hitOf(event: FeedEvent): { ko: boolean } | null {
if (!this.game.hitCopy || event.kind !== 'reward' || event.rewardKind) return null;
const match = HIT_LABEL.exec(event.label);
return match ? { ko: match[1] !== undefined } : null;
}
private hitTier(ko: boolean): TickerTier {
const copy = this.game.hitCopy;
return copy ? (ko ? copy.koTier : copy.tier) : 'quiet';
}
/**
* Fold a hit into the battle's row: the newest hit row whose last hit is within `gapMs`. The
* window slides with each hit (unlike `fold`'s, which is from creation) because a battle has
* no fixed length; a row that has left the panel is not resurrected, the next hit starts one.
* The row shows the summed reward, a `x<n>` count and a KO once any hit in it felled a Pokémon.
*/
private foldHit(event: FeedEvent, ko: boolean, nowMs: number): boolean {
const copy = this.game.hitCopy;
if (!copy) return false;
for (const item of [...this.visible, ...this.pending]) {
const last = this.lastHitMs.get(item);
if (last === undefined || nowMs - last > copy.gapMs) continue;
item.count += 1;
if (event.value !== undefined) item.amount = (item.amount ?? 0) + event.value;
const knocked = ko || item.label.endsWith(' KO');
item.label = `${copy.label} x${item.count}${knocked ? ' KO' : ''}`;
if (knocked) item.tier = copy.koTier;
this.lastHitMs.set(item, nowMs);
this.revision += 1;
return true;
}
return false;
}
private tierOf(event: FeedEvent): TickerTier { private tierOf(event: FeedEvent): TickerTier {
if (event.kind === 'reward' && event.rewardKind) { if (event.kind === 'reward' && event.rewardKind) {
return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet'; return this.game.rewardCopy[event.rewardKind]?.tier ?? 'quiet';

View file

@ -0,0 +1,129 @@
import { useEffect, useState } from 'react';
import { create } from 'zustand';
import { LAYOUT, boxStyle } from '@/lib/geometry';
import { recoveryView, type RecoveryNotice, type RecoveryView } from '@/lib/recovery';
/**
* The auto-recovery splash, over the game panel.
*
* `infra/bin/fly-loop-recover` announces a recovery a minute before it acts, then restarts flysim
* or resets the run to an earlier rung; without this, viewers see the game freeze and jump for no
* reason. The model is `src/lib/recovery.ts`, the data path `src/lib/recovery-poll.ts`.
*
* Two layouts, both in the Game Boy's own four greens, so it reads as the cartridge's text box
* rather than as one more rail panel:
*
* - **box** (countdown, done, failed): a Pokémon-style text box across the bottom of the game,
* with the countdown beside it. The top two thirds of the game stay visible, because the stuck
* loop is the thing the countdown is about.
* - **cover** (acting): the whole game panel, because the picture there is frozen or blank while
* flysim restarts.
*
* It re-renders at 4 Hz while a notice is held — the stage's own React cadence — and not at all
* otherwise. The countdown is wall-clock arithmetic against the helper's `executeAt`, which is why
* the page needs nothing but the file: it is right after a reload, and while the feed is down.
*/
export const useRecovery = create<{ notice: RecoveryNotice | null; pinnedNowS: number | null }>(() => ({
notice: null,
pinnedNowS: null,
}));
const TICK_MS = 250;
export function nowSeconds(pinned: number | null): number {
return pinned ?? Date.now() / 1000;
}
export function RecoverySplash() {
const notice = useRecovery((state) => state.notice);
const pinned = useRecovery((state) => state.pinnedNowS);
const [nowS, setNowS] = useState(() => nowSeconds(pinned));
useEffect(() => {
setNowS(nowSeconds(pinned));
if (notice === null || pinned !== null) return;
const timer = setInterval(() => setNowS(nowSeconds(null)), TICK_MS);
return () => clearInterval(timer);
}, [notice, pinned]);
let view: RecoveryView | null = null;
try {
view = recoveryView(notice, nowS);
} catch {
view = null;
}
if (view === null) return null;
return (
<div
className="recovery"
data-testid="recovery-splash"
data-phase={view.phase}
data-action={view.action}
data-layout={view.layout}
style={{ ...boxStyle(LAYOUT.game), zIndex: 50 }}
>
{view.layout === 'cover' ? <Cover view={view} /> : <Box view={view} />}
</div>
);
}
function LoopLine({ view }: { view: RecoveryView }) {
if (view.loop === '' && view.stuck === '') return null;
return (
<div className="recovery__loop" data-testid="recovery-loop">
{view.loop !== '' ? <span className="recovery__loop-macros">{view.loop}</span> : null}
{view.loop !== '' && view.stuck !== '' ? <span className="recovery__sep" aria-hidden /> : null}
{view.stuck !== '' ? <span>{view.stuck}</span> : null}
</div>
);
}
function Box({ view }: { view: RecoveryView }) {
return (
<div className="recovery__box">
<span className="recovery__chip">{view.chip}</span>
<div className="recovery__row">
<div className="recovery__text">
<p className="recovery__headline" data-testid="recovery-headline">
{view.headline}
</p>
<p className="recovery__body" data-testid="recovery-body">
{view.body}
{view.busy ? <span className="recovery__dots" aria-hidden /> : null}
</p>
</div>
{view.countdown !== '' ? (
<div className="recovery__countdown" data-testid="recovery-countdown">
{view.countdown}
</div>
) : null}
</div>
<LoopLine view={view} />
<span className="recovery__arrow" aria-hidden />
</div>
);
}
function Cover({ view }: { view: RecoveryView }) {
return (
<div className="recovery__cover">
<span className="recovery__chip recovery__chip--cover">{view.chip}</span>
<p className="recovery__big" data-testid="recovery-headline">
{view.headline}
<span className="recovery__dots" aria-hidden />
</p>
<p className="recovery__body recovery__body--cover" data-testid="recovery-body">
{view.body}
</p>
<div className={`recovery__bar recovery__bar--${view.action}`} aria-hidden>
{Array.from({ length: 8 }, (_, index) => (
<span key={index} style={{ animationDelay: `${index * 150}ms` }} />
))}
</div>
<div className="recovery__was">{view.loop !== '' ? 'IT WAS LOOPING ON' : null}</div>
<LoopLine view={view} />
</div>
);
}

View file

@ -0,0 +1,230 @@
/**
* The auto-recovery splash (`src/panels/RecoverySplash.tsx`), over the 800x720 game panel.
*
* Its own palette on purpose: the Game Boy's four greens, so the splash reads as the cartridge's
* own text box / screen and never as a rail panel or an alarm. Square corners, a 4 px outer frame
* and a 2 px inner line, like every other box on the page (`tokens.css`). Type sits on the page's
* floors: Press Start 2P for the dialogue line and the countdown, VT323 for the rest.
*/
.recovery {
--gb-0: #e0f0c8; /* lightest: the paper */
--gb-1: #8bac0f;
--gb-2: #306230;
--gb-3: #0f380f; /* darkest: the ink */
pointer-events: none;
}
/* -- Box: countdown, done, failed ---------------------------------------------------------- */
.recovery__box {
position: absolute;
left: 16px;
right: 16px;
bottom: 16px;
padding: 30px 28px 20px;
background: var(--gb-0);
color: var(--gb-3);
border: var(--border-w) solid var(--gb-3);
outline: var(--border-inner-w) solid var(--gb-0);
outline-offset: calc(-1 * var(--border-w) - 6px);
box-shadow: inset 0 0 0 10px var(--gb-0), inset 0 0 0 12px var(--gb-2);
animation: recovery-rise 320ms var(--ease-pixel, steps(8, end)) both;
}
.recovery__chip {
position: absolute;
top: -18px;
left: 24px;
padding: 2px 12px;
font-family: var(--font-label);
font-size: var(--fs-body);
line-height: 28px;
background: var(--gb-3);
color: var(--gb-0);
letter-spacing: 0.04em;
}
.recovery__row {
display: flex;
align-items: center;
gap: 24px;
}
.recovery__text {
flex: 1 1 auto;
min-width: 0;
}
.recovery__headline {
margin: 0 0 14px;
font-family: var(--font-pixel);
font-size: 24px;
line-height: 1.45;
}
.recovery__body {
margin: 0;
font-family: var(--font-text);
font-size: 40px;
line-height: 1.05;
color: var(--gb-2);
}
.recovery__countdown {
flex: 0 0 auto;
font-family: var(--font-pixel);
font-size: 52px;
line-height: 1;
padding: 16px 14px 12px;
background: var(--gb-3);
color: var(--gb-0);
font-variant-numeric: tabular-nums;
}
.recovery__loop {
margin-top: 14px;
font-family: var(--font-text);
font-size: 30px;
line-height: 1;
color: var(--gb-2);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.recovery__loop-macros {
color: var(--gb-3);
}
.recovery__sep {
display: inline-block;
width: 8px;
height: 8px;
margin: 0 14px;
vertical-align: middle;
background: var(--gb-1);
}
/* The Pokémon "more text" arrow, blinking in the corner. Drawn, not typed: no glyph to miss. */
.recovery__arrow {
position: absolute;
right: 22px;
bottom: 16px;
width: 0;
height: 0;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 12px solid var(--gb-3);
animation: recovery-blink 1s steps(1, end) infinite;
}
/* Three dots that count up, for "working on it". Steps, not a fade. */
.recovery__dots::after {
content: '...';
display: inline-block;
width: 3ch;
overflow: hidden;
vertical-align: bottom;
text-align: left;
animation: recovery-dots 1.2s steps(4, jump-none) infinite;
}
/* -- Cover: acting --------------------------------------------------------------------------- */
.recovery__cover {
position: absolute;
inset: 0;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
gap: 28px;
padding: 40px;
background: var(--gb-0);
color: var(--gb-3);
border: var(--border-w) solid var(--gb-3);
box-shadow: inset 0 0 0 12px var(--gb-0), inset 0 0 0 16px var(--gb-2);
text-align: center;
}
.recovery__chip--cover {
position: static;
}
.recovery__big {
margin: 0;
font-family: var(--font-pixel);
font-size: 44px;
line-height: 1.3;
}
.recovery__body--cover {
font-size: 48px;
}
.recovery__was {
margin-top: 8px;
font-family: var(--font-label);
font-size: var(--fs-body);
color: var(--gb-2);
min-height: 1px;
}
.recovery__cover .recovery__loop {
margin-top: 0;
max-width: 100%;
}
/* Eight cells lighting in turn: right-to-left for a rewind, left-to-right for a restart. */
.recovery__bar {
display: flex;
gap: 8px;
}
.recovery__bar--reset {
flex-direction: row-reverse;
}
.recovery__bar span {
width: 40px;
height: 24px;
background: var(--gb-1);
animation: recovery-cell 1.2s steps(1, end) infinite;
}
@keyframes recovery-rise {
from {
transform: translateY(24px);
opacity: 0;
}
to {
transform: none;
opacity: 1;
}
}
@keyframes recovery-blink {
50% {
visibility: hidden;
}
}
@keyframes recovery-dots {
from {
width: 0;
}
to {
width: 3ch;
}
}
@keyframes recovery-cell {
0%,
12% {
background: var(--gb-3);
}
13%,
100% {
background: var(--gb-1);
}
}

View file

@ -0,0 +1,138 @@
/**
* The auto-recovery splash, against the real build.
*
* The first two tests go through the page's real data path — the poller fetching
* `/recovery-notice.json` — with Playwright answering the route, which is exactly what
* `flystage-web` does with the helper's file. The rest drive the splash through
* `window.__stage.recovery` with a pinned clock, for the geometry and the text floor.
*/
import { expect, test, type Page } from '@playwright/test';
import { stageUrl } from './stage';
const now = (): number => Math.floor(Date.now() / 1000);
function notice(overrides: Record<string, unknown> = {}): Record<string, unknown> {
const t = now();
return {
v: 1,
id: `${t}-reset`,
phase: 'countdown',
action: 'reset',
fromRung: 12,
fromLabel: 'MT. MOON',
toRung: 11,
toLabel: 'PEWTER CITY',
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: t,
executeAt: t + 45,
updatedAt: t,
...overrides,
};
}
async function open(page: Page): Promise<void> {
await page.goto(`${stageUrl({ t: 95, tab: 'senses', audio: false })}&recovery=1`);
await page.waitForSelector('html[data-ready="1"]', { timeout: 60_000 });
}
test('a polled notice shows the countdown, follows the phases and clears', async ({ page }) => {
let body: string | null = JSON.stringify(notice());
await page.route('**/recovery-notice.json', (route) =>
body === null
? route.fulfill({ status: 204 })
: route.fulfill({ status: 200, contentType: 'application/json', body }),
);
await open(page);
const splash = page.getByTestId('recovery-splash');
await expect(splash).toBeVisible({ timeout: 10_000 });
await expect(splash).toHaveAttribute('data-phase', 'countdown');
await expect(splash).toHaveAttribute('data-layout', 'box');
await expect(page.getByTestId('recovery-countdown')).toHaveText(/^0:4\d$/);
await expect(page.getByTestId('recovery-body')).toContainText('Rewinding to PEWTER CITY');
await expect(page.getByTestId('recovery-loop')).toContainText('GO OBJECTIVE > GO WARP');
body = JSON.stringify(notice({ phase: 'acting' }));
await expect(splash).toHaveAttribute('data-layout', 'cover', { timeout: 5_000 });
body = JSON.stringify(notice({ phase: 'done' }));
await expect(splash).toHaveAttribute('data-phase', 'done', { timeout: 5_000 });
// The file going away is also an end: the page never holds a notice the server no longer has.
body = null;
await expect(splash).toHaveCount(0, { timeout: 5_000 });
});
test('stale, malformed and missing notices never show', async ({ page }) => {
const bodies = [
JSON.stringify(notice({ updatedAt: now() - 16 * 60 })),
'{"v":1,"phase":"countdown"',
JSON.stringify(notice({ v: 2 })),
JSON.stringify(notice({ phase: 'done', updatedAt: now() - 60 })),
];
let index = 0;
await page.route('**/recovery-notice.json', (route) => {
const body = bodies[Math.min(index, bodies.length - 1)] as string;
index += 1;
return route.fulfill({ status: 200, contentType: 'application/json', body });
});
await open(page);
await expect.poll(() => index, { timeout: 10_000 }).toBeGreaterThan(bodies.length);
await expect(page.getByTestId('recovery-splash')).toHaveCount(0);
});
test('player mode does not poll unless asked', async ({ page }) => {
let hits = 0;
await page.route('**/recovery-notice.json', (route) => {
hits += 1;
return route.fulfill({ status: 204 });
});
await page.goto(stageUrl({ t: 95, tab: 'senses', audio: false }));
await page.waitForSelector('html[data-ready="1"]', { timeout: 60_000 });
await page.waitForTimeout(2500);
expect(hits).toBe(0);
});
test('the box leaves the top of the game clear; the cover stays inside the game', async ({ page }) => {
await open(page);
const game = await page.getByTestId('game').boundingBox();
if (!game) throw new Error('no game box');
const t = 1_790_629_095;
const base = notice({ announcedAt: t, executeAt: t + 60, updatedAt: t });
await page.evaluate(([raw, nowS]) => window.__stage?.recovery(raw, nowS as number), [base, t + 18] as const);
// Measure after the 320 ms rise, not during it.
await page.locator('.recovery__box').evaluate((element) =>
Promise.all(element.getAnimations().map((animation) => animation.finished)).then(() => undefined),
);
const box = await page.locator('.recovery__box').boundingBox();
if (!box) throw new Error('no text box');
expect(box.y).toBeGreaterThan(game.y + game.height / 2);
expect(box.x).toBeGreaterThanOrEqual(game.x);
expect(box.x + box.width).toBeLessThanOrEqual(game.x + game.width);
expect(box.y + box.height).toBeLessThanOrEqual(game.y + game.height);
await expect(page.getByTestId('recovery-countdown')).toHaveText('0:42');
await page.evaluate(
([raw, nowS]) => window.__stage?.recovery(raw, nowS as number),
[{ ...base, phase: 'acting', updatedAt: t + 60 }, t + 70] as const,
);
const cover = await page.locator('.recovery__cover').boundingBox();
if (!cover) throw new Error('no cover');
expect(cover).toEqual(game);
// Every run of text on the splash sits on the page's body floor.
const sizes = await page.evaluate(() =>
[...document.querySelectorAll('[data-testid="recovery-splash"] *')]
.filter((element) => [...element.childNodes].some((node) => node.nodeType === 3 && node.textContent?.trim()))
.map((element) => Number.parseFloat(getComputedStyle(element).fontSize)),
);
expect(sizes.length).toBeGreaterThan(3);
for (const size of sizes) expect(size).toBeGreaterThanOrEqual(24);
await page.evaluate(() => window.__stage?.recovery(null));
await expect(page.getByTestId('recovery-splash')).toHaveCount(0);
});

View file

@ -0,0 +1,274 @@
/**
* The recovery splash's model, poller and server route.
*
* The one property every test here protects: the notice file can never break the stream. A
* missing, malformed, stale or hostile file is no splash, and a good one shows exactly the
* contract's lifetimes (countdown until acting, acting while flysim is down, done ~8 s, failed
* briefly) from the file alone.
*/
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { parseStageOptions } from '../../src/lib/query';
import {
RECOVERY_ACTING_MAX_S,
RECOVERY_DONE_S,
RECOVERY_FAILED_S,
RECOVERY_STALE_S,
cleanText,
formatCountdown,
formatStuck,
parseRecoveryBody,
parseRecoveryNotice,
recoveryView,
} from '../../src/lib/recovery';
import { RecoveryPoller } from '../../src/lib/recovery-poll';
const T = 1_790_629_095;
function notice(overrides: Record<string, unknown> = {}): Record<string, unknown> {
return {
v: 1,
id: `${T}-reset`,
phase: 'countdown',
action: 'reset',
fromRung: 12,
fromLabel: 'MT. MOON',
toRung: 11,
toLabel: 'PEWTER CITY',
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: T,
executeAt: T + 60,
updatedAt: T,
...overrides,
};
}
const view = (raw: Record<string, unknown>, now: number) => recoveryView(parseRecoveryNotice(raw), now);
test('the contract example parses', () => {
const parsed = parseRecoveryNotice(notice());
assert.ok(parsed);
assert.equal(parsed.phase, 'countdown');
assert.equal(parsed.action, 'reset');
assert.equal(parsed.toLabel, 'PEWTER CITY');
assert.equal(parsed.fromLabel, 'MT. MOON');
assert.deepEqual(parsed.loop, ['GO OBJECTIVE', 'GO WARP']);
});
test('anything malformed is no notice at all', () => {
const bad: unknown[] = [
null,
42,
'x',
[],
notice({ v: 2 }),
notice({ v: '1' }),
notice({ id: '' }),
notice({ id: 7 }),
notice({ phase: 'panic' }),
notice({ action: 'reboot' }),
notice({ executeAt: 'soon' }),
notice({ updatedAt: Number.NaN }),
notice({ announcedAt: undefined }),
];
for (const raw of bad) assert.equal(parseRecoveryNotice(raw), null, JSON.stringify(raw));
for (const body of ['', '{', 'null', '{"v":1}', 'x'.repeat(20_000)]) assert.equal(parseRecoveryBody(body), null);
assert.ok(parseRecoveryBody(JSON.stringify(notice())));
});
test('optional fields degrade the copy, not the notice', () => {
const bare = view({ v: 1, id: 'a', phase: 'countdown', action: 'reset', announcedAt: T, executeAt: T + 30, updatedAt: T }, T);
assert.ok(bare);
assert.equal(bare.body, 'Rewinding to the last milestone in');
assert.equal(bare.loop, '');
assert.equal(bare.stuck, '');
});
test('helper strings are clipped to a closed character set', () => {
assert.equal(cleanText('<img src=x onerror=alert(1)>', 24), 'img srcx onerroralert1');
assert.equal(cleanText('S.S. ANNE', 24), 'S.S. ANNE');
assert.equal(cleanText(' ROUTE\n\t22 ', 24), 'ROUTE 22');
assert.equal(cleanText('A'.repeat(100), 24).length, 24);
assert.equal(cleanText(12, 24), '');
const parsed = parseRecoveryNotice(notice({ loop: ['go objective', 5, '', 'A', 'B', 'C', 'D'], toLabel: 'pewter\u0000city' }));
assert.ok(parsed);
assert.deepEqual(parsed.loop, ['GO OBJECTIVE', 'A', 'B', 'C']);
assert.equal(parsed.toLabel, 'PEWTERCITY');
// A restart has no destination, whatever the file says.
assert.equal(parseRecoveryNotice(notice({ action: 'restart' }))?.toLabel, '');
});
test('countdown: the text box with M:SS to executeAt, reset and restart copy differ', () => {
const reset = view(notice(), T + 18);
assert.ok(reset);
assert.equal(reset.layout, 'box');
assert.equal(reset.countdown, '0:42');
assert.equal(reset.headline, 'The fly is stuck in a loop!');
assert.equal(reset.body, 'Rewinding to PEWTER CITY in');
assert.equal(reset.loop, 'GO OBJECTIVE > GO WARP');
assert.equal(reset.stuck, 'STUCK 30 MIN');
const restart = view(notice({ action: 'restart' }), T);
assert.ok(restart);
assert.equal(restart.body, 'Shaking it off in');
assert.equal(restart.countdown, '1:00');
// Past executeAt but not yet acting: say "now", never a negative clock.
const late = view(notice(), T + 75);
assert.ok(late);
assert.equal(late.countdown, '0:00');
assert.equal(late.body, 'Rewinding to PEWTER CITY now');
assert.equal(late.busy, true);
});
test('acting: covers the game while flysim is down, and gives up after a cap', () => {
const acting = notice({ phase: 'acting', updatedAt: T + 60 });
const reset = view(acting, T + 90);
assert.ok(reset);
assert.equal(reset.layout, 'cover');
assert.equal(reset.headline, 'Rewinding');
assert.equal(reset.body, 'Back to PEWTER CITY');
const restart = view({ ...acting, action: 'restart' }, T + 90);
assert.equal(restart?.headline, 'Shaking it off');
assert.equal(view(acting, T + 60 + RECOVERY_ACTING_MAX_S + 1), null);
});
test('a rung that is not a place reads as a milestone, and the current rung as its start', () => {
const badge = notice({ toRung: 11, toLabel: 'BOULDER BADGE' });
assert.equal(view(badge, T + 18)?.body, 'Rewinding to the BOULDER BADGE milestone in');
assert.equal(view({ ...badge, phase: 'acting' }, T + 63)?.body, 'Back to the BOULDER BADGE milestone');
assert.equal(view({ ...badge, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the BOULDER BADGE milestone!');
const same = notice({ toRung: 12, toLabel: 'MT. MOON' });
assert.equal(view(same, T + 18)?.body, 'Rewinding to the start of MT. MOON in');
assert.equal(view({ ...same, phase: 'done', updatedAt: T + 120 }, T + 120)?.headline, 'Back at the start of MT. MOON!');
assert.equal(view({ ...same, toLabel: 'BOULDER BADGE', toRung: 12, fromRung: 12 }, T + 18)?.body,
'Rewinding to the start of the BOULDER BADGE milestone in');
});
test('done shows about 8 s, failed a little longer, then both clear', () => {
const done = notice({ phase: 'done', updatedAt: T + 120 });
assert.equal(view(done, T + 120)?.headline, 'Back at PEWTER CITY!');
assert.equal(view({ ...done, action: 'restart' }, T + 121)?.headline, 'All shaken off!');
assert.ok(view(done, T + 120 + RECOVERY_DONE_S));
assert.equal(view(done, T + 120 + RECOVERY_DONE_S + 1), null);
const failed = notice({ phase: 'failed', updatedAt: T + 120 });
assert.equal(view(failed, T + 125)?.body, 'Trying something else next');
assert.equal(view(failed, T + 120 + RECOVERY_FAILED_S + 1), null);
});
test('a notice older than 15 minutes, or from the far future, is ignored', () => {
assert.ok(view(notice(), T + RECOVERY_STALE_S));
assert.equal(view(notice(), T + RECOVERY_STALE_S + 1), null);
assert.equal(view(notice(), T - 3600), null);
});
test('formatting', () => {
assert.equal(formatCountdown(59.2), '1:00');
assert.equal(formatCountdown(5), '0:05');
assert.equal(formatCountdown(725), '12:05');
assert.equal(formatCountdown(-3), '0:00');
assert.equal(formatStuck(null), '');
assert.equal(formatStuck(30), '');
assert.equal(formatStuck(1800), 'STUCK 30 MIN');
assert.equal(formatStuck(7200), 'STUCK 2 H');
assert.equal(formatStuck(3900), 'STUCK 1 H 5 MIN');
});
test('the page polls in live mode, not in player mode, unless told', () => {
assert.equal(parseStageOptions('?mode=live').recovery, true);
assert.equal(parseStageOptions('').recovery, false);
assert.equal(parseStageOptions('?recovery=1').recovery, true);
assert.equal(parseStageOptions('?mode=live&recovery=0').recovery, false);
});
test('the poller turns every failure into "no notice" and reports changes once', async () => {
const seen: (string | null)[] = [];
let reply: () => Promise<Response> = () => Promise.resolve(new Response(JSON.stringify(notice()), { status: 200 }));
const poller = new RecoveryPoller({
fetch: () => reply(),
onChange: (n) => seen.push(n === null ? null : n.phase),
});
assert.equal((await poller.poll())?.phase, 'countdown');
await poller.poll(); // unchanged: no second callback
reply = () => Promise.resolve(new Response(null, { status: 204 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response('{"v":1,', { status: 200 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response('not found', { status: 404 }));
assert.equal(await poller.poll(), null);
reply = () => Promise.reject(new Error('ECONNREFUSED'));
assert.equal(await poller.poll(), null);
reply = () => Promise.resolve(new Response(JSON.stringify(notice({ phase: 'acting' })), { status: 200 }));
assert.equal((await poller.poll())?.phase, 'acting');
assert.deepEqual(seen, ['countdown', null, 'acting']);
});
test('the poller survives a throwing listener', async () => {
const poller = new RecoveryPoller({
fetch: () => Promise.resolve(new Response(JSON.stringify(notice()), { status: 200 })),
onChange: () => {
throw new Error('boom');
},
});
const warn = console.warn;
console.warn = () => {};
try {
assert.equal((await poller.poll())?.phase, 'countdown');
} finally {
console.warn = warn;
}
});
test('flystage-web serves the notice file at /recovery-notice.json, 204 without one', async () => {
const here = dirname(fileURLToPath(import.meta.url));
const serve = resolve(here, '../../../../infra/config/serve.mjs');
const dir = await mkdtemp(join(tmpdir(), 'recovery-notice-'));
const file = join(dir, 'recovery-notice.json');
const child = spawn(process.execPath, [serve, dir, '127.0.0.1', '0'], {
env: { ...process.env, FLY_RECOVERY_NOTICE: file },
stdio: ['ignore', 'pipe', 'inherit'],
});
try {
const base = await new Promise<string>((done, fail) => {
let out = '';
child.stdout.on('data', (chunk: Buffer) => {
out += chunk.toString();
const match = /(http:\/\/127\.0\.0\.1:\d+)\//.exec(out);
if (match?.[1]) done(match[1]);
});
child.on('exit', () => fail(new Error(`serve.mjs exited: ${out}`)));
});
const missing = await fetch(`${base}/recovery-notice.json`);
assert.equal(missing.status, 204);
assert.equal(missing.headers.get('cache-control'), 'no-store');
const body = JSON.stringify(notice());
await writeFile(file, body);
const present = await fetch(`${base}/recovery-notice.json?t=1`);
assert.equal(present.status, 200);
assert.equal(await present.text(), body);
await writeFile(file, 'x'.repeat(20_000));
assert.equal((await fetch(`${base}/recovery-notice.json`)).status, 204, 'oversized files are not served');
// The static half still works, and the notice is not reachable any other way.
await writeFile(join(dir, 'index.html'), '<p>stage</p>');
assert.equal(await (await fetch(`${base}/`)).text(), '<p>stage</p>');
} finally {
child.kill('SIGTERM');
await rm(dir, { recursive: true, force: true });
}
});

View file

@ -147,3 +147,41 @@ test('the platformer config paces the same way with different copy', async () =>
queue.push(reward('explore'), 100); queue.push(reward('explore'), 100);
assert.equal(queue.items()[0]?.label, '2 new ground'); assert.equal(queue.items()[0]?.label, '2 new ground');
}); });
function hit(hp: number, value: number, ko = false): FeedEvent {
return event('reward', `HIT #59 FOR ${hp} HP${ko ? ' KO' : ''}`, { value });
}
test('a battle\'s hits fold into one damage row that sums and counts', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(9, 0.05), 7_000);
queue.push(hit(4, 0.03), 15_000);
assert.equal(queue.items().length, 1);
const row = queue.items()[0];
assert.equal(row?.label, 'damage dealt x3');
assert.equal(row?.count, 3);
assert.ok(Math.abs((row?.amount ?? 0) - 0.14) < 1e-9);
assert.equal(row?.tier, 'quiet');
});
test('a KO marks the row and raises its tier; the window slides, then a new battle is a new row', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(10, 0.06), 0);
queue.push(hit(5, 0.08, true), 30_000);
assert.equal(queue.items()[0]?.label, 'damage dealt x2 KO');
assert.equal(queue.items()[0]?.tier, 'notable');
queue.push(hit(3, 0.02), 70_000);
assert.equal(queue.items().length, 1, 'still inside 45 s of the last hit');
queue.push(hit(3, 0.02), 200_000);
assert.equal(queue.items().length, 2, 'a later battle gets its own row');
assert.equal(queue.items()[0]?.label, 'damage dealt');
});
test('a hit is not confused with other rewards, and a lone KO says so', () => {
const queue = new TickerQueue(pokemonRed, { minDwellMs: 0 });
queue.push(hit(31, 0.25, true), 0);
assert.equal(queue.items()[0]?.label, 'damage dealt KO');
queue.push(event('reward', 'NEW MAP', { value: 0.1 }), 10);
assert.equal(queue.items().length, 2, 'an unrelated no-kind reward keeps its own row');
});

View file

@ -24,6 +24,8 @@
* macros-center.png wide pad with both of its columns filled * macros-center.png wide pad with both of its columns filled
* macros-tab.png * macros-tab.png
* pad-strip.png * pad-strip.png
* recovery-{countdown,acting,done,failed}-{reset,restart}.png
* the auto-recovery splash, each phase and both actions
* *
* T1 Instrument is the chosen theme (`docs/stream-mvp-plan.md`, decisions 2026-09-15 evening), so * T1 Instrument is the chosen theme (`docs/stream-mvp-plan.md`, decisions 2026-09-15 evening), so
* the theme sweep the first gate needed is gone: what these images are for now is the *layout* and * the theme sweep the first gate needed is gone: what these images are for now is the *layout* and
@ -91,6 +93,31 @@ const CHAT_WRAP: { by: string; text: string; bot?: boolean }[] = [
}, },
]; ];
/**
* The ticker in a battle (row 68): the fly's hits arrive as `HIT #<species> FOR <n> HP` rewards and
* fold into one "damage dealt" row. Injected by hand through `window.__stage.ticker`, seven feed
* seconds apart, because no fixture holds a battle recorded on adapter v8.
*/
const TICKER_SHOTS: { name: string; events: { label: string; value: number }[] }[] = [
{
name: 'row68-ticker-hits',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
{ label: 'HIT #59 FOR 4 HP', value: 0.03 },
],
},
{
name: 'row68-ticker-ko',
events: [
{ label: 'HIT #59 FOR 10 HP', value: 0.07 },
{ label: 'HIT #59 FOR 9 HP', value: 0.06 },
{ label: 'HIT #59 FOR 12 HP KO', value: 0.13 },
],
},
];
const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [ const STILLS: { name: string; fixture: string; t: number; tab?: Tab; chat?: typeof CHAT_WRAP }[] = [
{ name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' }, { name: 'steady-t1-senses', fixture: 'steady', t: 95, tab: 'senses' },
{ name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' }, { name: 'steady-t1-connectome', fixture: 'steady', t: 95, tab: 'connectome' },
@ -142,6 +169,34 @@ const MOMENTS: { name: string; type: string; label: string; detail: string; tab?
{ name: 'moment-rollback', type: 'rollback', label: 'Rolled back to the archived frame', detail: 'try 3' }, { name: 'moment-rollback', type: 'rollback', label: 'Rolled back to the archived frame', detail: 'try 3' },
]; ];
/**
* The recovery splash shots (`src/panels/RecoverySplash.tsx`): every phase for both actions,
* driven through `window.__stage.recovery` with the splash's clock pinned 18 s into the countdown,
* so the clock reads 0:42 on every machine. The notice is the contract's own example.
*/
const RECOVERY_T = 1_790_629_095;
const RECOVERY_SHOTS = (['countdown', 'acting', 'done', 'failed'] as const).flatMap((phase) =>
(['reset', 'restart'] as const).map((action) => ({
name: `recovery-${phase}-${action}`,
nowS: phase === 'countdown' ? RECOVERY_T + 18 : RECOVERY_T + 63,
notice: {
v: 1,
id: `${RECOVERY_T}-${action}`,
phase,
action,
fromRung: 12,
fromLabel: 'MT. MOON',
...(action === 'reset' ? { toRung: 11, toLabel: 'BOULDER BADGE' } : {}),
reason: 'unrewarded',
loop: ['GO OBJECTIVE', 'GO WARP'],
stuckSeconds: 1800,
announcedAt: RECOVERY_T,
executeAt: RECOVERY_T + 60,
updatedAt: phase === 'countdown' ? RECOVERY_T : RECOVERY_T + 60,
},
})),
);
function run(command: string, args: string[]): Promise<void> { function run(command: string, args: string[]): Promise<void> {
return new Promise((done, fail) => { return new Promise((done, fail) => {
const child = spawn(command, args, { cwd: appDir, stdio: 'inherit' }); const child = spawn(command, args, { cwd: appDir, stdio: 'inherit' });
@ -264,6 +319,35 @@ async function main(): Promise<void> {
console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`); console.log(` ${path} (${String(state?.moment)} ${String(state?.momentPhase)}, ${String(state?.particles)} particles, tab ${String(state?.tab)})`);
} }
for (const shot of TICKER_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const rows = await page.evaluate((events) => window.__stage?.ticker(events) ?? [], shot.events);
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${rows.join(' | ')})`);
}
for (const shot of RECOVERY_SHOTS) {
if (!wanted(shot.name)) continue;
await page.goto(url(baseUrl, { fixture: 'steady', t: 95, tab: 'senses' }));
await settle(page);
const shown = await page.evaluate(([notice, nowS]) => window.__stage?.recovery(notice, nowS as number) ?? null, [
shot.notice,
shot.nowS,
] as const);
if (shown === null) throw new Error(`${shot.name}: the splash refused its notice`);
// The text box rises in over 320 ms (`src/theme/recovery.css`).
await page.waitForTimeout(500);
const path = resolve(outDir, `${shot.name}.png`);
await page.screenshot({ path, clip: FRAME });
written.push(path);
console.log(` ${path} (${shown.layout}: ${shown.headline} / ${shown.body} ${shown.countdown})`);
}
// Two extra review shots: the fly strip alone, at 2x, once per renderer. The strip is 800x220 // Two extra review shots: the fly strip alone, at 2x, once per renderer. The strip is 800x220
// in a 1920x1080 frame, which is too small to judge an animal in; these are what a human looks // in a 1920x1080 frame, which is too small to judge an animal in; these are what a human looks
// at to decide whether it reads. // at to decide whether it reads.

View file

@ -0,0 +1,92 @@
/**
* Write a fake auto-recovery notice, for looking at the recovery splash by hand.
*
* The file is the one `infra/bin/fly-loop-recover` writes (contract: `infra/docs/loop-recovery.md`,
* "Stream notice"), written the same way — a temporary file renamed over the target, mode 0644 —
* to `--out`, else `$FLY_RECOVERY_NOTICE`. Point the page's server at the same path:
*
* ```sh
* export FLY_RECOVERY_NOTICE=$PWD/.recovery-notice.json # any writable path
* npm run dev -w @flybrain/stage # serves it at /recovery-notice.json
* # http://127.0.0.1:5273/?mode=player&recovery=1
*
* npm run recovery-notice -w @flybrain/stage -- --phase countdown --action reset --in 45
* npm run recovery-notice -w @flybrain/stage -- --phase acting --action restart
* npm run recovery-notice -w @flybrain/stage -- --demo reset # countdown 20 s, acting 15 s, done
* npm run recovery-notice -w @flybrain/stage -- --clear
* ```
*
* On the release container the deployed `serve.mjs` reads `/run/fly/wd/recovery-notice.json`
* unless its unit sets `FLY_RECOVERY_NOTICE`; this tool is for a dev machine, not for faking a
* recovery on air.
*/
import { chmod, rename, rm, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
type Phase = 'countdown' | 'acting' | 'done' | 'failed';
type Action = 'restart' | 'reset';
function arg(name: string): string | null {
const at = process.argv.indexOf(`--${name}`);
return at === -1 ? null : (process.argv[at + 1] ?? null);
}
const out = arg('out') ?? process.env.FLY_RECOVERY_NOTICE ?? '';
if (out === '') {
console.error('recovery-notice: pass --out <path> or set FLY_RECOVERY_NOTICE');
process.exit(2);
}
async function write(phase: Phase, action: Action, id: string, announcedAt: number, executeAt: number): Promise<void> {
const notice = {
v: 1,
id,
phase,
action,
fromRung: Number(arg('from-rung') ?? 12),
fromLabel: arg('from-label') ?? 'MT. MOON',
...(action === 'reset' ? { toRung: Number(arg('to-rung') ?? 11), toLabel: arg('to-label') ?? 'PEWTER CITY' } : {}),
reason: arg('reason') ?? 'unrewarded',
loop: (arg('loop') ?? 'GO OBJECTIVE,GO WARP').split(',').map((step) => step.trim()),
stuckSeconds: Number(arg('stuck') ?? 1800),
announcedAt,
executeAt,
updatedAt: Math.floor(Date.now() / 1000),
};
const tmp = join(dirname(out), `.recovery-notice.${process.pid}.tmp`);
await writeFile(tmp, `${JSON.stringify(notice, null, 2)}\n`);
await chmod(tmp, 0o644);
await rename(tmp, out);
console.log(`${phase} ${action} -> ${out}`);
}
const sleep = (s: number): Promise<void> => new Promise((done) => setTimeout(done, s * 1000));
async function main(): Promise<void> {
if (process.argv.includes('--clear')) {
await rm(out, { force: true });
console.log(`removed ${out}`);
return;
}
const now = Math.floor(Date.now() / 1000);
const demo = arg('demo');
if (demo !== null) {
const action = (demo === 'restart' ? 'restart' : 'reset') as Action;
const id = `${now}-${action}`;
await write('countdown', action, id, now, now + 20);
await sleep(20);
await write('acting', action, id, now, now + 20);
await sleep(15);
await write(process.argv.includes('--fail') ? 'failed' : 'done', action, id, now, now + 20);
return;
}
const phase = (arg('phase') ?? 'countdown') as Phase;
const action = (arg('action') ?? 'reset') as Action;
const lead = Number(arg('in') ?? 60);
await write(phase, action, `${now}-${action}`, now, now + lead);
}
main().catch((error: unknown) => {
console.error(error);
process.exit(1);
});

View file

@ -16,7 +16,8 @@
*/ */
import { execFileSync } from 'node:child_process'; import { execFileSync } from 'node:child_process';
import { createReadStream } from 'node:fs'; import { createReadStream } from 'node:fs';
import { cp, stat } from 'node:fs/promises'; import { cp, readFile, stat } from 'node:fs/promises';
import type { IncomingMessage, ServerResponse } from 'node:http';
import { dirname, join, normalize, resolve } from 'node:path'; import { dirname, join, normalize, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import tailwindcss from '@tailwindcss/vite'; import tailwindcss from '@tailwindcss/vite';
@ -87,8 +88,41 @@ function datasetArtifacts(): Plugin {
}; };
} }
/**
* `GET /recovery-notice.json` in dev and preview, the same route `infra/config/serve.mjs` gives
* the deployed page: the auto-recovery helper's notice file (`FLY_RECOVERY_NOTICE`, default
* `/run/fly/wd/recovery-notice.json`), or 204 when there is none. What makes
* `npm run recovery-notice` (`tools/recovery-notice.mts`) work against a local page.
*/
function recoveryNotice(): Plugin {
const serve = async (req: IncomingMessage, res: ServerResponse, next: () => void): Promise<void> => {
if ((req.url ?? '').split('?')[0] !== '/recovery-notice.json') return next();
const path = process.env.FLY_RECOVERY_NOTICE || '/run/fly/wd/recovery-notice.json';
res.setHeader('cache-control', 'no-store');
try {
const info = await stat(path);
if (!info.isFile() || info.size === 0 || info.size > 16_384) throw new Error('no notice');
const body = await readFile(path);
res.setHeader('content-type', 'application/json; charset=utf-8');
res.end(body);
} catch {
res.statusCode = 204;
res.end();
}
};
return {
name: 'flystage-recovery-notice',
configureServer(server) {
server.middlewares.use((req, res, next) => void serve(req, res, next));
},
configurePreviewServer(server) {
server.middlewares.use((req, res, next) => void serve(req, res, next));
},
};
}
export default defineConfig(({ command }) => ({ export default defineConfig(({ command }) => ({
plugins: [react(), tailwindcss(), datasetArtifacts()], plugins: [react(), tailwindcss(), datasetArtifacts(), recoveryNotice()],
define: { define: {
__STAGE_VERSION__: JSON.stringify(stageVersion(command)), __STAGE_VERSION__: JSON.stringify(stageVersion(command)),
}, },

View file

@ -89,8 +89,9 @@ decoder preset to use.
disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already disassembly at commit 0cd19d3 (`symbols.rs`), gates rewards on a playable state, baselines already
achieved flags on the first sample so a restore never replays them, and pays only positive achieved flags on the first sample so a restore never replays them, and pays only positive
rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer rewards: story flags, exploration coverage (capped per map), new areas, Pokédex entries, trainer
flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors and items flags, decaying wild wins, badges, exits found outdoors, catches, conversations indoors, items
picked up (`docs/rewards-learning.md`). Version `pokered-unique8-v7`; a deploy that names the picked up and the HP the fly's own attacks remove in battle (`docs/rewards-learning.md`).
Version `pokered-unique8-v8`; a deploy that names the
previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them. previous version in `FLY_ACCEPT_ADAPTERS` migrates its checkpoints instead of refusing them.
- Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel, - Ratchet (`ratchet.rs`): a 38-rung ladder (boot, bedroom, Pallet Town, Oak's lab, starter, parcel,
Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a Pokédex, each town, each badge, the Elite Four, Champion). On first reaching a higher rung in a
@ -135,7 +136,8 @@ publish. Pacing uses absolute deadlines at 1.0x by default; it never skips frame
audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset. audio (binjgb's unipolar u8 converted and DC-blocked), and a 17,407-byte spike bitset.
flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an flysim serves it itself by default; with `FLY_FEED_VIA=bus` it publishes each snapshot on an
embedded flybus router and the `fly-edge` process serves the same bytes embedded flybus router and the `fly-edge` process serves the same bytes
(`docs/design/flybus.md`, "Feed over the bus"). (`docs/design/flybus.md`, "Feed over the bus"; on a container `fly-feed bus|direct` switches, runbook
"Feed over the bus").
- Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM - Control API (`docs/control-api.md`): loopback HTTP :7401. `POST /stimulate` (sugar: a timed PAM
pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat` pulse, rate-limited server side), `POST /reward` (present, disabled by config), `POST /chat`
(sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`, (sanitized, deny-listed, ring of 12), `/status`, `/checkpoint`, `/pause`, `/resume`,

View file

@ -6,6 +6,12 @@ nothing outside the container can reach it, and the bridge is the only intended
There is deliberately **no endpoint that presses buttons, edits game memory, or changes the There is deliberately **no endpoint that presses buttons, edits game memory, or changes the
reward catalog**. That is a structural guarantee, not a configuration. reward catalog**. That is a structural guarantee, not a configuration.
Who serves it (2026-10-01): flysim itself (`FLY_CONTROL_VIA=direct`, the default), or
`fly-control-edge` from flysim's control services on the bus (`FLY_CONTROL_VIA=bus`,
`docs/design/flybus.md`, "Control over the bus"). Both are the same HTTP code over the same
request handling, so nothing in this document depends on the switch. On the bus, the
guarantee above is also a grant table.
| Method and path | Body | Effect | | Method and path | Body | Effect |
|---|---|---| |---|---|---|
| `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). | | `GET /status` | | Same fields as the feed header minus events and attachments, plus `version` strings (kernel, plasticity, adapter, binjgb, dataset fingerprint) and `checkpoint: { latestWallMs, generation }`. Includes the macro buttons' `game.scene`, `game.macroMode`, `game.palette`, `game.macro` and `game.macroOutcome` (2026-09-16), because the body is the header reshaped rather than a parallel struct. `game.macroMode` is `"raw"` or `"macros"`, and each `game.palette` entry carries its `slot` (0..5), its `name`, its `gloss` and its `channel` tag (`docs/design/macros.md` section 12). |

View file

@ -1,7 +1,9 @@
# flybus: the communications bus # flybus: the communications bus
Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus`, off by default**. Status: **crate landed; the feed rides it behind `FLY_FEED_VIA=bus` and the control API behind
Written 2026-09-22, amended 2026-09-23 (EDGE-01, below). Index only; the `FLY_CONTROL_VIA=bus`, both off by default; EDGE-02 (2026-10-01) made the feed switchable in
production with one command, `fly-feed bus|direct`**. Written 2026-09-22, amended 2026-09-23
(EDGE-01) and 2026-10-01 (EDGE-02 and CTRL-01, below). Index only; the
authority for the API and the wire format is the crate's own authority for the API and the wire format is the crate's own
[README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against [README](../../services/flysim/crates/flybus/README.md), and the audit of the crate against
the draft is the [conformance report](session-framework/bus-conformance.md). the draft is the [conformance report](session-framework/bus-conformance.md).
@ -61,13 +63,13 @@ allocate/seal/read with quotas and router restarts, plus the conformance suites
## Wiring still pending ## Wiring still pending
- ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus". - ~~**flysim publisher.**~~ Done 2026-09-23 behind `FLY_FEED_VIA=bus`: see "Feed over the bus".
- **flysim control services.** The control endpoints as RPC services with grants, so the - ~~**flysim control services.**~~ Done 2026-10-01 behind `FLY_CONTROL_VIA=bus`: see "Control
"no button endpoint" structural guarantee is expressed as a grant table. over the bus". The "no button endpoint" guarantee is a grant table there.
- **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either - **Stage and bridge clients.** Both are TypeScript/Node; the crate is Rust only, so either
a binding or a thin translating edge process is required before they leave the WebSocket a binding or a thin translating edge process is required before they leave the WebSocket
and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for and HTTP surfaces. The operator chose the edge process (port decisions, 2026-09-23); for
the feed it exists (`fly-edge`), and they keep the WebSocket contract unchanged. The the feed it is `fly-edge` and for the control API `fly-control-edge`, and both keep their
control API (:7401) is the next slice and stays in flysim until then. contracts byte for byte.
- ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below. - ~~**Sizing.**~~ Decided 2026-09-23: amendment "Feed sizing" below.
- ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below. - ~~**Lifecycle.**~~ Decided 2026-09-23: amendment "Feed store lifecycle" below.
- **Migration order.** The feed is the cheaper first move; control should follow only once - **Migration order.** The feed is the cheaper first move; control should follow only once
@ -188,3 +190,252 @@ Accepted for now and written down rather than fixed:
escalates. Switch back to `direct` first (the unit header's way back), then roll back. escalates. Switch back to `direct` first (the unit header's way back), then roll back.
- **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a - **Old fixtures.** `cold-open`, `steady` and `big-moment` predate `game.scene` and cannot be a
Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`. Rust `FeedHeader`, so fixture parity covers `macros`, `shop`, `center` and `bigpad`.
### Amendment 2026-10-01: the feed in production (EDGE-02)
- **The session runtime needed nothing.** `flysim-session` serves its listeners through
`flysim::serve`, the same function `flysim` does, so `FLY_FEED_VIA=bus` works on it as it was
written for legacy. It is now a test, not an inference: `fly-legacy-session/tests/feed_bus.rs`
runs the real `flysim-session` binary (toy connectome, the real cartridge) twice from copies of
one store, direct and bus, records both feeds over a WebSocket and requires every frame in
common to be identical (header minus the wall-clock fields, frame, audio and spike bytes), then
stops the binary and starts a new one under the same edge, which must unbind, reconnect and
serve. In the session runtime the router and publisher (`flysim-bus`, two threads) inherit the
host mask of `place_workers` (PERF-02): on the host CPU with the listeners and the sim's dispatcher,
never on a pinned sweep CPU. That shared CPU costs the sim about a millisecond a frame (review
N1), so `FLY_SESSION_AUX_CPUS` moves them: `place_workers_aux` takes the aux CPUs out of the
sim's set and the `flysim-bus` runtime pins itself to them (`SESSION_AUX_CPUS` in the deploy puts
one page CPU into `flysim.slice` for it).
- **One switch.** `FLY_FEED_VIA` in `fly.env` decides everything: `flyedge.service` has an
`ExecCondition=` on it (skipped, not failed, in direct mode) and no `[Install]`;
`flysim.service` has `Wants=flyedge.service`, so every start of flysim, including the stop and
start of `fly-loop-reset` that `Requires=` alone left without an edge, brings the edge up in bus
mode. Checked on systemd 257 with the repo's own units: crash, restart and stop/start of flysim
all end with the edge serving; direct mode never starts it. `infra/bin/fly-feed bus|direct`
rewrites the line, restarts flysim, waits for a new invocation, the edge's `/healthz` and the
page on the feed (frames moving), and rolls a `bus` switch back (to `direct`) when that does not happen
or when it is interrupted; `direct` is never rolled back. It works on either runtime and survives `fly-runtime` changes.
- **Edge health.** `/healthz` is 503 unless the edge is subscribed **and** has taken a snapshot off
the bus within 15 s (`fly_edge_snapshot_age_seconds`): a loop publishes at least the 2 Hz idle
header, so silence means a wedged subscription, which `Subscription::next` alone would never
report.
- **Watchdog.** `feed_via` follows the *running* flysim's environment (a deploy that rewrote
fly.env but has not restarted flysim is not an outage). New check 2a judges the edge only while
flysim answers: second failed pass restarts it, third adds the page and the encoder, fourth
switches the feed back to flysim (`fly-feed direct --no-wait`, sudoers for exactly that line), whatever the time the failures were spread over; an edge fault never reboots.
Check 2 in bus mode leaves a silent edge to 2a instead of restarting a page with nothing to
connect to.
- **Deploy.** `05-deploy.sh` installs `fly-feed`, refuses a release without `fly-edge` while the
env file or the container says `bus` (before `current` moves; `fly-feed direct` needs no
binary), and warns when the container's `FLY_FEED_VIA` differs from the env file's. flysim and
the edge both follow fly.env at their next start, so a disagreement never leaves the stage with
no feed.
- **Known limits, revisited.** *Feed counters off the container*: the edge's `/metrics` now listens
on `0.0.0.0:9102` like flysim's `:9101`; a dashboard adds it as a second target (the watchdog
stays on loopback). *Rollback while in bus mode*: refused by the deploy and one command by
`fly-feed direct`. *Store quota per router* and *old fixtures*: unchanged, accepted as written.
## Control over the bus (2026-10-01, CTRL-01)
`control.via` (`FLY_CONTROL_VIA`) picks who serves `http://127.0.0.1:7401`. `direct` is the
default and the behaviour that predates the bus. With `bus`:
```text
api router (flysim::api) BusBackend flybus (Unix socket) control host (in flysim)
:7401 in fly-control-edge --> encode_request --> <bus_dir>/control-edge.sock --> fly.control.s.main.* services
same routes, extractors, (controlbus) bound to "fly-control-edge" -> flysim::control::handle
404s, headers, bodies -> the same Command queue
```
- `docs/control-api.md` is unchanged and still binding: every endpoint, status code and body.
flysim's control code is split in two. `flysim::control` holds the semantics: one
`ControlRequest` per endpoint, and `handle`, the only code that validates a request, talks to
the loop and picks a status. `flysim::api` is the HTTP layer over any `ControlBackend`. Direct
mode is `api` over `control` in one process. Bus mode is the same `api` in `fly-control-edge`
over a `BusBackend`, which carries the request to the `control` services in flysim. Neither
process has an HTTP table or a validation rule of its own, so the bytes on `:7401` are the
same in both modes. `crates/fly-control-edge/tests/parity.rs` sends every endpoint, each
validation case and each refusal to both paths and requires equal status, headers and
body. Over real sockets, it also requires the whole HTTP/1.1 response to be equal apart from
`date`. `fly-legacy-session/tests/service_parity.rs` runs the session runtime once more with
its control on the bus and compares it with the legacy loop. The comparison covers 120
frames, 19 control responses, the event log, the journal and the final checkpoint.
- Both runtimes get it: `flysim` and `flysim-session` both run `flysim::serve`, which in bus mode
does not bind `control.bind`. Instead it registers the services on the embedded router. That
is the feed's router when the feed is on the bus too: one router, one store, one closed policy
(`flysim::bus`). The read-only `control.metrics_bind` listener (`:9101`) stays in flysim in
both modes.
- Nothing about the fly changes. The command queue, its bound and its timeouts are the same.
The compatibility string is byte-identical in both modes.
### Services and methods
flybus grants name services, not methods. The surface is therefore split into six service
*families*, and a grant names families. Every family is scoped either to a session or to one
agent (fly) of it. Each method's payload and outcome:
| Service (live names) | Method | Endpoint | Payload |
| --- | --- | --- | --- |
| `fly.control.s.main.read` | `Control.Status` | `GET /status`, `/status.json` | `{}` |
| | `Control.Healthz` | `GET /healthz` | `{}` |
| | `Control.Metrics` | `GET /metrics` | `{}` |
| | `Control.Events` | `GET /events` | `{since?: string, limit?: string}`, the raw query values |
| `fly.control.s.main.a.fly.status` | `Control.Status` | (none: the fly's own status, for native clients) | `{}` |
| `fly.control.s.main.a.fly.sugar` | `Control.Stimulate` | `POST /stimulate` | `{request?: <body JSON>}` |
| `fly.control.s.main.a.fly.reward` | `Control.Reward` | `POST /reward` | `{request?: <body JSON>}` |
| `fly.control.s.main.chat` | `Control.Chat` | `POST /chat` | `{request?: <body JSON>}` |
| `fly.control.s.main.ops` | `Control.Checkpoint`, `Control.Pause`, `Control.Resume` | `POST /checkpoint`, `/pause`, `/resume` | `{}` |
- **Outcome.** `{"status": <the control-api.md code>, "body": <the JSON body>}`, or `{"status",
"text"}` for `/metrics`. Above 48 KiB (a full `/events` page can be 4,096 events) the body
travels as a sealed `body` artifact instead, with `bodyArtifact` naming its type. The status
code is the outcome's vocabulary, not transport. A bus caller reads `429 {retryAfterMs}` as an
HTTP caller does, so the edge needs no table of its own.
- **Requests** carry the body as the caller sent it (`request` is absent when it was empty or
not JSON), so validation stays in `control::handle`. A `request` over 48 KiB of JSON travels as
a sealed `request` artifact with `requestArtifact: true` in the payload, so a large body gets
the answer direct mode gives it, not an envelope error (`tests/parity.rs`). An unknown payload field is a 400. A
method the service does not have is a 404. Neither reaches the loop.
- **Concurrency.** Each service has 16 queued and 16 in flight (`controlbus::SERVICE_CONFIG`).
The router dispatches FIFO per service. The host answers each request in a task of its own, so
a pause waiting on a durable write does not hold up a resume. Families are separate services,
so a stuck `ops` never delays `/status`.
- **Backpressure.** The bound is on the queue at the moment of admission. A burst can
therefore be refused before the router has dispatched its first calls into the in-flight
slots. That is measured, not assumed (`tests/backpressure.rs`). A full service refuses at
once with `BACKPRESSURE`, and the edge answers it
with direct mode's `503 {"error": "the simulation command queue is full"}`. Bus failures use
direct mode's words for the same failure (`control::unavailable`). `NO_SERVICE` before
dispatch is "has stopped"; `NO_SERVICE` after dispatch, `CALL_GONE` and `ROUTER_LOST` are
"dropped the request". `NOT_AUTHORIZED` is a 403.
- **Deadlines and cancel.** The host keeps direct mode's own timeouts: 2 s for a command,
none for `/checkpoint` and `/pause`, which wait for a durable write. The edge adds a guard of
that plus 2 s for timed requests only. At the guard it cancels the call and answers direct
mode's timeout 503. A call cancelled before dispatch never reaches the loop. A dispatched call
may still act, as a direct request whose caller timed out may. An HTTP client that goes away
drops its handler, and with it the pending call. The router discards the late result, and
the call record goes once the host answers (`tests/backpressure.rs`).
### Grants: the structural guarantee as a table
| Participant (socket) | read | status | sugar | reward | chat | ops | register |
| --- | --- | --- | --- | --- | --- | --- | --- |
| `flysim-control`, the host (in-process, no socket) | | | | | | | every control service, exact names |
| `fly-stage` (`control/stage.sock`) | yes | yes | | | | | |
| `fly-bridge` (`control/bridge.sock`) | yes | yes | yes | | yes | | |
| `fly-watchdog` (`control/watchdog.sock`): watchdog, loop-recover ladder, `fly-runtime`, probation, shadow guard, stream check | yes | yes | | | | | |
| `fly-operator` (`control/operator.sock`) | yes | yes | yes | yes | yes | yes | |
| `fly-control-edge` (`control-edge.sock`): everything on `:7401` | yes | yes | yes | yes | yes | yes | |
| a player backing one fly (`player_grants`, not wired yet) | yes | that fly | that fly | | | | |
The status, sugar and reward columns are per agent: a role gets them for every fly of the
session (`grants`), or for one fly by id or by controller port (`grants_for`, `player_grants`
with `Agents::Id` or `Agents::Port`). The table is `controlbus::Role` and `controlbus::grants`. It reflects what each client calls
today: the stage only waits on `/healthz`; the bridge calls `/status`, `/stimulate`, `/chat`,
`/events` and `/healthz`; the infra scripts only read; the operator uses `curl`. Each socket is
launcher-bound to its participant. The watchdog and the ladder restart through systemd, never
through a control call.
"Nothing can press buttons" is structurally true because of four properties. Each is tested:
1. **No method takes input.** `ControlRequest` and the loop's `Command` have no variant that
presses a button, edits game memory or changes the reward catalog, so no method can be added
without a contract change. Service and method names are scanned for the same words `api.rs`
scans routes for (`controlbus` unit tests).
2. **Grants are exact calls and nothing else.** No role is granted `Any`, a prefix, `register`,
`publish`, `subscribe` or topic management (`every_grant_is_an_exact_call_...`). On a router
that also carries an environment's input service, no control participant can call that
service, the operator and the edge included. The router refuses before dispatch
(`tests/grants.rs`, `on_a_shared_router_no_control_participant_can_reach_an_input_service`).
3. **Only the host registers.** The one register grant belongs to an in-process participant
with no socket, so nothing outside flysim can stand in for a control service. A socket admits
only its own participant; claiming another id at hello is refused.
4. **The policy is closed.** An id that is not in the table cannot connect.
What this does not change: loopback HTTP has no caller identity, so `fly-control-edge` carries
the whole surface. That is exactly the trust `:7401` has today. A client is narrowed by moving
it off HTTP onto its own role socket. That needs a native client for the TypeScript processes
(a later slice; the operator chose edges over a Node binding for now). The bus's own limit still
applies: processes running as the same OS user are inside the trust boundary (crate README,
"Limitations").
### N flies, M environments, controller ports, players
Operator direction (2026-10-01): first the existing Game Boy fly goes fully onto the framework
and the bus. A later project puts several flies on multi-controller consoles, one fly per
controller port. This slice does not build that, but the services and grants are scoped per
session, per agent and per port from the start, so multi-fly is configuration, not a redesign.
A single-fly deployment is the same design with one agent.
- **Scope** (`controlbus::Scope`): a session id and its agents, each an id and, where the
environment has controller ports, the port it plays on (`AgentScope { id, port }`). The live
fly is session `main`, agent `fly` on port 0, the Game Boy's one pad (`Scope::live`). A scope
refuses two agents with one id or on one port.
- **Session-scoped** families (read, chat, ops) are `fly.control.s.<session>.<family>`. Pause and
checkpoint act on a whole session: one coordinator steps every agent, and one save is one
generation. The chat ring is the session's stage. `read` holds the session's status, health,
metrics and event log.
- **Agent-scoped** families (status, sugar, reward) are
`fly.control.s.<session>.a.<agent>.<family>`, one service per fly. A sugar or reward pulse goes
into one brain. Each fly's own view is its `status` service. Adding a fly adds its three
services, and nothing else changes.
- **Ports.** A port is a property of an agent's binding, not part of a name, because a pulse
goes into a brain, not into a controller. A grant limited to a port
(`Agents::Port(n)`) is resolved to the agent bound to that port when the policy is built. The
policy is fixed for a router's lifetime, so rebinding ports is a session restart. A port nobody
plays on grants no agent service.
- **M sessions** on one router (several games, or one multiplayer game) have disjoint names, so
a grant on one session never names another's. `:7401` addresses the live scope only. A second
session gets native bus clients, or an edge of its own on another port with its own scope.
- **Environments.** Environment-scoped status is reserved as
`fly.control.s.<session>.e.<env>.read`. Environment *input* services (`Environment.Step` and
the like) are never in a control scope. An agent's decision reaches its environment through
the coordinator, never through control, and on a multi-controller console each fly's decoder
writes only its own port. Property 2 holds however many environments and ports share the
router.
- **Players.** A viewer who backs one fly gets `player_grants(scope, Agents::Port(n))` or
`Agents::Id(..)`: read the session, see and sugar that fly, nothing else
(`a_player_sugars_their_own_fly_and_no_other`). In a multiplayer game the players on the pads
are flies, and their presses come from their decoders. A human input path would be a new
contract, never a control grant.
### What in `docs/control-api.md` is single-fly
The contract is unchanged by this slice. These parts of it assume one fly per session. Each
would need a contract amendment before a second fly could be served over HTTP. The bus services
above are already addressed per agent, so the amendments are to the HTTP shapes, not the bus.
| Endpoint or rule | Why it is single-fly | Multi-fly direction |
| --- | --- | --- |
| `GET /status` | The feed header reshaped: one `buttons`, `rates`, `decoder`, `learning`, `game`, `milestone`, `sugar`, `version` | Per agent: each fly's `status` service. The session's `Control.Status` becomes a session shape listing its agents and ports |
| `POST /stimulate` | No agent field; addresses "the fly" | The agent's `sugar` service; over HTTP an `agent` (or `port`) field, absent meaning the only fly |
| sugar limits ("6 per minute globally, no overlap with an active pulse") | The overlap rule is per brain; the budget is per deployment | Overlap per agent; whether the budget is per fly or per session is a policy decision |
| `POST /reward` | No agent field | The agent's `reward` service; same field as `/stimulate` |
| `GET /events`, `events.jsonl` | `FeedEvent` has no agent: reward, sugar and macro events cannot say whose they are | An `agent` field on agent events, absent for session events |
| `POST /checkpoint` | One generation of one FLYSIM01 envelope, which is single-fly by format | A session checkpoint holding every agent. FLYSIM01 stays the format of record until RETIRE-01 |
| `GET /metrics` | Series carry no agent label (`fly_reward_*`, the rates) | An `agent` label on per-fly series |
| `[macros]`, `loop.game` | One mode and one game per deployment | Per environment |
| `POST /chat`, `/pause`, `/resume`, `/healthz` | Session-level already | None |
### Lifecycle and operations
- `bus_dir` (`FLY_BUS_DIR`, `/run/fly/bus`) as for the feed. Sockets are `control-edge.sock` and
`control/{stage,bridge,watchdog,operator}.sock`. Stale sockets are removed at start. With
control on the bus, the router's `max_clients` and `max_services` are the feed's plus 8.
- `flycontrol-edge.service` has no `[Install]` section: `flysim.service` `Wants=` it, and its
`ExecCondition=` on `FLY_CONTROL_VIA` skips it in direct mode (EDGE-02's pattern for
`flyedge`), so every start of flysim, `fly-loop-reset`'s stop and start included, brings
`:7401` back. It is `After=` and `Requires=flysim.service`, gets the page's CPUs from the cpuset plan, and exports its own
counters on loopback `:9103` (`fly_control_edge_bus_connected`, `_calls_total`,
`_call_failures_total`, `_cancelled_total`, `_bus_lost_total`, `_bind_failures_total`).
- The edge binds `:7401` only once the services answer. When the bus goes away it unbinds and
reconnects every 500 ms. To a client that looks exactly like flysim restarting
(`tests/backpressure.rs`, `tests/serve.rs`).
- Watchdog. Check 1 reads flysim's own `/healthz` on `:9101` when `FLY_CONTROL_VIA=bus`, so an
edge outage never restarts the fly. Check 1b restarts the edge alone when `:7401` fails while
flysim is healthy. Every other `:7401` reader (`fly-runtime`, probation, shadow guard,
loop-recover, the stream check) goes through the edge unchanged.
- Switch and rollback: `infra/docs/runbook.md`, "Control over the bus".
- **Migration order.** This document's rule stands: the control API moves after the feed has
been on the bus in production for a full session. The switch exists independently of the
feed's, and when to throw it is the coordinator's call.

View file

@ -398,6 +398,19 @@ on-screen ticker cannot disagree with what the sim did.
slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed"). slot from before a `v6`-era pickup cannot pay for it (`docs/rewards-learning.md`, "The seed").
`STATE_VERSION` stays 4. `STATE_VERSION` stays 4.
**`v7` -> `v8`** (2026-09-29, the damage reward). `pokered-unique8-v8`'s `migrates_from()` is
`["pokered-unique8-v7", "pokered-unique8-v6"]`: the live run is `v7`, and `v6` still composes,
because `v7`'s own step (the item seed on the first sample without `items:seeded`) is still in
this build and the damage state starts empty either way. The deploy that ships it sets
`FLY_ACCEPT_ADAPTERS=pokered-unique8-v7`; naming `v7` does not admit a `v6` checkpoint, which
needs its own id. One optional field is added, `damageCounts` (the wild keys that have paid
damage), and one optional object inside a battle in flight, `battle.damage` (the per-battle
marks and what the battle has paid). A `v7` state has neither and restores with no wild key paid
and, if the checkpoint was taken mid-battle, every enemy Pokémon marked at the HP it has when
first read, so nothing it lost before the restore is paid. `STATE_VERSION` stays 4. The
compatibility string moves in segment 1 only: `.../pokered-unique8-v7/...` becomes
`.../pokered-unique8-v8/...`, every other segment byte-identical.
- **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away; - **Restarting a run from an earlier rung** (2026-09-22). `FLY_RESET_STATE=1` throws the run away;
`infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a `infra/bin/fly-reset-to-milestone <N>` keeps it and rewinds it. It archives both stores to a
dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and dated directory, rewrites `milestone-<N>.checkpoint` with the ratchet's `attempts` and

View file

@ -555,7 +555,7 @@ into this project.
| What | Where | Mode | | What | Where | Mode |
|---|---|---| |---|---|---|
| source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/helix-client-id`, `twitch/helix-client-secret`, `twitch/fly-pokemon-bot-token` | WSL box only | | source of truth | `pass twitch/<channel>-key`, `twitch/<platformer-channel>-key`, `twitch/<app>-client-id`, `twitch/<app>-client-secret`, `twitch/<bot>-token` | WSL box only |
| stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` | | stream key, in CT | `/etc/fly/creds/twitch-key.cred` | `root:root 0400`, dir `0700` |
| bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` | | bridge app creds, in CT | `/etc/fly/creds/twitch-app.cred` | `root:root 0400` |
| bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` | | bridge refresh tokens | `/var/lib/fly/bridge/tokens.json` | `fly:fly 0600` |

View file

@ -155,6 +155,21 @@ which neither `gen_symbols.py` nor `resolve_wram.py` resolves, and a hand-writte
thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame thing those tools exist to refuse. "The fly had the joypad and was standing still on the frame
before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM. before the box opened, and the box is about the thing it faces" is the same fact read out of WRAM.
### The damage reward's reads (2026-09-29)
**New 2026-09-29** (`damage`, `docs/rewards-learning.md`, "Damage rewards"). The two WRAM names were
resolved by `services/flysim/tools/resolve_wram.py` from `ram/wram.asm` at the pinned commit and
are bracketed by addresses `symbols.rs` already carried. The HRAM byte is the second hand-counted
HRAM address in the crate, after row 63's `hJoyLast`, and is held to the same standard: counted
from that pinned anchor and checked against the section's end, then pinned on the cartridge.
| what | symbol | address | notes | verified |
| --- | --- | --- | --- | --- |
| whose side is acting | `hWhoseTurn` | `$FFF3` | "0 on player's turn, 1 on enemy's turn" (`ram/hram.asm`). Counted from `hJoyLast` (`$FFB1`) with each `UNION` at its largest member; the nine bytes after it end at `$FFFE`, the end of HRAM. `ExecutePlayerMove` writes 0 before the fly's move and `MainInBattleLoop` 1 before the enemy's; `HandlePoisonBurnLeechSeed` picks whose HP to cut by it. MEM-01's memory image captures HRAM, so the session runtime reads the same byte. | survey (`tests/rom_damage.rs`, the row 67 state: every enemy HP drop with 0, every own HP drop with 1) |
| the move executing | `wPlayerMoveNum` | `$cfd2` | the first of the six move bytes `ExecutePlayerMove` loads; `STRUGGLE` (`$a5`) for a Pokémon with no PP. Bracketed by `wWalkCounter` and `wEnemyMonSpecies`. | survey (BUBBLE `$91` and TACKLE `$21` read on the frames their hits landed) |
| which enemy slot is out | `wEnemyMonPartyPos` | `$cfe8` | `battle_struct`'s third field (`macros/ram.asm`: Species, HP, PartyPos, aliasing BoxLevel); `$ff` until a trainer's first send-out, then the 0-based party slot. Bracketed by `wEnemyMonHP` and `wEnemyMonStatus`. | trace (`pokemon_red/tests.rs`), survey |
| (stale) the enemy | `wEnemyMonSpecies` ... `wEnemyMonMaxHP` | as above | **not cleared between battles**: `InitBattleVariables` leaves `wEnemyMon` alone, and a trainer battle sets `wIsInBattle` a whole transition before `LoadEnemyMonData`. The first samples of a battle can hold the last battle's Pokémon at the HP it finished on; the damage rule marks a target only once it reads full. | disassembly, trace |
### Battle menu and cursor, own turn against forced switch ### Battle menu and cursor, own turn against forced switch
`HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it `HandleMenuInput` is shared by every menu in the game, so which menu is up is read from where it
@ -995,3 +1010,96 @@ power, from `engine/battle/effects.asm` and `MoveHitTest`:
Confuse Ray and Supersonic on a confused target, Leech Seed on a seeded or Grass target, Focus Confuse Ray and Supersonic on a confused target, Leech Seed on a seeded or Grass target, Focus
Energy, Mist, Reflect and Light Screen already up, Disable on a disabled target, and a damaging Energy, Mist, Reflect and Light Screen already up, Disable on a disabled target, and a damaging
move the type chart makes "doesn't affect" (the chart is another ROM table). move the type chart makes "doesn't affect" (the chart is another ROM table).
## 14. What an item will do, and the joypad the cartridge last read (2026-09-24, `docs/design/macros.md` 12.27)
Row 63. Two addresses, both pinned and read back from the code that uses them by
`row63_the_joypad_latch_and_the_item_table_are_where_the_cartridge_says` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `ItemUsePtrTable` | `$03:$55E1` | one little-endian routine pointer per item id, `MASTER_BALL` (1) to `MAX_ELIXER` (`$53`); the operand of `UseItem_`'s `ld hl` |
| `hJoyLast` | `$FFB1` (HRAM) | the buttons `_Joypad` saw down last time the game asked; the operand of `_Joypad`'s `ldh a, [hJoyLast]` at `$03:$4000` |
**`state::item_routine`** reads an item's pointer and refuses a table where the five balls or the
potions and status heals do not share one routine. **`state::battle_item_use`** classes an item by
its routine, never by its id: the routine of `POKE_BALL`, `POTION`, `POKE_DOLL`, `ETHER`, or one of
`X_ACCURACY`, `GUARD_SPEC`, `DIRE_HIT`, `X_ATTACK`, `POKE_FLUTE`, and answers each one's check before
it acts (`engine/items/item_effects.asm`): a ball in a wild battle (a full party is `None`, the box
count unread; a trainer is `false`); medicine with somebody it would change, `ItemUseMedicine`'s
own id order (Revive: fainted; Full Heal and the status heals: that status; Full Restore: hurt or
statused; the HP items: neither fainted nor full), the Pokémon that is out read from the battle's
copy; a Poké Doll in a wild battle; the X items and the flute in any battle; a PP restore with a
move below its PP (PP Ups counted). Every other routine refuses in a battle. A TM or an HM goes to
`ItemUseTMHM` before the table and is `None`.
**`state::a_latched`** is `hJoyLast` bit 0 (`PAD_A`). `hJoyPressed` is `hJoyInput & ~hJoyLast`,
and the game only calls `_Joypad` while something reads input, so after the A that confirms a list
the latch keeps that A until the next list first asks. Measured on the Potion's party list: the
list reads open on the frame after the pulse, an A in the next 22 frames is lost, and across 120
rollback delays `hJoyLast`, `hJoyPressed`, `hJoyHeld` and `hJoy5` are the only bytes of WRAM and
HRAM whose values never overlap between lost and answered frames.
## 15. The naming screen (2026-09-29, `docs/design/macros.md` 12.32)
Row 69. Two bytes of a `UNION` in `ram/wram.asm` that the reviewed list does not carry, pinned the
way `hJoyLast` is and read back from the code that stores them by
`row69_the_naming_bytes_are_where_the_cartridge_stores_them` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `wNamingScreenNameLength` | `$CEE9` | the letters typed; the operand of `PrintNicknameAndUnderscores`'s `ld [wNamingScreenNameLength], a` before `hlcoord 10, 2` |
| `wNamingScreenSubmitName` | `$CEEA` | non-zero once START or ED is taken; the operand of `.pressedStart`'s `ld [wNamingScreenSubmitName], a` |
**`state::naming_screen`** is the keyboard only when the menu bytes `DisplayNamingScreen` writes
(`wTopMenuItemY` 3, `wMaxMenuItem` 7, `wMenuWatchedKeys` `$ff`) **and** its figure are on screen:
the whole `TextBoxBorder` at (0, 4)-(19, 14) and a run of seven or ten underscores (`$76`, the raised
one `$77`) from (10, 3). The run's length is the capacity (`PLAYER_NAME_LENGTH - 1` or
`NAME_LENGTH - 1`). The menu bytes outlive the screen, so both halves are needed, as for
`yes_no_prompt`. The player's and rival's names at the start of a game are this screen before
`wStatusFlags6`'s game-timer bit is set, and `scene::detect` answers `Title` for them first.
## 16. The list's scroll offset (2026-10-01, `docs/design/macros.md` 12.34)
Row 71. One byte the reviewed list does not carry. It is pinned the way `hJoyLast` is, and
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM) reads it back from the
code that uses it. Section 7's "cannot be pinned" applied to the symbol table. The pin comes from
the cartridge instead.
| name | where | what reads it |
| --- | --- | --- |
| `wListScrollOffset` | `$CC36` | entries scrolled off the top of a `DisplayListMenuID` window; the operand of `DisplayListMenuIDLoop.buttonAPressed`'s `ld a, [wCurrentMenuItem] / ld c, a / ld a, [wListScrollOffset] / add c / ld c, a`, found once in the cartridge |
**`BattleMenu::Bag`'s `cursor`** is now `wCurrentMenuItem + wListScrollOffset`, the bag entry
under the arrow, which is the sum the cartridge makes on A. In the live trap the arrow was on row 1
with an offset of 3, so it was on entry 4, the Poké Ball. `state::shop`'s buy and sell lists
report their cursor (and its `max`) as the entry the same way. The offset is added only while a
list is on screen, because the byte outlives every list. Purchases still use only the first three
rows (`MART_CURSOR_ROWS`, section 7).
## 17. The hidden-event tables (2026-10-02, `docs/design/macros.md` 12.35)
Row 73. Two ROM tables, read through `MemoryReader::read_rom` from the cartridge image the process
already holds, never through the bus and never by switching banks. Pinned the way
`ItemUsePtrTable` is, and read back from the code that uses them by
`row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` (FLY_ROM).
| name | where | what reads it |
| --- | --- | --- |
| `HiddenEventMaps` | `$11:$6A40` | one map id per byte to a `$ff` (85 maps at the pinned commit); the operand of `CheckForHiddenEvent`'s `ld hl, HiddenEventMaps`, followed by `ld a, [hli] / ld b, a / cp $ff` |
| `HiddenEventPointers` | `$11:$6A96` | one little-endian pointer per map of the list above, into the same bank; the operand of the routine's `ld hl, HiddenEventPointers`, followed by `add hl, de` |
Both are in `SECTION "Hidden Events Core"`, which `layout.link` places in bank `$11`. Each map's
list is six bytes an entry to a `$ff` (`hidden_event`): y, x, the routine's argument, and the
routine as `dba` (bank, then a little-endian address). The coordinates are in the same tile space as
`wXCoord`/`wYCoord`, like a sign's.
**`state::hidden_events`** answers the current map's entries as `HiddenEvent { x, y, index,
facing }`: `index` is the entry's position in the map's list, which is how `wHiddenEventIndex`
counts and the talked ledger's key (`TalkTarget::Hidden`); `facing` is the argument when it is a
`SPRITE_FACING_*` value (`$00`, `$04`, `$08`, `$0C`), the side a routine such as `BillsHousePC`
checks. It answers nothing for a map list with no end within 128 entries or an id above `$f7`, a
pointer outside `$4000..$8000`, a list longer than 64 entries (the Game Corner's 48 are the longest), a tile off the loaded map or a
routine address at `$8000` or above. Bill's house (`$58`) has one entry: (1, 4), argument `$04`,
`BillsHousePC` at `$07:$6B6E`.

View file

@ -1650,6 +1650,615 @@ Nothing is ranked or pressed for the fly: frames that were never the fly's deal
decoder, the reward catalog, the adapter version, the roles and the compatibility string are decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched. untouched.
### 12.26 A counter the fly has a use for is dealt again, and a purchase is done when it is paid (2026-09-24, row 62)
The operator's reset to milestone 1 was to watch the shop, the Poké Balls and the catching. Eleven
and a half hours later the live fly (v0.6.2) had reached rung 12, Mt. Moon, with the Boulder Badge,
and in the whole event log had done `GO SHOP` twice (the parcel) and nothing else of it: no `BUY`,
no `THROW BALL`, no `GO HEAL`, `HEAL` or nurse's YES. It whited out in Mt. Moon again and again and
walked back from Pallet Town each time. The log records what was chosen, not what was dealt, so
the question was which. Surveyed with a new probe mode (`FLY_PROBE_CATCH=offers` in
`examples/scene_probe.rs`: the service's frame behind a uniform stub, counting per decidable frame
what is on the pad and reading the cartridge beside it) from the live checkpoint and four others.
**It was the pad**, in five places:
- **The errand was paid by a visit on which the counter could do nothing, and never came back.**
Section 13's "one visit per area per run" is paid on entering, and since row 54 by the
adapter's lifetime map ledger too. The Viridian mart is first entered for Oak's parcel, when
its clerk sells nothing; a centre entered with a full party heals nothing. From then on
`GO SHOP` and `GO HEAL` were off every pad in that area for the run, whatever the party or the
bag read. **`service_needed`** is the other half of the question, read from the cartridge each
time: a centre while the party needs rest (`party_needs_rest`, the byte `HEAL` and the nurse's
prompt already read), a mart while the bag has no ball, the wallet covers one (200) and the bag
does not hold Oak's parcel (until it is delivered the Viridian clerk's text table is the
parcel's). A ball because `THROW BALL` is the one button a purchase has to make possible, and
every Kanto mart stocks it first, within the cursor's reach. It **satisfies itself**: a heal
leaves the party full and a purchase leaves a ball, so the button leaves the pad when its job
is done. `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds.
- **A counter person the session had talked to or reached was retired for the session.** Inside,
with the need, the walk to the counter and `TALK` at it ignore the talked and reached ledgers
(the blocked window is kept); `TALK` at a counter is `facing_service` beside `facing_untalked`.
12.12's rule is unchanged where it applies: a rested party has no use for the nurse and `TALK`
is off.
- **`HEAL` was off the pad on the one tile it is for.** Its goals were `counter_aims`, which drops
the tile already facing the nurse -- where `GO HEAL` leaves the fly -- and retires a nurse
`GO HEAL` has reached for ten brain minutes. `HEAL`'s goals now keep that tile and read neither
ledger; the party is its satiation.
- **From a centre's door the nurse is off the screen.** A centre is entered at (3, 7) and its
nurse stands at (3, 1), six rows up, so the drawn sprites held nobody behind the counter: on the
arrival frame `HEAL`, `GO HEAL` and the counter's suppression (13.1) were all off, and the pad
was the way out. The counter person is read from the drawn and the off-screen sprites, row 58's
reading of the cartridge's own availability rule.
- **Route 4's centre, the last before Mt. Moon, was on no table.** `MT_MOON_POKECENTER` (`$44`,
Route 4's warp at (11, 5)) is on the map graph, on Route 4's west piece and in the amenity table
as Route 4's centre, so `HEAL` is dealt in it, and a hurt fly in Mt. Moon's first floor (whose
area is Route 4) has `GO HEAL` to walk out to it.
**Two limits on where a service is wanted** (the row's review, round 2). Both are the existing
rules applied to the new half of the question, and both hold for the errand too.
- **The building is the area's only from ground whose road to it stays in the area**
(`geography::route_within`). An area is counted by map id, and Route 4 is split: its east side
and Mt. Moon B1F's exit chamber are "in Route 4", but the only road from them to the centre on
the west side runs through B2F, which is in no area. So east of the mountain -- where the fly
arrives hurt -- `GO HEAL` walked down into B2F and left the pad there, while `GO OBJECTIVE`
walked back up toward Cerulean: a two-map ring by construction. The errand had the same fault
under `GO OBJECTIVE` itself (`errand_place` sent it to the centre behind the mountain). From
there Route 4's centre is not the area's; the rung is, and Cerulean's centre is one edge away
and its own area's. Every town is one piece, so nothing moved for them.
- **The room the rung is in is not left for a service.** Row 29's rule (12.5), which already
withholds the ways out while the rung's own target stands in the room untalked and unexcluded,
now withholds `GO HEAL` and `GO SHOP`'s walk out as well. A hurt party in a gym is the usual
case -- its trainers are why -- and row 58's ROM test measured it: four of six arrivals in the
Pewter Gym bounced back out, two by `GO HEAL` and one by `GO SHOP`. The errand needs no such
line: while it stands it *is* the objective. The escape hatch is the rule's own: a target no
walk reaches is excluded for the window and the service is wanted again.
**And `BUY BALL` reported `done` with nothing bought.** Pressed at the counter it ran 55 times from
the Pewter checkpoint, 55 `done`, the wallet at 1,606 throughout. After the quantity the mart
prints "POKé BALL? / That will be" and **waits for a press** (a `cont`), then prints "¥200. OK?"
and only then draws its YES/NO box; the script's one blind A after a settle was that press, and
the macro ended before the box existed. A purchase now pulses A until the box is drawn (the
general `yes_no_prompt` reading of row 56), presses YES, and is `done` when the wallet reads less
than it did: the cartridge rings the item up a few frames after the press. Either wait running
out is `blocked`.
**Measured, and what stays the fly's.** `THROW BALL` was never the pad's fault: it is off with no
ball (it cannot work) and dealt on 385 of 1,070 wild-battle frames with one, on both arms; pressed,
it catches. The live run had no ball because nothing on the pad could buy one. Survey totals, ten
twenty-minute uniform-stub runs per arm (`infra/docs/macros-traps.md` row 62): `GO HEAL` dealt
140 -> 2,300 frames, heals 2 -> 12, the whiteout map moved off Pallet Town in 2 -> 9 runs,
whiteouts 14 -> 9; `GO SHOP` dealt 101 -> 569. Whether the fly presses `TALK` at an open counter,
`CONFIRM` at the clerk's greeting and `BUY BALL` on the list is its choice; under the uniform stub
it rarely strings the four together, and with them preferred the chain buys a ball on the
cartridge (the ROM test).
Nothing ranks a button or presses for the fly: preconditions read the cartridge, and a purchase
waits for the box it answers. The decoder, the reward catalog, the adapter version, the roles and
the compatibility string are untouched.
### 12.27 An A the cartridge has not let go of is not a press, and a menu it is acting on is not a pad (2026-09-24, row 63)
Live on v0.6.2, rung 12, Mt. Moon B2F (map 61), wild battles: per ten minutes `BACK` 62, `ITEM`
28, `RUN` 21, `MOVE 1` 10, no game event; the log ITEM, BACK, BACK, ITEM, BACK ... then RUN, and
MOVE 1, BACK. Reproduced from the live checkpoint (`scene_probe`, `FLY_PROBE_CATCH=bag`).
- **The bag was not the problem.** Wartortle out at 8/86 with an Antidote, a Potion and TM34. The
cartridge's own `ItemUsePtrTable` (`$03:$55E1`) and each routine's checks say: the Potion would
be taken, the Antidote has nobody poisoned, TM34 is never usable in a battle. `ITEM` was dealt
correctly and it never used the Potion.
- **`ITEM`'s last press was no press.** The A that chose the Potion opens the party list. Its
cursor bytes read open at once, and with one Pokémon the cursor is already on its target, so the
script confirmed on the first frame. But `_Joypad` makes a press out of an edge against
`hJoyLast`, and the game does not ask again until the list is drawn: the Potion's A is still
`hJoyLast`, and an A pressed into that window is down on both sides of the comparison. Measured
by rollback: an A in the first 22 frames after the pulse is lost every time, and `hJoyLast`
alone separates lost from answered frames (every other WRAM and HRAM byte overlaps). `ITEM`
reported done over a list still waiting; `BACK` left it (the item unused, back to the bag) and
`BACK` left the bag. The pair was `ITEM` and `BACK`, and `ITEM` never did anything.
- **A confirming A waits for the cartridge to let go of the last one** (`state::a_latched`, the
cursor step). A wait presses nothing and shares the cursor step's budget. It applies to every
confirm, so SWITCH, a move, a ball and a purchase get the same guarantee.
- **A battle menu the cartridge still holds an A on deals no pad.** The same latch after an
answer: RUN's A is taken and the menu's box stays up to sixteen frames while the game acts on
it. A macro dealt there pressed at a menu already gone and held the pad for its three-second
cursor wait over "Got away safely!". Empty for those frames, 12.13's reading.
- **`MOVE 1` over the menu is FIGHT's backstop only while nothing else is a move** (12.8, 12.23).
Slot one spent beside slot four with PP, it was dealt anyway; its script confirms FIGHT and
stops, which opens the list its `BACK` closes. That is 12.11's pair, and `MOVE 4` is on the same
menu. With nothing usable it is the backstop as before.
- `ITEM` also asks the cartridge about its Potion (`item_refused`). With `hurt` it always agrees.
It is the same kind of rule as 12.23, and it is there for the day `hurt`'s reading and the
cartridge's part.
Nothing is ranked, weighted or pressed for the fly: a press waits for the cartridge to read it,
and a menu nobody is reading has no pad. The decoder, the reward catalog, the adapter version, the
roles and the compatibility string are untouched.
### 12.28 A ladder underfoot is taken by stepping off it, a ledge is a hop one way, and a way out that goes nowhere is not done (2026-09-28, row 64)
(12.26 and 12.27 are rows 62 and 63.) Live on v0.6.2/v0.6.4 at rank 12
(MT. MOON), from 2026-09-26 to 09-28: about 750 macros per ten brain minutes, all `done`, no reward
and no new ground. They were `GO OBJECTIVE` (61%) and `GO WARP`, 27 frames each. Forty-eight flysim
restarts did not clear it. A milestone reset bought a few hours before it came back.
The pulled checkpoint has the fly on **Mt. Moon B2F (5, 7)**, the ladder up to B1F's exit chamber,
which is the one road on. It reproduces the ring with the ledgers empty; nothing needs rebuilding.
- **A ladder fires at the end of a step onto it, and at no other time.** `CheckWarpsNoCollision`
runs after a step completes. A bump while standing on a warp fires only where `ExtraWarpCheck`
agrees: `IsPlayerFacingEdgeOfMap` on most tilesets, the cave's among them, and
`IsWarpTileInFrontOfPlayer` (a warp carpet in front) on the OVERWORLD, SHIP, SHIP_PORT and
PLATEAU tilesets and on Rocket Hideout B1F/B2F/B4F and Rock Tunnel 1F (12.29).
The fly had come down the ladder and was standing on it. `GO OBJECTIVE`, whose first hop is B1F's
exit chamber, and `GO WARP`, whose second tier is the same ladder, both aimed at the tile
underfoot. Both settled there for twenty frames, pressed nothing, and reported `done`. That is
12.2's trap, with no ledger in it. `GO FRONTIER` was refused `no route` once per restore and marked
the map exhausted (12.14). The mark was **correct**: every reachable tile of B2F's main piece had
been stood on, and the 439 unstood tiles are in its two other pieces. The pad never lacked a way
on. Its two ways on did nothing.
- **A walk that starts on its own step-fired warp steps off and back on.** Taking the warp this way
is what the cartridge requires. The step off goes to free ground, never onto another warp. With
nowhere free it ends `blocked`.
- **Route 4 east of the mountain had no road to Cerulean.** The ledge tile is absent from every
passable list, so the route search read a ledge as a wall in both directions. From B1F's exit the
way down is over ledges (the column at x = 62 and the rows at y = 5 and 9). So `GO OBJECTIVE`
refused `no route`, the east edge rested in the blocked ledger, and `GO FRONTIER` or `GO ITEM`
walked the fly back through the cave mouth (24, 5). It arrived on B1F (27, 3) with a pad of
`GO OBJECTIVE` and `GO OUT`, the same trap one floor up (nobs' "GO OUT / GO OBJECTIVE" of 09-26).
A stray walk over B1F (23, 3) put it back on B2F (5, 7). This is why a milestone reset only
bought hours.
- **A ledge is a hop, one way.** The decoded grid now marks `LedgeTiles`
(`data/tilesets/ledge_tiles.asm`). These count on the OVERWORLD tileset only, read from the
lower-left anchor tiles `HandleLedges` reads. The route search takes a hop from above as one press
that lands two tiles on, if the landing is ground. From below a ledge is still a wall. The flood
that 12.24's pieces are measured with is unchanged.
`HandleLedges` takes the joypad for the jump, and that reads as a scripted push-back. So the walk
holds while the cartridge carries the fly along the hop's own line. It then plans again from the
landing. Nothing is written to the push-back or blocked ledgers. A wild battle on the landing
still ends the walk.
- **The general half: a way out that does not take the fly anywhere is not `done`.** 12.2's rule is
now held by the executor for every way out instead of by each macro. A `Settle` arrival on an exit
key that leaves the fly on the same map ends `blocked`, and the exit rests in the window. If the
fly never left the tile it pressed from, row 57's refused-from-here ledger (12.21) also keeps the
button off that tile for the window. Without that, the last resort, which ignores the blocked
ledger, would re-deal the dead exit once per hold. This guarantees that **no in-place ring
persists**: at most one no-op per button per tile per window. It cannot supply knowledge the
macros lack. With it alone on base, the live ring broke (1,500 `done` in place dropped to 0 in
72,000 frames), but the fly still did not reach Cerulean.
What does *not* guarantee the fly is never stuck, and why it was not built: a repetition budget
that withholds a button after N unrewarded starts. Rows 58, 59 and 61 were rings in which every
macro *moved* the fly across a door, so no effect-based rule sees them. A budget keyed on the fly's
own choice history is a rule about the choice, not knowledge inside a macro (section 12's first
line and the ethos check). In every one of those rows it would have turned a ring into a wait or a
wander, without adding the fact that was missing. The guarantee for those rings stays outside the
fly: the watchdog, the recovery ladder, and the ROM road tests from each trap's checkpoint.
The decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched. Nothing presses for the fly.
### 12.29 A floor whose way on is a passage is not left backwards, and a yard's one door is taken from where the fly stands (2026-09-29, row 65)
Two findings of the row-64 review, both on the road the release was about to put the live fly on.
**The merge.** Rows 62, 63 and 64 together crossed Route 4's west doors 34 times in row 59's ROM
test (bound 25; any two of them 3 to 18). The ring, traced: the fly arrives on Mt. Moon 1F's mouth
(14, 35) and `GO OUT` or `GO HEAL` takes it straight back out; on Route 4 (18, 6) `GO ROUTE` or
`GO OBJECTIVE` takes it straight back in, 70 to 80 frames a leg. `GO HEAL` (row 62, dealt on 1F
whenever the party is below full) is what brings a hurt fly back to that tile again and again,
but the leg that makes it a ring was older: `GO OUT`'s "a room has to be leavable" fallback. On
1F the exit is Route 4, ground the run has walked and not toward the rung, so the fallback dealt
it, one step from where the fly arrives. Which two rows were merged decided mostly where the
stub rotation stood when the fly arrived; the ring was there in all three. Swept over eight
rotation offsets the three-way tree crosses 24 to 44 times (three of eight over the bound).
- **A floor whose way on is a passage deals no `GO OUT` fallback** (`palette::ways`). While a
passage no ledger is resting leads toward the objective, the fly is on a floor of the road and
the way out is not the only way anywhere. It is `GO WARP`'s rule ("a floor that has its own
front door deals no staircase fallback") the other way round. The escape hatch is the blocked
window: a ladder no walk reaches rests, and the mouth is a way out again. A hurt party keeps its
way out under the button that says why, `GO HEAL`. Tiers one and two are untouched: a way out
into somewhere new, or toward the objective (an errand to the centre outside), is still dealt.
After: 2 to 7 crossings over the same eight offsets, all eight in the cave. The residual is
`GO HEAL` itself: a hurt fly on the mouth walks out toward the centre, and on Route 4 the pad has
the centre and the cave side by side. Both lead somewhere real, and which one is pressed is the
fly's (row 62's round-2 note on the same tug).
**The yard.** In the review's seed-7 survey `GO OUT` in the Cerulean badge house (`$e6`) took its
back door, (2, 0), onto Cerulean (9, 9): the door tile of a closed yard of 33 tiles whose only
way out is that door. The pad was empty from there to the end of the survey, 32,000 frames, with
`GO ROUTE` and `GO ITEM` refused `no route` whenever they came back. Reproduced with seed 99 on
the release tree, and saved there as a checkpoint. Four facts, each missing:
- **A door underfoot is the way out when nothing else of its kind can be walked to.** The exit
walks set a step-fired warp underfoot aside while any other exit is listed, reachable or not
(row 13's rule, for a fly that has just come down a staircase). Now they fall back on it after
every listed goal has failed the route search.
- **Where the tile in front is a warp carpet, the door is taken by a bump.** The back door's own
tile is no door tile, so it fires only through `ExtraWarpCheck`, and on the OVERWORLD tileset
that asks for a carpet tile in front (`data/tilesets/warp_carpet_tile_ids.asm`). Row 64's step
off and back on, sideways, was measured on the cartridge to do nothing here. The decoded grid
marks the carpets on the maps whose `ExtraWarpCheck` reads them, and a walk whose goal is a warp
underfoot presses toward one when it can (`CheckWarpsCollision`); a ladder is still stepped off.
- **Cerulean is two pieces.** Row 59's flood found the yard and left it off because the house was
not on the map graph. The house is on it now (both doors), and the yard is a piece of Cerulean
whose one neighbour is the house: from the house the road is the front door, so `GO OUT` no
longer takes the back one.
- **On a map in pieces, a way out on another piece is not a way out of here** (`path::exits`).
From the yard, every door and edge of the town was a candidate for the route search to refuse,
and each refusal rested that exit for the whole map: in a survey, the fly that got out stood
outside the front door with an empty pad for the rest of the window. A door no piece lists
(Cerulean Cave's mouth, the off-graph houses on Route 2) is not claimed either way. Route 4's
sides and Mt. Moon's chambers get the same rule.
From the yard checkpoint on the stub rotation, the base never leaves (an empty pad for 21,448 of
24,000 frames in a row); the branch is in the town on frame 266 and at the gym after. The route
survey from the same checkpoint, six seeds (1, 2, 3, 5, 7, 99) of 36,000 frames: all six leave
with no empty pad, and three win the Cascade Badge.
**And the guarantee reads where the fly stands** (the review's note on 12.28). A `Settle` on a way
out is `blocked` only while the fly is still on the tile it settled on: a warp that moves it on its
own map (the Saffron Gym's pads, Silph Co.'s) took it somewhere.
**Limit, named.** The frontier's exhausted mark (12.14) is per map. A fly in the yard that has
stood on all of it gets `GO FRONTIER` refused and the whole of Cerulean marked, for the session,
though the town's frontier is not exhausted. The yard is now reached only when the objective has
no route through the front door; a restart clears the mark.
Nothing ranks a button or presses for the fly: a fallback is withheld where a passage leads on,
a door is taken the way the cartridge takes it, and the map graph says what the ground says. The
decoder, the reward catalog, the adapter version, the roles and the compatibility string are
untouched.
### 12.30 A counter walked away from is not walked back to, a ball is bought with one button, and a closed bag is not the pad (2026-09-29, row 66)
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) to watch the fly shop,
buy Poké Balls and catch. On v0.6.5, 35 minutes in: `GO SHOP` done 33 times, `TALK` 5, `BUY BALL`
never dealt, `THROW BALL` 0, no catch. Three findings, two of them the pad.
**`GO SHOP` and the way out were a ring.** Row 62 (12.26) deals a service walk whenever the
cartridge says the service is needed, whatever the ledgers say. When the fly stands at the counter
and does not use it, that is a ring by construction: `GO SHOP` from the street to the Viridian
clerk, `GO OUT` or `GO OBJECTIVE` back out of the door, and `GO SHOP` on the street's pad again,
because the bag still holds no ball. Reproduced with the connectome from a post-parcel checkpoint
of the Viridian mart (`survey-rank8-row66-viridian-mart`, saved by the offers survey): three laps in
eighteen brain seconds. A `GO SHOP` or `GO HEAL` that finishes facing the counter person now
records the building's counter (`TargetKey::Counter`, keyed by the building's map, because the
question is asked from the street, where none of the building's sprite slots means anything). For
the reached window the service walk toward that building is not dealt, from the street or inside.
That is 12.1's ledger doing for the service walk what it does for every other walk: a target
arrived at and faced is not walked to again at once. `TALK` at the counter, `HEAL` in a centre and
`BUY BALL` in a mart are unchanged by it. When the window closes the counter is a service again.
**A ball is one button (the operator's decision).** Even without the ring the fly did not buy.
A purchase took four choices in a row at the counter: `TALK`, a press at the greeting, `CONFIRM`
on BUY, and `BUY BALL` on the list. With the connectome the fly walked to the clerk every time and
never once chose `TALK` there. So `BUY BALL` is now also the mart's `HEAL`. On the overworld pad
inside a mart, one press walks to the clerk, talks, advances the greeting until BUY / SELL / QUIT
is drawn, buys the first row, answers the price box as 12.26's purchase does, and is `done` when
the wallet drops. It is offered only while it can work:
- in a mart whose first stock row is a Poké Ball (`geography::BALL_FIRST_MARTS`: Viridian, Pewter,
Cerulean, `data/items/marts.asm`). The script reads the stock once the counter is open and
refuses if the first row is anything else;
- while `service_needed` holds for the mart: no ball in the bag, 200 in the wallet, no Oak's parcel
(while it is carried the Viridian clerk's text table is the parcel's and he sells nothing). In
Viridian it is also not offered before Oak has the parcel (`EVENT_OAK_GOT_PARCEL`);
- with the clerk not in the blocked window. The talked and reached ledgers do not retire him, as
for the nurse.
The fly still chooses it, as it chooses `HEAL`. The open-counter `BUY BALL` is unchanged.
**After a catch the pad read the bag.** `wListMenuID` is written when a list opens and never
cleared. After a ball was thrown, every frame to the end of the battle read as an open battle bag:
"All right! WEEDLE was caught!", the Pokédex page, the nickname offer and the naming screen. The pad
was `BACK` and `THROW BALL`, a `THROW BALL` that threw nothing. Its A presses said YES to the
nickname and typed it, 6,900 frames from the catch to the battle's end on a stub survey. The bag
is now the bag only while its box, a `TextBoxBorder` at (4, 2)-(19, 12), is on screen: row 50's rule
for the move list. After the catch the pad is `NEXT`. `NEXT` answers the nickname offer with YES
and names the Pokémon with A's. Offering the offer's two answers inside a battle is a pad change
not made here.
ROM tests: `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` and
`row66_buy_ball_from_the_marts_floor_rings_up_a_ball` (`FLY_ROW66_MART_CHECKPOINT`),
`row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 66.
Nothing ranks a button or presses for the fly. The walk back is withheld for a window, a purchase
is one offer, and the bag is read off the screen. The decoder, the reward catalog, the adapter
### 12.31 A battle lost on repeat is the readout's choice when the pad offers the move that wins (2026-09-29, row 67)
Live on v0.6.5, rung 10, an hour and a half in the Pewter Gym (map 54): per 3,000 events `NEXT`
1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17, no battle won. The feed
read `battle` most of the time, but the fly was not in one battle. It was in a ring. It lost
29 battles in a row to the gym's Jr. Trainer (Diglett L11, Sandshrew L11), whited out to Pewter
(`wLastBlackoutMap` `$02`, money 0) and walked straight back in. Reproduced from the live
checkpoint (`FLY_ROW67_CHECKPOINT`).
- **The pad was right.** Squirtle L11 has TACKLE 35/35, TAIL WHIP 30/30 and BUBBLE 30/30, and
the trainer's Pokémon are Ground type. In a trainer battle with a party of one and no Potion,
the menu's pad is `MOVE 1`, `MOVE 2`, `MOVE 3`, which is every move with PP and an effect.
RUN, ITEM, SWITCH and THROW BALL each have nothing behind them there. Every turn advances.
In 932 own-turn frames, no move with PP and an effect was missing from the pad.
- **The choice was the readout's.** Per live battle, TAIL WHIP was 155 of 178 moves and BUBBLE
23. TAIL WHIP has an effect until the stage reaches -6, and 12.23 withholds it from there. Squirtle
faints at about the sixth turn, so the rule arrives as the battle ends (live: `22222233`).
A readout with no favourite wins with the same pad: uniform over it, the trainer is beaten on
all three seeds, and on the committed seed in the third battle. The live readout's favourite,
replayed, loses 17 of 17 battles.
- **PP never runs out.** Each loss spends about six TAIL WHIPs of 30, and the whiteout heals the party and
restores PP. The out-of-PP path is sound anyway: from the no-PP checkpoint, a trainer battle
with a party of one and every move at 0, the pad is `MOVE 1` alone (FIGHT's backstop, 12.8),
and "has no moves left!" and Struggle end the battle in 1,487 frames.
- **Nothing in the macros changes.** Moving the fly off TAIL WHIP would be ranking a move. The
one pad rule measured that would work, withholding a stat-lowering move once the target's
stage has moved, wins the first battle on both seeds (two stages: the second). It is a rule
about which move is good rather than one about what the cartridge refuses, so it waits for
the operator, like the reward options (`infra/docs/macros-traps.md` row 67).
- **What ships is detection.** The watchdog's check 10 gains `unwon-battles`: 24 or more `MOVE
n` decisions and no battle-won reward (`wildwin`, `trainer`, `badge`) in the ten-brain-minute
window, on two probes, with no new ground. Replayed on the live log, it flags from 14:01. The
existing rules first flag at 14:46, because a stray tile reward on a walk back reset
`unrewarded`. The recovery ladder acts on the flag as on any other, and a restart alone
does not change the readout.
Nothing is ranked, weighted or pressed for the fly. The decoder, the reward catalog, the adapter
version, the roles and the compatibility string are untouched.
### 12.32 A ball at low HP is the only attack, and the fly spells its catch's name (2026-09-29, row 69)
(12.31 is row 67.) Two operator decisions of 2026-09-29, after row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag, and every catch named
`AAAAAAAAAA` by `NEXT`'s A presses on the keyboard.
**"Throw on low HP only."** In a wild battle, when `THROW BALL` is on the pad and the wild
Pokémon's HP is low, the ball is the only attack-side button: `MOVE 1` to `MOVE 4` are withheld on
the top-level menu, and so are `SWITCH` and `RUN`, and `BACK` in the bag.
- **Low is the cartridge's number.** `ItemUseBall` (`engine/items/item_effects.asm`) computes
`W = (MaxHP * 255 / BallFactor) / max(HP / 4, 1)`, floored at each step, with a `BallFactor`
of 8 for a Great Ball and 12 for every other. The ball holds on HP when a random byte is at most
`W`, so at `W >= 255` HP stops mattering. For a Poké Ball that is HP at about a third of its
maximum (7 of a Weedle's 20), for a Great Ball about a half. Lower HP buys nothing more; what is
left is the catch rate and the status, which no press changes. So low is where the throw stops
getting better (`palette::ball_holds_on_hp`, `palette::throw_only`), for the ball
`THROW BALL` would throw.
- **What stays beside the ball.** `ITEM`, because it is dealt only for a Pokémon that is out,
under half its HP, with a Potion the cartridge would take: the one non-attack need that keeps
the thrower standing. `SWITCH` is about a healthier fighter; `RUN` forfeits the catch the pad
exists for, with the enemy at its weakest; `BACK` in the bag leads to a menu whose pad is the
same ball. `palette::WITHHELD_FOR_THE_THROW` is the list.
- **It cannot loop.** It applies only while `THROW BALL` itself is dealt, so every precondition
of that button still holds it: a wild battle, a ball, room in the party, a species the party does
not hold. A missed throw is an ordinary turn (`NEXT` between turns, the ball again on the next
own turn while one is left). With no ball left the button is off the pad and so is the rule, and
the moves are back. An enemy that faints ends the battle as always. A catch goes to the nickname
offer, which `NEXT` answers YES as before.
**"Let the fly name it."** The keyboard (`DisplayNamingScreen`) is a screen of its own. It reads
`Unknown` in or out of a battle (the detector checks it before `wIsInBattle`), and its pad is the
fly's **own buttons**: the D-pad moves over the letters, A types one (or ED, which hands the name
back, or the case switch), B deletes, START hands the name back. SELECT is not on the operator's
list and is masked. No macro is dealt while the fly spells.
- **Why raw buttons and not a macro per key.** A macro per key is new types, and a new type
re-deals every macro population (`docs/readout.md`). The fly's raw buttons are already decoded
every frame in macros mode, and the title already passes them through (section 2). The player's
and rival's names at the start of a game are the same screen before the game timer starts, so
they read `Title` and the fly has always typed them with these buttons; the nickname is now
consistent with them. `Observed::raw` carries the scene's mask and the layer presses
`raw_mask & raw` while nothing is bound and nothing runs.
- **The bound.** Once the name is full (`wNamingScreenNameLength` at the capacity the underscores
show, ten or seven; the cartridge moves the cursor onto ED itself then), or sixty brain seconds
after the keyboard opened (`palette::NAMING_BOUND_MS`), the raw buttons are shut and `CONFIRM`
is the only button. On the keyboard `CONFIRM` pulses START until the screen is gone
(`Step::Submit`), `blocked` after 160 frames. `CONFIRM` is not offered earlier: a macro group of
one always has a winner at its next decision, so a lone `CONFIRM` would hand back an empty name
within a second.
- **What the name is.** Whatever the fly typed stays. An empty name is the species' own name,
which is the cartridge (`AskName.declinedNickname`).
- **The reading.** Red has no "keyboard open" byte, so `state::naming_screen` is the construction
`yes_no_prompt` makes: the menu bytes `DisplayNamingScreen` writes (`wTopMenuItemY` 3,
`wMaxMenuItem` 7, every key watched), the keyboard's whole box at (0, 4)-(19, 14), and the
underscores at (10, 3). `wNamingScreenNameLength` (`$CEE9`) and `wNamingScreenSubmitName`
(`$CEEA`) are read from the operands of the cartridge's own instructions, like `hJoyLast`, and
pinned by the ROM tests.
- `game.scene` is `unknown` on the keyboard, `game.palette` is `[]` while the fly spells, and
`game.padEmptyMs` stays 0: the fly's own buttons are a pad.
ROM tests (`tests/rom_catch.rs`): `row69_at_low_hp_a_wild_battles_pad_is_the_ball`
(`FLY_ROW69_CHECKPOINT`), `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`
and `row69_a_fly_that_types_nothing_is_ended_by_the_bound` (`FLY_CATCH_CHECKPOINT`). Survey
numbers are in `infra/docs/macros-traps.md` row 69.
Nothing presses for the fly on the keyboard but the bound's one button, dealt as a button and
chosen by the fly's own macro group. The decoder, the reward catalog, the adapter version, the
roles and the compatibility string are untouched.
### 12.33 The SHIFT offer's party list is the fly's turn, not a forced switch (2026-09-30, row 70)
Live on v0.7.0, rung 12, Mt. Moon 1F: the fly caught its first Pokémon (a Zubat). Minutes later, a
Lass's battle. Wartortle fainted to her Oddish, the forced switch sent out the Zubat, and the Zubat
knocked the Oddish out. With two Pokémon in the party, the cartridge's SHIFT battle style asks
"Will ZUBAT change POKéMON?" before the trainer's next one (`EnemySendOut`,
`engine/battle/core.asm`). The fly answered YES, and the game opened the party list. From then on,
the event log was `NEXT start/done` every 0.8 brain seconds for 58 brain minutes, and nothing
else happened until the ladder reset the run to rung 11.
- **The misread.** `EnemySendOut` opens that list with `wPartyMenuTypeOrMessageID =
BATTLE_PARTY_MENU`, the same value `ChooseNextMon` uses after a faint. `state::battle` took
BATTLE_PARTY_MENU alone as the forced switch, so the pad was the forced switch's `SWITCH, NEXT`.
`SWITCH` had no one to switch to, because the Wartortle had fainted. `NEXT`'s A landed on the
cursor, which the game parks on the Pokémon already out. The game printed "ZUBAT is already out!"
and reopened the list. The one press that leaves this list is B, which declines the offer:
`DisplayPartyMenu` returns carry and the trainer sends the next one out. No button on the pad
sent B.
- **The rule.** A battle party list is a forced switch only when BATTLE_PARTY_MENU is set **and
the active battler's HP is 0**. Both callers of `ChooseNextMon` (`HandlePlayerMonFainted`, and
the enemy's faint after a double knock-out) reach it only with `wBattleMonHP` at 0, so the faint
is what the forced switch has and the offer does not. On the offer's list it is the fly's turn,
and its pad is the party list's own answers, `SWITCH` and `BACK` (12.9). `SWITCH` is dealt only
when another Pokémon can go out. Nothing is chosen for the fly. It can still take the offer with
`SWITCH`, and `BACK` is the way out that the pad was missing.
- **Why it waited for a catch.** The offer needs a second Pokémon (`wPartyCount - 1 != 0`), so
with a party of one it never appeared. Every catch from now on makes it likelier.
Tests: `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, the second half of
`the_party_list_a_fainted_mon_forces_is_a_forced_switch`, and two ROM tests.
`row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` uses
`FLY_ROW70_CHECKPOINT`, the live trap. `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered`
uses `FLY_ROW70_FORCED_CHECKPOINT`, the rung-12 archive carried forward by the stub to the same
Lass with a Zubat caught.
### 12.34 The battle bag's cursor is the entry, not the window's row (2026-10-01, row 71)
Live on v0.7.3, rung 15, Route 25 (map 36): a wild Oddish L13 at 8 of 36, Wartortle L35 out, the
bag open. Row 69's rule saw the HP low enough for the ball and left `THROW BALL` alone on the pad.
Every start was `blocked`, 131 of 131 in ten minutes and about two hours in all. A flysim restart
restored the same battle with the same bag open, so the trap came straight back.
- **Not a trainer.** `wIsInBattle` was 1 (wild), so the cartridge would have taken the ball.
There were two Poké Balls in the bag, the party had room, the Oddish was a new species, and
Wartortle's moves had PP left. `THROW BALL` was a correct button that its script could not
carry out.
- **The misread.** The battle bag is a `DisplayListMenuID` list. Its window shows three entries,
the arrow moves over rows `0, 1, 2` (`wCurrentMenuItem`), and the list scrolls under the arrow.
The entry under the arrow is the row plus `wListScrollOffset`. `state::battle` reported the row
as the bag cursor. `THROW BALL` aims at the ball's bag index, here 4 (TM34, HELIX FOSSIL, NUGGET
and TM45 come first), and no row can ever be 4. The cursor step walked between rows 1 and 2, ran out
of budget and blocked, even though the arrow was on the ball (offset 3, row 1).
- **The rule.** The bag cursor is `wCurrentMenuItem + wListScrollOffset`, the same sum
`DisplayListMenuIDLoop` makes when A selects. `wListScrollOffset` (`$CC36`) is pinned from the
operand of that read and checked against the cartridge, the same way as `hJoyLast` (12.27).
Every UP or DOWN press then moves the entry by one, either by moving the arrow or by scrolling
the window, so the existing cursor step reaches any entry. `ITEM`'s Potion had the same limit
(fourth entry or later) and is fixed by the same change.
- **Why row 69 turned it into a trap.** Before row 69, a ball fourth or later in the bag was a
dead `THROW BALL` next to the moves. That cost a hold but did not trap the fly. Row 69 withholds
the moves, `SWITCH`, `RUN` and the bag's `BACK` at low HP, so the dead button became the only
one.
Other lists, checked: the mart's buy and sell lists are `DisplayListMenuID` lists too, and
`state::shop` now reports their cursor as the entry in the same way. The battle menu, the move
list, the party list and the start menu do not scroll. No macro navigates the PC's lists.
`MART_CURSOR_ROWS` (row 55) still limits purchases to the first three rows, because lifting it puts
new buttons on the pad and needs its own survey on the cartridge.
Tests: `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn` (state, a bag scrolled by
three), `a_mart_reports_which_of_its_screens_is_up` (a scrolled buy list, and a stale offset on the
counter menu), the catch test's check that its ball is in the window's first rows (it still
throws),
`row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`, the live trap) and
`row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` (FLY_ROM).
### 12.35 An errand is its people, then its things, and a hidden event is a thing (2026-10-02, row 73)
Live on v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. Scout B3 measured it from the live
checkpoint on six seeds (2.8 brain hours): `GO ROUTE` walked the fly into Bill's house, and inside
it `GO OBJECTIVE` or `GO OUT` walked it straight back out, 30 to 60 times per ten brain minutes.
`GO NPC` was chosen 0 times in about 600 starts in the house, and new tiles stopped (2527 to 2531
in 35 minutes). Rung 16 (MET BILL, `EVENT_GOT_SS_TICKET`) was never earned.
- **The place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`, because the house's id was
not derived. A fly on Route 25 was already "there", so inside the house `GO OBJECTIVE` was an
exit into the objective's own map, which is the same door as `GO OUT`. That is row 29's lab loop
again, one rung later.
- **The rung is an errand, not a conversation.** `scripts/BillsHouse.asm`: Bill (a Pokémon, a
person sprite) asks for help and walks into the teleporter, the cartridge hides his sprite; the
cell separator is started from the PC at (1, 4), pressed facing up; Bill then steps out of the
machine as a second sprite and hands over the ticket. Two people and a thing, in that order.
- **The PC is a hidden event.** `wNumSigns` is 0 in the house and the only sprite is Bill: the PC
is an entry of the cartridge's own hidden-event table (`data/events/hidden_events.asm`), which
`CheckForHiddenEvent` searches on every A in the overworld. No macro could aim at it and `TALK`
was never dealt in front of it, so even a fly that talked to Bill could not earn the rung.
What changed, all of it knowledge inside macros:
- **`PlaceKind::Errand`.** Rung 16's place is `errand(BILLS_HOUSE)` (`$58`, confirmed by Route
25's warp table and by the hidden-event map list). An errand's targets are the room's people,
drawn or off the screen, and once none is left untalked, its things: objects, signs and hidden
events. No step is named anywhere. The cartridge shows and hides the people as the errand moves
on, the talked ledger records what has been had, and what is left is the next step. People come
first because a thing pressed out of turn is in the talked ledger for the session: Bill's PC
pressed before he has asked prints the monitor and does nothing, and a PC recorded as talked to
would never be the next step again. Everything 12.5 and 12.22 give a person place applies: the
ways out are withheld while a target waits, `GO OBJECTIVE` aims at the four sides, facing a
target is the arrival and `TALK` is the press; the blocked ledger is the escape hatch.
- **Hidden events are read from the cartridge's table, not written down.** `state::hidden_events`
walks `HiddenEventMaps` and `HiddenEventPointers` in ROM bank `$11` through
`MemoryReader::read_rom`, the same read the move and item tables use: no WRAM is written and the
mapper's bank register is not touched. The two addresses are pinned from the operands of
`CheckForHiddenEvent`'s own `ld hl` instructions and checked on the cartridge
(`macros-wram.md` section 17); every read checks the table's shape and answers nothing for a
table that is not the one the disassembly describes, which narrows and never invents a tile. A
hard-coded `(1, 4)` would have been a number nobody can check from the running game; the table is
what the cartridge itself consults when the A is pressed.
- **A hidden event is only ever the errand's next step.** It is in `objective_targets` for an
errand and in `facing_target` (so `TALK` is dealt) only while it is that step. It is not added to
`GO ITEM`, `GO NPC` or `TALK` anywhere else. The table holds every PC, poster, trash can,
bookshelf and hidden item in Kanto; making them general targets would add a walk to most
buildings' pads and an entry to the talked ledger for each, which is a change to what the fly is
offered everywhere and not a fix for this trap. The day that is wanted it is one line in
`path::interactable_targets`, and it needs its own survey.
- **A hidden event's side.** Where the entry's argument is a `SPRITE_FACING_*` value it is the side
the routine checks before it does anything (`BillsHousePC` returns unless the player faces up),
so the walk's one aim is the tile on that side and only facing it from there is the arrival and
`TALK`'s precondition. An argument that is an item or a text id and happens to equal a facing
value only narrows the approach.
- **An errand is recoverable inside one session (row 73 review).** The talked ledger is the
session's and never forgot, but the cartridge re-shows people: Route 25's script resets Bill's
event once the fly has left, and a Bill whose bag was full never handed over the ticket. A
conversation had on the last visit then retired this one's and the rung was unreachable until a
restart. The palette now notes the room while the errand is the objective and, on the first
frame the fly stands anywhere else with that errand still the objective, forgets that room's
talked entries (`Talked::forget_map`). Other rooms' entries and a room that is not the errand
keep theirs. The bag-full case needs no extra rule: nothing is left to aim at, the exits return,
and the fly leaves and comes back.
- **A one-sided target nobody can stand in front of is not waited for.** If every tile a hidden
event can be pressed from is one the cartridge pushes the fly off (the pushed ledger, row 37),
the walk had no aim, so no walk ended `blocked` and the ways out stayed withheld for good. Such
a target leaves the errand's list at once (`palette::servable`), which returns the exits.
- **A hidden-event entry off its own map is skipped.** The Safari Zone gate lists a nugget
"inaccessible" at (10, 1) on an 8 x 6 map, and the rest houses a copied Pokecenter PC; one such
entry no longer voids the rest of the map's list.
The fly still chooses every press: `GO OBJECTIVE` to walk, `TALK` to press A, `YES`, `NO` or
`NEXT` in Bill's boxes. Nothing presses for it, no button is added to any pad, and the readout, the
catalog, the adapter and the compatibility string are unchanged. What the scene deals inside the
house is narrower than before, not wider: the ways out leave the pad while the errand waits.
**The road after the ticket (the third trap).** With the ticket the objective is rung 17,
Vermilion, south through Cerulean. Cerulean's ground is in three pieces, not two: the town's ends at
row 28 (the gap at (16, 28) opens onto a wall and the trainer-tips sign), and the south of the map,
the road to Route 5 and the east edge onto Route 9 are reached through the trashed house (`$3e`),
in by its front door at (27, 11) and out by the hole in its back wall onto (27, 9) in the Rocket's
yard. Scout B3 flooded the grid: 378 of the map's 801 walkable tiles are the town's. The house was
off the map graph, so `GO OBJECTIVE` aimed at ground the town cannot reach (`blocked` at (17, 28))
and the fly rang between the town and its houses (0 of 6 seeds past row 28 in 43 brain minutes
each). The house is now on the graph and the south is `SPLIT`'s third piece of Cerulean, so the
objective walks into the house and out through the hole. Before the ticket a guard stands on the
tile in front of the door (`TOGGLE_CERULEAN_GUARD_2`, (27, 12)), which the ticket's own script hides; the objective only
points south after the ticket.
**Not fixed, predicted:** the road from Route 5 to Vermilion on the graph is Route 5, Saffron,
Route 6, as plain map edges. The cartridge's gate houses are guarded until the guard's drink is
given, and the way the game means is the Underground Path, whose houses are off the graph. No run
has reached Route 5's gate yet; it needs its own checkpoint and row.
Tests: `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`,
`a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`,
`a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`,
and on the cartridge `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it`,
`row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door`,
`row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket`,
`row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket`,
`row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` and
`row73_the_fly_takes_the_trashed_house_south_to_route_5`.
## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a ## 13. Shops and Pokémon Centers (the operator, 2026-09-17: "refactor the shop macros. make it a
## priority to visit the shop at least once per area; make shop macros item purchases. same ## priority to visit the shop at least once per area; make shop macros item purchases. same
## for the Pokécenter. heal should be a macro.") ## for the Pokécenter. heal should be a macro.")
@ -1664,7 +2273,8 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
- **`GO SHOP` / `GO HEAL`** are the errands as buttons of their own too (populations - **`GO SHOP` / `GO HEAL`** are the errands as buttons of their own too (populations
`macro_go_shop`, `macro_go_heal`, from the same MBON/motor pool by the same rule): on the pad `macro_go_shop`, `macro_go_heal`, from the same MBON/motor pool by the same rule): on the pad
when the area's mart / center is unvisited (GO SHOP also needs money), walk to its door and when the area's mart / center is unvisited (GO SHOP also needs money), walk to its door and
in; inside, walk to the counter / nurse and face them. in; inside, walk to the counter / nurse and face them. Since **12.26** also while the building
has a job to do: a centre for a party that needs rest, a mart for a bag with no ball.
- **Shop scene.** Buttons are purchases: `BUY POTION`, `BUY BALL`, `BUY ANTIDOTE`, `BUY REPEL`, - **Shop scene.** Buttons are purchases: `BUY POTION`, `BUY BALL`, `BUY ANTIDOTE`, `BUY REPEL`,
each bound only when the mart's stock (read from WRAM, `shop_stock` accessor, verified by each bound only when the mart's stock (read from WRAM, `shop_stock` accessor, verified by
the survey method) lists it and money allows at least one; each macro buys ONE unit through the survey method) lists it and money allows at least one; each macro buys ONE unit through
@ -1678,9 +2288,10 @@ Knowledge inside macros, never in the choice; the pad still lists buttons and th
- **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's, - **Ladder.** Unchanged; no reward for shopping or healing (rewards are the adapter's,
untouched). untouched).
- **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come. - **Screen.** Two new channel tags; the cells and the MACROS rate row take them as they come.
- **Proof.** ROM-gated from the Viridian checkpoint: `GO SHOP` enters the Viridian mart and - **Proof.** ROM-gated: from the Viridian checkpoint `GO HEAL` enters the center and `HEAL`
`BUY POTION` buys one; `GO HEAL` enters the center and `HEAL` restores the party; the errand is restores the party; from the rung-11 Pewter checkpoint (a state where `GO SHOP` is dealt, since
not offered again in Viridian; trap hunt before/after. rows 62/66: money, no ball, no parcel) `GO SHOP` enters the mart and walks to its counter, and
is not dealt back from the street for the reached window; trap hunt before/after.
## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2 ## 14. The full pad and four move buttons (the operator, 2026-09-17: "scoot fly over. make it 2
## columns" … "four, one per move slot" … "2 cols.") ## columns" … "four, one per move slot" … "2 cols.")
@ -1729,10 +2340,13 @@ observe is not a precondition, it is a guess.
| Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad | | Dialog, a readable YES/NO box (**the box the cartridge drew**, 12.20) | YES, NO — or **one of them** at a Pokémon Center's nurse | **new, 12.12.** `NEXT` is off it: an A press at a two-option menu confirms the option the cursor is on, which is what `YES` is, so the two are one press under two names (12.10). At the nurse's own prompt the bound answer is the one that changes something — `YES` with a hurt or statused party, `NO` with a full one. An answer whose prompt comes straight back is excluded for the blocked window, and the exclusion never empties the pad |
| Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it | | Menu (the start menu) | CLOSE, CONFIRM, BACK | unchanged as a *scene*, and since **12.11** nothing on any other pad opens it: the fly reaches it with the **raw** START button, which still reaches the cartridge in macros mode, and moves its cursor with the raw D-pad. A SAVE or a POKéDEX button would be a macro per start-menu entry and is not asked for -- which is precisely why `MENU` had nothing behind it |
| Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged | | Menu (the bag, an elevator, the party list outside a battle) | CLOSE, CONFIRM, BACK | unchanged |
| Unknown (the Pokédex, the trainer card, OPTION, a naming screen, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them | | Unknown (the Pokédex, the trainer card, OPTION, a mid-warp frame) | NEXT, **BACK** | **BACK added** (row 9): B is what leaves the first three, and A leaves none of them |
| Unknown, the naming screen (**12.32**) | the fly's own D-pad, A, B and START; **CONFIRM** alone once the name is full or after sixty brain seconds | new, row 69: read before the battle test, so a nickname typed in a battle is here too |
| Battle, own turn, main menu, a wild Pokémon at low HP with THROW BALL dealt (**12.32**) | THROW BALL, and ITEM for a hurt thrower | new, row 69: the moves, SWITCH and RUN withheld; the bag's BACK too |
| Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as | | Battle, own turn, main menu | MOVE 1..4, SWITCH, ITEM, THROW BALL, RUN (whose cursor indices are FIGHT 0, **ITEM 1, PKMN 2**, RUN 3 -- two columns, 12.11) | four move buttons for `ATTACK` (section 14); THROW BALL added, and gated on the species since 12.9; **RUN gated**, below. No `BACK`: the four entries are the answers to this menu. **`NEXT` removed by 12.10** — an A press here confirms FIGHT and reopens the list the move list's `BACK` just closed, and `MOVE 1` is the backstop instead, bound here whatever the battler reads as |
| Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands | | Battle, own turn, move list (**the box on screen**, 12.18) | MOVE 1..4, BACK -- or **MOVE 1 alone** | as above, plus **12.11**: `BACK` is dealt here only while `wBattleMon*` reads, because a list that binds no `MOVE n` has a pad whose one button closes the list `MOVE 1` underneath had just opened. With nothing readable the pad is `MOVE 1` and its script confirms where the cursor stands |
| Battle, own turn, party list | SWITCH, BACK | unchanged | | Battle, own turn, party list | SWITCH, BACK | unchanged |
| Battle, own turn, any menu the cartridge still holds an A on (**12.27**) | nothing | new: the answer is taken or the list is not yet asking; the pad is back on the first frame the game reads the joypad |
| Battle, own turn, the bag | ITEM, THROW BALL, **BACK** | the bag reports a *cursor* (`macros-wram.md` 7.1), and since **12.10** it is the own turn, because a cursor accepting input is one. Its pad is the list's own answers; `NEXT` and `CONFIRM` are both off it, being the same blind A press that *uses* whatever the cursor holds | | Battle, own turn, the bag | ITEM, THROW BALL, **BACK** | the bag reports a *cursor* (`macros-wram.md` 7.1), and since **12.10** it is the own turn, because a cursor accepting input is one. Its pad is the list's own answers; `NEXT` and `CONFIRM` are both off it, being the same blind A press that *uses* whatever the cursor holds |
| Battle, forced switch | SWITCH, NEXT | unchanged (row 8). The one arm that keeps `NEXT` with a cursor up, because it cannot be cancelled and has no `BACK` to undo it | | Battle, forced switch | SWITCH, NEXT | unchanged (row 8). The one arm that keeps `NEXT` with a cursor up, because it cannot be cancelled and has no `BACK` to undo it |
| Battle, between turns | NEXT | since **12.18** this row is most of a battle, and correctly so: a frame whose move list is remembered rather than drawn lands here. `BACK` was added here for the bag and **taken back out by 12.9**: on a frame of battle text there is no list to leave, and a `BACK` that changes nothing is the trap of section 12.2. Since **12.10** the bag is not on this row at all, so `NEXT` here is only ever the A that advances text | | Battle, between turns | NEXT | since **12.18** this row is most of a battle, and correctly so: a frame whose move list is remembered rather than drawn lands here. `BACK` was added here for the bag and **taken back out by 12.9**: on a frame of battle text there is no list to leave, and a `BACK` that changes nothing is the trap of section 12.2. Since **12.10** the bag is not on this row at all, so `NEXT` here is only ever the A that advances text |
@ -1779,8 +2393,9 @@ measured where it cannot.
| a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one | | a running macro aborts and the pad is not re-dealt until the next frame | not a cause: `observe` runs after every frame and the decoder is handed the bound channels again on the very next one |
| a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette | | a restore, before the first `observe` | not a cause: the loop calls `observe` once at the end of boot and once after a ratchet recovery, so the first frame is decided on a real palette |
| the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt | | the title screen, and raw mode | not an empty pad by contract: the readout's boot variant applies and no palette is dealt |
| a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`; a screen neither press leaves (the naming screen, row 14) is a genuine stall and still needs START, which is a contract change | | a scene the detector cannot name | `Unknown` deals `NEXT` and `BACK`. The naming screen (row 14), which neither press leaves, is read since **12.32** and its pad is the fly's own buttons, then `CONFIRM` (START) once the name is full or the bound runs |
| an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other | | an `Unknown` frame that is the **overworld with the cartridge driving** -- a warp in flight, a scripted push-back, a guide walking the fly through a door | **empty on purpose** (12.13). There is no box to advance and no screen to leave, so an A or a B press is a press into somebody else's script: it changes nothing and completes where the fly stands. This is the one empty pad that ends itself -- the cartridge gives the buttons back within a few frames -- and `game.padEmptyMs` reports it like any other |
| the fly's own turn while the cartridge holds the A it last took (`hJoyLast`) | **empty on purpose** (12.27): a menu the game is acting on or has not started reading. Ends itself on the game's next joypad read |
| the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens | | the fly's own turn where the seam cannot read the battler, now that `NEXT` is off that row (12.10) | **fixed**: `MOVE 1` is bound over the top-level menu whatever `wBattleMon*` reads as, because FIGHT is one of that menu's four entries and always opens |
And because "closed where a macro can close it" is not "closed": And because "closed where a macro can close it" is not "closed":

View file

@ -78,7 +78,10 @@ Application / supervisor Application presentation
This diagram is connectivity, not execution order. The step contract defines causal order. This diagram is connectivity, not execution order. The step contract defines causal order.
One router can host several independent sessions and application consumers; a deployment may One router can host several independent sessions and application consumers; a deployment may
choose one router per application for fault isolation. A router crash affects all its clients, choose one router per application for fault isolation. A router crash affects all its clients,
so choose that boundary deliberately. In-process mode still exercises routing and ownership. so choose that boundary deliberately. In-process mode still exercises routing and ownership,
unless its participants are offered over the local lane ([session RPCs](ipc-v1.md) section 1,
amendment 2026-09-30), as the legacy composition's in-process release configuration is; process
mode always goes through the router.
Defaults: coordinator per session, worker per fly, environment worker per world. Task and Defaults: coordinator per session, worker per fly, environment worker per world. Task and
per-agent executors begin as coordinator-local libraries. An environment helper may own a per-agent executors begin as coordinator-local libraries. An environment helper may own a

View file

@ -105,7 +105,7 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` | | Method strings are 1..128 printable ASCII | conforms | `wire.rs::is_method` | `wire.rs::tests::scalars` |
| The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) | | The call target is a service name; `expectedIncarnation` is the registration id | conforms | `router/state.rs::op_call` (`f.name`, `f.nullable_id`) | `tests/rpc.rs::registration_is_exclusive_and_pinned` (both) |
| Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Location grants are `{storeId, relativePath}` resolved under the configured root; absolute paths, parent traversal and symlink escapes are rejected | conforms | `store.rs::resolve`, opened `O_NOFOLLOW` | `store.rs::tests::resolve_refuses_escapes`, `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies | `wire.rs::Location`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are SDK-private and do not appear in an application's `ArtifactRef`; runtime paths are not committed into schemas | conforms: `Location` only ever appears in `artifact.allocate`/`artifact.open` replies and, since the 2026-10-01 amendment (BUS-01), in a delivery's attachments, never in a body | `wire.rs::Location`, `wire.rs::Attachment`, `client/handles.rs::Artifact::open` | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained`, `::deliveries_carry_the_read_location_their_ownership_grants` (both) |
| Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse | | Deliveries carry exactly the listed bodies (`rpc.request`, `rpc.result`, `topic.message`) | conforms | `router/state.rs::{Call::request_body, Call::result_body, TopicMsg::body}` | `tests/conformance_wire.rs` + `client/reactor.rs::on_delivery` strict parse |
| `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) | | `caller`/`responder` include clientId and clientIncarnation | conforms | `wire.rs::Identity` | `tests/rpc.rs::request_reply_roundtrip` (both) |
| Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) | | Delivery attachment ownerIds are replaced by the recipient's deliveryId; source tokens are never delegated | conforms, and the client refuses a delivery whose attachment owner is not its delivery | `router/state.rs::attachments_with_owner`, `client/reactor.rs::attachments` | `tests/conformance_artifacts.rs::owner_ids_are_scoped_to_their_connection` (both) |
@ -187,9 +187,10 @@ and once over a Unix socket, so `tests/rpc.rs::request_reply_roundtrip` means
| The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` | | The first backend is runtime-configured local files, optionally on tmpfs | conforms | `store.rs::Store::create` under `RouterConfig::store_root` | `store.rs::tests::orphans_are_removed_and_live_stores_kept` |
| The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) | | The producer writes staging storage outside the message stream | conforms | `store.rs::create_staging`, `client/mod.rs::Artifacts::allocate` | `tests/artifacts.rs::allocate_write_seal_read` (both) |
| Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) | | Seal closes writable handles in the SDK, checks length and digest, then finishes an immutable store-owned object before acknowledging | conforms: a writable descriptor kept after sealing reaches only the unlinked staging inode | `client/handles.rs::seal_with_digest` (drops the file first), `store.rs::seal` (fresh 0444 inode) | `tests/artifacts.rs::seal_is_immune_to_live_writable_handles` (both), `tests/conformance_artifacts.rs::seal_is_immutable_despite_a_stale_writable_handle` (both) |
| Sealing on send (amendment 2026-10-02, BUS-02): an `rpc.call`/`rpc.reply`/`publish` attachment naming the sender's own writer is sealed (its declared prefix, copied outside the state lock) before the command is admitted, the writer becomes the sender's hold, `recycle` reissues the staging file as a new writer, and a refused sealing send releases every writer it named | conforms | `router/state.rs::{sealing_attachments, finish_sealing_send}`, `router/mod.rs::read_loop` (`SealThenAdmit`), `store.rs::{seal_prefix, rename}`, `client/handles.rs::{ArtifactWriter::into_unsealed, Responder::reply_sealing}` | `tests/sealing.rs::{a_reply_seals_and_recycles_its_writers, a_refused_sealing_send_releases_its_writers}` (both), `tests/artifacts.rs::unsealed_artifacts_cannot_be_used` (both) |
| A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) | | A copy into a fresh sealed inode is allowed; account for both allocations during sealing | conforms | `router/state.rs::op_seal` (`store_bytes += len` for the copy, released in `finish_seal`) | `tests/artifacts.rs::quotas_are_enforced` (both) |
| No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) | | No per-frame fsync for transient media | conforms by absence | `store.rs` | `tests/perf.rs` (seal p50 1.3 ms for 1.2 MB) |
| Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) | | Consumers resolve a readLocation through `artifact.open` and read it read-only | conforms; amended 2026-10-01 (bus-v1 section 12, BUS-01): a delivered handle uses the location its delivery carries, every other handle still asks | `router/state.rs::op_open`, `store.rs::open_read` | `tests/conformance_artifacts.rs::allocate_write_seal_open_roundtrip_and_mismatches` (both) |
| Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) | | Locations are private grants, not placed in application bodies or public feeds | conforms | `router/state.rs::op_open` reply only | `tests/conformance_artifacts.rs::issued_locations_are_relative_and_contained` (both) |
| All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` | | All filesystem access stays behind the client Artifact API; no second bulk-transfer server | conforms in the API. The store is only as private as the OS user, which the crate's Limitations section states | `client/handles.rs`, `store.rs` | `store.rs::tests::resolve_refuses_escapes` |
@ -345,7 +346,7 @@ behind "latest replaces only queued messages": the replacement never turns into
## The crate README's differences from the draft ## The crate README's differences from the draft
Each of the ten differences the crate lists, kept with the sentence that allows it or fixed. Each of the differences the crate lists, kept with the sentence that allows it or fixed.
| README difference | Verdict | | README difference | Verdict |
| --- | --- | | --- | --- |
@ -359,6 +360,8 @@ Each of the ten differences the crate lists, kept with the sentence that allows
| 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) | | 8. No `budget` argument on calls, and no router executable | Kept. Section 1 calls the executable "optional"; section 6 puts the deadline in the calling client, and the section 2 sketch no longer shows a budget either (amendment, contradiction 2) |
| 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` | | 9. Wire strictness: unknown fields in management bodies refused, `minor` must be 0 after hello | Kept. Stricter than section 4's "unknown envelope fields", forbidden nowhere, and section 4's envelope literally fixes `minor: 0` |
| 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) | | 10. `rpc.responder.release` and its terminal `call.failed` | Kept. Section 4 allows draft schema changes ("Changes to these draft schemas change contractDigest"), and it is how section 6's "bounded call correlation metadata" stays bounded when a handler outlives its request delivery. Added to the bus-v1 amendment (section 12) |
| 11. Read locations in deliveries | Kept. The bus-v1 amendment of 2026-10-01 (BUS-01) |
| 12. Sealing sends, `recycle`, and no `rpc.responder.release` after an admitted reply | Kept. The bus-v1 amendment of 2026-10-02 (BUS-02); section 8.1's immutability holds because the sealed bytes are still a copy, and a reply the router admitted already ended the reply authority the release would give up |
## Measured on the dev VM ## Measured on the dev VM

View file

@ -207,7 +207,11 @@ roots, so an idempotent repeat may report zero. Queue/credit requests are intege
and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters. and cannot exceed configured limits. Method strings are 1..128 printable ASCII characters.
call target is a service name; expectedIncarnation is its registration ID, not worker process ID. call target is a service name; expectedIncarnation is its registration ID, not worker process ID.
Location grants are `{storeId, relativePath}` resolved by the client beneath the configured Location grants are `{storeId, relativePath}` resolved by the client beneath the configured
local store root; absolute paths, parent traversal and symlink escapes are rejected. They local store root; absolute paths, parent traversal and symlink escapes are rejected (the
reference SDK caches a store's canonical directories per connection, BUS-02, and still checks
each file with an lstat and an `O_NOFOLLOW` open; a store directory replaced by a symlink after a
connection first used it is not re-checked by that connection, which the store's 0700 owner-only
directory makes a same-user act). They
are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not are SDK-private and do not appear in the application's ArtifactRef. Runtime paths are not
committed into application schemas or source configuration. committed into application schemas or source configuration.
@ -523,3 +527,83 @@ this same section forbids to reject one.
longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because longer passes a `budget` into `bus.call` and shows the deadline at the caller instead, because
section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled section 5's wire contract for `rpc.call` has no budget field and section 2 is self-labelled
illustrative. illustrative.
**2026-09-30, PERF-01 (SDK only; no wire change, `contractDigest` unchanged).** The Rust client
gains *in-memory artifacts*: `Artifact::in_memory(contentType, bytes)` is an immutable buffer in
the caller's address space with an ordinary `ArtifactRef` whose `storeId` is `in-memory` (no
router issues that id) and whose digest is null; `Artifact::to_memory` reads a sealed handle into
one under the same reference. They read, clone and retain without a router, and no router ever
learns of them: the SDK refuses one as an attachment of `rpc.call`, `rpc.reply` or `publish`
before anything is sent (`INVALID_ENVELOPE`, not dispatched). They exist for participants of one
process that hand each other buffers directly ([session RPCs](ipc-v1.md) section 1, amendment of
the same date); section 8's ownership rules apply to every artifact a router stores, which these
never are.
**2026-10-01, BUS-01 (wire change; `contractDigest` changes).** A delivery's attachments carry the
read location their delivery ownership grants. Section 8.1 makes a consumer resolve a
store-issued `readLocation` through `artifact.open` before it reads, which is one router round
trip per artifact read. The legacy composition on the bus reads four artifacts a frame on its
critical path (the frame in `Agent.Prepare`, the memory image and the audio chunk after
`Environment.Advance`, the spike bitset after `Agent.Commit`), so that rule cost four round trips
a frame for an answer the router already knows when it delivers.
- In an `rpc.request`, `rpc.result` or `topic.message` delivery, every attachment is
`{name, ref, ownerId, readLocation}`, where `readLocation` is the `{storeId, relativePath}`
`artifact.open` would return for that artifact under that delivery's ownership. It is still
store-issued, private to the SDK, resolved beneath the store root with the same traversal and
symlink checks, and never placed in an application body.
- A client never sends one: an attachment in a command that carries `readLocation` is an unknown
field, and the connection closes as for any malformed envelope.
- The SDK's handle on a delivered artifact reads through it with no round trip. Section 8.1's
guarantee is unchanged: the delivery's root holds the bytes while the handle (or a file opened
from it) lives, exactly as after an `artifact.open`. `artifact.open` stays for every handle that
did not come from a delivery (a sealed writer's hold, an explicit `retain` of one) and for any
client that prefers to ask.
Two SDK-only changes of the same slice, no wire change: small store operations (creating or sealing
a staging file, reading a sealed one, up to 256 KiB) run in place rather than on the blocking pool
-- on the store's tmpfs a hop to the pool and back costs more than the copy -- and
`Artifact::is_hold` tells a sealed writer's or a retained hold from a delivery's handle, so a holder
that needs the bytes kept alive can keep a clone instead of taking a second hold.
**2026-10-02, BUS-02 (wire change; `contractDigest` changes).** A sending command may seal the
artifacts it attaches. Section 8.1 makes a producer seal (`artifact.seal`, one router round trip)
before any message may name the artifact, and section 5 allocates every artifact afresh
(`artifact.allocate`, another). A participant that replies with media every transition -- the
legacy world a frame, a memory image and an audio chunk, the agent a spike bitset and its feed
status -- paid both for every artifact of every transition, two of them on the transition's
critical path, for answers the router could give as it admits the reply.
- **Sealing attachments.** In `rpc.call`, `rpc.reply` and `publish`, an attachment's `ownerId` may
be the sender's own writer of `ref.artifactId`, still unsealed. Its `ref` is the reference the
sealed artifact will have: this store, generation 1, the allocation's content type, a null
digest, and a `byteLength` of at most the allocation -- the sealed artifact is the first
`byteLength` staging bytes. As part of admitting the command the router seals each such writer
exactly as `artifact.seal` would (section 8.1: the copy into a fresh sealed inode happens outside
the routing state lock, before anything is admitted, and the connection's later commands wait
for it), the writer becomes the sender's explicit hold on the sealed artifact (as after
`artifact.seal`), and only then is the command admitted as if its sender had sealed first. If a
seal fails, or the command is then refused, nothing is admitted and every writer the command
named is released (with whatever it sealed): the reply carries the refusal, `not-dispatched`.
- **Recycling.** Such a command's body may carry `recycle: true` (a body member of `rpc.call`,
`rpc.reply` and `publish` with at least one sealing attachment, refused otherwise). The router
then keeps each sealed writer's staging file and reissues it as a new writer -- a new
`artifactId`, a new hold `ownerId`, the same allocation and content type -- and the command's
reply value carries `writers: [{name, artifactId, generation, ownerId, writeLocation}]`, one per
attachment it sealed, named by attachment. A writer it cannot reissue (owner budget) is simply
left out. Section 8.1's immutability is unchanged: the sealed bytes are a copy, so a producer
writing into the recycled staging file reaches only the staging inode. A reissued writer is a
fresh allocation in content as well: the router overwrites the staging file with zeros before
the reply, so it reads as zeros and no artifact sealed from it -- a prefix, or the whole
allocation through `artifact.seal` -- can carry bytes of the artifact it was before (review N3,
2026-10-02). `recycle` in a body with no sealing attachment is refused, `false` included, and
one writer named by two attachments of the same command is refused (`INVALID_ENVELOPE`).
- Nothing else changes: deliveries, ownership roots, credits and quotas are those of the command
with pre-sealed attachments; a sealing attachment counts its sealed copy against the store quota
at admission, as `artifact.seal` counts it at the seal.
SDK changes of the same slice, no wire change: `ArtifactWriter::into_unsealed` and
`Responder::reply_sealing` (the client side of the above); a reply the router admitted spends the
call's reply authority, so the SDK no longer sends `rpc.responder.release` after one (it was a
no-op command on every call); the router encodes each frame once and forwards an admitted
payload as the bytes it re-encoded once at admission instead of deep-copying it per delivery.

View file

@ -176,6 +176,35 @@ window and last location as private readout state; report `stimulusRemainingMs`;
legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`, legacy rate-role names (`command_0`, `macro_*`, which are not `Id`s) to `AgentGraph.rateRoles`,
which that contract leaves open. which that contract leaves open.
**2026-09-23 (AGENT-01 built, `feat/agent-legacy-worker`).** `LegacyAgentWorker`
(`fly-session/src/legacy_agent.rs`) serves the legacy profile under the launcher in all three
execution modes (`legacy-agent` subcommand). Its parity harness (`legacy_parity.rs`) drives
`NeuralAgent` directly in `Sim::step_frame` order from recorded inputs. On the committed toy
connectome, the worker's records match that reference exactly in every mode, including a
rollback and a restore, and are pinned as goldens. A gated FAFB run
(`FLY_AGENT01_FAFB=1`) shows the same on `gameboy-legacy-fafb-v783-v1`. The rate-role mapping
turned out to be the identity: the legacy names are already `Id`s. It is recorded in
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 13, with the other agent-adapter choices. The
harness's `ReferenceSource` is the seam for FND-01's `FLY_TRACE`.
**2026-09-29 (AGENT-01 rebased onto v0.6.5 and checked against FND-01's trace).** The rebase onto
main had no conflicts. Main changed nothing the worker reads except the adapter id in the
fixtures (v7). The toy goldens and the FAFB reference digest are unchanged. `FLY_TRACE` carries
the frames only as digests and not the `{boot, bound, location}` context, so it checks a worker
and cannot drive one. `legacy_parity::read_frame_trace` and `check_against_trace` hold a run's
records to it: ticks, clock, exact remainder, rates digest, spike-set digest and decision. The
script is checked too: the same sugar, frames, reward events and rollback.
`flysim/tests/agent_trace_parity.rs` is the host. It runs `LegacyFrame` on the ROM with the trace
on, records the missing inputs and checks the worker (in-process, thread and process) and the
direct reference against the trace:
- the toy connectome in raw mode from power-on, for every ROM run;
- `gameboy-legacy-fafb-v783-v1` in macros mode from stream checkpoints (`FLY_AGENT01_FAFB=1`),
with sugar and a ratchet rollback, the worker seeded from the checkpoint's agent state.
Both are identical. Found on the way: a `FLYSIM01` import must start `learning.updates` at the
legacy `plasticity.updates` (legacy-gameboy-v1 section 13, amendment of 2026-09-29).
**Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives; **Implement:** adapter over existing LIF, plasticity, retina and fixed readout primitives;
reference-first composition/goldens; independently seeded agent state and shared immutable data. reference-first composition/goldens; independently seeded agent state and shared immutable data.
Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering. Avoid using the old whole-frame `tick` wrapper if it changes the specified phase ordering.
@ -213,6 +242,64 @@ the frame order maps one to one (section 4), the legacy clock equals the rationa
(section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2 (section 3), and the fingerprint and compatibility string are embedded unchanged (sections 2
and 12). The acceptance criteria below stand. and 12). The acceptance criteria below stand.
**2026-09-29: built on `port/env-01` (off main `9f2345d`).** `fly-session::legacy_env` is the
environment worker (`LegacyGameboyEnvironment`), launched by `Launcher::launch_legacy_environment`
and the `legacy-environment` subcommand in all three execution modes. It makes exactly the emulator
calls flysim's `LegacyFrame` makes, in the same order: `Environment.Initialize` runs the one-frame
setup scaffold with no button down (O[0] has `engineFrame` "1", no audio chunk);
`Environment.Advance` takes one complete `gameboy-joypad-v1` batch for the one port, runs one frame
and returns the `lcd` view, the `apu` chunk as `f32le` (`sample / 255`, unfiltered) and the
`gameboy-memory-inspection-v1` image; `Environment.SaveSlot` / `RestoreSlot` are
`gameboy-slots-v1` (a restore imports, releases the pad, shows the slot's frame, runs no frame and
moves to the new epoch at the same boundary); `State.Capture` / `StageRestore` / `ActivateRestore`
carry every slot and stage on a stopped replacement emulator. The joypad is the only write into a
running game. The coordinator now refuses `episodeRequest.kind = "rollback"` (task failure, epoch
fenced) unless the composition declares `legacy-ratchet-rollback-v1`
(`Coordinator::declare_rollback_policy`); with the policy declared it still pauses at the boundary,
because the rollback sequence is TASK-01's. Parity (`tests/legacy_env.rs`, harness
`legacy_env_parity`): records equal to the emulator driven directly, frame by frame (view, 64 KiB
image, WRAM, audio chunk, slot and capture state digests), in-process, thread and process, on a
toy cartridge the harness assembles (committed golden `fixtures/legacy-env/toy-cart.golden.json`)
and, with rom-env, on the real cartridge from the row-58 checkpoint; and the service's own
`FLY_TRACE`s (FND-01's harness; `FLY_ENV01_TRACE_DIR`) replayed through the worker reproduce every
recorded frame, WRAM and slot-state digest, including a ratchet slot save and a rollback. Not in
this slice: the shim's bulk read (MEM-01, behind the one seam `legacy_env::memory_image`), the
coordinator's save/rollback/`Agent.Rollback` sequence and the executor (TASK-01), and assembling
the FLYSIM01 export from the three halves (STATE-02; the world's half is
`Flysim01World::{manifest_entries, chunks}`).
**Amendment, 2026-09-29 (ENV-01).** Four readings the contract left open, fixed by this slice:
- ~~*The image read is not state-neutral, so it is guarded.* `emulator_read_mem` of OAM, VRAM,
`FF01`/`FF02`, `FF04`-`FF06`, `IF`, `STAT` or `LY` runs binjgb's lazy synchronisation, and
`export_state` afterwards differs (never, over 17,398 replayed frames, a frame or WRAM). The
legacy loop reads none of these between a frame and the ratchet's capture, so an unguarded image
would make every slot and capture differ from the service's bytes. The worker reads the image
between `export_state` and `import_state` of the same bytes, which leaves the emulator exactly as
the frame left it; `legacy-gameboy-v1` section 8's proof ("export before and after, compare")
therefore fails for a plain 65,536-read loop and holds for the guarded one. MEM-01's bulk read
must keep that guard (or equivalent).~~
*Struck 2026-09-29 (ENV-01 review, R1):* superseded by MEM-01 (legacy-gameboy-v1 section 8
amendment). The register windows are not captured, so `legacy_env::memory_image` is MEM-01's
`Emulator::read_memory_image` with no guard, neutral by construction; the service traces still
match, and the toy golden's image digests were regenerated.
- *A `FLYSIM01` world starts at `k = emulatorFrame - setupFrames`.* The legacy file has no
boundary, world clock or audio position. The frame counter advances once per transition and
never across a rollback, so `engineFrame = k + 1` from a fresh start on; `worldTime` is
`k x stepDuration` and the audio position is that time's sample at the configured rate, rounded
down. The first chunk after the restore marks the discontinuity. The ratchet's one slot is the
composition's first declared slot (`best`).
- *Names.* The image travels as the attachment `inspection.memory`; the audio stream is `apu`;
the port is `p1`. `backendConfig` is the canonical JSON of `gameboy-backend-config-v1`
`{form, romDigest, portId, slots, audio {sampleRate, channels, bufferFrames}, setupFrames, view,
controllerSchema, inspectionSchema}`; `Environment.Initialize` naming any other document, and a
cartridge on disk that is not `romDigest`, are refused `INCOMPATIBLE_STATE` with nothing mutated.
The capture payload is flybrain-core's envelope with magic `FLYENV01`, and its participant
compatibility uses the state format `fly-gb-env-v1`.
- *`legacy-transient-reset` for the world is empty.* Everything the environment holds is restored:
emulator, frame on screen, joypad, frame counter, slots, clock and audio position. The reset
applies to the executor, the agent's readout transient and the task's transient observations.
**Implement:** binjgb environment, task-local memory inspector and identity/existing action **Implement:** binjgb environment, task-local memory inspector and identity/existing action
adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics. adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash semantics.
@ -220,6 +307,553 @@ adapter. Keep `legacy-gameboy-v1` separately routed with exact old ordering/hash
its own identity and public adapter selection. No console-specific state enters generic its own identity and public adapter selection. No console-specific state enters generic
session types. ROM-backed checks are optional explicit jobs, not required downloads. session types. ROM-backed checks are optional explicit jobs, not required downloads.
### MEM-01 — The boundary memory image (port slice)
**2026-09-29: built** on `port/mem-01` off v0.6.5 and awaiting review. It changes no live
behaviour: nothing in `flysim` calls the new read, and the compatibility string is unchanged. It
delivers the piece of ENV-01 above that reads "add the one read-only bulk memory read to the shim
and prove it mutates nothing", together with the executor-side reader that TASK-01 and the
CUT-01 shadow need.
- **Shim.** `fly_gb_read_memory_image(gb, out, 65536)` fills the buffer in address order.
`Emulator::read_memory_image{,_into}` wraps it. There is no new write path.
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 8 carries a dated amendment (2026-09-29):
VRAM, OAM and I/O are not captured and read `$FF`. binjgb's read of those windows runs a
catch-up that moves the exported state. Every memory byte is captured exactly.
- **Executor reader.** `flybrain_gb::{MemoryImage, Cartridge, ImageReader}`. `ImageReader`
implements `MemoryReader`. The palette, `MacroLayer`, `PokeState` and `PokemonRedReward` run
over it unchanged; this is the same code, not a port. The emulator's own bank reads now go
through the same `Cartridge::read_bank`.
- **Proof.** flybrain-gb `tests/rom_memory_image.rs` (ROM) checks three things. The exported
state is byte-identical before and after each bulk read over 4,200 boot frames. The image
equals the single and cached reads. Reading every frame leaves framebuffers, audio and state
frame-for-frame equal to a run that is never read. flysim `tests/rom_memory_image.rs` runs a
live arm and an image-only shadow arm (task and executor) from nine rom-env checkpoints for
3,000 frames each: 27,000 frames with about 5.5 M `MacroState` answers, deals, pads,
decisions, rewards, ledgers and rollbacks. It finds 0 mismatches and 0 reads outside the
captured ranges.
- **Cost.** A bulk read has a median of 0.31 ms per boundary, 1.9 % of a 16.74 ms frame or
about 209 MB/s of reading. This is the same cost as the 57,120 single reads it replaces. The
image is 3.91 MB/s at 59.7275 fps. A 64 KiB copy has a median of 5 µs, and the optional
SHA-256 digest a median of 0.36 ms. Means and p99 values are dominated by preemption: the
measurement ran on the shared 4-core build box at load 16.
**For ENV-01:** after `run_frame` and after a slot import, publish
`read_memory_image` as the `gameboy-memory-inspection-v1` artifact (`MEMORY_IMAGE_CONTENT_TYPE`,
65,536 bytes, digest optional, `romDigest` = `Cartridge::sha256_hex`). **For TASK-01:** build
the executor over `ImageReader::new(&O[k], &cartridge)` in Phase B and over O[k+1] in Phase C,
retaining O[k] until then. The `Cartridge` comes from `Cartridge::verified(rom, contentDigest)`.
### TASK-01 — The `pokered-macros-v1` task and executor (port slice)
**2026-09-29: built** on `port/task-01` off `port/integration` (main v0.6.5 + AGENT-01 + MEM-01 +
ENV-01) and awaiting review. It changes no live behaviour: `flysim` is only a library dependency of
the new crate, nothing in the service calls it, and the compatibility string is unchanged. With it
the live fly's whole composition -- agent, world, task and executor -- runs on the session
framework, from a fresh start or from a FLYSIM01 checkpoint.
- **The object** (`fly-legacy-session::task::PokeredTask`). The task and the executor are one
object with two faces, `Task` and `ActionExecutor`, which the coordinator holds where it holds
any task and executor (legacy-gameboy-v1 section 10). Phase B runs flysim's `MacroLayer::decide`
over `ImageReader(O[k], cartridge)` at the agent's brain time. Phase C runs
`PokemonRedReward::sample`, `MacroLayer::observe`, the location, the progress and the ratchet's
decision over `ImageReader(O[k+1])`. A rollback runs `clear_transient`, `cancel` and `observe`
over `ImageReader(O'[k+1])`. These are the legacy engine's own calls in `LegacyFrame`'s order;
there is no port of a rule. The cartridge is `Cartridge::verified(rom, contentDigest)`, and O[k] is
retained until Phase C has read it.
- **The coordinator** (fly-session). A task declares the inspection attachments it reads, and the
coordinator holds them and hands over their bytes (`task::Inspection`). The executor's clock is the
agent's brain time after Prepare. `Evaluation.slot_saves` asks for `Environment.SaveSlot`. A
declared rollback policy now runs itself: `Ready(e, k) -> RollingBack(e', k) -> Ready(e', k)`, with
`RestoreSlot`, then `Task::rollback`, then `Agent.Rollback` on every agent. Composition setters
cover the backend and task config, the media, the decision schema, the world's state format and
per-agent model versions. The admission queue (`AdmissionQueue`) is cut into each Prepare's
`preStepStimulations` and reports every admission applied or aborted. `Coordinator::import`
installs a checkpoint of another format as a session's start. Step details (`StepDetails`) are
kept for a parity run.
- **FLYSIM01 as the start** (`fly-legacy-session::import`, on STATE-02's
`legacy_checkpoint::{halves, agent_payload, world_payload}`). The world, agent and task halves
go into each participant's own capture format, and the ordinary group restore installs them:
stage, validate, activate, `Paused(k)`, resume. The world is replaced by a fresh one first,
because ENV-01 stages only on a replacement. The context the agent resumes with is computed
from the checkpoint's own memory image, and the coordinator holds the task to it after the
install (`Task::restored`). The task ledger is STATE-02's `{reward, ratchet, slotFilled}`.
- **The store and the boot** (`fly-legacy-session::composition`, on STATE-02's
`LegacyCheckpointer`).
- `boot` is `Sim::boot`. It restores from the live hot and durable stores in the legacy
candidate order, holding each candidate to the legacy gate. Any refusal falls to the next
candidate; each attempt runs on a session of its own, because a refused install fences its
session. It is a fresh start when the stores are empty. After either, the startup durable
save is written and the intervals start.
- `advance` keeps the declared boundary order: the slot save (inside the step), the milestone
archive on a rank climb, the rollback (deferred by the coordinator until the host has
captured), a durable save after a rollback, then the interval saves.
- `shutdown_save` is the legacy shutdown's durable save.
- The session runtime writes no sugar journal yet: its admission is the coordinator's, and the
journal's boot header needs the edge.
- `lastEventId` carries the restored file's watermark; the runtime has no feed event log
before EDGE-01.
- **Sugar** (`fly-legacy-session::admission`). flysim's `RateLimiter` and clamp run unchanged,
against the last commit's `stimulusRemainingMs` (one commit stale). An admission waits for the
next cut.
- **The operator reward pulse is refused.** See the legacy-gameboy-v1 section 15 amendment.
**Parity** (`fly-legacy-session/tests/session_trace.rs`, rom-env). A whole new-runtime session
writes its own `FLY_TRACE` line per transition (`fly-legacy-session::trace`). Each line is built
from what crossed its boundaries: `Agent.Prepare`, `Agent.Commit`'s rates and spike bitset, the
executor's batch, the view, the image and the boundary actions. It is compared field by field with
the legacy loop's. The decision is compared as a set, because `gameboy-channels-v1` carries no list
order. Where the legacy side runs in the test, the ledgers are compared after every boundary as
well: adapter export, ratchet state, and the executor's scene, bound channels, running macro,
counts and "nearer". Results: see the TASK-01 run report and the amendment below.
**Amendment, 2026-09-29 (TASK-01 review fix round).** The review blocked on B1 and noted
N1 to N5. All are fixed here; the dated amendments to legacy-gameboy-v1 section 10 and 15 cover
B1, N1 and N3.
- **B1: the task ledger is artifact-backed.** On the live fly the adapter ledger is 42-46 KB,
past the 32 KiB `TypedValue` bound.
- `Task` gains `capture_attachments`, `validate_restore_with` and `install_restore_with`.
- The coordinator files those attachments as `task-ledger-<name>` payloads in captures and
imports.
- A bad ledger is an error, never a panic, so a boot falls to the next candidate.
- Boot parity now covers row 64 (42 KB) and the row 65 yard (46 KB).
- **N1: a sugar admitted before the next commit is an active pulse.**
- **N3: a restore seeds the palette as `Sim::boot` does.** `tests/palette_seed.rs` shows that the
seed is never read.
- **N4: saves are queued to the writer thread.**
- **N5: speed.** The profile is below. Changes:
- The world seals its three artifacts concurrently.
- Cache and caller holds are taken concurrently.
- In-process participants use the in-memory transport.
- A service session publishes every other boundary (the feed's 30 Hz) and keeps a bounded
history.
- `State.Capture` is off the loop. The worker shell lets a handler finish its reply outside
the endpoint's lock, and takes mutations in arrival order. The legacy agent copies its state
under the lock, then encodes, digests and seals it off the lock. The coordinator's
`begin_capture` / `finish_capture` let the session step on while the payload is written.
- **Measured** (`tests/speed.rs`, `tests/speed_ab.rs`):
- The brain is the same: the legacy `ticks` phase and the agent's `ticks` span agree within a
few percent.
- What remains is a fixed per-frame overhead of the process boundary. It is about 3-5 ms on a
quiet 8-core build box: roughly 0.7-1 ms per RPC round trip for Prepare, Advance and Commit,
plus the world's and the agent's artifact seals and reads.
- Against it, the legacy loop spends about 0.7 ms per frame outside the ticks.
- The report `claude-task-01` has the per-phase table and what would close the rest.
### PERF-01 — The session runtime's per-frame cost (port slice)
**2026-09-30: built** on `port/perf-01` (off `port/task-01`, with `main` v0.6.7 merged) and
awaiting review. Goal: cutover must not slow the live stream. TASK-01's fix round left the
in-process session about 4.7 ms a frame above its brain, against 0.7 ms for everything the legacy
loop does outside its ticks. No behaviour changes: the parity runs are identical frame by frame,
in-process and process, and the compatibility string is unchanged.
- **The local lane** (the big one; ipc-v1 section 1 and bus-v1 section 12, amended 2026-09-30).
An in-process worker's shell is offered to the coordinator directly (`worker::LocalLane`,
`launcher::Via::Local`, `WorkerRef::local`); `rpc::send` takes it for every endpoint method.
The request still goes through the shell's admission, deduplication, arrival order and
endpoint, and the reply is the same outcome. Handler media over the lane are in-memory
artifacts (`flybus::Artifact::in_memory`, `HandlerCtx::seal`): no store file, no seal copy,
no retain or open round trip. A bus call or a publication carries a sealed copy
(`rpc::promote`), begun while the task and the commits run. Process mode is untouched.
`FLY_SESSION_LOCAL_LANE=0` runs in-process over the bus. Every synthetic transport test also
runs over the lane.
- **The spike bitset** is the union of the kernel's per-tick spike lists, gathered while Prepare
ticks (`LifNetwork::tick_spikes`), instead of a 139,255-neuron scan in Commit. Same bits,
proved by `flybrain-core/tests/tick_spikes.rs` and compared every frame by the parity runs.
- **The session topic** gets a committed snapshot every 60th boundary in a service session (and
at every boundary with events or boundary actions), not every other one. Nothing in the
release subscribes; the stream is the legacy feed.
- Small ones: a single dispatch job is called in place, the shell moves the reply result
instead of cloning it, `digest_views` and `media_bytes` as SERVE-01 has them, and profiling
spans for the shell, the lane, each handler and the brain's own phase clock.
- **Tried and dropped**: publishing without waiting for the router (a deferred publish) and any
other overlap with Prepare. On the release CPU the sweep owns every core of the cpuset, and
work beside the ticks slowed them by up to 30% in one run. Spikes only at the feed rate
(an AGENT-01 amendment) was not needed once the bitset cost nothing.
- **Measured** (`tests/speed_ab.rs` with `FLY_PERF_ARMS`, `FLY_PERF_SERVICE`, `FLY_PERF_WORKERS`;
the report `claude-perf-01` has the tables): on the release host's CPU model, pinned to the
release cpuset's size, the in-process session's cost outside the brain fell from about 9.3 ms
to about 3.5 ms a frame. The legacy loop's is about 1.3 ms. What is left is mostly the per-frame
memory image (0.37 ms, 65,536 shim reads), the three domain calls' JSON, digests and cache
(about 0.5 ms together) and the task's evaluation, which the legacy loop does too.
### PERF-02 — The session's ticks on the release cpuset (port slice)
**2026-10-01: built** on `port/perf-02` off `main` (v0.7.3 + two infra fixes), awaiting review.
CUT-01's probation fell back at a median realtime factor of 0.959. Cause: with exactly as many
CPUs as sweep threads, the session's sleeping and waking host threads let the scheduler stack two
sweep workers on one CPU, and the ticks ran about 35% slower than the legacy loop's (same frames,
same work; with a spare CPU they matched). Fix: `flybrain_core::pool::place_workers`, called by
`flysim-session` before any thread exists, pins each spawned sweep worker to a CPU of its own and
keeps every other thread on the rest ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 12,
amended 2026-10-01). `FLY_SESSION_PIN=0` turns it off. Pinning is only safe in a cpuset that is the sim's alone (a pinned worker cannot leave a CPU that something else hogs: 0.14x real time): the deploy makes it so with `flysim.slice` and `fly-cpu-confine` and writes `FLY_SESSION_PIN=0` when it cannot (`infra/docs/runbook.md`). The legacy loop and process mode are
unchanged; the compatibility string is unchanged. `flybrain-core/tests/placement.rs` runs pinned
workers against the sequential kernel on the real connectome. The service's periodic profile
line also prints the measurement spans (and the brain's phase split) when
`FLY_SESSION_PROFILE` is set at start; the service reads the same variable as its profile name, so
a measured service sets it to `production`. The report `claude-perf-02` has the measurements.
### BUS-01 (port slice) — The live session's participants on the router
Not the framework guide's BUS-01 above (the router itself); the port plan reuses the name.
**2026-10-01: built** on `port/bus-01` off `main` (v0.7.5), awaiting review. Operator direction:
run the live session over the flybus router on Unix sockets, one emulator and one fly, because
multiplayer and more flies follow. The topology, its rules and the shadow procedure are
[legacy-gameboy-v1](legacy-gameboy-v1.md) section 12 (amendment 2026-10-01) and section 18
(amendment of the same date); the wire change is [bus-v1](bus-v1.md) section 12 (2026-10-01).
- **Selecting it.** `FLY_SESSION_TRANSPORT=bus` / `flysim-session --transport bus` (process mode
by default; `FLY_SESSION_MODE=thread` and `in-process` too), `fly-runtime session --bus`
(`session-bus`) on the container, `fly-shadow --mode bus/process` and
`fly-shadow-run start --bus` / `check --bus` for its shadow. The local lane stays the default.
`SessionArm` names the four arms; `FLY_PARITY_ARMS` picks them for the parity suites (default
`local,bus/thread,bus/process`).
- **What it took.** Per-process CPU placement (`Launcher::place_process`,
`--host-cpus`/`--sweep-cpus`, `flybrain_core::pool::apply_placement`), the launcher's own clients
in memory in thread and process modes, `block_in_place` for a bus request's handler (without it a
slow `Agent.Initialize` could not be resolved and a process-mode session failed to boot on a
loaded box: "never resolved"), delivered read locations (bus-v1 amendment), writers allocated
ahead (`WriterPool`), no second hold on a worker's own seals, small store I/O in place, the
envelope encoded without copying its body, and the agent's feed status attached to a bus Commit
(the host's 30 Hz `Legacy.FeedStatus` call was a round trip of its own).
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`, as v0.7.5) are the same in every arm: the toy and FAFB parity suites
(`session_trace`, `service_parity`, `rollback_sequence`, `save_handoff`) ran `local`,
`bus/thread` and `bus/process`.
- **Measured, and not fast enough to go live.** The report `claude-bus-01` has the tables. On a
build box with the release CPU model and the release cpuset's shape (four CPUs, four sweep
threads), same frames, interleaved, unpaced: legacy 16.1 ms a frame, the lane 17.4,
`bus/thread` 25.1, `bus/process` 25.7 (`main`'s process mode: 30.4, so this slice took about a
third off the bus's cost). Paced at real time the lane holds 1.00 and the bus 0.69 to 0.71, with a
neighbour CPU busy or not. Every round trip through the router is 0.5 to 1 ms there (the
synthetic `fly-session measure` puts a bare `Worker.Status` at 0.5 ms whether the processes
share one CPU or four), and a transition needs at least five in sequence: Prepare; Advance and
its seals; Commit and its seals. That is a realtime factor of roughly 0.7 on the release
container, so the lane stays live and nothing is switched. Moving the router, the coordinator
and the world to a fifth CPU (`FLY_SESSION_AUX_CPUS`) made it 1.5 to 2 ms slower. What would close
it is a cheaper round trip, not more CPUs: the router's own per-message work (strict JSON parsed
and re-encoded per hop, the state lock, about three task hops a direction), and sealing a reply's
media in the reply itself (one round trip fewer for Advance and for Commit).
- **`fly_frame_work_*`** on `/metrics` (both runtimes): the loop's compute time per frame without
its pacing sleep, mean, p99 and max over the last 3,600 frames. It agrees with the unpaced
ms/frame within 1% on every arm measured, and it is the headroom a paced realtime factor of 1.0
hides.
### BUS-02 (port slice) — A cheaper bus transition
**2026-10-02: built** on `port/bus-02` off `port/bus-01`, awaiting review. Goal: make the
session-over-flybus transport cheap enough to carry the live fly (operator: run on the bus with
real sockets, because more consoles and more flies follow). The wire change is [bus-v1](bus-v1.md)
section 12 (amendment 2026-10-02); [step-v1](step-v1.md)'s ordering is untouched.
- **Where a bus transition's time went** (a build box with the release CPU model and the release
cpuset's shape, router traffic counted per frame, cross-process timestamps per hop). About 35
commands a transition went through the router -- three calls and their replies, but also five
`artifact.seal`, six `artifact.allocate`, five `artifact.retain`, four `artifact.release`, six
`delivery.consumed` and three no-op `rpc.responder.release` -- and the router encoded every frame
twice and deep-copied every payload three or four times. The session's host CPU (the dispatcher's
CPU, which the router, the coordinator and the world share) was about 96% busy in every arm, so
bus cost was frame time almost one for one.
- **What changed.** Sealing sends (bus-v1 amendment: a reply seals the writers it attaches and
recycles their staging files as new writers, so a reply's media cost no seal or allocate round
trip); result attachments kept as delivered instead of retained; no responder release after an
admitted reply; the router encodes each frame once and forwards an admitted payload as bytes;
seal copies with `copy_file_range`; client location resolution cached; the session's writer pool
keyed by capacity (4 KiB buckets) so the variable-length feed status no longer misses it. About
14 commands a transition remain (three calls, three replies, consumes, cache releases).
- **Measured.** Before/after tables in the run report `claude-bus-02`. Unpaced, same rounds:
`bus/process` 17.1-17.2 ms a frame before, 14.9-15.8 after; paced at 1.0, the frame-work metric
17.4 before, 15.0 after (the lane 12.5, legacy 10.7). The bus still costs 2.5 to 3.5 ms a frame
more than the lane on that box, short of the 1.5 ms target, so the lane stays live. Also found:
BUS-01's numbers had the bus store on a disk-backed directory; on tmpfs (as the release, under
`/run`) its own binaries were 2.5 ms a frame faster.
- **Identical.** Traces, checkpoints, feed snapshots and the compatibility string (648 B,
`7b940584`) in `local`, `bus/thread` and `bus/process` (the FAFB parity suites, all arms).
- **Review notes (2026-10-02).** The review approved with notes; since the feed and the control
API already run over flybus in production, the router and SDK changes carry live traffic, so
every note was treated as live-path correctness. A recycled writer's staging file is zero-filled
when the router reissues it (about 10 us a 92,160-byte reply on tmpfs), so no artifact sealed from it -- by prefix or
whole -- carries the previous artifact's bytes (N3). A sealing reply is sent with the worker's
result cache held, so a duplicate replays the sealed artifacts rather than racing the reply
with an unsealed writer (N2). A refused sealing reply is answered as the handler's own seal
failure was before this slice (`BACKEND_FAILURE`, mutation applied), cached the same way, and
logged (N1). A failed staging rename leaves no file (N5). `recycle` without a sealing
attachment is refused even when false, a writer named by two attachments is refused, and the
SDK checks `writers` on every sealing send's reply (N4). The store-directory cache is per
connection (N6). Two test races are closed: the fly-edge stall test waits for the feed topic,
and SERVE-01's parity accepts a refused `/stimulate` drained one frame late (N7). The review's
adversarial lifecycle tests are in `flybus/tests/sealing_lifecycle.rs`.
### SHADOW-01 — The session runtime beside the live fly (port slice)
**2026-09-29: built** on `port/shadow-01` off `port/task-01`, and awaiting review. It changes no
live behaviour. flysim gains trace switches that are off unless set, and the compatibility string
is unchanged. The contract is [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18: the inputs,
the architecture, what is compared, the declared differences, the window and the verdict CUT-01
reads.
- **flysim** (`trace.rs`, `frame.rs`). These additions are recording only:
- `FLY_TRACE_DIR` writes one trace file per process. A restart truncated the one `FLY_TRACE`
path.
- `FLY_TRACE_MAX_BYTES` caps a file; the default in directory mode is 4 GiB.
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions.
- `frame::ledgers_string` is now the one definition of the ledger string. The session task's
`ledgers_of` calls it.
- **`fly-legacy-session::shadow`** and the binary `fly-shadow`:
- `follow` reads the per-process files. It hands out complete lines only, and a file ends when
a newer one exists.
- `spool` copies every new store generation as it appears. It keeps a floor and a byte bound,
and never writes to a live store.
- `checkpoint` exports the shadow's capture of a live save's boundary and compares it with the
live file byte for byte, after `host-fields` and `archive-order`.
- `verdict` is `fly-shadow-verdict-v1` and the cutover rule (`allows_cutover`,
`fly-shadow check`).
- The runner boots each segment from the live process's startup save (TASK-01's import). It
replays the admissions, runs the transition, and takes the live captures in the live order
around a deferred rollback. It compares with `trace::compare_line`, which is now shared with
`trace::compare`. It stops on the first divergence and writes `divergence.json` with 30
transitions of context.
- **infra.** `units/flyshadow.service` is report-only and has no `[Install]`. It is not bound to
flysim, runs `SCHED_IDLE` and stays stopped on exit status 3. `bin/fly-shadow-run` has the
commands `start`, `stop`, `status` and `check`. `05-deploy.sh` converges both and pins the
unit to the page and encoder CPUs. `build-flysim.sh` and `package-release.sh` ship
`fly-shadow` and `fly-session`. `lint.sh` holds the unit to all of this. The runbook has a
"Shadow run (SHADOW-01)" section.
- **Rehearsal** (`tools/shadow-rehearsal.sh`). It runs the real `flysim` service and the real
`fly-shadow` side by side from one checkpoint, with sugar posted to the control API and service
restarts. It runs on a build box, never on a host.
**Offline rehearsal** (a build box, `tools/shadow-rehearsal.sh`, FAFB in macros mode). The real
service ran at real time or unthrottled, with sugar posted every 10 to 20 s and a restart in every
run. It totalled **4,090 brain seconds (68 brain minutes), 244,327 transitions, 13 processes and
zero divergence**:
| Run | Start | Brain s | Transitions | What it covered |
| --- | --- | --- | --- | --- |
| main | the row 67 Pewter Gym stream checkpoint (rung 10), real time, restarts at 12 and 24 min | 2,161 | 129,086 | 126 sugar, 7 rewards, 4,134 macro events, 484 saves byte-identical, a ledger digest every boundary |
| reward | row 58 door, adapter ledger thinned (the TASK-01 brain arm, `examples/reward_bearing.rs`) | 601 | 35,894 | the real brain earns `map`, `exploration`, `boundary`, `talk` and `battle` (11 rewards); 138 saves |
| rollback | FND-01's `rollback` checkpoint | 302 | 18,056 | a ratchet rollback and the durable save after it; a `talk` reward |
| climb | FND-01's `climb` checkpoint | 303 | 18,069 | a ratchet slot save, and the milestone archive before it compared under `archive-order` |
| smoke | row 67, unthrottled | 122 | 7,305 | the first run |
| final | row 67, real time, the final binary, the lag guard on | 601 | 35,917 | the box was contended by other runs, so the live loop fell behind real time 5 times; each time the guard paused the shadow (667 s in all), and all 143 saves were still compared |
The reward run's box was loaded: the shadow ran at 25 frames a second against the live 52 and
finished 12 minutes behind. Every save was still compared, from the spool.
`tests/shadow.rs` (ROM, the toy connectome in raw mode) runs the real service through a restart
under a shadow, then plants four differences on copies of that run's trace and spool. Each one
stops a fresh shadow with the right kind, field and step:
- a work-RAM digest;
- a ledger digest;
- a sugar removed, which diverges on the brain at that transition;
- a live save's `rankSinceMs`.
**Cost.** These figures come from a shared 8-core build box, so they are indicative only. Other
agents' runs made paired measurements vary by up to 2x.
- *The shadow.* Over the whole main run it used 1.47 cores to follow 52.3 frames a second. The
live service used 1.43 cores for 53.5 frames a second. That is about 28 ms and 27 ms of CPU a
frame, so the session runtime costs about what the legacy loop does (x1.05).
- *Wall time a frame.* With 2 sweep threads the mean was 14.7 ms on the quieter box. Replaying the
main trace unthrottled gave these means:
- in-process with 1, 2 and 3 threads: 23.7, 19.7 and 17.0 ms;
- thread mode with 2 threads: 18.5 ms;
- process mode with 2 threads: 18.5 ms.
Every replay was identical again: five more comparisons of 20,000 transitions each.
- *Memory.* The shadow's resident size was about 130 MB, against the live service's 54 MB.
- *The live trace* with a ledger digest every frame costs about 1 ms of CPU a frame in the best
paired sample, which is within this box's noise; FND-01 measured about 2 ms. The live loop has
1.7-1.8x real-time capacity on 3 threads. The trace is about 750 bytes a transition, which is
160 MB per live hour.
The resource plan for the release container is in the SHADOW-01 run report and in
`units/flyshadow.service`:
- `SCHED_IDLE` on the page and encoder CPUs, never flysim's;
- 2 sweep threads;
- a back-off whenever the live `fly_lag_seconds` grows;
- a 3 GB memory ceiling;
- a ledger digest every 60 transitions.
To keep up, the shadow needs about 1.7 idle cores. With less it runs behind real time: the trace
is on disk, the spool covers about 15 minutes of hot saves, and the verdict comes later.
**Found on the way.** binjgb's exported state does not carry the audio resampler's phase. An
emulator imported from a state therefore drifts from a powered-on one in its channel accumulators.
The drift shows in the exported bytes only (frame and WRAM are identical). Every restart restores
through an import in both runtimes, so the two agree. A fresh start does not import, and the
shadow follows one by powering on as well.
**Gates** (a build box with rom-env): `cargo test --workspace --release` with `--no-fail-fast`
had three failures, each accounted for:
- `flysim` `integration` is the known load-sensitive test. It failed at box load 25 and passes
alone.
- `rom_macros_mode`'s no-PP turn is red on this base. Row 67 fixes it on main.
- A shadow-test threshold depended on the box's speed. It was fixed, and the test passes at load
22.
`clippy --workspace --all-targets -D warnings` is clean. `npm test` passed 688 with 0 failures,
typecheck is clean, and `infra/tests/lint.sh` passed every check. The compatibility string is
648 B `8ce67b97...` in raw and macros mode, unchanged.
**Review fix round, 2026-09-29** (APPROVE-WITH-NOTES). The branch was rebased onto port/task-01's
fix round, `2fc9fd7`: an artifact-backed task ledger, the palette seed, queued saves and bounded
history. The shadow now bounds its coordinator's history per segment. The fixes:
- *R1.* The verdict hashes `flysim-session`, SERVE-01's service, with the other release binaries.
`check` defaults to `--binary flysim-session --current /opt/fly/current`. It requires the
verdict's release to be the directory the link resolves to, with every shadowed binary
unchanged there.
- *R2.* Every session-side failure is a divergence:
- a session that does not start;
- a restore-gate refusal (`tests/shadow.rs` now plants one);
- a capture with no agent;
- an unrecorded transition;
- an unbuildable trace line.
Skips carry a kind, and only the live side's own kinds allow a cutover.
- *N1.* The live trace needs the shadow's heartbeat to start and to keep going, and flysim keeps
the trace directory under 8 GiB. The runbook's claim is corrected.
- *N2.* `fly-shadow-run` records a baseline and runs `flyshadow-guard.timer`. The guard stops
everything and restarts flysim without the trace on 1 s of lag growth, or when the realtime
factor drops below min(0.97, baseline - 0.03). `lint.sh` drives the rule on six cases.
- *N3.* Both `pass` and the cutover require one live save compared per 600 brain seconds, with at
most 10 % unavailable. The cutover also requires a shadow at most 3,600 transitions behind.
**Cost re-measured on the rebased tip.** This was a 12-brain-minute rehearsal on the same box,
at real time, with a restart and the guard on. It had 43,104 transitions, 197 saves byte-identical
and zero divergence. The box was contended by other runs again; the guard paused the shadow for
911 s and it still passed. Unthrottled replays of its trace, all identical, gave these mean
milliseconds per frame:
| Mode | ms per frame (mean) |
| --- | --- |
| in-process, 2 threads | 15.1 |
| in-process, 3 threads | 13.3 |
| thread mode, 3 threads | 14.9 |
| process mode, 2 threads | 15.4 |
Earlier the same 2-thread and 3-thread in-process arms took 19.7 and 17.0 ms. With 3 threads the
shadow keeps real time with about 20 % to spare.
**Review round 2, 2026-09-30** (APPROVE-WITH-NOTES; R3 and G1 were required before `start`).
The branch was rebased onto port/task-01 `eaf588d`, and main v0.6.7 was merged in: row 68 and
adapter `pokered-unique8-v8`. The live shadow will therefore carry the v8 compatibility string.
The fixtures were already v8 on main.
- *R3.* `allows_cutover` floors the window at `REQUIRED_BRAIN_SECONDS` (10,800). A verdict run with
a shorter `--required-brain-seconds` passes as a rehearsal but never passes `check`. There is a
test case for this.
- *G1, the host guard.*
- `start` measures a 10-minute baseline of 60 samples before the shadow exists: the median RTF,
its spread as 1.4826 x MAD, and the lag growth rate over the most recent half.
- The guard trips only on a sustained degradation *against that baseline*: 3 checks in a row in
which the last 5 samples of the same process fall below it, in RTF or in lag rate, by more
than max(0.05, 4 x spread / sqrt 5).
- It stops itself when the shadow is not running. `check` refuses after a trip or with the
shadow down.
- Tested over two kinds of trace:
- *Synthetic*, shaped on the release container: a flat 0.66, 0.77-0.99 and 0.6-1.0 noisy, per
second and per sample, and real time with hiccups. There was no false trip in 800 3-hour
runs, and every one of 400 degradations tripped (to 0.55-0.75, and 0.66 to 0.58).
- *Recorded* from a real flysim, now fixtures: alone (at about 1.0, and at 0.4-1.0 under box
load) no trip; with a real idle shadow on other cpus no trip; with a real shadow on the fly's
own cpu (0.66 to 0.44-0.60) a trip at check 7.
- One recording had a load step inside its baseline, which widened a mean/sd baseline to a
0.25 margin. That is why the baseline is robust.
- *G1, the in-shadow back-off* (`LagJudge`). It pauses the shadow while the live lag grows faster
than the baseline rate plus the margin (re-read from `baseline.json`). It lifts itself for
10 minutes when a pause did not help, because then the shadow is not the cause. Tests show:
- a flat 0.66 fly is never paused;
- with no baseline, at most 1 minute in 11 is paused;
- a shadow that costs the fly time stays paused about half the time.
- *N3.* `lagTransitions` is recomputed at every verdict write, over the rest of the current file
and every newer one, including while the shadow is backed off.
**2026-09-30: `tests/shadow.rs` "one trace file per process" (0 vs 2) on a build box.** It is not
a timing, load or segment-handling bug.
- *Cause.* The failing runs used a `flysim` binary that was not built from the tree under test.
`cargo test -p fly-legacy-session` does not build `flysim`'s binary, and the build box's bx
target directory was shared by name with other trees. That binary predated `FLY_TRACE_DIR`, so
it wrote no trace at all. The failure was reproduced by running such a test binary against its
own stale `flysim`.
- *Fix.* The test now builds the `flysim` binary itself: `cargo build -p flysim --bin flysim`,
with the same target directory and profile, which does nothing when the binary is current.
This was proved on a target that another tree's `flysim` had populated.
- *What production could miss, and now cannot.* A live process that runs without a trace is now
a `coverage` divergence (above). That covers a process whose consumer check failed, and one
whose trace could not be created. In `FLY_TRACE_DIR` mode, a trace-creation failure no longer
stops flysim from starting. The test adds such a process, untraced, and the shadow fails.
### SHADOW-02 — The shadow on a build box (port slice)
**2026-09-30: built** on `port/shadow-02` off main (v0.7.0), and awaiting review. It changes no
live behaviour until `fly-shadow-run start` runs; the flysim binary is unchanged. The contract is
the SHADOW-02 amendment of [legacy-gameboy-v1](legacy-gameboy-v1.md) section 18.
**Why.** On the release container the shadow (v0.7.0, started 2026-09-30) compared 1,119 brain
seconds with zero divergence, but at about 27 ms a frame on the page and encoder CPUs it fell
further behind every hour, and the live realtime factor fell from 0.9998 to 0.93-0.98. It went
back to 0.999-1.0 the moment the shadow was stopped.
- **`shadow::remote`**: the frame protocol (a JSON header line and a body), the name checks that
guard every path, the forwarded settings (`FORWARDED_ENV`: game, macro mode, accepted adapters,
pins; no path, no secret).
- **`shadow::relay`** (`fly-shadow relay`, the container's `flyshadow.service` through a drop-in):
per quarter-second tick, the new saves, then the trace bytes of this run in file order, then
the journal read before the listing. A writer thread owns the ssh pipe, so a stalled link never
blocks it: saves are read as they appear and queued in memory (256 MiB), trace bytes wait on
disk, and a newer file and the journal wait for every older file. The heartbeat is touched only
while healthy (connected, the box's shadow of this run alive within 30 s, the box has every
byte that was on disk a minute ago). The box's verdict is written back only when it is this
run's, with the unsynced tail added to `lagTransitions` and a `relay` member.
- **`shadow::ingest`** (`fly-shadow ingest --root`, the forced command of the relay's key on the
box): the release directory and binary hashes must equal its own; a new run id resets the mirror
and restarts the shadow; appends only at the offset it holds (else `resync`); a file the shadow
finished is never written again (`done`, and the relay then deletes the container's copy);
reports liveness (heartbeat fresh, verdict this run's and running or passed).
- **The shadow**: `--run-id-file` (the verdict's `runId`; a new id exits 4); a `no-consumer` trace
stop while following is a `coverage` divergence; coverage reads the journal before listing the
traces. `shadow::release` holds the release hashing the binary and `check` share.
- **infra.** `fly-shadow-run start` runs remote when `/etc/fly/shadow-remote.env` exists and
refuses otherwise (`--local` keeps the old placement); `check` also needs `relay.json` healthy
and under a minute old; `status` shows the relay. `infra/box/` (never deployed by 05-deploy):
`flyshadow-remote.service` (the same release at the same path, `--run-id-file`, no lag back-off,
`Restart=always`, stays stopped on exit 3, `CPUWeight=1000`), `flyshadow-remote.path` (starts it
on a new run id) and `fly-shadow-remote-setup` (MANIFEST-verified root-owned release, the
`flyshadow` user, a root-owned `authorized_keys` with `restrict,command=` and optional `from=`).
`02-base.sh` installs `openssh-client` (no sshd). Lint holds all of it; the runbook's shadow
section has the set-up.
**Tests.** `tests/shadow_remote.rs` (ROM, the toy connectome) runs the real `flysim`, the relay and
the real `fly-shadow ingest` binary (over pipes where production has ssh) and a remote shadow:
a fresh fly and a restart with sugar pass and come back with the run id; a dead remote shadow stops
the heartbeat and flysim's trace, and the new shadow ends its window at that stop (what it compared before it no longer counts, B2) and
follows the next process; a stalled ingest leaves the relay reporting "not healthy", flysim stops
its trace, and when the link is back the box fails the verdict as `coverage` and the relay brings
it and `divergence.json` back and exits 3. Unit tests: frames, names, the release refusal, offsets
and `resync`, the run reset, the env allowlist.
**Two-box rehearsal** (FAFB, macros, row 67, real time, sugar every 10-30 s; a real flysim on one
build box standing in for the release container, the remote shadow on another behind a real sshd
with a `restrict,command=` key): see the SHADOW-02 run report. Cost of the shadow per live frame
(unthrottled replay of a recorded trace, mean of the step): fly-build-1 14.1 ms with 3 threads,
11.9 ms with 6; fly-build-2 13.9 / 13.0 / 12.2 ms with 3 / 4 / 6; fly-build-3 11.9 / 11.8 ms with
3 / 4 (beside another agent's 1.6-core soak). The relay took about 0.5 % of a core; the stream to
the box is about 2.1 GB per live hour (a 2.7 MB hot save every 5 s, and about 140 MB of trace).
**The trace's own cost on the live loop** (the coordinator's question): +1.3 ms a frame on the
sim thread (11.14 to 12.45 ms, unpaced, 3 threads, 4 A/B rounds on a build box), about half in
the post-frame digests (frame and work RAM) and half in the record's digests and JSON. A writer
thread for the digests and the file was tried and rejected: on flysim's pinned CPUs it preempts
the brain's parallel sweep and the frame took 19 ms. The live guard's baseline is taken before
the trace is on, so the trace's cost counts against it.
### STATE-01 — Coherent all-participant checkpoint/recovery ### STATE-01 — Coherent all-participant checkpoint/recovery
**Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01. **Depends on:** SESSION-02, MEDIA-01; validate with fake agents first, then AGENT-01/ENV-01.
@ -233,6 +867,244 @@ for new epoch metadata; corrupt any participant and installation fails as a grou
reply doesn't advance durable metadata; failure during activation cannot resume half a world. reply doesn't advance durable metadata; failure during activation cannot resume half a world.
Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery. Checkpoint queue stress remains bounded; verify old media/parser data cannot cross recovery.
### STATE-02 — The legacy composition's checkpoints in `FLYSIM01` (port slice)
**2026-09-29: built** on `port/state-02` off `port/integration` and awaiting review. The operator's
decision of 2026-09-23 makes `FLYSIM01` the format of record until RETIRE-01, and the session
runtime exports it on every durable save ([legacy-gameboy-v1](legacy-gameboy-v1.md) section 16).
This slice is that export, the import back, the store policy and the restore selection. It adds
no `FLYSESS1` production file. Nothing in `flysim`'s frame, checkpoint bytes or compatibility
string changes.
- **One store, two runtimes.** `flysim`'s `store.rs` and `journal.rs` move unchanged into the new
crate `flysim-store`, which `flysim` re-exports (`flysim::store`, `flysim::journal`) and
`fly-session` links. Both runtimes write through the one `store::encode` and commit through the
one `Store`, so they share the envelope bytes, the generations, `manifest.json`, the
`milestone-<N>` archives, `keep_generations` rotation and the restore order by construction.
- **Export** (`fly-session::legacy_checkpoint`). A `FLYSIM01` file is assembled from its owners'
halves: the agent's `FLYAGT01` capture payload (the seven agent chunks, the remainder already the
accumulator's), the world's `FLYENV01` payload (emulator, frame on screen, joypad, frame
counter, cartridge digest, and slot `best` as `ratchetGame`/`ratchetFrame`), the task's
`{reward, ratchet}` and the host's `{generation, wallMs, compatibility, speed, rankSinceMs,
lastEventId}`. `runtime_state` builds the legacy `RuntimeState` field for field as
`Sim::snapshot_state` does.
- **Import.** `split`/`halves` read a `FLYSIM01` file back into those halves. `agent_payload` is
the shipped form of AGENT-01's `seed_from_legacy_state` prototype. It builds the `FLYAGT01`
payload a replacement agent stages, using the same encoder the worker's own capture uses
(`legacy_agent::encode_payload`). The accumulator is `{remainder, executedTicks = network.ms,
warmupOffset = 2500}`. `learning.updates` is the file's `reinforcements`. A file from before
that member starts at `plasticity.updates` once (`legacy_reinforcements`, section 13
amendment). The checkpoint id is the file's generation (`flysim01-g<N>`). No template worker
is involved. This fixes the four points the AGENT-01 review raised against the prototype:
template dependence, borrowed ids, no compatibility gate (the gate is `restore_from_store`'s,
below), and the count falling back on every round trip. The payload also carries the file's
`framebuffer` as an `inputFrame` chunk, which `State.StageRestore` installs as the next input.
`LegacyFrame::restore` re-projects the framebuffer and does not keep the saved visual drive,
and the two differ on the row 65 yard survey checkpoint (found here; see the section 13
amendment). `world_payload` is ENV-01's `FLYENV01` from
the same world. The source scope of both is `(session, "legacy", emulatorFrame - 1)`.
`legacy_parity` now seeds its workers through this import.
- **`reinforcements`, an optional `FLYSIM01` manifest member.** `LegacyFrame` now counts
reinforcement calls the way the agent worker does: one per commit while the rule is enabled,
zero sums included. `Sim` writes the count, and `LegacyFrame::restore` reads it (falling back
to `plasticity.updates`), so the count survives every round trip in either runtime. Readers
that predate it ignore it. The member changes no behaviour and not the compatibility string,
but it does change legacy checkpoint bytes: a file written from now on is the old layout plus
this member.
- **Store policy.** `LegacyCheckpointer` follows `Sim` at each call site:
- one generation counter over both stores, starting above the highest either has allocated;
- a hot copy every `hot_seconds`, and a durable one every `checkpoint_seconds`, which also
restarts the hot interval;
- a durable save for a climb, archived as `milestone-<rank>` when the rank is above every rank
this process has archived (`best_archived_rank`, per process as in the legacy loop);
- rank tracking as in `track_rank`;
- encoding and fsyncs on a writer thread.
- **Restore selection.** `restore_from_store` walks `store::restore_order`: hot latest, hot
previous, durable latest, durable previous, then the archives by descending rank, each as its
generation and then as its `milestone-<N>` file. It checks the legacy gate: the cartridge, and
`flybrain_gb::compatibility::decide` with `FLY_ACCEPT_ADAPTERS`. It moves to the next candidate
on *any* refusal, including a participant's `State.StageRestore`. It reports `Fresh` when no
candidate exists, and `Refused` when every candidate failed. In that case the runtime must exit
as `Sim::restore_or_warm_up` does.
- **The agent worker** now refuses a conflicting stage (a restore already staged, or a token
already activated) before it builds a replacement network (AGENT-01 review).
- **Sugar journal** (the FND-01 review note, before SHADOW-01). A per-process boot header
records the runtime, start frame, brain ms, restore origin, generation and compatibility. The
journal rotates at 4 MiB and keeps three files; every rotated-in file starts with a
`continues` line. `journal::clear` removes the journal. `flysim` writes the header at boot, and
`flysim --reset-to-milestone` clears the journal after it has copied both stores aside.
`read_segments` cuts the journal into per-process segments. `read` still returns input lines
only.
**Boundary order the session host must keep** (section 16, and section 11 step 6). At `Ready(k+1)`
the order is:
1. `Environment.SaveSlot`, if one is due.
2. The milestone capture, if the rank climbed.
3. The rollback, if one was requested.
4. The durable capture after the rollback, then the hot and durable interval saves.
The capture itself uses `State.Capture` on the world and the agent at the same committed
boundary, plus the task's ledger, `{reward, ratchet, slotFilled}` (`TaskHalf::to_ledger`). Wiring
it into the coordinator and the boot-time restore path is left to the legacy composition's
coordinator (TASK-01); this slice ships the pieces and proves them on the workers.
**Proof** (flysim `tests/state_02.rs`, `tests/state_02_store.rs`; `fly-session`
`legacy_checkpoint` unit tests):
- *legacy -> session -> legacy on 18 real checkpoints* (every distinct rom-env checkpoint, which
includes the row 64, row 65 and row 67 ones). Each file is split and the world is restored
into the real environment worker and captured again. The agent goes through the imported
`FLYAGT01` payload and the task through the Pokémon adapter and the ratchet. Every export is
byte-identical to the legacy loop's own restore outcome of the same file, checkpointed at once.
Against the files themselves, every export differs only in named fields. All 18 gain
`reinforcements`, because the files predate it. Twelve written by adapters v5 or v6 also
differ in `reward`, which the adapter's import migrates. One survey checkpoint also differs in
a joypad byte of its emulator state that its own `buttons` field does not match; both runtimes
apply `buttons` on restore. Before the counter was added, six of the 18 were byte-identical to
the file.
- *Restore then continue, toy connectome, raw mode* (every ROM run). The legacy frame writes a
checkpoint. The session runtime selects it from a store whose hot copy is torn. The legacy
loop and the session runtime then each run 600 frames from it. World: 1,800 values identical
to `FLY_TRACE` (frame, WRAM). Agent: 600 transitions identical (ticks, clock, exact remainder,
rates, spikes, decision). The session runtime's export at the last boundary is byte-identical
to the legacy loop's checkpoint of that boundary. That export also survives session -> legacy
-> session unchanged: a fresh legacy loop restores it and checkpoints the same bytes, and a
fresh world and agent import it and export the same bytes.
- *The same with `gameboy-legacy-fafb-v783-v1` in macros mode* from the row 67 checkpoint, with
sugar and a ratchet rollback (`FLY_STATE02_FAFB=1`). Four checkpoints were run for 1,800 frames
each: rows 58, 64 and 67, and the row 65 yard survey. Each run has 5,400 world values and 1,800
agent transitions identical to the trace, with 2 sugar and 1 rollback. Each export is
byte-identical to the legacy checkpoint and survives session -> legacy -> session.
- *The tools, both ways* (`tests/state_02_store.rs`, the real `infra/bin` scripts and the real
binary). `fly-loop-reset --list` and `--print-state-compatibility` read a store the session
runtime wrote. `fly-reset-to-milestone` promotes its rung with the recovery budget back and
clears the journal. The legacy order and the session runtime then choose the same candidate,
and the session runtime carries on above every generation and archives its next climb. The
other way round, the session runtime restores a store the legacy writer wrote and the tool
reset, and it would save it as the same bytes.
**Not in this slice, and why:**
- *The coordinator hook and the boot-time restore.* Both need the legacy composition's
bootstrap, which is TASK-01's. The restore order is Initialize-free: stage and activate the
world, have the task install `{reward, ratchet}` and observe O[k] for the first context
(`{boot, bound, location: null}`), then build the agent's payload with that context
(`agent_payload`) and stage and activate it.
- *The task's per-frame half in the proofs.* The executor and the task's evaluation are TASK-01's.
The proofs take the joypad masks from the trace and the task's end-of-run `{reward, ratchet}`
from the legacy loop.
- *Declared difference, archive order* (sections 4 and 16). A session-runtime milestone archive
holds the post-capture ratchet and slot. It is excluded from the shadow comparison.
### SERVE-01 — The session runtime as the live service (port slice)
**2026-09-29: built** on `port/serve-01` off `port/task-01` and awaiting review. It makes the
session runtime a drop-in for the live `flysim` service, so CUT-01 can switch the stream over
with one command and roll back with one. It changes no live behaviour: the legacy loop's frame,
feed, checkpoint bytes and compatibility string are unchanged, and nothing runs the new binary
until `fly-runtime session` is run on a container.
- **One service shell, two runtimes** (`flysim::serve`). `flysim::run` is split: `serve(config,
sim)` binds the feed (`:7400`, or the feed bus that `fly-edge` serves), the control API
(`:7401`) and the metrics listener (`:9101`), handles SIGTERM/SIGINT/SIGHUP, and runs `sim` on
the calling thread with the `Shared` state, the snapshot slot and the command queue. The
legacy loop is `serve(config, Sim::boot + Sim::run)`. The pieces of a feed header that come
from the fly (`feed_rates`, `feed_learning`, `feed_game`, `feed_milestone`, `feed_sugar`) and
the chat admission (`admit_chat`) move out of `Sim` into free functions both runtimes call.
The feed codec, the bus publisher, the router, `/status`, `/events`, `/metrics` and the
WebSocket framing are therefore one copy of the code whichever runtime is behind them.
- **The service host** (`fly-legacy-session::service`, binary `flysim-session`). It reads
`flysim`'s own `Config` (so `/etc/fly/fly.env`, `FLY_ACCEPT_ADAPTERS` through STATE-02's
`RestoreGate`, the macro mode, speed, threads, chat, the store paths) and keeps `Sim`'s order
call site for call site: boot by TASK-01's `boot_unsaved` (the legacy candidate order and gate),
the boot event, the chat sidecar, the journal's boot header (`runtime: fly-session`), the
startup durable save, then per frame the command drain, `Coordinator::step`, the task's macro
and reward events, the rank and its milestone archive, the deferred ratchet rollback with its
recovery event and durable save, the 30 Hz publish, the hot (5 s) and durable (300 s) wall-clock
saves, the event log fsync and flysim's `Pacer`. Saves are queued (`queue_save`, TASK-01) so the
encoding and the fsyncs stay off the loop, as the legacy writer thread keeps them.
- **Where each header field comes from.** The frame is the committed `lcd` view; the audio is
each transition's `apu` chunk through the legacy DC blocker (`DcBlocker::process_f32_into`,
the same filter on the environment's `v / 255`); the spike bitset is the OR of the commits'
`telemetry.spikes` since the last publish, which equals the legacy window exactly; `buttons`
is the executor's mask (the checkpoint's after an import, 0 after a rollback, as
`LegacyFrame` has it); the game, milestone and macro fields are the task's own adapter,
ratchet and macro layer (`PokeredTask::inspect`, `take_feed`). The numbers from inside the
network that no session message carries -- the plasticity statistics (`learning.changed`,
`learning.synapses`), the decoder's baselines and scores for `/status`, and the rates and pulse
at the boundary -- come from one declared extension of the legacy agent,
`Legacy.FeedStatus` (capability `legacy-feed-status-v1`): read-only, answered at a committed
`Ready(k)`, once per published snapshot, never in a trace. `Coordinator::read_agent_extension`
calls it without fencing the epoch; `Coordinator::media_bytes` reads the committed view and
audio chunk.
- **Sugar.** flysim's `RateLimiter` and clamp, over the pulse the network holds: the last commit's
`stimulusRemainingMs`, raised by each sugar admitted since (`network.stimulate` is a maximum),
so a second request in one drain is refused with the legacy `retryAfterMs`. The admission lands
in the next Prepare, which is the frame the legacy drain applies it before, and the journal
stamps it with that frame.
- **Long-running hygiene.** The coordinator kept every transition's trace, every phase change,
an audit line per step and every timing sample: about 120 KB/s of heap on the live fly
(the first soak's RSS). `Coordinator::trim_records` bounds them at each boundary; the timings
are logged once a minute as a `session profile` line and cleared.
- **Declared differences** (the rest is byte-equal, below): `POST /reward` is always 403
(`control.allow_reward` is forced off; the operator pulse has no session-framework
counterpart, `legacy-gameboy-v1` section 15); a fresh start publishes no audio for its setup
frame (the environment discards O[0]'s); `FLY_TRACE` and `FLY_PROFILE_SECONDS` are the legacy
loop's tools; only the Pokémon composition exists (another `FLY_GAME` is refused at start); the
toy connectome cannot run macros mode (AGENT-01 refuses a macro channel the dataset does not
track, and the toy tracks none).
- **Infra.** `flysim.service` stays the fly's one unit. `infra/bin/fly-runtime session|legacy|status`
switches the binary it runs with one drop-in (`flysim.service.d/10-runtime.conf`), so every
consumer that names `flysim.service` -- `fly.target`, `flyedge.service`'s `Requires=`, the
watchdog, `fly-loop-recover`'s sudoers-granted restart, `fly-loop-reset`,
`fly-reset-to-milestone`, the unstick rule -- works unchanged and the choice survives reboots and
deploys. It refuses a release without `flysim-session` or with a different compatibility
string, waits for `/healthz` and an advancing frame, and falls back to legacy by itself if the
session runtime does not come up. `flysim-session.service` is the standalone unit (flysim's
limits and cpuset, `Conflicts=flysim.service`, no `[Install]`) for rehearsals.
`build-flysim.sh`/`package-release.sh` ship `flysim-session` and `fly-session`; `05-deploy.sh`
installs `fly-runtime`, writes the standalone unit's cpuset drop-in and refuses a release
without `flysim-session` while the drop-in is present; tmpfiles creates `/run/fly/session`.
The runbook's "Switch the runtime" is the operator's page.
**Proof** (`fly-legacy-session/tests/service_parity.rs`, `journal_replay.rs`, rom-env; the SERVE-01
run report has the numbers). Both runtimes are started from the same seeded store behind
flysim's own control router and driven by one script of control requests, each landing before
the same frame: every running feed header is equal field by field (wall-clock fields excepted)
and every frame, audio and spike attachment byte for byte; every control response is equal
(`/stimulate` 202/429 with the same `retryAfterMs`, `/reward` 403, `/chat` 202/422,
`/checkpoint` the same generation, `/pause`, `/resume`, `/events`, 404s); the event log, the
journal and the final checkpoint are equal. Toy connectome raw mode, and the real connectome in
macros mode through a ratchet rollback, each in-process and as processes. A soak of both
runtimes side by side with the stage's decoder and the bridge's `HttpSimClient`
(`tools/runtime-soak.ts`), the hot/durable cadence sampled from the stores, and a `SIGKILL`
whose journal is replayed from the seed in the legacy loop onto the killed process's last hot
checkpoint.
Results (2026-09-29, the build boxes; the run report has the logs):
| Proof | Result |
| --- | --- |
| Toy raw, 120 frames, 19 scripted requests incl. two sugars in one drain | identical, in-process and process |
| Real connectome, macros, `rollback` checkpoint (ratchet rollback on frame 1), 120 frames | identical, both modes, before and after the TASK-01 fixes |
| Real connectome, macros, engage checkpoint (ledger thinned), 2400 frames, 46 macro and 2 reward events | identical, both modes |
| Real connectome, macros, row 64 (a 42 KB adapter ledger, TASK-01 B1), 1200 frames | identical, both modes |
| Soak, 35 min, both runtimes from the row 67 checkpoint, production configuration | 0 decode or schema errors, no 2 s stall, `/healthz` 100 %, event ids gapless, hot every 5 s and durable at 300 s on both (same intervals) |
| Soak, 36 min, the session killed -9 at +6 min | back in about 1 s from the hot checkpoint 3.5 s old, 1 `/healthz` 503, the feed client reconnected (533 ms gap), two journal segments |
| The killed process's journal, 17 sugars, replayed from the seed in the legacy loop | 18,838 frames onto its last hot checkpoint: agent, emulator, frame, adapter, ratchet equal |
| Feed over the bus (`FLY_FEED_VIA=bus`) with `fly-edge` | 3,050 snapshots through the edge, 0 errors |
Open for CUT-01: **speed.** Unpaced on a shared box the session ran 54-61 fps where the legacy
loop ran 68-118 (per frame p50: `Agent.Prepare` 7.8 ms, `Environment.Advance` 2.6,
`Agent.Commit` 1.6, publication 0.4; `Legacy.FeedStatus` 0.9 ms at 30 Hz). The live container
must be measured (SHADOW-01's cost run) before cutover. **Memory.** After `trim_records` the
session's RSS still grows about 5-8 MB an hour, tied to the saves (an unpaced run without saves
is flat); at `MemoryMax=4G` that is weeks, and a restart clears it, but it is not explained yet.
**Number form.** A checkpoint the session writes carries the adapter ledger's integral numbers
as `7580031` where the legacy loop writes `7580031.0` (the ledger crossed canonical JSON); equal
values, and both runtimes read both.
### PUBLISH-01 — Committed snapshots and observer isolation ### PUBLISH-01 — Committed snapshots and observer isolation
**Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to **Depends on:** SESSION-02, MEDIA-01; public v2 contract work is a separate prerequisite to

View file

@ -17,6 +17,37 @@ ownership. This document owns Scope, model-related scalar types, worker capabili
domain operation deduplication and errors. Domain request identity is independent of the bus domain operation deduplication and errors. Domain request identity is independent of the bus
callId: a safe retry has a new transport callId but the original domain requestId/body. callId: a safe retry has a new transport callId but the original domain requestId/body.
**Amendment, 2026-09-30 (PERF-01; operator-approved slice).** One exception to "every session/worker
RPC is a Flybus call", for participants that share the coordinator's process. The release
container runs the legacy composition in-process, and there the bus path cost about 4.7 ms a
frame above the brain (three round trips through the router and four or five sealed store files
a frame), against 0.7 ms for everything the legacy loop does outside its ticks.
- **The local lane.** A launcher MAY offer an in-process worker's shell to the coordinator
directly (`fly-session` `worker::LocalLane`, `launcher::Via::Local`). Endpoint methods --
step mutations, lifecycle/capture and an endpoint's own read-only extensions -- then go to
that shell without a bus message. `Worker.*` stays on the bus, where the supervisor asks.
- **Same domain semantics.** The request is the same `SessionRpcRequest`, and it goes through
the same shell code as a bus request: section 5's classification, canonical body digest,
result cache and conflict/IN_PROGRESS/RESULT_EXPIRED rules, the arrival-order lock, and the
endpoint. The reply is the same `SessionRpcOutcome`, checked by the coordinator for worker,
incarnation, scope and request id exactly as a bus reply is. Section 6's deadline and
resolution procedure are unchanged: a lane send is the "bus call", and a worker that stopped
before answering is a lost connection (mutation unknown).
- **Artifacts.** Over the lane, a handler's reply media are *in-memory artifacts* (bus-v1
section 12, 2026-09-30): immutable buffers in the process with a normal `ArtifactRef`
(`storeId` `in-memory`, no digest), no store file and no router owner. The rule of section 3
holds as written: every `ArtifactRef` in a payload is backed by a live handle the message
carries. An in-memory artifact never crosses a router: a bus call or a publication that needs
one carries a sealed copy (the coordinator makes it), and the snapshot names the copy.
A sealed handle a handler returns over the lane reaches the caller in memory under the same
reference.
- **Scope.** Only `ExecutionMode::InProcess`. A thread or process participant is always reached
over the bus, so process mode keeps exercising routing and ownership, and the bus path stays
the reference: `FLY_SESSION_LOCAL_LANE=0` runs an in-process session over it. Every synthetic
transport test also runs over the lane (`tests/common` `local_lane` module), and the legacy
parity runs in-process (lane) and process (bus).
## 2. Common domain types ## 2. Common domain types
```ts ```ts

View file

@ -125,7 +125,8 @@ interface GameboyReadoutContext {
``` ```
`ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so `ChannelName` is `^[a-z][a-z0-9_]{0,63}$`. Decoder channel and rate-role names carry `_`, so
they are not `Id`s. The context is what the task hands the decoder with each Prepare (the they are not `Id`s (corrected 2026-09-23, AGENT-01: they are; see the section 13 amendment).
The context is what the task hands the decoder with each Prepare (the
`initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the `initialDecisionContext`, then every `nextDecisionContext`). `bound` is an ordered subset of the
composition's `macroChannels`. composition's `macroChannels`.
@ -168,7 +169,8 @@ interface GameboyMemoryInspection {
} }
``` ```
- **The image.** Byte *i* is what `fly_gb_read_mem(i)` returns at this boundary, which is - **The image.** (Amended 2026-09-29, below: the register windows are not captured.) Byte *i*
is what `fly_gb_read_mem(i)` returns at this boundary, which is
what every task and executor read in the legacy loop sees through the per-frame read cache. what every task and executor read in the legacy loop sees through the per-frame read cache.
It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional, It is a listed bus attachment, content type `application/octet-stream`. Its digest is optional,
because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At because it is a transient live artifact ([state-media-v1](state-media-v1.md) section 1). At
@ -186,6 +188,38 @@ interface GameboyMemoryInspection {
- **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated. - **Retention.** The coordinator keeps O[k]'s image until transition k→k+1 has been evaluated.
The executor reads it in Phase B, and the task reads old and new images in Phase C. The executor reads it in Phase B, and the task reads old and new images in Phase C.
**Amendment, 2026-09-29 (MEM-01).** The image captures the address space's *memory*, not its
*registers*. The two proofs this section demands contradicted each other for three windows: a
read of VRAM (`$8000-$9FFF`), OAM (`$FE00-$FE9F`) or I/O with the APU and wave RAM
(`$FF00-$FF7F`) goes through binjgb's lazy catch-up (`ppu_synchronize`, `timer_synchronize`,
`serial_synchronize`, `intr_synchronize`, `apu_synchronize`) before it answers. The catch-up
rewrites the subsystem's sync bookkeeping, so the exported state changes. On a boot run it
changed on 104 to 105 of 105 sampled boundaries for each window. A full 65,536-byte read
through `emulator_read_mem` is therefore not read-only by the state-comparison test. The amended
rule:
- **Captured**: `$0000-$7FFF` (ROM as mapped), `$A000-$FDFF` (cartridge RAM, work RAM and its
echo), `$FEA0-$FEFF` (the unused block) and `$FF80-$FFFF` (high RAM and `IE`). Byte *i* is
exactly what `fly_gb_read_mem(i)` returns at this boundary. binjgb reads each of these
straight out of an array, with no catch-up.
- **Not captured**: the three register windows above. They read `$FF` (binjgb's
`INVALID_READ_BYTE`), and the shim does not call `emulator_read_mem` for them.
- **Unchanged**: the artifact is still 65,536 bytes in address order,
`application/octet-stream`, with an optional digest. `gameboy-memory-inspection-v1` is
therefore unchanged, and so are its schema digest and the contract digest.
- **Why no task or executor loses anything**: none of them reads a register window. The Pokémon
adapter, scene detector and macro engine read WRAM, HRAM and ROM only. MEM-01's equivalence
harness (flysim `tests/rom_memory_image.rs`) counts every address the image-backed arm reads
over 27,000 frames from nine checkpoints and finds no read outside the captured ranges. A future
task that needs a register must amend this section first. A register cannot be captured
read-only through this shim.
The shim function is `fly_gb_read_memory_image(gb, out, 65536)`, and in Rust it is
`Emulator::read_memory_image{,_into}`. The executor's reader is `flybrain_gb::ImageReader`,
which pairs a `MemoryImage` with a `Cartridge`. `Cartridge::verified` refuses a ROM whose SHA-256
is not the environment's `contentDigest`. The emulator answers its own bank reads through the same
`Cartridge::read_bank`.
## 9. Environment ## 9. Environment
- **Initialize.** The backend configuration declares a setup scaffold of **one frame with no - **Initialize.** The backend configuration declares a setup scaffold of **one frame with no
@ -214,6 +248,22 @@ interface GameboyMemoryInspection {
FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary FLYSIM01's `ratchet_game` and `ratchet_frame` are today. A slot save due at a boundary
completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16). completes before any `State.Capture` or FLYSIM01 export at that boundary (section 16).
**Amendment, 2026-09-29 (ENV-01).** Two consequences of building this section, recorded in the
[implementation guide](implementation.md) ENV-01 entry: ~~the memory image cannot be taken with a
plain loop of `emulator_read_mem`, because reading OAM, VRAM, the serial and timer registers,
`IF`, `STAT` or `LY` advances binjgb's lazy synchronisation and changes what `export_state` writes
-- the environment reads it between an export and an import of the same bytes, so slots and
captures stay byte for byte the legacy loop's;~~ and a `FLYSIM01` world is restored at boundary
`emulatorFrame - 1`, its world time and audio position derived from that boundary, with the
ratchet's snapshot as the slot `best`.
*Struck 2026-09-29 (ENV-01 review, R1).* The first consequence is superseded by section 8's MEM-01
amendment of the same day: the register windows are not captured and read `$FF`, so the image is
MEM-01's one bulk read with no export/import guard around it, read-only by construction
(`legacy_env::memory_image`). With it the service's traces still reproduce every frame, WRAM and
slot-state digest (rollback 3,199, climb 3,156, r58 11,043 transitions), because the legacy
adapter and macros never read VRAM, OAM or I/O.
## 10. Executor `pokered-macros-v1` ## 10. Executor `pokered-macros-v1`
The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the The Pokémon Red task (reward adapter, ladder, ratchet ledger) and its action executor (the
@ -238,6 +288,37 @@ signal. The object serves exactly one agent on one port.
- **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world - **Cancel.** `cancel(ms)` abandons a running macro. It is followed by `observe` on the world
the fly now stands in. the fly now stands in.
**Amendment, 2026-09-29 (TASK-01).** Choices the section above leaves open, fixed as built by
`fly-legacy-session::task`:
- *The ratchet's slot.* The ratchet ledger stays in the task. Its snapshot lives in the environment
as the slot `best`. The ratchet only asks whether one exists: its budget test is "no snapshot".
So the task holds a marker snapshot in its place, and a task ledger records `slotFilled`. A slot
save is asked for exactly when the legacy capture closure runs: safe, and rank above best.
- *The task ledger is artifact-backed* (amended 2026-09-29, TASK-01 review B1). The adapter's
lifetime ledger grows with play: it is 42-46 KB on the live fly at rungs 12-15, which is past
the 32 KiB `TypedValue` bound. So the typed ledger is `{reward: {digest, byteLength}, ratchet,
slotFilled}`, and the adapter state's JSON travels as the ledger attachment `reward`. A
checkpoint files it as the payload `task-ledger-reward` ([workers-v1](workers-v1.md) section 1's
explicit artifact-backed schema; `Task::capture_attachments`). A missing, altered or unreadable
attachment is `INCOMPATIBLE_STATE`, never a panic, so a boot falls to the next candidate.
- *The palette seed* (amended 2026-09-29, TASK-01 review N3). The legacy loop seeds the palette
from the brain's RNG state after boot. A restore does the same: it seeds with the restored
agent state's RNG, which it holds. A fresh start cannot see the agent's RNG after the warm-up,
so it uses a constant. That is exact because `MacroMachine` never reads its generator: no macro
has a random step. `fly-legacy-session` `tests/palette_seed.rs` holds this on the cartridge:
two seeds, driven by the same decisions, press the same buttons for 3000 frames. A future
macro that draws from the generator fails there.
- *The clock of the first observation.* A fresh start's layer observes O[0] at the end of the
warm-up, `warmupMs` = 2500 ms, which the profile pins. That is the same time the legacy loop's
`Sim::boot` observes at, although the agent is initialized after the task bootstraps. After a
restore the layer observes at the restored brain time.
- *A reward event with `stimulation_ms` = 0* is one `Reward` and no `Stimulus`, because
`Stimulus.durationMs` is positive. The legacy `stimulate(0)` changes nothing.
- *Executor events.* Macro starts and finishes are not `executionEvents`. They are reported as
`FLY_TRACE` `macroEvents` (phases `execute`, `evaluate`, `rollback`). Reward events are the
task's `TaskEvent`s.
## 11. Episode policy `legacy-ratchet-rollback-v1` ## 11. Episode policy `legacy-ratchet-rollback-v1`
The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during The ratchet's game-only rollback is a declared episode policy. When the ratchet fires during
@ -281,6 +362,14 @@ the adapter's persistent state. The first audio chunk after the rollback marks a
discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent. discontinuity. This is the legacy `recover_game` sequence with the neural half moved into the agent.
Each half touches only its own state, so the order between the halves does not matter. Each half touches only its own state, so the order between the halves does not matter.
**Amendment, 2026-09-29 (TASK-01).** The coordinator applies the policy itself, as the section
describes. The phase is `RollingBack(k)`. The new epoch is the session's epoch root plus `.rb<n>`,
which is deterministic, so two runs of one session name the same epochs. A composition that
declares the policy refuses to start unless every agent advertises `legacy-ratchet-rollback-v1`.
The task's rollback request carries `{slotId: best, trigger}`. The world must advertise
`gameboy-slots-v1` before anything is saved or restored. Service traces with a ratchet slot save
and a ratchet rollback reproduce as described in the implementation guide's TASK-01 entry.
## 12. Composition declaration and digest ## 12. Composition declaration and digest
```ts ```ts
@ -326,6 +415,120 @@ interface LegacyGameboyComposition {
for publication, traces and descriptor revisions, not a restore gate. This matches today's for publication, traces and descriptor revisions, not a restore gate. This matches today's
behaviour, where a decoder change does not refuse a checkpoint. behaviour, where a decoder change does not refuse a checkpoint.
**Amendment, 2026-09-30 (PERF-01): the in-process release configuration.** Nothing in the
declaration, the digest or the compatibility string changes; these are execution choices of the
composition as `fly-legacy-session` builds it, recorded here because the shadow compares the
behaviour they must not change.
- *In-process participants are called over the local lane* ([session RPCs](ipc-v1.md) section 1,
2026-09-30): the frame, the memory image, the audio chunk and the spike bitset are in-memory
artifacts, handed over without a store file. Process mode is unchanged and still goes through
the router. `FLY_SESSION_LOCAL_LANE=0` puts an in-process session back on the bus.
- *`telemetry.spikes` is unchanged*: one bitset per transition, bit `i` set when neuron `i`
spiked in `[transition start, brain time)`, the legacy layout. The agent now builds it as the
union of the kernel's per-tick spike lists while Prepare ticks (`LifNetwork::tick_spikes`)
instead of scanning 139,255 last-spike times in Commit; the two are equal by construction and
by test, and the parity runs compare the bitset every frame. The AGENT-01 alternative -- attach
it only at the feed rate -- was not needed and was not made.
- *Committed snapshots on the session topic*: a service session publishes every 60th boundary and
every boundary with task events or boundary actions (it was every other boundary). The live
presentation is the legacy feed, which the service host builds from the committed boundary at
30 Hz; nothing in the release subscribes to the session topic, and each publication seals a
store copy of the frame and the audio chunk. Every publication is still of a committed
boundary and still attaches the media it names (publishing-v1 section 3).
- *Nothing runs beside the brain's ticks.* On the release CPU with the sweep owning every core of
the flysim cpuset, work overlapping Prepare (a publication left in flight, for instance) slowed
the ticks by up to a third, so the coordinator finishes each boundary before the next Prepare.
**Amendment, 2026-10-01 (PERF-02): thread placement in the service.** Again nothing in the
declaration, the digest or the compatibility string changes, and no result can: placement chooses
the CPU a thread runs on, never what an index of a parallel phase computes.
- `flysim-session` (in-process and thread modes), before it spawns any thread, gives each of the
`RAYON_NUM_THREADS - 1` spawned sweep workers one CPU of the unit's cpuset to itself and confines
every other thread -- the dispatching runtime worker, the coordinator, the listeners, the
checkpoint writer -- to the rest (the first CPU, plus any beyond the sweep's). Process mode and
the legacy loop are unchanged. `FLY_SESSION_PIN=0` keeps every thread floating, as before. The infra keeps other processes off the pinned CPUs (`flysim.slice`, `fly-cpu-confine`) and sets it to `0` where it cannot.
- Why: the session's host threads sleep and wake around every transition, so the sweep workers
park and wake every transition too, and the scheduler often woke two of them onto one CPU while
a host thread held another: each parallel phase of that transition then took two shares' time.
On the release CPU model with a four-CPU cpuset the session's ticks ran 35% slower than the
legacy loop's, which is what failed CUT-01's speed probation (0.959 < 0.97); placed, they cost
what the legacy loop's do.
**Amendment, 2026-10-01 (BUS-01): the composition on the router.** The operator's direction of
2026-10-01: run the live session's participants over the flybus router on Unix sockets, one
emulator and one fly today, because multiplayer and more flies follow. Nothing in the declaration,
the digest or the compatibility string changes, and no result can: the bus carries the same
domain calls, in the same order, to the same endpoints as the local lane. Traces, checkpoints and
the FAFB parity runs are identical in every arm (`local`, `bus/thread`, `bus/process`;
`fly_legacy_session::composition::SessionArm`).
*Selecting it.* `FLY_SESSION_TRANSPORT=bus` (or `flysim-session --transport bus`) puts every
participant on the router's sockets; `FLY_SESSION_MODE` then defaults to `process`, and `thread` and
`in-process` are also allowed (`in-process` on the bus is every participant a socket client from
the coordinator's own runtime). `local`, the default, is the PERF-01 lane and stays the release
configuration until a cutover onto the bus. `local` with a thread or a process is refused: those
have no lane. On the container, `fly-runtime session --bus` (`session-bus`) writes
`Environment=FLY_SESSION_TRANSPORT=bus` into the runtime drop-in, and `session --local` takes it out.
*The topology (process mode, the bus default).*
| Process | Runs | Bus client | Reached by |
| --- | --- | --- | --- |
| `flysim-session` (the unit's main process) | the router (one per session), the launcher's supervisor, the coordinator with the `pokered-macros-v1` task and executor, the service host (feed, control API, metrics, checkpoint writer, sugar journal) | `coordinator`, `launcher` | in memory: they live with the router |
| `fly-session legacy-agent` (child) | AGENT-01: the brain, its readout and its sweep pool | `legacy-fly`, registers `agent.fly` | `<session dir>/attempt-N/sockets/legacy-fly-<n>.sock`, launcher-bound |
| `fly-session legacy-environment` (child) | ENV-01: binjgb, the slot, the memory image | `legacy-world`, then `legacy-world-r2` for the restore's replacement world; registers `env.world` | `.../sockets/legacy-world[-r2]-<n>.sock`, launcher-bound |
- *Policy* (closed, `composition.rs`): the coordinator may call `agent.*` and `env.*` and owns
`session.*` (publish, topics, its query service); the supervisor may call `agent.*` and `env.*`
and register nothing; each participant may register exactly its own service and call nothing.
An identity is bound by the launcher before Hello, so a process cannot answer as another.
- *Media* stay artifacts in the router's store (`<session dir>/attempt-N/store`, tmpfs, `fly`
0700): the 92,160-byte frame, the 65,536-byte memory image, the audio chunk (about 6.4 KB a frame
of `f32le`) and the 17,407-byte spike bitset every transition, and the captures (MBs, every hot
save). Inline is not an option: bus-v1 section 8.1 forbids binary in a body, and the image alone
would not fit the 64 KiB envelope once encoded. A delivery names each attachment's read location
(bus-v1 section 12, 2026-10-01), so a read is a local file read; a worker seals into writers it
allocated after the previous step (`worker::WriterPool`). Over the bus the agent's Commit also
attaches its feed status (`legacy.feed-status`, the `Legacy.FeedStatus` result's bytes as of the
committed boundary), which the service host reads instead of making that call at every publish;
a rollback after the Commit makes it ask again.
- *One unit, restarted as a whole.* The session cannot survive the loss of a participant: its
state is split across them and is recovered only as a group (STATE-01), and the store's last save
is that group. So the children belong to `flysim.service` (the launcher spawns them; systemd's
default `KillMode=control-group` reaps them with the unit), a dead participant fails the step
within `ipc-v1` section 6's ten seconds, `flysim-session` exits, and `Restart=always` starts the
whole session again from the store -- what a crash of the in-process session does today. A
child also exits when its router connection closes. The router lives in the coordinator's
process for the same reason: its loss is the session's. One unit keeps `fly-runtime`'s one
drop-in switch, the `OnFailure=` fallback to legacy (three starts in ten minutes), the speed
probation, the watchdog and the unstick rule's restart unchanged; separate units would need
`BindsTo=` chains and three start limits for no recovery a group restore does not already give.
- *CPUs.* The unit's cpuset is unchanged (on the release container `flysim.slice`'s four CPUs).
The service splits it as PERF-02 does and hands the split out: the agent process pins its spawned
sweep workers one per CPU and keeps its other threads (its dispatcher is sweep worker 0) on the
remaining CPU (`fly-session ... --sweep-cpus 3,5,7 --host-cpus 1`); the service process and the
world process run on that same host CPU. The transaction is serial -- nothing overlaps Prepare
(PERF-01) -- so they take turns on it rather than contend. `FLY_SESSION_AUX_CPUS` moves the
service and the world elsewhere in the unit's cpuset; it was measured and does not pay
(implementation guide, BUS-01). `FLY_SESSION_PIN=0` floats everything, as before.
- *Each participant process has one async worker, and a long handler gives it up*
(`tokio::task::block_in_place` for `*.Initialize`, `State.*`, `Agent.Rollback`): the agent's
warm-up runs for seconds, and a Tokio worker blocked that long stranded the shell's own bus loop,
so `ipc-v1` section 6's resolution of a slow `Agent.Initialize` failed ("never resolved") and a
session could not boot on a loaded box. A step's handlers (milliseconds) run in place, so a bus
request crosses no thread inside a participant. The local lane is unchanged.
*N agents and M environments are configuration.* Nothing above assumes one of each: the
launcher starts any number of `LegacyAgentLaunch` and environment launches, each with its own
client id, service name and socket; the policy grants are per client; placements are per worker
id (`Launcher::place_process`), so each agent process pins its own sweep to its own CPUs; the
coordinator calls agents concurrently and assembles one batch over every declared port; the router
has no notion of a fly. What is one-of-each today is this composition (`LegacyConfig`, one
`PokeredTask`, `FLYSIM01`'s one agent and one world) and the service's CPU split (one agent's
plan), which a multi-agent composition replaces rather than extends.
## 13. Machine-readable parts ## 13. Machine-readable parts
| Where | What | | Where | What |
@ -351,6 +554,79 @@ stale files.
valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The valid `Id`s, while `AgentGraph.rateRoles` and `AgentTelemetry.rates[].roleId` are `Id`s. The
mapping belongs to the agent adapter. This contract does not choose it. mapping belongs to the agent adapter. This contract does not choose it.
**Amendment, 2026-09-23 (AGENT-01): the rate-role mapping `legacy-rate-role-id-v1`.** The
premise above is wrong. The session `Id` grammar is `^[a-z0-9][a-z0-9._-]{0,63}$`
([session RPC](ipc-v1.md) section 1, `flybus::wire::is_id`, `isId` in `@flybrain/session-types`),
and it admits `_`. Every role `data/fafb-v783` declares, including the 31 `macro_*` populations
merged after the fingerprint, and every role the kernel tracks, is already an `Id`; so is every
`ChannelName`, whose grammar is a subset. The mapping is therefore the identity:
- a legacy rate-role name `n` is published as `roleId = n` when `n` is an `Id`, and a `roleId`
names the rate role of the same spelling. The mapping is reversible by construction;
- a name that is not an `Id` has no `roleId`. The agent refuses to initialize over a dataset
that tracks one (`INCOMPATIBLE_STATE`), rather than invent an encoding no consumer could read
back. No shipped dataset has one;
- the published list keeps the kernel's tracked-role order and its bounds: at most 64
(`MAX_RATE_ROLES`, the kernel's role bitmask) and unique. On `fafb-v783` it is 45 roles.
`gameboy::rate_role_id`, `rate_role_name` and `rate_role_ids` in `fly-session-types`, and
`rateRoleId`, `rateRoleName` and `rateRoleIds` in `@flybrain/session-types`, implement it.
`fixtures/gameboy-rate-roles.json` holds both languages to the same accepted and refused names and
records the FAFB tracked list, which `fly-session`'s gated FAFB test recomputes from the
committed dataset. The mapping changes no schema, digest or fixture digest.
**Amendment, 2026-09-23 (AGENT-01): what the legacy agent reports and captures.** These are
agent-adapter choices that the sections above leave open. `LegacyAgentWorker`
(`fly-session/src/legacy_agent.rs`) implements them:
- *Seed.* The kernel version `lif-1ms-f64-v2` hashes the LIF seed. Every seed except the legacy
default `22222` gives a different kernel version, so the profile pins the seed.
`Agent.Initialize` refuses any other seed (`INCOMPATIBLE_STATE`) before it builds a model. The
coordinator of this composition passes `22222`. It does not use a seed derived under
[seed-derivation-v1](seed-derivation-v1.md).
- *Learning telemetry.* `AgentTelemetry.learning` requires `changed <= updates`. The legacy
counters mean something else, so they map as follows. `updates` is the number of reinforcement
calls the agent has applied: one per commit while the rule is enabled, zero sums included.
`changed` is the legacy `plasticity.updates`: the reinforcements that moved at least one gain.
`signal` is `plasticity.signal`. The legacy per-synapse count (`LearningStats.changed`, the
gains away from 1.0) is not carried. It can still be read from a captured state.
`stimulusRemainingMs` is the network's `reward_remaining` after the operation.
*Amended 2026-09-29 (AGENT-01 rebase):* `FLYSIM01` records `plasticity.updates` but not the
reinforcement calls. An agent imported from a `FLYSIM01` agent state therefore starts
`updates` at that state's `plasticity.updates`, which is a lower bound on the calls made. Starting
it at zero makes the first telemetry violate `changed <= updates`: on the live fly `changed` is
in the thousands. `legacy_parity::legacy_reinforcements` is the rule. The import that ENV-01
or STATE-01 ships must apply it.
- *Spikes.* Each `Agent.Commit` reply carries the attachment `telemetry.spikes`, with content type
`application/x-fly-spike-bitset`. It uses the legacy feed's layout: bit *i* is neuron *i*,
`ceil(neurons/8)` bytes. It covers the transition's ticks: a neuron is set when its last spike
is at or after the brain time before that transition's Prepare ticked. The mapping of bit
*i* is the graph's `indexDigest`.
- *Graph.* `datasetDigest` is the SHA-256 of the schema-1 fingerprint string. `indexDigest` is the
SHA-256 of `fly-session/legacy-agent-index-v1`, the fingerprint, the neuron count and every
`macro_*` population's members. The macro populations are the profile's declared
`macro-roles-outside-fingerprint` exception. Two datasets that relabel them differently
therefore get the same fingerprint and different index digests.
- *Initialize.* The readout transient starts as it does in a fresh legacy process: no held
channel, no last location, and a blocked window from 0 ms. `initialDecisionContext.location`
is **not** taken as the last location. The legacy loop reads a location only at the end of a
frame, so the window first restarts on it at the first commit, as it does in the legacy loop.
- *Capture.* The `State.Capture` payload is a `flybrain-core` checkpoint envelope with magic
`FLYAGT01`. Its manifest and chunks are exactly `agent_to_chunks`, with the frame remainder
taken from the session accumulator, as `Sim::checkpoint` does. It adds one `session` member: the
accumulator, the context, the profile, the seed, the reinforcement count, the macro channels
and the decoder configuration digest. It does not carry the readout transient (section 14). It
is not FLYSIM01. Writing a FLYSIM01 export from it and from the environment's state is still
STATE-01/ENV-01 work (section 16).
- *Restore.* `State.StageRestore` builds a replacement network over the same dataset, imports
the state and refuses any mismatch between the state's clock and the accumulator.
`ActivateRestore` then installs the state and resets the readout transient, as a fresh legacy
process does. The visual drive is the restored `visualDrive` chunk. Legacy `try_restore`
instead re-projects the saved framebuffer, and the two are the same values (the parity
harness compares the full state after a restore).
- *Decision.* `macro` is the first channel in the context's `bound` order that the decode holds.
This is the channel the legacy macro layer's `asked` would start.
## 14. Restore `legacy-transient-reset` ## 14. Restore `legacy-transient-reset`
The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore The legacy composition declares that a restore (a FLYSIM01 load today, and any group restore
@ -377,6 +653,27 @@ Resume tests compare against the legacy restore outcome, not against an uninterr
unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps unstick procedure depends on: restarting the service clears the ledger-shaped traps and keeps
the rung. the rung.
**Amendment, 2026-09-29 (TASK-01): a FLYSIM01 checkpoint as the start.** A new-runtime session
starts from the live fly's own save through the ordinary group restore
(`Coordinator::import`, `fly-legacy-session::import`):
- The world is ENV-01's `WorldState::from_flysim01` at `k = emulatorFrame - 1`, staged on a
replacement world.
- The agent is the checkpoint's agent state in the worker's own capture format: STATE-02's
`legacy_checkpoint::agent_payload`. It carries the file's reinforcement count and the file's
framebuffer as the next input, and its ids come from the file.
- The task is STATE-02's ledger `{reward, ratchet, slotFilled}`.
A session boots from the live stores the way `Sim::boot` does: the legacy candidate order, the
legacy gate, the next candidate on any refusal, then a startup durable save. See the
implementation guide's TASK-01 entry.
This section's resets then apply, and nothing else. The executor is fresh and observes the restored
image once, at the restored brain time. The agent's readout transient is a fresh process's. The
decision context is computed from the checkpoint's memory image before the install, and the
coordinator refuses the install if the task, re-observing the restored world, derives another
context.
## 15. Sugar admission ## 15. Sugar admission
The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap The coordinator owns admission, with the legacy rules: the per-minute limiter, and "no overlap
@ -400,6 +697,29 @@ applies it never commits, the admission is reported aborted and the edge refunds
bridge's fulfil path and refund path both get tests in the slice that wires them bridge's fulfil path and refund path both get tests in the slice that wires them
([workers-v1](workers-v1.md) section 5 amendment). ([workers-v1](workers-v1.md) section 5 amendment).
**Amendment, 2026-09-29 (TASK-01).** As built:
- *Admission.* The coordinator's `AdmissionQueue` is cut at the top of each Prepare. It reports
every admission `applied` at the boundary its Prepare committed at, or `aborted` when the epoch
fails first. The legacy rules run on the edge side, unchanged: flysim's `RateLimiter` and the
clamp. They read `stimulusRemainingMs` from the last `Agent.Commit` or `Agent.Rollback` reply.
After a restore the pulse is unknown and a request is refused with a retry of one frame.
*Amended 2026-09-29 (TASK-01 review N1):* a sugar admitted but not yet reported on by a commit
counts as an active pulse, at its full duration (`AdmissionQueue::pending_stimulus_ms`). The
legacy `stimulate` activates the pulse the moment it admits, so this matches:
- two sugars between two commits get one admission and one `PulseActive`, as the legacy drain
gives them;
- the rate-limit slot is not spent on the refused one.
The retry advice may differ by less than a frame. Legacy reports the pulse decayed by the
ticks between drains; here it is undecayed until the commit reports it.
- *The operator's `POST /reward` pulse is refused (declared).* In the legacy loop it is off unless
an operator sets `control.allow_reward`. Every shipped configuration leaves it off, and the API
answers 403. The session runtime has no counterpart to turn on, because a reinforcement outside
`Agent.Commit` is not a session-framework operation. `LegacyAdmission::reward` therefore always
refuses. A legacy trace that carries a reward pulse cannot be reproduced; FND-01's checker
refuses one as well.
## 16. Checkpoint format of record ## 16. Checkpoint format of record
**Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)` **Order at a boundary (amended 2026-09-23, review round 1).** A slot save due at `Ready(k)`
@ -428,6 +748,45 @@ current `flysim` reads, under the unchanged compatibility string. The deploy gat
checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01 checkpoint may be written beside it, but it is not what a restore selects until RETIRE-01
says so. says so.
**Amendment, 2026-09-29 (STATE-02).** Six readings of this section, fixed by building it
([implementation guide](implementation.md) STATE-02):
- *"A FLYSIM01 envelope that the current `flysim` reads" means the same bytes.* The session
runtime writes through the legacy loop's own encoder and store, which now live in the crate
`flysim-store` that both link. For the same state it writes the same bytes, and it keeps the
same generations, `manifest.json`, `milestone-<N>` archives, rotation and restore order. The
owners of the fields are: the agent (the seven agent chunks, the remainder), the environment
(`emulator`, `framebuffer`, `emulatorFrame`, `buttons`, `romHash`, and slot `best` as
`ratchetGame` and `ratchetFrame`), the task (`reward`, `ratchet`) and the host (`generation`,
`wallMs`, `compatibility`, `speed`, `rankSinceMs`, `lastEventId`); the agent's reinforcement
count, `reinforcements`, is new (below).
- *The milestone archive is per process, as in the legacy loop.* A rank climb is archived when
the rank is above every rank *this process* has archived. After a restart, the first climb
rewrites `milestone-<rank>` even if an older process had archived that rank. That is the
legacy behaviour, and the reset tools rely on the newest archive of a rung.
- *A restore is the legacy restore, candidate for candidate.* The candidate order is hot latest,
hot previous, durable latest, durable previous, then the archives by descending rank. The gate
is the cartridge and the compatibility decision. A refusal at any step, including a
participant's `State.StageRestore`, moves to the next candidate. If every candidate fails, the
runtime does not start. The world applies the recorded `buttons` on restore, as
`LegacyFrame::restore` does, so a file whose emulator state disagrees with its own `buttons`
restores to the same state in both runtimes, not to the file's bytes.
- *The visual drive after a `FLYSIM01` import is the framebuffer's projection* (a correction to
section 13's *Restore*, "the two are the same values"). They are the same on stream
checkpoints. On the row 65 yard survey checkpoint they are not: the first transition's rates
and spikes differed from the legacy loop's. The import therefore carries the framebuffer in
the agent payload (chunk `inputFrame`), and `State.StageRestore` installs it after the import,
as `LegacyFrame::restore` does. A worker's own capture carries no such chunk and restores
exactly.
- *`learning.updates` is carried in `FLYSIM01`.* This corrects section 13's *Learning telemetry*
amendment, which started every import at `plasticity.updates` and so dropped the count on
every round trip. Both runtimes count reinforcement calls the same way and write the count
as the optional manifest member `reinforcements`. A file without it (every file from before
2026-09-29) starts at `plasticity.updates` once.
- *The sugar journal is the shadow run's input record.* It gets a per-process boot header, is
rotated at 4 MiB with three kept files, and `fly-reset-to-milestone` clears it
(`flysim-store::journal`). It is not a checkpoint and nothing restores from it.
## 17. PROF-02b: MaleCNS bundles (later) ## 17. PROF-02b: MaleCNS bundles (later)
Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict Dataset manifests, original-ID mapping, anatomical roles, sensory and readout bindings, strict
@ -435,3 +794,247 @@ graph validation for new bundles, and the composite behaviour identity of FOUNDA
**not** in this document. They ship with PROF-02b, before DATA-01, as their own contract. **not** in this document. They ship with PROF-02b, before DATA-01, as their own contract.
Nothing here constrains them, except that a new profile never reuses this profile's id or its Nothing here constrains them, except that a new profile never reuses this profile's id or its
legacy exception. legacy exception.
## 18. The shadow run (SHADOW-01)
**Amendment, 2026-09-29 (SHADOW-01).** The operator's decision of 2026-09-23 gates the automatic
cutover (CUT-01) on "a 3-hour shadow run with zero divergence". This section fixes what that
means. The implementation is `fly-legacy-session::shadow` and the binary `fly-shadow`, with the unit
`infra/units/flyshadow.service` and the script `infra/bin/fly-shadow-run`.
**The inputs.** The legacy loop is deterministic, given two things: the state a process starts
from and the admissions applied at the top of each frame. Every nondeterministic input reaches
the fly through one of those two:
| Input | How it reaches the fly | How the shadow gets it |
| --- | --- | --- |
| Restart, watchdog kill, `fly-loop-recover`, `fly-reset-to-milestone`, deploy | A new process restores a checkpoint (section 14), or warms up a fresh fly, and writes a durable startup save of the state it starts from | The trace's start line names that save (`g<N>`); the shadow boots a new session from it through the ordinary FLYSIM01 import |
| Sugar (`POST /stimulate`) | Admitted on wall time and the live pulse (rate limiter, "no overlap"), applied at the top of a frame | The transition's `admissions`, replayed into the admission queue (`LegacyAdmission::replay_sugar`) |
| Operator reward pulse (`POST /reward`) | Off in every shipped configuration (403) | Cannot be reproduced (section 15 amendment): the rest of that segment is reported uncompared |
| Wall time | Pacing, publish rate, checkpoint intervals, pause (no frame runs). None changes a transition | Not needed. The trace records which saves were taken where |
| Chat | A caption track; it reaches nothing the fly does | Not needed |
| Threads | The sweep's result does not depend on the thread count (AGENT-01) | The shadow picks its own |
So "the same inputs" means *the same start state per process and the same admissions per
transition*. Admission itself is not compared. The session runtime decides admission against a
pulse one commit stale, by the operator's decision (section 15). A shadow that re-decided sugar on
its own clock would diverge by design, not by fault.
**The architecture: the legacy fly stays primary, and the shadow follows its trace.** The live
service writes `FLY_TRACE` (FND-01) with three switches added for the shadow. None changes a
behaviour field or anything the fly does:
- `FLY_TRACE_DIR` writes one file per process, `trace-<start wall ms>-<pid>.jsonl`.
- `FLY_TRACE_MAX_BYTES` caps each file (4 GiB by default in directory mode).
- `FLY_TRACE_LEDGERS=<n>` adds `ledgersDigest` every *n* transitions. This is the SHA-256 of
`flysim::frame::ledgers_string` after the boundary: adapter export, ratchet, slot, and the
executor's scene, bound set, running macro, counts and "nearer".
`fly-shadow` follows the files in start order. For each file it takes these steps:
1. It boots a session (agent, world, task and executor, as in TASK-01) from that process's startup
save. A fresh start is different: the stores were empty and the startup save is at boundary 0.
In that case the shadow runs the same power-on scaffold and warm-up
(`Environment.Initialize`, `Agent.Initialize`), and holds the startup save to its own
boundary 0, byte for byte. An import would not give the same emulator. binjgb's audio
resampler phase is not in its exported state, so the channel accumulators of an imported
emulator drift from those of a powered-on one, in the exported state only. Both restores of a
restart import, so they agree.
2. For every transition, it replays the admissions and runs `Coordinator::step`. It takes a
capture wherever the live trace records one, before or after the boundary's rollback as the
live loop took it, then applies the deferred rollback.
3. It builds its own trace line from what crossed the session's boundaries (`trace::line`) and
compares it with the live line, field by field.
A spool thread copies every new store generation as it appears, because a hot file lives only
about ten seconds. The shadow never writes to the live stores.
The reverse arrangement was considered: the session runtime as primary, with legacy as the
checker. It would make the shadow run the cutover itself, and a divergence would already be on
the stream. A second legacy process in lockstep was also considered. It adds nothing, because the
live process's own trace *is* the legacy behaviour.
**What is compared, per boundary.**
- *The trace line*, every transition. The fields are `step`, `admissions`, `ticksAdvanced`,
`brainTicks`, `remainder`, `ratesDigest`, `spikesDigest`, `spikeCount`, `decision`, `mask`,
`macroEvents`, `framebufferDigest`, `wramDigest`, `rewards`, `rank`, `acknowledgedBoundary`
and `boundaryActions`. `boundaryActions` covers the slot saves with their state digests and
the rollbacks.
- *The ledgers*: `ledgersDigest` on the transitions that carry it. The shadow digests the same
string from its own task (`task::ledgers_of` is `ledgers_string`). This covers the executor's
ledgers, which no checkpoint carries.
- *The checkpoint bytes*, at every live save the spool still holds. The shadow captures the same
boundary and exports FLYSIM01 through the shared encoder (STATE-02). It compares the export
byte for byte with the live file after the substitutions named below. `compatibility`,
`speed` and `rankSinceMs` are the shadow's own, so they are compared too.
**Declared differences**, excluded by name. The verdict lists the same names.
| Name | What is excluded |
| --- | --- |
| `archive-order` | A legacy milestone archive taken before that boundary's slot save (`afterActions` 0 ahead of a `save-slot`, sections 4 and 16) holds the pre-capture ratchet and slot. The live file's `ratchet`, `ratchetGame` and `ratchetFrame` stand in for the shadow's in that capture only. The operator accepted this on 2026-09-23 ("Archive order") |
| `decision-list-order` | The decision is compared as `gameboy-channels-v1` sees it (section 6, `trace::channels`) |
| `host-fields` | `generation`, `wallMs` and `lastEventId` are the live file's. They are host bookkeeping: the shadow keeps no feed event log (SERVE-01's service host keeps its own) and allocates no generations, because it writes no store |
| `admission-replay` | Sugar is replayed, not re-decided (above) |
| `operator-reward-pulse` | A segment with one is reported uncompared from that transition on |
**The window.** The verdict is `pass` once the compared transitions add up to **10,800 s of
live brain time** (the sum of `ticksAdvanced`, 3 h at real time) with zero divergence, and at least
one live save per 600 of those brain seconds has been compared byte for byte. That time may span
several processes.
*Skips* are only the live side's own events (`SKIP_KINDS`):
- `startup-save-gone`: a process whose startup save was already gone when the shadow reached it,
because the shadow started late or its spool evicted the file;
- `operator-reward-pulse`;
- `no-transition`: a process that ran none.
A skip adds nothing to the window. A trace the shadow cannot read is `trace-malformed`, which
refuses the cutover. A process killed hard loses its unflushed tail, and those transitions are
not compared.
The first difference of any kind stops the shadow with `diverged` (exit status 3) and writes
`divergence.json` with the 30 transition pairs before it. The same applies to every session-side
failure, which is **never** a skip:
- a trace field;
- the ledgers;
- the checkpoint bytes;
- a session that does not start;
- a startup save the candidate's restore gate refuses or the session runtime cannot restore;
- a step, capture or rollback error;
- a transition the session did not record;
- *coverage*: a live flysim process that booted while the shadow ran and left no trace
(amended 2026-09-30).
The shadow reads every boot header in the live sugar journal. Every flysim process writes one,
traced or not. It holds each header to a trace file created after the previous boot and before
this one. A process that ran untraced can never be compared, so the verdict fails. It does not
pass on the processes that were traced.
A shadow that keeps running after `pass` turns the verdict to `diverged` on a later difference.
**The live fly never pays for the shadow (amended by the SHADOW-01 review).** Three mechanisms
make sure of it:
- *The trace is on only while a shadow consumes it.* The shadow writes a heartbeat
(`<trace dir>/consumer`) every 30 s and removes it when it stops. flysim starts no trace without
a fresh heartbeat, stops a running one within a minute of frames once the heartbeat is more than
10 minutes old, and keeps the directory under 8 GiB. A heartbeat dated ahead of flysim's clock
counts as fresh. A trace flysim cannot create (a full disk, the directory's permissions) never
stops the live fly from starting: that process runs untraced, and the shadow reports it as a
coverage divergence.
- *The guard* (`fly-shadow-run guard`, every 60 s, root) judges the live fly against its own pace
before the shadow existed. The live fly does not always keep real time: the release container
has run at a realtime factor of 0.66, and at 0.77-0.99 after its cpuset rebalance. So `start`
first measures a 10-minute baseline over sixty 10-s `fly_realtime_factor` means. It records
their median and their spread (1.4826 x MAD), so a step in the window cannot set or widen it,
and the `fly_lag_seconds` growth rate over the most recent half. The guard trips only on a *sustained* degradation against
that baseline: 3 checks in a row in which the last 5 samples of the same process fall below the
baseline realtime factor, or grow lag faster than the baseline rate, by more than
max(0.05, 4 x spread / sqrt 5). A trip stops everything and restarts flysim without the trace.
The guard stops itself when the shadow is not running. `lint.sh` holds the rule to the release
container's profiles, synthesized, and to four traces recorded from a real flysim with and
without a real shadow (`infra/tests/fixtures/shadow-guard`). In 800 synthetic 3-hour runs it
found no false trip, and it caught all 400 degradations.
- *The shadow* runs at `SCHED_IDLE` off flysim's CPUs. It pauses for a minute while the live lag
grows faster than the baseline rate. When a pause does not help, the shadow is not the cause,
and it stops pausing for 10 minutes.
**The verdict contract (for CUT-01).** The shadow writes `verdict.json` in the format
`fly-shadow-verdict-v1` (`shadow::verdict`, whose module notes list the fields). CUT-01 cuts over
automatically only if all of the following hold when it reads the file, at the moment of cutting
over:
- `status` is `pass` and `firstDivergence` is `null`;
- `compared.brainSeconds` ≥ `required.brainSeconds`, and never less than the operator's 10,800 s,
whatever window the shadow was run with;
- *Saves were compared.* At least one per 600 brain seconds was compared byte for byte, and at
most 10 % of those the trace named were unavailable.
- *The release.* `candidate.release` is the directory `/opt/fly/current` resolves to now. Every
binary in `candidate.binaries` still has its recorded SHA-256 there. The binary switched to,
`flysim-session` (SERVE-01's service), is one of them.
- `candidate.compatibility` is the live `--print-compatibility`;
- every `skipped` entry is one of the live side's own kinds;
- *the shadow is alive and caught up*: `updatedAt` is at most 5 minutes old and
`lagTransitions` is at most 3,600, counted at every write (paused or not) over the rest of the
current file and every newer one;
- (`fly-shadow-run check`) the guard has not tripped and `flyshadow.service` is running.
`fly-shadow check` (and `fly-shadow-run check`) implements exactly this rule and exits 0 only when
it holds. Anything else keeps the legacy fly. The one-command rollback `fly-runtime legacy` is
CUT-01's.
**Amendment, 2026-09-30 (SHADOW-02): the shadow runs on a build box.** On the release container
the shadow cost the live fly real time: SCHED_IDLE on the page and encoder CPUs, sharing them with
the encoder and the browser and the memory bandwidth of flysim's NUMA node, it took about 27 ms a
frame, fell further behind every hour (so it could never meet the catch-up bound), and the live
realtime factor fell from 0.9998 to 0.93-0.98. It recovered to 0.999-1.0 the moment the shadow
stopped. The comparison itself is unchanged: the shadow is the same binary of the same release,
following the same trace. What moves is where it runs, and so how its inputs reach it and its
verdict comes back (`shadow::remote`, `shadow::relay`, `shadow::ingest`).
- *The relay* (`fly-shadow relay`, the container's `flyshadow.service` with the drop-in
`fly-shadow-run start` writes) opens one ssh connection to the box and streams, every quarter
second: the new live saves of both stores, then the new bytes of every trace file of this run
(oldest first; a file's size read after the directory listing, so an older file is complete
when a newer one reaches the box), then the sugar journal as read before the listing. Trace files
that started before the run (`FLY_SHADOW_RUN_ID`, the start's Unix ms) and saves older than a
minute before it are not sent. A writer thread owns the link, so a stall never blocks the relay:
new saves are read as they appear and held in memory (256 MiB, about 8 minutes; a hot save lives
about ten seconds), trace bytes wait on disk, and a newer file and the journal wait until every
older file is complete on its way.
- *The ingest* (`fly-shadow ingest --root <dir>`) is the forced command of the relay's key on the
box (`authorized_keys` `restrict,command=`); the box holds no credential for the container. It
refuses a relay whose release directory or binary SHA-256 differ from its own, so the box runs the
container's release, installed from the same tarball at the same path, and the verdict's
`candidate` is exactly what `check` recomputes on the container. A new run id resets the mirror
and restarts the box's shadow (it exits with status 4; `--run-id-file`).
- *The heartbeat.* flysim's `<trace dir>/consumer` on the container is now the relay's. The relay
touches it only while it is healthy: connected; the box reported within 30 s that the shadow of
this run is alive (its own heartbeat fresh and its verdict this run's, running or passed); and
the box has acknowledged every byte that was on the container's disk a minute earlier. A dead box,
shadow or link, and a stalled sync, therefore stop the live trace exactly as a dead local shadow
does. The relay removes the file when it stops.
- *The verdict* on the container is the box's `verdict.json`, written back only when its new
`runId` member is this run's, with two changes: `lagTransitions` is the box's plus the live
trace not yet acknowledged by the box, so the catch-up bound covers the sync; and a `relay`
member (`relayedAt`, `remoteLagTransitions`, `unsyncedBytes`, `unsyncedTransitions`). A diverged
verdict brings `divergence.json` and the checkpoint files back, and the relay exits with status 3.
- *Coverage, tightened for both placements.* A trace that stops for want of a consumer
(`"truncated":true,"reason":"no-consumer"`) while the shadow is following it is now a `coverage`
divergence, not a `trace-cap` skip: the rest of that live process can never be compared, and with
a relay a stalled sync is exactly how that happens. A stop already in the file when the shadow
started, and the byte cap, end the verdict's window instead (`window.ends`): what was compared
before them stops counting, and a pass needs its brain time after the last one (SHADOW-02 B2). The coverage
check reads the sugar journal before it lists the trace directory (a process creates its trace
file before it writes its boot header, so a boot between the two reads could look untraced
the other way round).
- *`fly-shadow-run check`*, remote: in addition to everything above, `/srv/fly/shadow/relay.json`
must be less than a minute old and say `healthy`. `fly-shadow check` (the Rust rule) is
unchanged. `fly-shadow-run start` runs the shadow on the container only with `--local`.
- *The guard* stays on the container and guards the live fly as before; it now watches the relay's
cost, which is a few file reads and one ssh stream.
**Amendment, 2026-10-01 (BUS-01): a shadow of the bus topology.** A cutover onto the bus is a
cutover into another topology, so it needs a shadow that ran it. `fly-shadow --mode` (and
`FLY_SHADOW_MODE`) names the topology as `SessionArm` does: `local` (the default, the in-process
lane; `in-process` is the same), `bus/thread`, `bus/process` (`bus`, `process`), `bus/in-process`.
`fly-shadow-run start --bus` sets `FLY_SHADOW_MODE=bus/process` in a drop-in of
`flyshadow.service` (`mode.conf`); in remote mode the relay forwards it with the rest of the live
composition's settings (it is in `FORWARDED_ENV`), so the box's shadow -- the same release, which
ships `fly-session` beside `fly-shadow` -- starts its agent and its world as child processes on its
own router's sockets. Its placement is the box's: the shadow places no thread. The verdict records
the topology (`candidate.executionMode`, and `candidate.transport`, new), and
`fly-shadow check --require-arm bus/process` (`fly-shadow-run check --bus`) refuses a verdict that
did not run it; a verdict from before this amendment, with no `transport`, counts as `local` when
it ran in process. The comparison, the window and every other rule of this section are unchanged.
The shadow follows the trace only the legacy loop writes (`FLY_TRACE_DIR`); the session runtime
ignores it. So the live fly runs the legacy runtime for the shadow's window, as it did for CUT-01:
`fly-shadow-run start` refuses while `flysim.service` runs the session runtime. The procedure for a
switch onto the bus is: `fly-runtime legacy`; `fly-shadow-run start --bus`; three hours of zero
divergence; `fly-shadow-run check --bus && fly-runtime session --bus` (the probation then judges
the bus topology). Shadowing the session runtime from its own trace is not built.

View file

@ -12,6 +12,14 @@ ordering. Its frame order is this document's transaction order (legacy-gameboy-v
maps it step by step), so the amendments below add capabilities to the protocol and change maps it step by step), so the amendments below add capabilities to the protocol and change
none of its ordering rules. none of its ordering rules.
**Amendment, 2026-09-30 (PERF-01).** In-process participants MAY be called over the local lane of
[session RPC](ipc-v1.md) section 1 (amendment of the same date) instead of through the router:
the arrows below are then direct calls into the same worker shell, carrying the same requests and
replies. No ordering rule changes. Measured on the release container's CPU and cpuset, work that
overlaps the brain's ticks slows them (the sweep owns every core of the cpuset), so the
coordinator overlaps nothing with Prepare: a boundary's publication copies are made while the
world, the task and the commits run, and the snapshot is published before the next Prepare.
## 1. Committed boundary ## 1. Committed boundary
At `Ready(epoch, k)`: At `Ready(epoch, k)`:
@ -65,6 +73,19 @@ amendment). The boundary number does not change; the epoch does. A pause request
lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is lands on `Ready(e', k)`; any failure inside it is `Failed → Restoring(new epoch)`. Capture is
not allowed in `RollingBack`. not allowed in `RollingBack`.
**Amendment, 2026-09-29 (TASK-01).** Two edges are implemented as written above (`fly-session`
`phase.rs`): `Ready(k) -> RollingBack(k) -> Ready(k)`, where the epoch is the coordinator's and
the boundary stays the same. One edge is added for a checkpoint of another format installed as a
session's start (the legacy composition's FLYSIM01 import):
```text
Ready(0), no transition taken -> Restoring(k) -> Paused(k)
```
The install is the group restore of [state-media-v1](state-media-v1.md) section 6, unchanged. Only
a session that has not advanced may take the edge; the coordinator enforces this, because the phase
alone cannot tell a fresh `Ready(0)` from a reset one.
## 3. Transaction sequence ## 3. Transaction sequence
### Phase A: prepare all agents concurrently ### Phase A: prepare all agents concurrently
@ -111,6 +132,12 @@ and returns StepResult for `k+1`. It MUST NOT advance another interval while wai
the next request. Transport/control scaffolding may have a measured fixed latency; it must the next request. Transport/control scaffolding may have a measured fixed latency; it must
be declared in its descriptor and conformance tests. be declared in its descriptor and conformance tests.
*Amendment, 2026-09-29 (TASK-01):* as built, the clock the executor is handed is
`brainTicks x tickDuration` from the agent's `PreparedDecision`, exact in `RationalNs`. For the
legacy profile this is the legacy `network.ms` in nanoseconds. An artifact-backed inspection reaches
the executor and the task as bytes: the coordinator holds each attachment the task declares
(`inspection.memory`) from the world's reply until the transition that reads it has been evaluated.
### Phase C: observe and evaluate the task ### Phase C: observe and evaluate the task
The coordinator receives the environment result and verifies batch identity, boundary, The coordinator receives the environment result and verifies batch identity, boundary,

View file

@ -426,6 +426,22 @@ composition that declares no rollback policy treats the request as a task failur
"cannot reset the environment directly": the coordinator applies the policy through the "cannot reset the environment directly": the coordinator applies the policy through the
section 7 methods. section 7 methods.
**Amendment, 2026-09-29 (TASK-01).** The Rust interfaces, as built in `fly-session::task`:
- The inspection argument is an `Inspection`: the observation's typed `inspection` value, plus the
bytes of every attachment the task declares (`Task::inspection_attachments`, for example
`inspection.memory`). A synthetic task declares none, and its inspection reads as the typed value
it always was.
- `Evaluation.slot_saves` names the `Environment.SaveSlot`s the transition asks for at the boundary
it reached. They are applied after every Commit, saves first.
- `Task::rollback(scope', restored)` is step 3 of a declared rollback policy. It returns the next
contexts.
- `Task::restored(scope', restored, clock)` runs after a group restore installed the ledger. A task
whose executor state is transient re-observes the restored world here, and returns the contexts
the coordinator holds against the checkpoint's.
- A task and an executor that are one object (`pokered-macros-v1`) are two handles on one shared
state.
## 5. Admission and audience boundary ## 5. Admission and audience boundary
The first synthetic implementation has no audience input. Later integration maps permitted The first synthetic implementation has no audience input. Later integration maps permitted
@ -453,6 +469,13 @@ first and refunds the second, and the slice wiring the bridge tests both. This i
accepted/applied/aborted distinction the paragraph above asks for, for this one interaction accepted/applied/aborted distinction the paragraph above asks for, for this one interaction
kind; paid interactions in general still need the public v2 contract. kind; paid interactions in general still need the public v2 contract.
**Amendment, 2026-09-29 (TASK-01).** As built, the coordinator's `AdmissionQueue` is the
admission record: an admitted stimulus carries its interaction id into `preStepStimulations`, and it
ends `applied` (with its boundary) or `aborted` (the epoch failed before its Prepare committed). The
legacy composition's rules run on the edge side of the queue. No other interaction kind is admitted.
The legacy operator reward pulse is refused (legacy-gameboy-v1 section 15, amendment of
2026-09-29).
## 6. Health, shutdown and extensions ## 6. Health, shutdown and extensions
All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore All workers implement the common Hello/Status/Shutdown/Acknowledge methods. Capture/restore

View file

@ -177,7 +177,7 @@ Node 22, TypeScript, `tsx` for dev, `node --test` for tests. Deps: `@twurple/aut
One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim. One-time interactive authorization in `tools/authorize.mts`, run by hand on the WSL box, producing a refresh token. Primary path: authorization-code flow with a temporary `http://localhost:3000/callback` listener (Twitch permits `http://localhost` redirects) and `exchangeCode` from `@twurple/auth`. Device-code grant against `https://id.twitch.tv/oauth2/device` is the fallback for headless authorization; twurple's first-class support for it is **unverified**, so if used it is 30 lines of hand-rolled polling rather than a library claim.
Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/fly-pokemon-client-{id,secret}`, matching the stream-key posture already documented. Runtime uses `RefreshingAuthProvider` with `onRefresh` persisting to `/var/lib/flybridge/tokens.json`, written `0600` by an atomic temp-file rename, owned by the service user, never in git (`.gitignore` plus a repo-level check). `TWITCH_CLIENT_ID` and `TWITCH_CLIENT_SECRET` arrive via systemd `LoadCredentialEncrypted=`, sourced from `pass` on the WSL box under `twitch/<app>-client-{id,secret}`, matching the stream-key posture already documented.
Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope: Two identities, both registered on the provider: the **bot account** (chat send) and the **broadcaster account** (redemptions, predictions, markers). Scopes to request, with the intent recorded per scope:
@ -193,7 +193,7 @@ Two identities, both registered on the provider: the **bot account** (chat send)
| `channel:manage:broadcast` | broadcaster | stream markers | | `channel:manage:broadcast` | broadcaster | stream markers |
| `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) | | `channel:manage:predictions` | broadcaster | predictions (later, Affiliate-gated) |
Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition. Startup asserts the actual granted scopes via `getTokenInfo` and refuses to start with a named missing scope rather than failing at the first subscription. Before that assertion, each role's stored token is made usable (added 2026-09-28): an access token expired by `obtainmentTimestamp + expiresIn`, or one `validate` rejects with 401, is refreshed once through that role's `RefreshingAuthProvider`, and every refresh is persisted under the role whose provider made it (serialized atomic writes), so both roles survive a restart even when they are one account. Only a refresh Twitch refuses (4xx) is fatal, with one line naming the role and the runbook's re-authorize step; tokens, the client secret and request URLs never reach the log. `channel.raid` needs no scope but does need a user token and a `to_broadcaster_user_id` condition.
## B2. Day one (pre-channel-setup) ## B2. Day one (pre-channel-setup)

View file

@ -187,7 +187,8 @@ before. The Rust producer always sends all five, in both modes.
- **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in - **`game.padEmptyMs`** is how long the pad has had nothing on it **in a playable scene**, in
brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound, brain milliseconds, and 0 otherwise — in raw mode, on the title screen, when something is bound,
and while a macro is running, because a running macro owns the pad. It is **report only**: no on the naming screen, whose pad is the fly's own buttons (`docs/design/macros.md` 12.32), and
while a macro is running, because a running macro owns the pad. It is **report only**: no
producer acts on it and no consumer should, and nothing in the loop reads it back. It exists producer acts on it and no consumer should, and nothing in the loop reads it back. It exists
because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no because an empty pad is the doctrine working — nothing presses for the fly, so a scene with no
button waits — and on screen that is indistinguishable from a hang button waits — and on screen that is indistinguishable from a hang

View file

@ -178,8 +178,9 @@ achievements.
| Badge | +3 | each newly set badge bit | | Badge | +3 | each newly set badge bit |
That is the prototype's catalog as it shipped, kept here as history. The live one is That is the prototype's catalog as it shipped, kept here as history. The live one is
`docs/rewards-learning.md`: `pokered-unique8-v7` adds `boundary` (v5), `catch` (v6), and `talk` and `docs/rewards-learning.md`: `pokered-unique8-v8` adds `boundary` (v5), `catch` (v6), `talk` and
`item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23). `item` with no `boundary` payout indoors (v7, the operator's decision of 2026-09-23), and `damage`
(v8, the operator's decision of 2026-09-29).
Every value is positive; there were no loss or blackout penalties. Values in a frame summed into Every value is positive; there were no loss or blackout penalties. Values in a frame summed into
`R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with `R`, then `m = tanh(R)`. PAM stimulation ran 80 to 400 ms depending on reward kind, with

View file

@ -9,8 +9,8 @@ the project."
1. The release watchdog (`infra/bin/fly-watchdog` check 10) flags a suspected loop: few distinct 1. The release watchdog (`infra/bin/fly-watchdog` check 10) flags a suspected loop: few distinct
macros, a short sequence repeating, no growth in places explored. It exports macros, a short sequence repeating, no growth in places explored. It exports
`fly_loop_suspected` and writes `/run/fly/wd/loop.json`. It never acts. The separate `fly_loop_suspected` and writes `/run/fly/wd/loop.json`. It never acts. The separate
`fly-loop-recover.timer` can restart only flysim after two fresh suspected probes; `fly-loop-recover.timer` unsticks a confirmed trap on its own: flysim restart, then milestone
see `infra/docs/loop-recovery.md`. This does not replace checkpoint-based review. resets (`infra/docs/loop-recovery.md`). That buys time; it does not replace checkpoint-based review.
2. The coordinator session (Fable) checks that marker on a schedule. On a flag it pulls the 2. The coordinator session (Fable) checks that marker on a schedule. On a flag it pulls the
live checkpoint read-only (`pct pull`, into `.local/checkpoints/`, never committed), and live checkpoint read-only (`pct pull`, into `.local/checkpoints/`, never committed), and
spawns a review agent with the trap brief: reproduce from the checkpoint with the real spawns a review agent with the trap brief: reproduce from the checkpoint with the real

View file

@ -1,6 +1,6 @@
# Rewards and learning # Rewards and learning
The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v7`. The code of record is The live reward catalog of the Pokémon Red adapter, `pokered-unique8-v8`. The code of record is
`services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the `services/flysim/crates/flybrain-gb/src/pokemon_red/` (`catalog.rs` holds the values, `mod.rs` the
gates and the rules); this page says what each rule pays for and why it is allowed to. The gates and the rules); this page says what each rule pays for and why it is allowed to. The
prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules prototype's own `docs/rewards-learning.md` in `fly-plays-pokemon` is where the first seven rules
@ -27,6 +27,7 @@ change what the fly can do.
| `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger | | `catch` | `wildwin` | +0.30, +0.10 | 150 ms | A wild Pokémon kept by a ball: +0.30 for a species this run had never owned, +0.10 for a repeat; at most three payouts per species for the lifetime of the ledger |
| `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger | | `talk` | `explore` | +0.10 | 100 ms | A conversation the fly opened with a person or a sign **indoors**, paid when its box closes; once per `(map, sprite slot or sign text id)` for the lifetime of the ledger |
| `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger | | `item` | `explore` | +0.15 | 120 ms | An item ball or a hidden item picked up, on any map; once per item for the lifetime of the ledger |
| `damage` | -- | +0.20 per whole Pokémon, in proportion; +0.05 knockout | 80 ms | HP the fly's own attack removed from the enemy (since v8): its share of the target's max HP, below the lowest HP that target has shown this battle; +0.05 when the hit knocks out a trainer's Pokémon; at most 0.50 a battle; a wild battle at 1, 1/2, 1/3 for its first three per `(map, species, level)`, then nothing |
Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")` Every value is positive: there are no loss or blackout penalties, and `catalog::rule("blackout")`
is `None` by test. The values in one frame sum into `R`, and the network reinforces once with is `None` by test. The values in one frame sum into `R`, and the network reinforces once with
@ -34,7 +35,8 @@ is `None` by test. The values in one frame sum into `R`, and the network reinfor
The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`: The feed-kind column is `RewardKind::from_adapter` in `services/flysim/crates/flysim/src/snapshot.rs`:
`docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its `docs/feed-protocol.md` publishes seven counters, and an adapter kind that has no counter of its
own shares the nearest one. It still reaches the page as an event with its own label. own shares the nearest one. It still reaches the page as an event with its own label. `damage` is
the one Pokémon kind with no counter at all ("Damage rewards" below says why).
Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on Two consequences of that sharing are worth stating rather than discovering. `catch` publishes on
`wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on `wildwin` because a catch is a wild battle the fly won by keeping the Pokémon, and *not* on
@ -177,6 +179,87 @@ half, 0.10, once, keyed under the building's id as it always was; walking out pa
person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no person, far below a badge. Everything is once per thing for the lifetime of the ledger, so no
building can be farmed. building can be farmed.
## Damage rewards
The operator's decision of 2026-09-29, chosen over a pad rule that would have withheld a stat move
once it had been used: pay the fly for the HP its own attack removes from the Pokémon it is
fighting. It is a catalog change, an operator decision like the catch and engagement rewards, not a
loop-review fix. It answers row 67 (`infra/docs/macros-traps.md`): the live fly lost the Pewter
Gym's Jr. Trainer 29 times running, choosing TAIL WHIP 155 times, BUBBLE 23 and TACKLE 0, and
nothing in the catalog paid for anything that happened inside a battle it did not win. The pad
offered every move; the readout's favourite was the one move that cannot win. The code is
`pokemon_red/damage.rs`.
**What counts as the fly's attack.** A drop in `wEnemyMonHP` on a sample where `hWhoseTurn`
(`$FFF3`) reads 0 and `wPlayerMoveNum` is not `STRUGGLE`. At the pinned commit
(`engine/battle/core.asm`), `ApplyDamageToEnemyPokemon` subtracts the damage inside
`ExecutePlayerMove`, with `hWhoseTurn` 0, once per hit of a multi-hit move. Everything else that
lowers the enemy's HP lands with it 1: the enemy's poison and burn ticks and a Leech Seed on the
enemy (`HandlePoisonBurnLeechSeed` picks whose HP to cut *by* `hWhoseTurn`), its recoil, its
confusion self-hit, its own Explosion or Self-Destruct, and the HP it pays for a Substitute. A
Leech Seed on the fly heals the enemy, and HP going up never pays. Damage into an enemy Substitute
never touches `wEnemyMonHP`. `STRUGGLE` is the move the cartridge executes for a Pokémon with no
PP; the fly chose FIGHT, not the move, so it pays nothing (winning still pays what winning pays).
`tests/rom_damage.rs` pins the address on the cartridge from the live row 67 state: every drop of
the enemy's HP lands with `hWhoseTurn` 0 and every drop of the fly's own with 1.
**How much.** 0.20 per whole enemy Pokémon's max HP, paid in proportion on the sample the HP
drops -- BUBBLE for 10 of Diglett's 24 is 0.083, TACKLE for 4 of Sandshrew's 33 is 0.024. The hit
that knocks out a trainer's Pokémon adds 0.05 on the same event. At most **0.50 a battle**, which is
the `trainer` rule's own value: a battle's worth of damage is worth what winning it is, and the
Jr. Trainer's two Pokémon reach it exactly (2 x (0.20 + 0.05)). A wild knockout adds nothing here
because the `battle` rule already pays it, on the way out of the battle. Next to the rest of the
catalog: a wild battle's damage (0.20) is twice its knockout (0.10) and equal to a new area (0.20);
a trainer battle's (0.50) is the trainer's flag; a gym's is a sixth of the badge (3.0).
**What cannot be farmed.**
- *Heal.* Each target keeps the lowest HP it has shown this battle, and only HP below that pays. A
Potion, Recover, Rest or a drain lifts the HP; the same HP is not paid twice.
- *Switch.* A target is `(wEnemyMonPartyPos, species, level)`, so a trainer's Pokémon that goes out
and comes back keeps its mark, and two Weedles of one level are two targets.
- *A stale enemy.* `InitBattleVariables` does not clear `wEnemyMon`, and a trainer battle sets
`wIsInBattle` a whole transition before `LoadEnemyMonData` runs, so the first samples of a
battle can hold the last battle's Pokémon at the HP it finished on -- in the row 67 ring, the
same trainer's Diglett in the same slot. A target is marked the first time it reads full HP,
which is how every enemy Pokémon enters a battle in this game, so the stale one neither pays nor
hides the real one's first hit.
- *The battle.* 0.50 at most, whatever the party size.
- *Wild Pokémon.* A wild battle pays at the wild-KO rule's scale, 1, 1/2, 1/3, for its first three
battles per `(map, species, level)` that paid any damage (`damageCounts`), then nothing; attacking
a wild Pokémon and running from it counts. A rollback blocks every key that has paid, the way it
blocks a paid wild KO or catch.
- *Trainers* keep no lifetime ledger. A trainer is fought again only after the fly has lost to it
(or after a rollback), and each of those battles is bounded by the cap. In the row 67 ring that
is the point: every lost battle pays for the hits that landed, and the hits that land are the
moves that win.
**Feed.** `damage` publishes on no counter (`RewardKind::from_adapter` is `None`). Every other
Pokémon kind shares the nearest counter, and the nearest here is `wildwin`, but the stage folds
that row into "N wild wins": false of a trainer battle, and false of a battle the fly goes on to
lose. A hit reaches the page as a reward event with its own label, `HIT #<species> FOR <n> HP`
(`... KO` for a knockout; the species is the cartridge's internal index, as `CAUGHT #<species>` is),
and the event log, `/status` and the checkpoint carry it; it is only left out of
`game.rewardCounts` and the ticker's per-kind copy, the way the platformer's `started` and `clear`
are. No feed kind was added. The stage rolls the hits up itself (`apps/stage/src/lib/ticker.ts`,
`hitCopy` in the game config): a reward with no `rewardKind` and that label folds into one
"damage dealt x<n>" row with the summed value, ` KO` once a hit in it felled a Pokémon, joined by
each hit within 45 s of the last; a later battle starts a new row (`apps/stage/mockups/row68-ticker-*.png`).
**Learning.** A payout reinforces the recent spike history with `m = tanh(R)` over a 5 s
eligibility trace ([plasticity](plasticity.md)). Measured on the cartridge from the row 67 state
(`tests/rom_damage.rs`), the HP drops 176 frames (2.9 s) after the `MOVE n` press when the fly
moves first and about 420 frames (7 s) when the Jr. Trainer's Pokémon does -- its attack and text
come first. So the choice's trace is at a half to a quarter when its hit is paid, and the previous
turn's choice, one turn (about 7.5 s) earlier still, at a tenth to a twentieth. That ratio is the
whole mechanism: nothing tells the readout which move to press. A hit is small (0.02 to 0.10), so what it can move per battle is small too; whether
the brain learns the attacking move inside a few brain hours is a measurement, not a promise, and
the first one is `infra/docs/macros-traps.md`, row 68.
**Migration.** `v7` -> `v8` adds `damageCounts` and, inside a battle in flight, `battle.damage`;
both are optional and a `v7` state restores with no wild key paid and its battle's Pokémon marked
where they stand. See `docs/design/flysim.md`, "Restoring across an adapter version".
## Gates ## Gates
Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other Semantic rewards are enabled for exactly one cartridge, the SHA-256 in `SUPPORTED_ROM`. Any other
@ -276,6 +359,15 @@ body picks the macro; the descending neurons press the buttons.**
## Honesty ## Honesty
The catalog now includes damage (v8). It is the first rule that pays for something inside a battle
the fly may still lose, and the closest the catalog has come to grading a *choice*: the moves are
all on the pad, and the one that lands pays. It is still a reward read out of WRAM after the frame,
not a press: nothing in the adapter picks a move, removes one from the pad or tells the readout
which is good, and a move pays only if the cartridge says it took HP off the enemy. The pad rule
the operator declined (withholding a stat move once used) would have been the doctrine change; this
one leaves the pad exactly as the scene deals it. It is also bounded on purpose: at most what winning
pays, per battle, and a wild Pokémon only three times.
The catalog now includes conversations and items (v7). Paying for a conversation is the closest The catalog now includes conversations and items (v7). Paying for a conversation is the closest
the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a the catalog has come to paying for a *button*: A is what opens one. It is still a reward, not a
press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is press. Nothing in the adapter presses A, chooses when, or tells the fly who is there; the payout is

176
docs/scorecard.md Normal file
View file

@ -0,0 +1,176 @@
# The behavioural scorecard
A repeatable, multi-seed "good play" regression harness. The unit tests say the macros do what
they were written to; the trap hunt says a fly stuck in one place got out. Neither says whether a
release plays *better or worse* than the one before it across the places the fly actually is. The
scorecard does: a fixed set of checkpoints, K seeds each, T brain minutes each, on the real
connectome with the macro layer, reduced to one JSON per release and compared release against
release by a test over the paired runs, never by a single run.
It measures and presses nothing. It restores a checkpoint, lets the brain play, and counts. The
ethos check (`docs/loop-review.md`) is untouched: the harness is outside the fly.
```sh
export FLY_ROM=/path/to/the-cartridge # read, never copied
cargo build --release -p fly-scorecard # from services/flysim
fly-scorecard list # the set, resolved, each checkpoint's rung
fly-scorecard suite --label v0.7.5 --out card.json # the set x 3 seeds x 10 brain minutes
fly-scorecard summary card.json # one screen of markdown
fly-scorecard compare old.json new.json # exit 1 when a metric regressed
fly-scorecard run-one --checkpoint X --seed 1 # one run, JSON out (--out FILE)
```
`--runtime session` (the default) runs the session composition the release cut over to
(`fly-legacy-session`, in-process, unpaced); `--runtime legacy` runs the stream's own frame
(`flysim::frame::LegacyFrame`). Both hand the same per-frame observation to the same tally, so a
card from one runtime is comparable with a card from the other. From the same checkpoint and seed
the two give identical reports apart from wall time (`tests/rom_scorecard.rs` holds it), which makes a scorecard
run on both a second piece of shadow evidence. `--mode raw` runs without the macro layer.
## The set
`tools/scorecard/checkpoints.json` names each checkpoint by the environment variable that holds
its path (the ROM tests' own, `rom-env.sh`), never by a path; `--extra id=path` adds more (the
newest live checkpoint, a trap's). The checkpoints are not committed (`.local/` is untracked).
`list` prints the rung each one stands on, from its reward ledger. The set has two or three
states at each of rungs 8, 9, 10, 11, 12 and 15; rungs 13 and 14 have no checkpoint yet and join
the set when the scout makes them (a new entry is a line in the JSON). A checkpoint missing from
the environment is named on stderr and, with `--strict`, an error.
## Seeds
A checkpoint restores a deterministic brain, so two runs from it would be the same run. A seed
therefore chooses how many frames the brain's readout is ignored before the measurement starts
(60 to 1,800 frames, a splitmix of the seed; seed 0 is none). The brain still ticks and its noise
generator still advances, the game sees no button, and from the first measured frame the readout
is the brain's own: the run sits on a different point of its own trajectory. The idle frames are
not measured. The same seed twice is the same run.
## What a run reports
One `RunReport` per (checkpoint, seed). Every number is computed from per-frame observations by
`tally.rs`, which has no emulator in it and is unit-tested on synthetic frames.
| group | what |
| --- | --- |
| rungs | start, end, gained, the brain minute of each climb; reported per brain hour |
| places | the adapter's exploration count, start and end |
| empty pad | frames with the macro layer on, nothing running and no button dealt; seconds, share, longest stretch |
| watchdog | `fly-watchdog` check 10, rule for rule (`watchdog.rs`): probes, suspected, reasons, **confirmed** (two suspected probes in a row) and **ladder events** (one per run of two or more: a trap the recovery ladder would act on) |
| hunt | the trap hunt's windows (two brain minutes, fewer than four tiles or a sequence repeated more than ten times) |
| ratchet | rollbacks, split by game over and stall |
| macros | starts, done, blocked, timeout, refused, by macro |
| funnel | GO SHOP, BUY BALL, THROW BALL, catch: counts at each stage, balls gained and spent, species gained, and how far down the funnel the run got |
| heals | GO HEAL and the nurse's HEAL |
| whiteouts | the whole party fainted (a rising edge) |
| battles | started, ended, wild and trainer, won (a battle or trainer payout), lost (the party fainted in it), caught, other |
| rewards, scenes | counts and totals by adapter kind; frames by scene |
The watchdog's rules are the shell's: the same thresholds, the same order, the same two-probe
memory for the zero-progress, unrewarded and unwon-battle rules. Two things differ, both about
time: a run is short, so the probe cadence is a parameter (default every 120 brain seconds,
first at 240; the stream's is five wall minutes) and the window is the last ten brain minutes or
the whole run when it is shorter; and the first probe compares the exploration count with the
run's starting count, which the live check lacks after a boot.
## Compare
`compare A.json B.json` pairs runs by (checkpoint, seed). Each metric (`compare.rs`, `METRICS`)
has a direction (more is better, less is better, or info), an absolute tolerance and a relative
one. For each metric the pairs give one difference, signed so that positive means B is worse. B
**fails** a metric when it is worse by more than the tolerance **and** a one-sided sign-flip
permutation test over the pairs gives a **Holm-adjusted** p below alpha (default 0.05; Holm over
the judged metrics, so the whole compare, not each metric, has a false-fail rate of at most
alpha when nothing changed; unadjusted, 13 metrics at 0.05 each false-failed about 15% of
releases in a bootstrap of the baseline, with Holm 0 of 200). It reports **better** by the
same two tests, and **pass** otherwise: a change inside the tolerance is noise however consistent,
and one bad run among eighteen is not a regression. The test is exact up to 20 pairs and a
fixed-seed Monte-Carlo beyond, so the same two cards always give the same verdicts. The
comparison also names its caveats (different lengths, different runtimes, fewer than eight
pairs, unpaired runs). Exit status 1 is a failed metric or a failed checkpoint.
**The trap rule.** The pooled test cannot see a fault confined to one place: three seeds of one
checkpoint give a sign-flip p of at least 1/8, and the shift is diluted over thirty-six pairs
(the row-71 bag bug, 131 blocked THROW BALLs in every seed of one checkpoint, passed the pooled
compare even spliced into an otherwise identical suite). So each checkpoint is also judged on its
own, without statistics: it **fails**, named as `trap@<checkpoint>`, when B is trapped on at least
two of its runs and on at least two more than A, or when any run of B has a blocked-macro storm
(50 or more blocked finishes of one macro) and no run of A on that checkpoint does. A run is
trapped on a recovery-ladder event (two suspected watchdog probes in a row, any rule: stalled,
zero-progress, sequence, ...), on at least half its probes suspected, or on a storm. Costs: with
three seeds a checkpoint whose trap is a coin flip in A already (r09-forest-catch, r10-pewter-center
on the baseline) can fail by chance when B traps all three seeds (about 1 in 27 each by bootstrap,
so roughly 7% of releases that changed nothing but the trajectory); five seeds make it 1 in 243.
Identical suites never fail.
The metrics: rungs per hour, places per hour, empty pad %, suspected probes %, ladder events per
hour, rollbacks per hour, blocked macro %, buy ball, throws (THROW BALL that finished, not blocked starts) and catches per hour, battles won and
lost per hour, whiteouts per hour. Blocked throws per hour, heals per hour, macro starts per minute and the trap hunt's
flagged windows are reported, never judged: healing more can follow losing more, and a fly that
fights for most of a run presses NEXT through battle text more than ten times in two minutes,
which the hunt reads as a repeated sequence (nine windows in ten are flagged on the baseline, so
the number has no room to move).
## Cost and size
A run's brain minute costs about 75 CPU seconds however it is split, and the result does not
depend on the thread count (the same seed gives an identical report at one thread and at four).
The split matters for wall time, because a run's sweep pool spins at its barriers: on a quiet
ten-core box two jobs of four threads are fine, but on a box shared with compiles and tests one
job of four threads ran five times slower per brain minute than one-thread jobs did. So the
default is one thread per run and eight runs at a time. The default suite, twelve checkpoints by
three seeds by ten brain minutes, is 360 brain minutes: about three quarters of an hour of ten
quiet cores, about twice that when the box is busy. More seeds tighten the test; longer runs let
rungs climb. Three seeds is the smallest suite whose pair count (36) can reach p < 0.001.
`--resume` keeps the runs an interrupted suite had finished (`<out>.runs.jsonl`).
## What it does not do
- It does not rebuild session ledgers a restore starts empty (the trap hunt's
`FLY_TRAP_SEED_*`); a trap that needs them is that tool's.
- Ten brain minutes rarely climb two rungs. Rungs per hour is a rate over many runs, not a
per-run prediction; a release that is faster by a rung every few hours shows only across the
suite.
- It judges play against the previous release, not against a notion of good. A regression is
"worse than last time"; the absolute numbers say how good last time was.
## Releases and nightly
`tools/scorecard/overlay.sh <ref> <tree>` puts the tool on the tree of an older release (the crate,
the set, the docs, and the one read-only accessor `PokeredTask::with_reader`), so a release that
predates it can be scored and its numbers are its own. The operator's nightly runner builds the
latest release tag on a build box, runs the suite, writes the card and a one-screen summary and
compares with the previous release's card.
## The v0.7.5 baseline
`tools/scorecard/baseline-v0.7.5.json` is the reference card of v0.7.5 (adapter v8,
compatibility `ff09d7dd5483`): the default set, 12 checkpoints by 3 seeds by 10 brain minutes on
the session runtime, 6.0 brain hours, 6,130 s wall on a shared build box.
| headline | v0.7.5 |
| --- | ---: |
| rungs per brain hour | 1.50 (9 of 36 runs climbed) |
| empty-pad time | 6.96% of frames |
| watchdog probes suspected | 2.8% |
| ladder-worthy traps | 1 (one run, `r09-forest-catch`) |
| blocked macro finishes | 0.5% |
| buy ball / throw / catch | 10 / 10 / 8 |
| heals / whiteouts | 9 / 46 |
| battles won / lost | 33 / 45 |
| ratchet rollbacks | 1 |
What the card shows about v0.7.5, worth reading before the next release is compared with it:
- **The fly fights for most of the frames it is given.** On nine of the twelve checkpoints a
battle is half to nine tenths of the frames, and it loses more than it wins (45 lost, 33 won;
46 whiteouts). The longest single battle is 18,354 frames (five brain minutes, a trainer, on
`r11-mart`); `r09-forest-catch` has one of 26,245 frames in a wild battle.
- **`r15-nugget-bridge` keeps walking and finds nothing.** After the Oddish is caught (all three
seeds), the fly spends the rest of the run in the overworld, GO OBJECTIVE and GO OUT
alternating 13 times each in ten minutes, with the exploration count unmoved (2,527). The
watchdog does not flag it (a ring this slow stays under its twenty repeats), so no recovery
step would act on it.
- The shop-to-catch funnel closes: buy ball, throw and catch all occur, across rungs 9 to 15.

View file

@ -878,3 +878,175 @@ median; a two-fly transition near 10 to 12 ms at the median in every execution m
branch reaches Pewter on frame 23,755, and offers no button on any of the 67 challenge frames branch reaches Pewter on frame 23,755, and offers no button on any of the 67 challenge frames
(67 of 67 before). Survey seed 7: rung 9 -> BOULDER BADGE. The trap hunt's stub cannot see this (67 of 67 before). Survey seed 7: rung 9 -> BOULDER BADGE. The trap hunt's stub cannot see this
trap; the ROM test and survey are the proof (recorded deviation). Ethos check held. trap; the ROM test and survey are the proof (recorded deviation). Ethos check held.
- 2026-09-28 (v0.6.4, infra + stage, auto): automatic loop recovery that climbs. The v0.6.3 timer
only restarted flysim, once an hour; a trap that outlives a restore (Mt. Moon, rung 12, GO
OBJECTIVE / GO WARP) was restarted 48 times in two days. `fly-loop-recover` now climbs a ladder
per confirmed trap that outlives the last step: restart flysim, reset to the current rung's
milestone, reset to the rung below the best (never lower); two resets a day, restarts three
hours apart once they are spent; it starts over at a new best rung or after six quiet hours, and
its state survives a reboot. A router model list confirms each step and can delay it three
probes, never deny it. Resets go through one root wrapper (`fly-loop-reset`) that runs only a
root-owned flysim identical to the running one, uses only archives this build can restore,
and pauses the watchdog for the reset. Every step is announced 60 s ahead on stream: the
recovery splash counts down over the stuck loop, covers the game while it acts, and reports the
result (`apps/stage/mockups/`). Independent review: BLOCK, then fixed; round 2 approved with
the watchdog wait fixed.
- 2026-09-28 (bridge, unreleased): chat died for hours after an unrelated bridge outage outlived
both access tokens (~4 h) and the next start failed `validate` with 401 in a crash loop, with
both refresh tokens still good. Closes the v0.2.3 debt: on load, a stored token expired by its
timestamps or rejected with 401 is refreshed once through its role's provider before giving up,
and every refresh is persisted under its own role (serialized atomic 0600 writes), so both roles
survive when they are one account. Only a refresh Twitch refuses is fatal, one line pointing at
the runbook's re-authorize step; Twitch errors are logged without URLs, tokens or the secret.
- 2026-09-29 (v0.6.5, loop review, auto, plus infra/stage): the two-day Mt. Moon trap and what the
merge of its fixes surfaced. Row 64: the fly stood on B2F's exit ladder (5,7), the only road on;
GO OBJECTIVE and GO WARP both aimed at the tile underfoot and reported done without a step, and
the cartridge fires a ladder only at the end of a step onto it (1,500 of 1,500 macros from the
checkpoint, no ledger involved, so 48 restarts restored it). A walk standing on its warp now steps
off and back on; Route 4's ledges are one-way hops the route search takes (they read as walls,
so the road to Cerulean was "no route"); a way out that leaves the fly on its own map is not done
(the effect-based guarantee against in-place rings). The operator's GO WARP / GO FRONTIER
exhaustion lead was checked and refuted (GO WARP 25,554 starts; the frontier correctly spent).
Row 62 round 2 (shop, balls, nurse): no GO HEAL east of Mt. Moon, no service out of the rung's
room; Pewter buys a ball. Row 63: a confirming A waits for the cartridge's release (ITEM/BACK
with a usable Potion). Row 65: the merge of 62+63+64 failed row 59's ROM test (a Mt. Moon 1F
mouth door ring, 34 crossings) and review found a Cerulean badge-house yard stall; both fixed.
The release gate now refuses to run without FLY_ROM: the ROM suites had been passing vacuously
whenever it was unset, v0.6.4's gate included. Also: recovery timer every minute, the splash's
approved copy and STUCK from the last progress, flybridge refreshes expired tokens on load (and
redacts Twitch errors), a release deploy refuses an empty GAME_TITLE. Reviews: row 62 r2, 63,
64, 65 APPROVE-WITH-NOTES.
- 2026-09-29 (v0.6.6, loop review + port foundation): the fly shops, throws and names what it
catches. Row 66: a counter walked away from is not walked back to for the ledger window (the
GO SHOP/GO OUT re-entry ring: 31 to 0), BUY BALL is one walk-talk-buy button like HEAL (the
operator's call; offered in a mart that sells balls, with no ball and 200 in the wallet), and a
closed battle bag is not the pad (post-catch presses typed the nickname). Row 67: the live fly
lost the Pewter Gym's Jr. Trainer 29 times in a row choosing TAIL WHIP (the pad offered every
move); a report-only `unwon-battles` watchdog reason lets the recovery ladder act 45 minutes
sooner, and the no-PP ROM test is fixed (Struggle is the cartridge's answer). Row 69 (the
operator's calls): in a wild battle at the catch formula's low-HP threshold with a ball in the
bag, THROW BALL is the only attack-side button; the naming screen takes the fly's own buttons
("AAAAAAAAAA" before), bounded by CONFIRM after a full name or 60 brain seconds. Port
foundation merged, dormant on the stream: AGENT-01, MEM-01, ENV-01, STATE-02 (the checkpoint
store is now the shared `flysim-store` crate; FLYSIM01 gains an optional `reinforcements`
field, downgrade-safe both ways). A PII guard scans lint, tag-release and pushes. Reviews: all
APPROVE-WITH-NOTES.
- 2026-09-29 (unreleased, the operator's decision, row 68): the fly is paid for the HP its own
attack removes in battle, the catalog's answer to row 67 (the Pewter Gym's Jr. Trainer lost on
repeat with TAIL WHIP six turns in seven). New kind `damage`: 0.20 per whole enemy Pokémon, in
proportion, +0.05 when it knocks out a trainer's Pokémon, at most 0.50 a battle; a wild battle at
1, 1/2, 1/3 per map/species/level. Only a drop on the fly's own turn (`hWhoseTurn` 0) by a move it
chose (not Struggle); a heal is never paid twice; no feed counter (a hit is not a "wild win").
Adapter `pokered-unique8-v8`; a deploy with FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 migrates the
run (v6 still migrates when named). Survey, 3 starts x 120 brain minutes from the row 67
checkpoint: v8 beat the trainer in 2 of 3 (one run also won the Boulder Badge), v7 in 0 of 3, but
the move choice did not shift more under v8 than v7 (BUBBLE ~15% -> ~20% in both): no learned
preference is shown inside two hours (`infra/docs/macros-traps.md` row 68).
- 2026-09-30 (v0.6.7, the operator's call, reward catalog): the fly is paid for damage its own
attacks deal. Row 67 found the live fly losing the Pewter Gym's Jr. Trainer on repeat with TAIL
WHIP while BUBBLE was on the pad; the operator chose a reward over a pad rule. HP removed on the
fly's own turn (hWhoseTurn 0, not Struggle; poison/burn/Leech Seed/recoil/enemy moves never pay;
healed HP not re-paid) pays 0.20 per whole enemy mon, +0.05 for knocking out a trainer's mon,
capped at 0.50 per battle (a trainer beaten); wild battles diminish 1, 1/2, 1/3 per
map/species/level. Adapter pokered-unique8-v8, migrating v7 (compat differs in the adapter
segment only). The stage folds a battle's hits into one ticker row ("damage dealt x3 KO").
Survey: v8 beat the trainer from 2 of 3 starts (v7 0 of 3); move choice did not measurably shift
within two hours. Review: APPROVE-WITH-NOTES.
- 2026-09-30 (v0.7.0, the port): the flybus session runtime ships beside the legacy loop, installed
and not selected. AGENT-01 (the brain as a worker), MEM-01 (the macros read a 64 KiB memory image
with the same engine), ENV-01 (the Game Boy as a worker), STATE-02 (one checkpoint store for
both runtimes, FLYSIM01 of record), TASK-01 (the macros in the coordinator), PERF-01 (an
in-process local lane: the session costs ~1.3x legacy per frame, down from 2.45x), SERVE-01
(`flysim-session` serves the same feed/control/metrics contracts; `fly-runtime session|legacy`
swaps the binary behind flysim.service; a crash loop falls back to legacy by itself), SHADOW-01
(`fly-shadow` replays the live fly's trace through the session runtime and compares every
transition, ledger and save byte; a baseline-relative guard stops it if the live fly suffers),
CUT-01 (the switch is a 30-minute speed probation: a median realtime factor under 0.97 falls back
with reason "speed"). Deploying changes nothing live: legacy's output is byte-identical to
v0.6.7. Cutover is `fly-shadow-run check && fly-runtime session` after three hours of zero
divergence; rollback is `fly-runtime legacy`. Every slice and the release candidate were
independently reviewed (APPROVE-WITH-NOTES).
- 2026-09-30 (v0.7.1, loop review hotfix): row 70. The fly's first live catch (a Zubat, Mt. Moon)
gave it a second party member, and in the next trainer battle the cartridge's SHIFT-style offer
"Will ZUBAT change POKéMON?" opened the battle party list with the same menu id as a forced
switch after a faint. Read as forced, the pad was SWITCH (no healthy target) and NEXT ("ZUBAT is
already out!", the list again) for 58 brain minutes; the recovery ladder's rung-11 reset erased
the catch and, restores being deterministic, replayed the path back into the trap. A forced
switch now also requires the active battler at 0 HP; the offer is the fly's own turn with SWITCH
and BACK. ROM test from the live checkpoint: NEXT on all 6,000 frames before, BACK and the battle
continues after; a real post-faint switch unchanged. The ladder change (protect recent catches
from resets) is held back for a review finding. Review: APPROVE.
- 2026-10-01 (v0.7.2, loop review): row 70's recovery ladder. A milestone reset within 2 hours of a
new species becomes a restart (operator decision: a catch is worth up to 2 h of a trap, not more);
a reset's deterministic replay re-earns rewards the restored archive already had, so progress and
catch protection now count only reward names the ladder has not seen; a held reset does not climb;
the last-archive marker expires. Escape from a trap only the lower rung clears: 2.08 h (as v0.7.0),
3.33 h with a catch just before it; 200-seed mean 4.80 h vs 4.44 h, worst unchanged at 25.4 h; at
most 2 resets per 24 h, restarts at least 3 h apart. Watchdog flags unchanged. Reviews: r1 BLOCK,
r2 BLOCK, r3 APPROVE, independent read APPROVE-WITH-NOTES.
- 2026-10-01 (v0.7.3, port slice SHADOW-02): the shadow moves off the release container. On the
container a light relay forwards the live trace, new saves and the sugar journal over one outbound
ssh link whose key can only run the receiver; a build box mirrors them and runs the unchanged
shadow on its own cores; the verdict comes back. Release binding by binary hashes; the relay's
heartbeat is fresh only while the link, the box's shadow and the sync are; any trace stop (no
consumer, byte cap, outage) ends the verdict window, so a pass needs 3 h of compared brain time
after the last loss. The guard and `check` stay on the container. The on-box shadow (v0.7.0)
slowed the live fly; the relay costs about 0.5% of a core. Reviews: BLOCK, BLOCK,
APPROVE-WITH-NOTES, APPROVE.
- 2026-10-01 (v0.7.4, loop review hotfix): row 71. On Route 24 (rung 15) the fly met a wild
Oddish at low HP with two Poké Balls in a bag that had grown to five items (TMs, HELIX FOSSIL,
NUGGET), so the ball was the fifth entry and the list scrolled. The macro state read the bag
cursor as the window row only, so THROW BALL could never reach the ball and was blocked every
time; row 69's low-HP rule left it the only card. A restart restores the open bag, so the ladder
could not clear it. The cursor is now the row plus the list's scroll offset, as the cartridge
computes it; the mart's lists the same. ROM test from the live checkpoint: 10 blocked before,
Oddish caught after. Review: APPROVE.
- 2026-10-01 (v0.7.5, port slice PERF-02): the first cutover (v0.7.3, after a 3 h shadow with zero
divergence) failed its speed probation at a median 0.959x real time and fell back to legacy on
its own. Cause: with exactly as many CPUs as sweep threads, the session's other threads woke each
frame and the scheduler often stacked two sweep threads on one CPU. flysim-session now pins each
sweep worker to its own CPU and its other threads to the remaining one (16.2 to 13.0 ms a frame on
a build box of the release CPU; legacy 10.5), and the sim gets its own slice: every other unit,
user session and `pct exec` shell is confined off its CPUs (a hog there collapsed a pinned
session). Results, traces and the compatibility string are unchanged. Reviews: two rounds,
APPROVE-WITH-NOTES; notes addressed.
- 2026-10-01 20:07Z (CUT-01, milestone M4): the stream runs on the session runtime. v0.7.5's remote
shadow compared 3 h of live brain time (645,560 transitions, 2,161 identical checkpoints) with
zero divergence; `check` allowed the switch; the 30-minute speed probation passed at a median
1.000x real time with no lag growth. Legacy stays one command away (`fly-runtime legacy`);
RETIRE-01 after a clean week.
- 2026-10-02 (v0.7.6, flybus groundwork, nothing switched): the control API as flybus RPC with
per-agent grants (CTRL-01, `FLY_CONTROL_VIA`), the video feed over the bus in production form
(EDGE-02, `fly-feed bus|direct`), the session's agent and world as processes on the router's
Unix sockets (BUS-01, `fly-runtime session --bus`), an optional aux cpu for bus threads off the
sim's cores, and a per-frame work metric for both runtimes. All default off; the live stream
is unchanged until each is switched on with its rollback. Also: the multi-seed behavioural
scorecard (nightly), two stale ROM tests fixed and every ROM suite mapped (row 72), and the
parity test's idle-header race.
- 2026-10-02 07:13Z: the stream's video feed runs over flybus (`fly-feed bus`, one aux cpu for the
bus threads). Over the first 20 minutes the sim's mean work per frame fell from 15.2 to about
14.5 ms and its p99 from 46 to about 21 ms (the publisher left the sim's shared cpu); realtime
factor unchanged at about 1.0. Rollback: `fly-feed direct`.
- 2026-10-02 07:41Z: the control API runs over flybus too (`FLY_CONTROL_VIA=bus`): `:7401` is
served by the control edge calling flysim's RPC services under per-client grants. First 15
minutes: bus connected, calls flowing, no failures, no restarts, realtime factor about 1.0.
Both switches are in the host env, so a deploy keeps them. The session's agent and world stay
on the in-process lane: over the router they cost 2.5 to 3.5 ms a frame, more than the
release box's headroom (live work about 14.5 of 16.74 ms); the GPU brain is the way there.
- 2026-10-02 (v0.7.7, loop review): row 73. The scout found rung 16 unreachable: its place was
"on Route 25", so inside Bill's house the walks just left again, and Bill's PC is a hidden
object no macro could press. Rung 16 is now Bill's errand inside the house (people first, then
things; exits off the pad while the errand waits), and hidden objects are read from the
cartridge's own table and become a target only as that errand's next step. Cerulean's north half
joins the map graph through the trashed house. Trap hunts: rung 16 in 0 of 6 seeds before, 6 of 6
after; Route 5 from the ticket 0 of 6 before, 5 of 6 after. Review: APPROVE-WITH-NOTES; notes
fixed. Also: bus worker children die with their parent; the feed test asserts structure, not a
wall-clock rate.
- 2026-10-02 (v0.7.8, groundwork for the GPU and the bus): the GPU brain steps a whole frame per
call with its state resident on the card (about 230 KB a frame crosses PCIe instead of 24 MB),
bit-exact against the CPU through rollback, restore and checkpoints; a dead GPU makes the process
CPU-only and the replacement restores the last checkpoint on the CPU (cuda feature, off; operator
decision: the live brain moves to the release host's Quadro after a 3 h shadow). Cheaper flybus
round trips (seal on reply, recycled zero-filled staging writers, frames encoded once); the
session's own transport stays on the in-process lane. No behaviour change on the live stream.

View file

@ -18,7 +18,10 @@ need pct
PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \ PACKAGES="xvfb x11-utils x11-xserver-utils xauth chromium pulseaudio pulseaudio-utils \
ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \ ffmpeg fonts-dejavu-core fonts-liberation2 fonts-noto-core fonts-noto-color-emoji \
fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo" fontconfig prometheus-node-exporter curl ca-certificates jq rsync sysstat procps zstd sudo \
openssh-client"
# openssh-client (SHADOW-02): the remote shadow's relay dials OUT to a build box. The client only;
# the container still runs no sshd (below).
# Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage # Nothing was added for the capture-freeze fix (2026-09-16): bin/wait-for-stage
# needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl` # needs `xdpyinfo` and `xwininfo` (x11-utils) and `pactl`
# (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three # (pulseaudio-utils), and check 9 of fly-watchdog needs `ffmpeg` — all three

View file

@ -46,6 +46,13 @@ SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
[ $# -ge 1 ] || die "usage: $0 ENVFILE [RELEASE_TARBALL]" [ $# -ge 1 ] || die "usage: $0 ENVFILE [RELEASE_TARBALL]"
load_env "$1" load_env "$1"
# flybridge refuses to start on an empty GAME_TITLE, and the generated fly.env below writes the
# variable whether or not the env file sets it. It only reads the file at start, so a missing
# value surfaced as dead chat at the next reboot, a day and a deploy later (2026-09-28). A release
# with a channel therefore needs the title before anything is touched.
if [ "$ROLE" = release ] && [ -n "${TWITCH_CHANNEL:-}" ] && [ -z "${GAME_TITLE:-}" ]; then
die "TWITCH_CHANNEL is set but GAME_TITLE is empty in $1: flybridge would refuse to start. Set GAME_TITLE (infra/env/example.env)."
fi
RELEASE_TARBALL="${2:-}" RELEASE_TARBALL="${2:-}"
# The label this script writes into the files it GENERATES (/etc/fly/fly.env, # The label this script writes into the files it GENERATES (/etc/fly/fly.env,
@ -116,6 +123,22 @@ need pct
# /opt/fly/current, rather than half way through the deploy or at flysim's boot. # /opt/fly/current, rather than half way through the deploy or at flysim's boot.
FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \ FLY_FEED_VIA_EFFECTIVE="$(feed_via_normalize "${FLY_FEED_VIA:-}")" \
|| die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'" || die "05-deploy: FLY_FEED_VIA must be 'direct' or 'bus', got '${FLY_FEED_VIA}'"
# Who serves the control API (docs/design/flybus.md, "Control over the bus"): the same.
FLY_CONTROL_VIA_EFFECTIVE="$(control_via_normalize "${FLY_CONTROL_VIA:-}")" \
|| die "05-deploy: FLY_CONTROL_VIA must be 'direct' or 'bus', got '${FLY_CONTROL_VIA}'"
# The container's own value, read before anything changes. A `fly-feed bus` (or `direct`) on the
# container is not in the env file unless the operator put it there, and this deploy writes the env
# file's value into fly.env. Nothing breaks (flysim and flyedge.service both follow fly.env at
# their next start, so the feed stays served either way) but the mode would change at the next
# restart of flysim, which is not what anyone meant. Said once, loudly, here.
FLY_FEED_VIA_LIVE="$(ct_exec "$CTID" -- awk -F= '/^FLY_FEED_VIA=/ { v=$2 } END { print v }' /etc/fly/fly.env 2>/dev/null \
| tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
if [ -n "$FLY_FEED_VIA_LIVE" ] && [ "$FLY_FEED_VIA_LIVE" != "$FLY_FEED_VIA_EFFECTIVE" ]; then
log "05-deploy: WARNING: the container's fly.env says FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} and $1 says ${FLY_FEED_VIA_EFFECTIVE};" \
"this deploy writes ${FLY_FEED_VIA_EFFECTIVE}, which flysim applies at its next restart (no restart is done here)." \
"If ${FLY_FEED_VIA_LIVE} is what you want, set FLY_FEED_VIA=${FLY_FEED_VIA_LIVE} in $1 and deploy again; \`fly-feed status\` shows both."
fi
# CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a # CHROMIUM_PROFILE is validated here, not left to the launcher: a typo or a
# `vgl` on a container that never had VirtualGL installed would only show up as # `vgl` on a container that never had VirtualGL installed would only show up as
@ -174,13 +197,26 @@ NEED_RELOAD=0
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}" RAYON_THREADS_EFFECTIVE="${RAYON_THREADS:-3}"
ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}" ENCODER_CORES_EFFECTIVE="${ENCODER_CORES:-2}"
# Page cpus given to flysim's bus threads (EDGE-02 review N1): added to flysim.slice, taken from the
# page group, named to the session as FLY_SESSION_AUX_CPUS. 0 (the default) changes nothing.
SESSION_AUX_EFFECTIVE="${SESSION_AUX_CPUS:-0}"
case "$SESSION_AUX_EFFECTIVE" in ''|*[!0-9]*) die "SESSION_AUX_CPUS ('${SESSION_AUX_EFFECTIVE}') must be a number of cpus (0 = none)" ;; esac
SESSION_AUX_LIST=""
DEPLOY_CPUS="" DEPLOY_CPUS=""
# 1 once the cpuset partition is in force for this deploy (section 3b writes it); fly.env says so to
# flysim-session, which pins its sweep workers only into a cpuset that is the sim's alone.
PARTITION_ACTIVE=0
if [ -n "${CPUSET:-}" ]; then if [ -n "${CPUSET:-}" ]; then
deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \ deploy_conf_cpus="$(awk '$1 == "lxc.cgroup2.cpuset.cpus:" { print $2; exit }' \
"/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)" "/etc/pve/lxc/${CTID}.conf" 2>/dev/null || true)"
if [ "$deploy_conf_cpus" = "$CPUSET" ]; then if [ "$deploy_conf_cpus" = "$CPUSET" ]; then
read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \ read -r _deploy_sim_cpus DEPLOY_CPUS _deploy_encoder_cpus \
<<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")"
PARTITION_ACTIVE=1
if [ "$SESSION_AUX_EFFECTIVE" -gt 0 ]; then
_aux_split="$(cpuset_aux_split "$DEPLOY_CPUS" "$SESSION_AUX_EFFECTIVE")" || exit 1
read -r DEPLOY_CPUS SESSION_AUX_LIST <<< "$_aux_split"
fi
log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim" log "05-deploy: heavy in-container steps pinned to the page cpus (${DEPLOY_CPUS}) so extraction/verification cannot compete with flysim"
else else
log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \ log "05-deploy: NOT pinning the heavy in-container steps — the fly-cpuset block in" \
@ -272,6 +308,21 @@ if [ -n "$RELEASE_TARBALL" ]; then
cpu_pin chown -R fly:fly "$release_path" cpu_pin chown -R fly:fly "$release_path"
fi fi
# A root-owned flysim for fly-loop-reset, which runs as root and so must never execute the
# fly-owned copy above (the fly account could replace it). Taken from the tarball on the host
# and checked against the tarball's own MANIFEST on every deploy, so a release installed by
# an earlier deploy is covered too.
log "05-deploy: installing a root-owned flysim at /opt/fly/sbin/flysim for fly-loop-reset"
root_flysim="$(mktemp)"
tar -xzOf "$RELEASE_TARBALL" ./flysim > "$root_flysim"
want_sha="$(tar -xzOf "$RELEASE_TARBALL" ./MANIFEST | awk '$2 == "flysim" || $2 == "./flysim" {print $1; exit}')"
[ -n "$want_sha" ] && [ "$(sha256sum "$root_flysim" | cut -d' ' -f1)" = "$want_sha" ] \
|| { rm -f "$root_flysim"; die "the tarball's flysim does not match its MANIFEST; not installing /opt/fly/sbin/flysim"; }
ct_exec "$CTID" -- install -d -o root -g root -m 0755 /opt/fly/sbin
ct_push_file "$CTID" "$root_flysim" /opt/fly/sbin/flysim.new 0755
ct_exec "$CTID" -- sh -c 'chown root:root /opt/fly/sbin/flysim.new && mv -f /opt/fly/sbin/flysim.new /opt/fly/sbin/flysim'
rm -f "$root_flysim"
log "05-deploy: overlaying infra-owned stage/serve.{mjs,sh} (docs/design/infra.md's 'own tiny static server' clarification)" log "05-deploy: overlaying infra-owned stage/serve.{mjs,sh} (docs/design/infra.md's 'own tiny static server' clarification)"
converge_file "$CTID" "$INFRA_DIR/config/serve.mjs" "${release_path}/stage/serve.mjs" 0644 fly:fly >/dev/null converge_file "$CTID" "$INFRA_DIR/config/serve.mjs" "${release_path}/stage/serve.mjs" 0644 fly:fly >/dev/null
converge_file "$CTID" "$INFRA_DIR/config/serve.sh" "${release_path}/stage/serve.sh" 0755 fly:fly >/dev/null converge_file "$CTID" "$INFRA_DIR/config/serve.sh" "${release_path}/stage/serve.sh" 0755 fly:fly >/dev/null
@ -300,8 +351,9 @@ if [ -n "$RELEASE_TARBALL" ]; then
# #
# FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps # FLY_ACCEPT_ADAPTERS is the *other* override, and the opposite one: it keeps
# the run. It names adapter version strings whose checkpoints the new build # the run. It names adapter version strings whose checkpoints the new build
# may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 for the deploy # may migrate — e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 for the deploy
# that adds the engagement rewards (v7; v5 -> v6 was the catch reward's). # that adds the damage reward (v8; v6 -> v7 was the engagement rewards', v5 -> v6
# the catch reward's).
# It only applies when the adapter segment is the # It only applies when the adapter segment is the
# ONLY difference between the two strings and the new build's adapter says it # ONLY difference between the two strings and the new build's adapter says it
# can read that one; a dataset, kernel, emulator or state-format change is # can read that one; a dataset, kernel, emulator or state-format change is
@ -355,7 +407,7 @@ The difference is usually an adapter/ladder or dataset version bump. Three ways
* deploy a build whose string matches (check out the commit the running release was built from), or * deploy a build whose string matches (check out the commit the running release was built from), or
* if the ADAPTER VERSION is the only segment that differs and the new build documents a * if the ADAPTER VERSION is the only segment that differs and the new build documents a
migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live migration from the old one, re-run with FLY_ACCEPT_ADAPTERS set to the adapter id in the live
string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v6). The run is kept; flysim applies the same string (e.g. FLY_ACCEPT_ADAPTERS=pokered-unique8-v7). The run is kept; flysim applies the same
rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or rule at restore. See docs/design/flysim.md, \"Restoring across an adapter version\", or
* accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which * accept losing everything the brain has learned and re-run with FLY_RESET_STATE=1, which
archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and archives ${state_dir}'s checkpoints to ${state_dir}.<timestamp> (kept, not deleted) and
@ -364,6 +416,53 @@ The 'current' symlink has NOT been moved; the running release is untouched."
fi fi
fi fi
# The session runtime (SERVE-01). While `fly-runtime session` has pointed flysim.service at
# flysim-session (the drop-in below), a release without that binary would leave the fly
# unable to start at all, and one whose session string differs from flysim's would write
# checkpoints the other runtime refuses. Refused here, before the symlink moves; to deploy
# such a release anyway, `fly-runtime legacy` first.
#
# Policy (C2 of the SERVE-01 review), operator decision 2026-09-29: "Session stays, trust gates".
# A deploy KEEPS the chosen runtime. It does not drop to legacy and does not re-run
# the shadow for the new flysim-session binary; the trust gates before the release (the
# parity and service tests, the compat check just below) are what vouch for it. A bad
# release is caught afterwards by the persistent fallback: while the drop-in exists,
# flysim.service carries OnFailure=fly-runtime-fallback.service and RestartMode=direct with a 3-starts-in-10-minutes
# limit, so a session binary that will not stay up puts the fly back on legacy by itself
# (`fly-runtime fallback`, /run/fly/runtime-fellback.json), whoever restarted it.
if ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/flysim-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime (fly-runtime session) and this release has no flysim-session. Run \`fly-runtime legacy\` in the container first, or deploy a release that ships it. The 'current' symlink has NOT been moved."
# BUS-01: on the bus transport flysim-session starts its participants from fly-session.
if ct_exec "$CTID" -- grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- test -x "${release_path}/fly-session" \
|| die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime on the bus (fly-runtime session --bus) and this release has no fly-session worker. Run \`fly-runtime session --local\` in the container first. The 'current' symlink has NOT been moved."
fi
session_compat="$(ct_exec "$CTID" -- env \
"FLY_GAME=${GAME}" \
"FLY_DATASET=${release_path}/data/fafb-v783" \
"FLY_ROM=/srv/fly/rom/${ROM_SHA256:-none}.gb" \
"${release_path}/flysim-session" --print-compatibility 2>/dev/null | tr -d '\r' || true)"
if [ -n "${new_compat:-}" ] && [ "$session_compat" != "$new_compat" ]; then
die "05-deploy: REFUSING to deploy release ${version}: flysim.service runs the session runtime and its compatibility string differs from flysim's.
flysim: ${new_compat}
flysim-session: ${session_compat}
The 'current' symlink has NOT been moved."
fi
log "05-deploy: flysim.service runs the session runtime; this release ships flysim-session with flysim's compatibility string"
fi
# The feed bus (EDGE-02). Bus mode needs the release's fly-edge: without it flyedge.service's
# ConditionPathExists= skips the unit, flysim has left :7400 to it, and the stage has no feed.
# Refused when the env file asks for bus, and when the container is in bus mode now (an edge
# that is running keeps running, but the first time it restarts there is nothing to start; and
# the way back is `fly-feed direct`, which needs no binary of this release).
if [ "$FLY_FEED_VIA_EFFECTIVE" = bus ] || [ "$FLY_FEED_VIA_LIVE" = bus ]; then
ct_exec "$CTID" -- test -x "${release_path}/fly-edge" \
|| die "05-deploy: REFUSING to deploy release ${version}: the feed is on the bus (FLY_FEED_VIA=bus: $([ "$FLY_FEED_VIA_EFFECTIVE" = bus ] && echo "in $1" || echo "on the container")) and this release has no fly-edge. Run \`fly-feed direct\` in the container and set FLY_FEED_VIA=direct in $1 first, or deploy a release that ships fly-edge. The 'current' symlink has NOT been moved."
log "05-deploy: the feed is on the bus; this release ships fly-edge"
fi
log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically" log "05-deploy: flipping /opt/fly/current -> ${release_path} atomically"
ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current" ct_exec "$CTID" -- sh -c "ln -sfn '$release_path' /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current"
else else
@ -374,7 +473,7 @@ fi
# 2. systemd units # 2. systemd units
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging systemd units" log "05-deploy: converging systemd units"
for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do for f in "$INFRA_DIR"/units/*.service "$INFRA_DIR"/units/*.slice "$INFRA_DIR"/units/*.timer "$INFRA_DIR"/units/fly.target; do
[ -f "$f" ] || continue [ -f "$f" ] || continue
name="$(basename "$f")" name="$(basename "$f")"
changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)" changed="$(converge_file "$CTID" "$f" "/etc/systemd/system/${name}" 0644 root:root)"
@ -490,6 +589,10 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# so FLY_ENCODER-style flipping between backends across restarts keeps the # so FLY_ENCODER-style flipping between backends across restarts keeps the
# checkpoint: the compatibility string this script gates on does not move. # checkpoint: the compatibility string this script gates on does not move.
echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}" echo "FLY_LIF_CUDA=${FLY_LIF_CUDA:-0}"
# Where the session worker writes fly_brain_backend (which hardware runs the
# LIF tick, and the GPU fallback count): the same textfile directory as
# fly_encoder.prom, read by fly-watchdog check 11 (runbook, "FLY_LIF_CUDA").
echo "FLY_BRAIN_BACKEND_PROM=${TEXTFILE_DIR:-/var/lib/node_exporter/textfile}/fly_brain_backend.prom"
# On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the # On-screen chat (docs/control-api.md [chat]). FLY_CHAT_ENABLED=0 is the
# kill switch: POST /chat answers 403 and the feed header omits `chat`, so # kill switch: POST /chat answers 403 and the feed header omits `chat`, so
# the CHAT panel blanks without touching flybridge or the page. flysim reads # the CHAT panel blanks without touching flybridge or the page. flysim reads
@ -505,6 +608,21 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# refuses anything but "raw" for a game with no macros, reads the retired # refuses anything but "raw" for a game with no macros, reads the retired
# "palette"/"plan" as "macros" with a warning, and refuses an unrecognised # "palette"/"plan" as "macros" with a warning, and refuses an unrecognised
# value outright. # value outright.
# PERF-02: flysim-session pins its sweep workers one per cpu of the cpuset it finds. That is only
# safe when the cpuset is the sim's alone: with the partition in force (section 3b) it is, and
# bin/fly-cpu-confine keeps every other process off it. Without it (no CPUSET, or a conf that does
# not match) the unit sees the container's whole cpuset, where a pinned worker would sit on a cpu
# anything can hog (measured 0.14x real time), so pinning is turned off: the threads float. The
# runtime reads the exact value 0 as off.
if [ "$PARTITION_ACTIVE" -eq 1 ]; then
echo "FLY_SESSION_PIN=1"
else
echo "FLY_SESSION_PIN=0"
fi
# EDGE-02 review N1: the bus threads' own cpu, in flysim.slice and in nobody else's set.
if [ "$PARTITION_ACTIVE" -eq 1 ] && [ -n "$SESSION_AUX_LIST" ]; then
echo "FLY_SESSION_AUX_CPUS=${SESSION_AUX_LIST}"
fi
echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}" echo "FLY_MACRO_MODE=${FLY_MACRO_MODE:-raw}"
# Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the # Who serves the feed WebSocket (docs/design/flybus.md, "Feed over the
# bus"). "direct" is the default and is flysim binding :7400 itself, as # bus"). "direct" is the default and is flysim binding :7400 itself, as
@ -513,9 +631,17 @@ trap 'rm -f "$tmp_fly_env" "$tmp_flypush_env"' EXIT
# never enables: see that unit's header for the switch. Written # never enables: see that unit's header for the switch. Written
# unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs. # unconditionally, like FLY_MACRO_MODE, so one grep says which a box runs.
# Watchdog check 2 reads this line to know whose /metrics carries the # Watchdog check 2 reads this line to know whose /metrics carries the
# feed counters (flysim's :9101, or flyedge's loopback :9102). # feed counters (flysim's :9101, or flyedge's :9102 (all interfaces, counters only)).
# Validated and lowercased above (feed_via_normalize). # Validated and lowercased above (feed_via_normalize).
echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}" echo "FLY_FEED_VIA=${FLY_FEED_VIA_EFFECTIVE}"
# Who serves the control API on :7401 (docs/design/flybus.md, "Control over
# the bus"). "direct" is the default: flysim binds it. "bus" makes flysim
# register the control services on its embedded router and leave :7401 to
# flycontrol-edge.service, which this script never enables (runbook,
# "Control over the bus"). Written unconditionally; the watchdog reads it
# to know whose /healthz is flysim's own (check 1) and whether to watch
# the edge (check 1b). Validated and lowercased above.
echo "FLY_CONTROL_VIA=${FLY_CONTROL_VIA_EFFECTIVE}"
# How long a macro leaves a target alone after a walk to it aborted # How long a macro leaves a target alone after a walk to it aborted
# (macros.md section 12.1, the Viridian stall). Only written when it is set, # (macros.md section 12.1, the Viridian stall). Only written when it is set,
# because the default lives in the crate and a box that has not tuned it # because the default lives in the crate and a box that has not tuned it
@ -649,35 +775,52 @@ if [ -n "${CPUSET:-}" ]; then
"Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \ "Run 01-create-ct.sh first; an AllowedCPUs= outside the container's own cpuset" \
"leaves cpuset.cpus.effective empty and the unit unstartable." "leaves cpuset.cpus.effective empty and the unit unstartable."
else else
read -r sim_cpus page_cpus encoder_cpus <<< "$(cpuset_partition "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE")" plan="$(cpuset_dropin_plan "$CPUSET" "$RAYON_THREADS_EFFECTIVE" "$ENCODER_CORES_EFFECTIVE" "$SESSION_AUX_EFFECTIVE")"
log "05-deploy: cpuset partition — flysim=$sim_cpus, xvfb/flystage/flystage-web/pulse/mediamtx/flyedge=$page_cpus, flycast=$encoder_cpus" log "05-deploy: cpuset partition — $(echo "$plan" | awk '$1 !~ /=$/ {printf "%s%s=%s", sep, $1, $2; sep=", "}')"
tmp_dropin="$(mktemp)" tmp_dropin="$(mktemp)"
# flyedge is off by default, but its drop-in is written with the rest so that the day # flyedge is off by default, but its drop-in is written with the rest so that the day
# it is enabled it serves the page from the page's CPUs, never from flysim's. # it is enabled it serves the page from the page's CPUs, never from flysim's; likewise
for u in flysim xvfb flystage flystage-web flycast pulse mediamtx flyedge; do # flycontrol-edge (CTRL-01).
case "$u" in # flysim-session (SERVE-01) is the session runtime's standalone unit: flysim's cores.
flysim) cpus="$sim_cpus" ;; # (`fly-runtime session` runs it AS flysim.service, which already has them.)
flycast) cpus="$encoder_cpus" ;; # flyshadow (SHADOW-01) is off by default too; when started it gets every CPU that is not
*) cpus="$page_cpus" ;; # flysim's, at SCHED_IDLE (its unit), so it only ever uses what the page and the encoder
esac # leave idle and never a cycle of the live fly's.
{ # flysim.slice (PERF-02 review N1) is where flysim.service and flysim-session.service run;
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit." # its CPUs are the sim's alone, and bin/fly-cpu-confine (run by those units' ExecStartPre,
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4." # using /etc/fly/cpuset.env below) confines system.slice, user.slice and init.scope to
echo "[Service]" # everything else. See that script's header for the cgroup semantics and the ordering rule.
echo "AllowedCPUs=${cpus}" # A for loop over an array, not `while read` fed from the plan: `pct exec` reads stdin.
} > "$tmp_dropin" mapfile -t plan_lines <<< "$plan"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.service.d" for plan_line in "${plan_lines[@]}"; do
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.service.d/cpuset.conf" 0644 root:root)" read -r u cpus <<< "$plan_line"
case "$u" in *=) continue ;; esac
cpuset_dropin_text "$u" "$cpus" "$ENV_LABEL" > "$tmp_dropin"
ct_exec "$CTID" -- mkdir -p "/etc/systemd/system/${u}.d"
changed="$(converge_file "$CTID" "$tmp_dropin" "/etc/systemd/system/${u}.d/cpuset.conf" 0644 root:root)"
if [ "$changed" = changed ]; then if [ "$changed" = changed ]; then
NEED_RELOAD=1 NEED_RELOAD=1
log "05-deploy: ${u}.service.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload" log "05-deploy: ${u}.d/cpuset.conf changed — it applies at the next RESTART of that unit, not at daemon-reload"
fi fi
done done
{
echo "# generated by infra/05-deploy.sh from CPUSET in ${ENV_LABEL} — do not hand-edit."
echo "$plan" | awk '$1 ~ /=$/ {print $1 $2}'
} > "$tmp_dropin"
changed="$(converge_file "$CTID" "$tmp_dropin" /etc/fly/cpuset.env 0644 root:root)"
[ "$changed" = changed ] && log "05-deploy: /etc/fly/cpuset.env changed — fly-cpu-confine applies it when flysim next (re)starts, by which time it runs in flysim.slice"
rm -f "$tmp_dropin" rm -f "$tmp_dropin"
fi fi
else else
log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)" log "05-deploy: CPUSET unset — no cpuset partition drop-ins (see infra/README.md step 4)"
fi fi
# No partition in force: nothing may stay confined by an earlier one, and the session runtime must
# not pin (fly.env above says FLY_SESSION_PIN=0). A confinement already applied lasts until the next
# boot or `fly-cpu-confine release`.
if [ "$PARTITION_ACTIVE" -ne 1 ]; then
ct_exec "$CTID" -- rm -f /etc/fly/cpuset.env
log "05-deploy: no cpuset partition: /etc/fly/cpuset.env removed, FLY_SESSION_PIN=0 in fly.env (sweep workers float); run \`fly-cpu-confine release\` if an earlier partition is still applied"
fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not # 4. bin/ helpers (fly-backup-stage is host-side only, deliberately not
@ -685,10 +828,28 @@ fi
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
log "05-deploy: converging bin/ helpers to /opt/fly/bin" log "05-deploy: converging bin/ helpers to /opt/fly/bin"
ct_exec "$CTID" -- mkdir -p /opt/fly/bin ct_exec "$CTID" -- mkdir -p /opt/fly/bin
for name in fly-watchdog fly-loop-recover fly-recap fly-retention fly-reset-to-milestone flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do for name in fly-watchdog fly-loop-recover fly-loop-reset fly-recap fly-retention fly-reset-to-milestone fly-cpu-confine fly-feed fly-runtime fly-runtime-probation fly-shadow-run flypush flystage-launch flycast-launch wait-for-x wait-for-stage wait-for-health; do
converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null converge_file "$CTID" "$INFRA_DIR/bin/$name" "/opt/fly/bin/$name" 0755 root:root >/dev/null
done done
# A container already on the session runtime keeps it (see the policy note at the compat check
# above), and its drop-in is rewritten in place from the current template (no restart) so that
# the OnFailure= fallback and MALLOC_ARENA_MAX reach containers switched before they existed.
if [ -n "${RELEASE_TARBALL:-}" ] && ct_exec "$CTID" -- test -f /etc/systemd/system/flysim.service.d/10-runtime.conf; then
ct_exec "$CTID" -- /opt/fly/bin/fly-runtime session --no-restart \
|| log "05-deploy: WARNING: could not refresh the session drop-in; it keeps its old content (no OnFailure= fallback until \`fly-runtime session\` is re-run)"
fi
# The NOPASSWD surface those helpers use (config/fly-sudoers). 02-base installs it at
# provision time; converging it here too means a release that adds a helper's line
# (fly-loop-reset, v0.6.4) does not need a re-provision. Validated before install.
log "05-deploy: converging config/fly-sudoers, validated before install"
TMP_SUDOERS="/tmp/fly-sudoers.$$"
ct_push_file "$CTID" "$INFRA_DIR/config/fly-sudoers" "$TMP_SUDOERS" 0440
ct_exec "$CTID" -- visudo -c -f "$TMP_SUDOERS" || die "config/fly-sudoers failed visudo -c, refusing to install it"
ct_exec "$CTID" -- install -o root -g root -m 0440 "$TMP_SUDOERS" /etc/sudoers.d/fly-watchdog
ct_exec "$CTID" -- rm -f "$TMP_SUDOERS"
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# 5. reload if anything unit-shaped changed # 5. reload if anything unit-shaped changed
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -26,7 +26,7 @@
# docs/design/stage-bridge.md section B1 has flybridge read # docs/design/stage-bridge.md section B1 has flybridge read
# TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate # TWITCH_CLIENT_ID and TWITCH_CLIENT_SECRET as two separate
# LoadCredentialEncrypted= values sourced from # LoadCredentialEncrypted= values sourced from
# twitch/fly-pokemon-client-{id,secret}. This script follows infra.md (the # twitch/<app>-client-{id,secret}. This script follows infra.md (the
# doc this task implements) and writes ONE twitch-app.cred containing both # doc this task implements) and writes ONE twitch-app.cred containing both
# values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own # values as two lines ("<client_id>\n<client_secret>\n"); flybridge's own
# implementation (out of scope here, not yet written) will need to parse # implementation (out of scope here, not yet written) will need to parse
@ -118,9 +118,14 @@ fi
# docs/stream-mvp-plan.md's rollout order) — install only if both pass # docs/stream-mvp-plan.md's rollout order) — install only if both pass
# entries already exist, so running this before the Twitch app is # entries already exist, so running this before the Twitch app is
# registered is a clean no-op rather than a hard failure. # registered is a clean no-op rather than a hard failure.
BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-twitch/helix-client-id}" # The two entry NAMES come from the env file (BRIDGE_ID_KEY, BRIDGE_SECRET_KEY): a
BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-twitch/helix-client-secret}" # `pass` entry name identifies the operator's store, so it is not spelled here.
if command -v pass >/dev/null 2>&1 \ BRIDGE_ID_KEY="${BRIDGE_ID_KEY:-}"
BRIDGE_SECRET_KEY="${BRIDGE_SECRET_KEY:-}"
if [ -z "$BRIDGE_ID_KEY" ] || [ -z "$BRIDGE_SECRET_KEY" ]; then
log "06-secrets: WARNING: BRIDGE_ID_KEY / BRIDGE_SECRET_KEY are not set in the env file, skipping twitch-app." \
"Set both to the pass entry names of the Twitch app id and secret (infra/env/example.env) to install it."
elif command -v pass >/dev/null 2>&1 \
&& pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \ && pass show "$BRIDGE_ID_KEY" >/dev/null 2>&1 \
&& pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then && pass show "$BRIDGE_SECRET_KEY" >/dev/null 2>&1; then
log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}" log "06-secrets: installing twitch-app from pass:${BRIDGE_ID_KEY} + pass:${BRIDGE_SECRET_KEY}"

View file

@ -267,6 +267,12 @@ refuses to write the drop-ins until the conf actually carries
`CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves `CPUSET`, because an `AllowedCPUs=` outside the container's own cpuset leaves
`cpuset.cpus.effective` empty and the unit unstartable. `cpuset.cpus.effective` empty and the unit unstartable.
The sim's CPUs are also kept exclusive to it (PERF-02 review N1, `infra/docs/runbook.md` "The sim's
CPUs are exclusive to the sim"): the sim units run in `flysim.slice`, and `bin/fly-cpu-confine`
confines `system.slice`, `user.slice`, `init.scope` and `/.lxc` (`pct exec`) to the other CPUs when the sim starts.
Without a partition (`CPUSET` unset) none of this applies and the deploy turns the session
runtime's worker pinning off (`FLY_SESSION_PIN=0`).
`CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local `CPUSET` is now eight WHOLE physical cores on one socket (node 0 for the release container, the GPU-local
socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md` socket; node 1 for the platformer container), not the four-cores-plus-SMT-siblings set `docs/design/gpu.md`
section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three section 1 originally specified: a four-core set cannot be partitioned so that flysim owns three

188
infra/bin/fly-cpu-confine Executable file
View file

@ -0,0 +1,188 @@
#!/usr/bin/env bash
# infra/bin/fly-cpu-confine — keep every process that is not the sim off the sim's CPUs.
#
# Usage (INSIDE the container, as root):
# fly-cpu-confine apply confine system.slice, user.slice, init.scope and /.lxc (where `pct exec`
# lands) to the non-sim CPUs
# fly-cpu-confine release undo `apply` (all of them go back to the container's whole cpuset)
# fly-cpu-confine status what each of them is confined to, and where the sim runs
# fly-cpu-confine check list every process that is not in flysim.slice but may run on a
# sim CPU (exit 1 if there is one); this command's own process and its
# parents (the shell it was started from) are noted, not failed
#
# Why. The session runtime pins its sweep workers one per CPU (PERF-02). A pinned worker cannot
# leave its CPU, so any sustained CPU-bound process that may run there stalls every barrier:
# measured 0.14x real time with a plain busy loop (0.68x at nice 19; SCHED_IDLE is harmless).
# Priorities do not fix that; keeping the sim's CPUs to the sim does.
#
# How (cgroup v2). flysim.service and flysim-session.service run in flysim.slice, which has
# AllowedCPUs= the sim's CPUs (a drop-in written by 05-deploy.sh). Its siblings under the root
# cgroup are system.slice (every other service, cron, apt, sshd), user.slice (every login
# session) and init.scope (PID 1 and what it forks). `apply` sets AllowedCPUs= the NON-sim CPUs
# on those three, so nothing that systemd places anywhere else can reach a sim CPU. A child's
# cpuset is bounded by its parent's, so the sim must never sit under a slice that excludes its
# CPUs: that is why it has a slice of its own and is not left in system.slice.
#
# The CPU lists come from ${CPUSET_ENV} (written by 05-deploy.sh, from the same cpuset_partition
# call as the AllowedCPUs= drop-ins). No file means no partition: nothing is confined.
#
# `apply` is runtime-only (systemctl set-property --runtime) and is run by flysim.service and
# flysim-session.service's ExecStartPre, so it is re-applied after every boot and every restart
# and can never run while the sim still sits in system.slice: shrinking system.slice under a
# sim that has not been restarted into flysim.slice would silently make it float over the page
# CPUs. `apply` refuses (exit 3, nothing changed) if a sim unit is outside flysim.slice.
#
# `pct exec` / `pct enter` (lxc-attach) put their processes in the cgroup `/.lxc` (or `/.lxc-N`),
# a sibling of system.slice that systemd does not manage. It is written directly
# (cpuset.cpus), only if it already exists (a cgroup lxc owns is never created here), and a
# failure is a warning, never an error: it must not stop the sim from starting. If it cannot be
# written, `check` lists what is running there; run long operator jobs with
# `systemd-run --scope --slice=system.slice -- <cmd>` (or `... -- bash`).
set -euo pipefail
: "${CPUSET_ENV:=/etc/fly/cpuset.env}"
: "${SYSTEMCTL:=systemctl}"
: "${PROC_ROOT:=/proc}"
: "${CGROUP_ROOT:=/sys/fs/cgroup}"
: "${SIM_SLICE:=flysim.slice}"
: "${SIM_UNITS:=flysim.service flysim-session.service}"
CONFINED_UNITS="system.slice user.slice init.scope"
# existing lxc attach cgroups (/.lxc, /.lxc-N) that have a cpuset
lxc_cgroups() {
local d
for d in "$CGROUP_ROOT"/.lxc "$CGROUP_ROOT"/.lxc-*; do
[ -d "$d" ] && [ -e "$d/cpuset.cpus" ] && echo "$d"
done
return 0
}
# set_lxc CPUS — write CPUS into every lxc attach cgroup; warn, never fail.
set_lxc() {
local d
for d in $(lxc_cgroups); do
if ! echo "$1" > "$d/cpuset.cpus" 2>/dev/null; then
log "WARNING: cannot write ${d}/cpuset.cpus; processes started with pct exec stay unconfined (run long jobs with systemd-run --scope --slice=system.slice)"
fi
done
return 0
}
log() { echo "fly-cpu-confine: $*" >&2; }
# read_env — set SIM_CPUS and OTHER_CPUS from ${CPUSET_ENV}, or return 1 when there is no partition.
# Parsed as KEY=VALUE lines, never sourced.
read_env() {
SIM_CPUS="" OTHER_CPUS=""
[ -r "$CPUSET_ENV" ] || return 1
local k v
while IFS='=' read -r k v; do
case "$k" in
FLY_SIM_CPUS) SIM_CPUS="$v" ;;
FLY_OTHER_CPUS) OTHER_CPUS="$v" ;;
esac
done < "$CPUSET_ENV"
[ -n "$SIM_CPUS" ] && [ -n "$OTHER_CPUS" ]
}
# expand LIST — one cpu number per line for a list such as 1,3,5-7.
expand() {
echo "$1" | tr ',' '\n' | awk -F- 'NF==1 && $1 != "" {print $1} NF==2 {for (i=$1;i<=$2;i++) print i}'
}
sim_outside_slice() {
local u cg
for u in $SIM_UNITS; do
cg="$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
[ -n "$cg" ] || continue
case "$cg" in
"/${SIM_SLICE}/"*) ;;
*) echo "$u ($cg)"; return 0 ;;
esac
done
return 1
}
cmd="${1:-}"
case "$cmd" in
apply)
if ! read_env; then
log "no partition configured (${CPUSET_ENV} missing or empty): nothing confined"
exit 0
fi
if out="$(sim_outside_slice)"; then
log "REFUSING to confine: $out runs outside ${SIM_SLICE}; restart it first (it would float over the page cpus otherwise)"
exit 3
fi
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${OTHER_CPUS}"
done
set_lxc "$OTHER_CPUS"
log "system.slice, user.slice, init.scope and /.lxc confined to ${OTHER_CPUS}; ${SIM_SLICE} keeps ${SIM_CPUS}"
;;
release)
# Not `AllowedCPUs=` (empty): systemd leaves the cgroup's cpuset.cpus at its last value while
# the cpuset controller stays enabled for some other unit (here flysim.slice), so the slices
# would stay confined. Set the container's whole cpuset explicitly.
all_cpus="$(cat "${CGROUP_ROOT}/cpuset.cpus.effective" 2>/dev/null || true)"
for u in $CONFINED_UNITS; do
timeout 20 "$SYSTEMCTL" set-property --runtime "$u" "AllowedCPUs=${all_cpus}"
done
set_lxc "$all_cpus"
log "system.slice, user.slice, init.scope and /.lxc released to the container's whole cpuset (${all_cpus:-unknown})"
;;
status)
for u in $CONFINED_UNITS $SIM_SLICE; do
echo "$u AllowedCPUs=$("$SYSTEMCTL" show -p AllowedCPUs --value "$u" 2>/dev/null || true)"
done
for d in $(lxc_cgroups); do
echo "${d#"$CGROUP_ROOT"} cpuset.cpus=$(cat "$d/cpuset.cpus" 2>/dev/null || true)"
done
for u in $SIM_UNITS; do
echo "$u ControlGroup=$("$SYSTEMCTL" show -p ControlGroup --value "$u" 2>/dev/null || true)"
done
;;
check)
if ! read_env; then
log "no partition configured: nothing to check"
exit 0
fi
sim="$(expand "$SIM_CPUS" | sort -n | tr '\n' ' ')"
bad=0
# this process and its parents (the pct exec shell chain) are not a CPU hog
self=" "
p="${SELF_PID:-$$}"
while [ -n "$p" ] && [ "$p" -gt 1 ] 2>/dev/null && [ "${#self}" -lt 400 ]; do
self="$self$p "
p="$(sed -n 's/^PPid:[[:space:]]*//p' "$PROC_ROOT/$p/status" 2>/dev/null || true)"
done
for d in "$PROC_ROOT"/[0-9]*; do
pid="${d##*/}"
[ -r "$d/status" ] || continue
cg="$(sed -n 's/^0:://p' "$d/cgroup" 2>/dev/null || true)"
case "$cg" in "/${SIM_SLICE}/"* | "/${SIM_SLICE}") continue ;; esac
# kernel threads have no cgroup of their own in this sense and are not a CPU hog
if [ -z "$(readlink "$d/exe" 2>/dev/null || true)" ]; then continue; fi
allowed="$(sed -n 's/^Cpus_allowed_list:[[:space:]]*//p' "$d/status")"
[ -n "$allowed" ] || continue
hit=""
for c in $(expand "$allowed"); do
for s in $sim; do [ "$c" = "$s" ] && hit="$hit$c,"; done
done
if [ -n "$hit" ]; then
case "$self" in *" $pid "*)
log "note: ${pid} ($(cat "$d/comm" 2>/dev/null)) is this check's own process chain in ${cg:-?} and may run on sim cpu ${hit%,}; not counted"
continue ;;
esac
echo "process $pid ($(cat "$d/comm" 2>/dev/null)) in ${cg:-?} may run on sim cpu ${hit%,}"
bad=1
fi
done
[ "$bad" -eq 0 ] && log "ok: only ${SIM_SLICE} can run on ${SIM_CPUS}"
exit "$bad"
;;
*)
sed -n '2,11p' "$0" >&2
exit 2
;;
esac

332
infra/bin/fly-feed Executable file
View file

@ -0,0 +1,332 @@
#!/usr/bin/env bash
# infra/bin/fly-feed — who serves the feed WebSocket (ws://127.0.0.1:7400/feed): flysim itself
# (`direct`) or fly-edge over flysim's feed bus (`bus`). EDGE-02; docs/design/flybus.md, "Feed over
# the bus"; the runbook's "Feed over the bus".
#
# Usage (INSIDE the container, as root):
# fly-feed status configured, running, the edge and its counters (any user)
# fly-feed bus [--no-restart] [--no-rollback]
# fly-feed direct [--no-restart] [--no-wait]
#
# One line decides: FLY_FEED_VIA in /etc/fly/fly.env. flysim reads it, flyedge.service's
# ExecCondition= reads it, flysim.service has Wants=flyedge.service, so every start of flysim brings
# up the edge in bus mode and skips it in direct mode, whoever started flysim and on whichever
# runtime (flysim or flysim-session, `fly-runtime`): nothing else has to be enabled, started or
# remembered. `fly-feed bus|direct` rewrites that line, restarts flysim.service (the feed changes
# hands at the start, so the stream is down for the length of a flysim restart, exactly like the
# unstick rule's) and waits until the page is on the feed again.
#
# What "healthy" means after a switch, in this order, within FLY_FEED_HEALTH_TIMEOUT (300 s):
# 1. flysim's /healthz answers (a NEW invocation: the old process is not mistaken for it);
# 2. bus: the edge's /healthz answers 200 (subscribed, snapshots arriving);
# 3. if flystage.service is active: its page is on the feed (`fly_feed_clients` >= 1 on the
# counters of whoever serves it) and `fly_frames_sent_total` advances. Without a page unit
# (a box that only serves the feed) the wait ends at 2.
# If that does not happen, `bus` puts FLY_FEED_VIA back to what it was, restarts flysim and checks
# the same way (--no-rollback leaves it to the operator); `direct` is already the way back, so it
# only reports. `direct` is the safe terminal state: once the line says direct nothing, an
# interrupted switch included (ssh drops, INT/TERM/HUP), puts bus back, and an interrupted
# `direct` restarts flysim itself so the running process matches the line. An interrupted `bus`
# rolls back the same way as a failed one.
# `--no-restart` only rewrites the line (the next start of flysim applies it). `--no-wait` restarts
# flysim without blocking and does not wait for health or roll anything back: it is what the
# watchdog runs (as a sudoers-granted `fly-feed direct --no-wait`) when the edge cannot be kept up.
#
# 05-deploy.sh writes FLY_FEED_VIA into fly.env from the operator's env file on every deploy and
# does not restart flysim. After a `fly-feed bus`, put FLY_FEED_VIA=bus in the env file too, or the
# next deploy writes `direct` back (the next flysim start would then follow it) and says so.
#
# Restarts count against flysim.service's start limit (3 in 10 minutes while the session runtime is
# selected, `fly-runtime`): a switch and its rollback are two.
#
# Every switch is logged to the journal (tag fly-feed) and ${FEED_LOG}.
set -euo pipefail
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_EDGE_SERVICE:=flyedge.service}"
: "${FLY_PAGE_SERVICE:=flystage.service}"
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_EDGE_METRICS_URL:=http://127.0.0.1:9102}"
: "${FLY_PROC_DIR:=/proc}"
: "${FLY_FEED_HEALTH_TIMEOUT:=300}"
: "${FLY_FEED_LOG:=/var/lib/fly/feed.log}"
: "${FLY_FEED_LOCK:=/run/fly/feed.lock}"
: "${FLY_FEED_SAMPLE_SECONDS:=3}"
FEED_LOG="$FLY_FEED_LOG"
log() { echo "fly-feed: $*" >&2; }
die() { log "$*"; exit 1; }
record() {
if command -v logger >/dev/null 2>&1; then
logger -t fly-feed -- "$*" || true
fi
mkdir -p "$(dirname "$FEED_LOG")" 2>/dev/null || true
echo "$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*" >>"$FEED_LOG" 2>/dev/null || log "could not append to $FEED_LOG"
}
usage() {
echo "usage: fly-feed status | bus [--no-restart] [--no-rollback] [--no-wait] | direct [--no-restart] [--no-wait]" >&2
exit 2
}
# direct | bus | invalid:<value>. flysim reads the value case-insensitively; a missing line is direct.
configured() {
local value=""
if [ -f "$FLY_ENV_FILE" ]; then
value="$(awk -F= '/^FLY_FEED_VIA=/ { v=$0; sub(/^FLY_FEED_VIA=/, "", v); last=v } END { print last }' "$FLY_ENV_FILE" 2>/dev/null || true)"
fi
value="$(printf '%s' "$value" | tr -d ' \r"' | tr '[:upper:]' '[:lower:]')"
case "$value" in
""|direct) echo direct ;;
bus) echo bus ;;
*) echo "invalid:${value}" ;;
esac
}
# What the running flysim process started with (its environment, not the file): direct | bus |
# stopped | unknown.
running() {
local pid value
pid="$(systemctl show -p MainPID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
if [ -z "$pid" ] || [ "$pid" = 0 ]; then echo stopped; return; fi
if [ ! -r "${FLY_PROC_DIR}/${pid}/environ" ]; then echo unknown; return; fi
value="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
case "$value" in
bus) echo bus ;;
*) echo direct ;;
esac
}
# The counters of whoever serves the feed in `via` mode.
metrics_url() {
if [ "$1" = bus ]; then echo "$FLY_EDGE_METRICS_URL"; else echo "$FLY_METRICS_URL"; fi
}
# metric URL NAME -> the value of the first sample of NAME, or empty.
metric() {
curl -fsS --max-time 5 "$1/metrics" 2>/dev/null | awk -v n="$2" '$1 == n { print $2; exit }' || true
}
# Whole-number part of a Prometheus value ("3", "3.0", "1e+06" is not expected for these).
whole() { printf '%.0f' "${1:-0}" 2>/dev/null || echo 0; }
# The page is on the feed: at least one client, and the frames counter moves over a sample.
page_on_feed() {
local url first second clients
url="$(metrics_url "$1")"
clients="$(metric "$url" fly_feed_clients)"
[ "$(whole "$clients")" -ge 1 ] || return 1
first="$(metric "$url" fly_frames_sent_total)"
sleep "$FLY_FEED_SAMPLE_SECONDS"
second="$(metric "$url" fly_frames_sent_total)"
[ -n "$first" ] && [ -n "$second" ] && [ "$(whole "$second")" -gt "$(whole "$first")" ]
}
page_unit_active() { systemctl is-active --quiet "$FLY_PAGE_SERVICE" 2>/dev/null; }
old_invocation=""
# Print to stdout, exiting quietly once the reader has gone (`fly-feed status | head -1`).
# Under `pct exec` SIGPIPE is ignored, so a write to a closed pipe fails with EPIPE and bash's
# printf/echo print "write error: Broken pipe": silence that one write and stop printing.
say() {
printf '%s\n' "$*" 2>/dev/null || exit 0
}
# Wait for a NEW flysim invocation to be healthy and the feed to be flowing in `via` mode.
healthy() {
local via="$1" deadline
deadline=$(( $(date +%s) + FLY_FEED_HEALTH_TIMEOUT ))
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
if [ "$via" = bus ] && ! curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
sleep 1
continue
fi
if ! page_unit_active; then
log "healthy (${via}): ${FLY_PAGE_SERVICE} is not active, so no page to wait for"
return 0
fi
if page_on_feed "$via"; then
log "healthy (${via}): the page is on the feed and frames are moving"
return 0
fi
fi
sleep 1
done
return 1
}
# Rewrite (or add) the FLY_FEED_VIA line, keeping every other line, the mode and the owner.
set_via() {
local value="$1" tmp
[ -f "$FLY_ENV_FILE" ] || die "no ${FLY_ENV_FILE}; deploy first (infra/05-deploy.sh writes it)"
tmp="$(mktemp "${FLY_ENV_FILE}.XXXXXX")"
awk -v v="$value" '
/^FLY_FEED_VIA=/ { if (!done) { print "FLY_FEED_VIA=" v; done=1 } ; next }
{ print }
END { if (!done) print "FLY_FEED_VIA=" v }
' "$FLY_ENV_FILE" >"$tmp"
chmod --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || chmod 0640 "$tmp"
chown --reference="$FLY_ENV_FILE" "$tmp" 2>/dev/null || true
mv -f "$tmp" "$FLY_ENV_FILE"
}
locked=0
take_lock() {
[ "$locked" -eq 0 ] || return 0
mkdir -p "$(dirname "$FLY_FEED_LOCK")" 2>/dev/null || true
exec 8>>"$FLY_FEED_LOCK"
flock -w 60 8 || die "another fly-feed holds ${FLY_FEED_LOCK}; not switching"
locked=1
}
restart_flysim() {
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
log "restarting ${FLY_SERVICE}"
# --no-block: a start that never becomes READY must not hold this process (and the lock);
# `healthy` proves it is talking to the new invocation.
systemctl restart --no-block "$FLY_SERVICE"
}
status_report() {
local conf run edge_state url
conf="$(configured)"
run="$(running)"
say "configured: ${conf}"
say "running: ${run}"
if [ "$run" != stopped ] && [ "$run" != unknown ] && [ "$conf" != "$run" ] && [[ "$conf" != invalid:* ]]; then
say " fly.env and the running flysim disagree: the next start of ${FLY_SERVICE} applies ${conf} (fly-feed ${conf} does it now)"
fi
edge_state="$(systemctl is-active "$FLY_EDGE_SERVICE" 2>/dev/null || true)"
say "${FLY_EDGE_SERVICE}: ${edge_state:-unknown}"
url="$(metrics_url "$run")"
if [ "$run" = bus ]; then
if curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
say "edge healthz: ok"
else
say "edge healthz: NOT OK ($(curl -sS --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>&1 | head -c 100))"
fi
say "edge snapshot age: $(metric "$url" fly_edge_snapshot_age_seconds) s; bus lost: $(metric "$url" fly_edge_bus_lost_total); bind failures: $(metric "$url" fly_edge_bind_failures_total); decode failures: $(metric "$url" fly_edge_decode_failures_total)"
fi
say "feed clients: $(metric "$url" fly_feed_clients) (counters of the ${run} server); frames sent: $(metric "$url" fly_frames_sent_total)"
if [ -f "$FEED_LOG" ]; then say "last switch: $(tail -n1 "$FEED_LOG")"; fi
}
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
rollback=1
wait_for_health=1
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-rollback) rollback=0 ;;
--no-wait) wait_for_health=0 ;;
*) usage ;;
esac
done
case "$command" in
status) status_report; exit 0 ;;
bus|direct) ;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${FLY_ENV_FILE} and restarts ${FLY_SERVICE})"
before="$(configured)"
[[ "$before" != invalid:* ]] || die "FLY_FEED_VIA in ${FLY_ENV_FILE} is '${before#invalid:}', not direct or bus; fix it (a deploy rewrites it) before switching"
if [ "$command" = bus ]; then
[ -x "${FLY_RELEASE_DIR}/fly-edge" ] || die "this release has no ${FLY_RELEASE_DIR}/fly-edge; bus mode needs one (deploy a release that ships it)"
fi
take_lock
running_before="$(running)"
if [ "$before" = "$command" ] && [ "$running_before" = "$command" ] && [ "$restart" -eq 1 ]; then
log "already ${command}: fly.env says it and the running flysim started that way; nothing to do"
status_report
exit 0
fi
# An interrupted or failed `bus` puts the previous value back and restarts flysim on it. When
# the line already said bus (a deploy wrote it, the running flysim never started that way), the
# way back is direct: the state that worked.
back="$before"
if [ "$before" = bus ] && [ "$command" = bus ]; then back=direct; fi
# Direct is where a failed bus ends up, so a switch TO direct has nowhere safer to go: it is never
# undone (it used to roll back to `before`, which sent an operator escaping a bad bus back onto it).
if [ "$command" = direct ]; then back=direct; fi
switching=0
restarted=0
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
set_via "$back" || true
if [ "$command" = direct ]; then
record "direct (switch to direct interrupted (exit ${rc}); kept: direct is the safe state, flysim restarted to match)"
else
record "${back} (switch to ${command} interrupted or failed (exit ${rc}); rolled back)"
fi
if [ "$restarted" -eq 1 ]; then restart_flysim || true; fi
fi
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
switching=1
set_via "$command"
record "${command} (was ${before}; flysim was running ${running_before})"
if [ "$restart" -ne 1 ]; then
switching=0
log "FLY_FEED_VIA=${command} written; the next start of ${FLY_SERVICE} applies it"
exit 0
fi
restarted=1
restart_flysim
if [ "$wait_for_health" -ne 1 ]; then
switching=0
record "${command}: flysim restart queued (--no-wait); health not checked"
log "restart queued; fly-feed status shows the result"
exit 0
fi
if healthy "$command"; then
switching=0
if [ "$command" = direct ] && systemctl is-active --quiet "$FLY_EDGE_SERVICE" 2>/dev/null; then
log "WARNING: ${FLY_EDGE_SERVICE} is still active in direct mode; stopping it"
systemctl stop "$FLY_EDGE_SERVICE" || true
fi
record "${command}: healthy"
log "the feed is served ${command}"
exit 0
fi
log "the feed did not come up healthy (${command}) within ${FLY_FEED_HEALTH_TIMEOUT}s"
if [ "$command" = bus ] && [ "$rollback" -eq 1 ]; then
set_via "$back"
switching=0
record "${back} (automatic rollback: ${command} was not healthy within ${FLY_FEED_HEALTH_TIMEOUT}s)"
restart_flysim
if healthy "$back"; then
log "rolled back to ${back}; it is healthy"
else
log "rolled back to ${back}, and it is NOT healthy either: journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE}"
fi
else
switching=0
record "${command}: NOT healthy; left as it is (journalctl -u ${FLY_SERVICE} -u ${FLY_EDGE_SERVICE})"
fi
exit 1

View file

@ -1,67 +1,381 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
"""Conservative, out-of-process loop recovery; invoked after the watchdog probe.""" """Out-of-process loop recovery with an escalation ladder; invoked after the watchdog probe.
Ladder (infra/docs/loop-recovery.md): restart flysim, then reset to the current rung's
milestone, then to the rung below. It climbs one step per confirmed trap that outlives
the previous step, and starts over once the fly reaches a new best rung, makes lasting
progress after the last step that it had not made before (a reset's replay re-earns its
archive's rewards, which is not progress), or has been quiet for QUIET seconds. A milestone reset
never erases a species first owned within PROTECT seconds, and never repeats the last
reset's archive (a restore replays it exactly); either is a restart instead. A router model can
delay a step, never deny it.
"""
import json import json
import os import os
from pathlib import Path from pathlib import Path
import re
import subprocess import subprocess
import sys import sys
import time import time
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
REPORT = Path(os.environ.get("FLY_LOOP_REPORT", "/run/fly/wd/loop.json")) REPORT = Path(os.environ.get("FLY_LOOP_REPORT", "/run/fly/wd/loop.json"))
STATE = Path(os.environ.get("FLY_LOOP_RECOVERY_STATE", "/run/fly/wd/recovery.json")) STATE = Path(os.environ.get("FLY_LOOP_RECOVERY_STATE", "/var/lib/fly-loop-recover/state.json"))
HISTORY = Path(os.environ.get("FLY_LOOP_RECOVERY_HISTORY", "/var/lib/fly-loop-recover/history.jsonl"))
NOTICE = Path(os.environ.get("FLY_RECOVERY_NOTICE", "/run/fly/wd/recovery-notice.json"))
MILESTONES = Path(os.environ.get("FLY_STATE_DIR", "/srv/fly/state"))
STATUS_URL = os.environ.get("FLY_STATUS_URL", "http://127.0.0.1:7401/status")
RESET_BIN = os.environ.get("FLY_LOOP_RESET_BIN", "/opt/fly/bin/fly-loop-reset")
INTERVAL = int(os.environ.get("WD_LOOP_INTERVAL", "300")) INTERVAL = int(os.environ.get("WD_LOOP_INTERVAL", "300"))
COOLDOWN = 3600 COUNTDOWN = int(os.environ.get("FLY_LOOP_COUNTDOWN", "60"))
SETTLE = 1200 # a report inside this after an action may still hold the old window
QUIET = 6 * 3600 # this long without a suspected report starts the ladder over
HOLD = 3 * 3600 # restart-only spacing while the reset budget is spent
DAY = 24 * 3600
MAX_RESETS = 2 # milestone resets per DAY
AGAIN = 12 * 3600 # after this long the last reset's archive may be restored again (row 70)
PROTECT = 2 * 3600 # a species owned this recently is not reset away (row 70)
SEEN = 2000 # lasting-progress names remembered, oldest dropped first (row 70 r3)
VETO_LIMIT = 3 # model vetoes of one step before it goes ahead anyway
MODEL_BUDGET = 90 # seconds across all models in one decision
VERIFY_TIMEOUT = 240
LIST_TIMEOUT = 120
RESTART_TIMEOUT = 180
RESET_TIMEOUT = 480 # the wrapper waits up to 60 s for the watchdog, then stop, reset, start
# docs/design/ladder.md; mirrors RANK_LADDER in flybrain-gb's pokemon_red/mod.rs (a test pins it).
LADDER = [
"BOOT", "BEDROOM", "DOWNSTAIRS", "PALLET TOWN", "OAK'S LAB", "GOT A STARTER", "OAK'S PARCEL",
"POKEDEX", "VIRIDIAN CITY", "VIRIDIAN FOREST", "PEWTER CITY", "BOULDER BADGE", "MT. MOON",
"CERULEAN CITY", "CASCADE BADGE", "NUGGET BRIDGE", "MET BILL", "VERMILION CITY", "HM CUT",
"THUNDER BADGE", "ROCK TUNNEL", "LAVENDER TOWN", "CELADON CITY", "SILPH SCOPE", "RAINBOW BADGE",
"POKE FLUTE", "FUCHSIA CITY", "SOUL BADGE", "SILPH CO. FREED", "MARSH BADGE", "CINNABAR ISLAND",
"VOLCANO BADGE", "EARTH BADGE", "INDIGO PLATEAU", "BEAT LORELEI", "BEAT BRUNO", "BEAT AGATHA",
"CHAMPION",
]
PROMPT = (
"You check a Game Boy Pokemon Red run played by a simulated fly brain through macros "
"(GO OBJECTIVE, GO WARP, GO ROUTE, FIGHT, ...). A watchdog flagged a suspected loop over "
"a 10-minute brain window. Stuck means the same few macros repeat with no new places "
"(places.delta 0) and no rewards; healthy play finds new places, wins battles or earns "
"rewards. Answer with only the JSON object {\"stuck\": true} or {\"stuck\": false}. "
"No explanation, no reasoning, no other text."
)
def load(path, default):
try:
return json.loads(path.read_text())
except (OSError, ValueError):
return default
def write_json(path, value):
path.parent.mkdir(parents=True, exist_ok=True)
tmp = path.with_name(path.name + ".tmp")
tmp.write_text(json.dumps(value) + "\n")
os.chmod(tmp, 0o644)
tmp.replace(path)
def log(event):
try:
HISTORY.parent.mkdir(parents=True, exist_ok=True)
with HISTORY.open("a") as out:
out.write(json.dumps(event) + "\n")
except OSError as error:
print("history not written:", error, file=sys.stderr)
def models():
names = os.environ.get("FLY_LOOP_MODELS") or os.environ.get("FLY_LOOP_MODEL") or ""
return [name.strip() for name in names.split(",") if name.strip()]
def parse_stuck(content):
"""The stuck flag from a free model's reply, which may wrap the JSON in prose or fences."""
for match in re.finditer(r"\{[^{}]*\}", content or ""):
try:
decision = json.loads(match.group(0))
except ValueError:
continue
if type(decision) is dict and type(decision.get("stuck")) is bool:
return decision["stuck"]
return None
def verdict(report): def verdict(report):
"""True/False from the first model that answers, None when no router or none answered."""
url = os.environ.get("FLY_LOOP_ROUTER_URL") url = os.environ.get("FLY_LOOP_ROUTER_URL")
model = os.environ.get("FLY_LOOP_MODEL") names = models()
if not url and not model: if not url or not names:
return True return None, None
if not url or not model: brief = {key: report.get(key) for key in ("reason", "sequence", "window", "places", "milestone", "dominant", "map")}
return False
payload = {"model": model, "temperature": 0, "messages": [
{"role": "system", "content": "Classify whether a suspected repeating game macro loop is truly stuck. Return only JSON {\"stuck\":true|false}. No instructions or commands."},
{"role": "user", "content": json.dumps({key: report.get(key) for key in ("reason", "sequence", "window", "places", "milestone")})},
]}
headers = {"Content-Type": "application/json"} headers = {"Content-Type": "application/json"}
key = os.environ.get("FLY_LOOP_ROUTER_KEY") key = os.environ.get("FLY_LOOP_ROUTER_KEY")
if key: if key:
headers["Authorization"] = "Bearer " + key headers["Authorization"] = "Bearer " + key
request = Request(url.rstrip("/") + "/chat/completions", json.dumps(payload).encode(), headers) deadline = time.monotonic() + MODEL_BUDGET
with urlopen(request, timeout=20) as response: for name in names:
answer = json.load(response) left = deadline - time.monotonic()
decision = json.loads(answer["choices"][0]["message"]["content"]) if left < 5:
return type(decision) is dict and type(decision.get("stuck")) is bool and decision["stuck"] break
payload = {"model": name, "temperature": 0, "max_tokens": 400, "messages": [
{"role": "system", "content": PROMPT},
{"role": "user", "content": json.dumps(brief)},
]}
request = Request(url.rstrip("/") + "/chat/completions", json.dumps(payload).encode(), headers)
try:
with urlopen(request, timeout=min(30, left)) as response:
answer = json.load(response)
stuck = parse_stuck(answer["choices"][0]["message"]["content"])
except (OSError, ValueError, KeyError, IndexError, TypeError) as error:
print(f"model {name}: {type(error).__name__} {getattr(error, 'code', '')}".rstrip(), file=sys.stderr)
continue
if stuck is None:
print(f"model {name}: no stuck flag in reply", file=sys.stderr)
continue
return stuck, name
return None, None
def run(now=None): def rungs():
now = int(time.time() if now is None else now) found = []
report = json.loads(REPORT.read_text()) for path in MILESTONES.glob("milestone-*.checkpoint"):
previous = json.loads(STATE.read_text()) if STATE.exists() else {} number = path.stem.removeprefix("milestone-")
if number.isdigit():
found.append(int(number))
return sorted(found)
def plan(level, rank, best, resets_left, last_reset=None):
"""(action, target rung) for a ladder level; a spent budget or no restorable archive is a restart.
Level 1 resets to the current rung's archive; level 2 and beyond to the rung below the best,
and never lower, so repeated days of a trap cannot walk the run down the ladder. The archive
the last reset restored is not restored again (`last_reset`, cleared by a new best rung): a
restore is deterministic, so the same archive replays the same run into the same trap (row 70:
the second reset to rung 11 matched the first event for event).
"""
if level == 0 or not resets_left or rank is None:
return "restart", None
target = rank if level == 1 else max(best, rank) - 1
if target > rank or target == last_reset or target not in restorable_rungs():
return "restart", None
return "reset", target
def restorable_rungs():
"""The rungs the running build can restore (fly-loop-reset --list), empty on any failure."""
try:
done = subprocess.run(["sudo", "-n", RESET_BIN, "--list"], check=False, timeout=LIST_TIMEOUT,
capture_output=True, text=True)
except (OSError, subprocess.SubprocessError) as error:
print("restorable rungs unknown:", type(error).__name__, file=sys.stderr)
return set()
if done.returncode != 0:
return set()
return {int(line) for line in done.stdout.split() if line.isdigit()}
def status():
try:
with urlopen(STATUS_URL, timeout=5) as response:
return json.load(response)
except (OSError, ValueError):
return None
def verify(target, deadline):
while time.monotonic() < deadline:
now = status()
if now and now.get("status") == "running":
rank = (now.get("milestone") or {}).get("rank")
if target is None or rank == target:
return True
time.sleep(5)
return False
def act(action, target):
if action == "restart":
command, limit = ["sudo", "-n", "systemctl", "restart", "flysim.service"], RESTART_TIMEOUT
else:
command, limit = ["sudo", "-n", RESET_BIN, str(target)], RESET_TIMEOUT
try:
done = subprocess.run(command, check=False, timeout=limit)
except (OSError, subprocess.SubprocessError) as error:
print(f"{action} did not complete: {type(error).__name__}", file=sys.stderr)
return False
if done.returncode != 0:
return False
return verify(target, time.monotonic() + VERIFY_TIMEOUT)
def notice(base, phase, now):
try:
write_json(NOTICE, dict(base, phase=phase, updatedAt=int(now)))
except OSError as error:
print("notice not written:", error, file=sys.stderr)
def run(now=None, sleep=time.sleep, clock=None):
clock = clock or (time.time if now is None else (lambda: now))
now = int(clock())
report = load(REPORT, None)
if type(report) is not dict:
return "no watchdog report"
state = load(STATE, {})
if type(state) is not dict:
state = {}
rank = (report.get("milestone") or {}).get("rank")
level = state.get("level", 0)
if type(rank) is int and rank > state.get("bestRank", 0):
if level:
log({"at": now, "event": "ladder-reset", "why": "new best rung", "rank": rank})
state.update(bestRank=rank, level=0)
state.pop("lastReset", None)
level = 0
if "lastReset" in state and now - state.get("lastResetAt", 0) >= AGAIN:
state.pop("lastReset", None)
last = state.get("lastSuspectedAt")
if level and last and now - last > QUIET:
log({"at": now, "event": "ladder-reset", "why": "quiet", "rank": rank})
state["level"] = level = 0
state["resets"] = [at for at in state.get("resets", []) if now - at < DAY]
at = report.get("at") at = report.get("at")
# Row 70: lasting progress in the probe's window (a new rung, a species owned, a map entered,
# a trainer or badge beaten; the watchdog's window.progress). The ladder climbs for a trap that
# OUTLIVES its last step; one that follows real progress after that step is a new trap and
# starts again from a restart. A species owned is also kept from a milestone reset for PROTECT.
# A new trap means the old one let go: a clear probe more than SETTLE after the step, so a catch
# made while the fly stays flagged does not start the ladder over.
#
# Progress is measured against everything the ladder has seen before, not against the
# restored archive (row 70 review r3): a milestone reset restores the reward ledger, so the
# replay pays the archive's areas, trainers, species and rungs again, and counting those
# started the ladder over after every reset (a rung-12 replay re-earning an area and a
# species cost two extra steps and a three-hour hold before the rung below). The watchdog
# names each lasting reward (`window.progress.keys`, `kind:label`); only a name not in
# `progressSeen` is progress, and only a species not in it is protected (the replayed catch
# was the fly's before the reset too, and was protected then). A watchdog without names falls
# back to the counts.
progress = (report.get("window") or {}).get("progress") or {}
fresh = type(at) is int and 0 <= now - at <= 600
if fresh and report.get("suspected") == 0:
state["clearAt"] = max(at, state.get("clearAt", 0))
if fresh and type(progress) is dict:
keys = progress.get("keys")
if type(keys) is list:
seen = state.get("progressSeen")
seen = [key for key in seen if type(key) is str] if type(seen) is list else []
known = set(seen)
new = [key for key in dict.fromkeys(key for key in keys if type(key) is str) if key not in known]
state["progressSeen"] = (seen + new)[-SEEN:]
lasting, species = len(new), sum(key.startswith("pokedex:") for key in new)
else:
lasting, species = (progress.get(name) if type(progress.get(name)) is int else 0
for name in ("lasting", "species"))
if lasting > 0:
state["progressAt"] = max(at, state.get("progressAt", 0))
if species > 0:
state["speciesAt"] = max(at, state.get("speciesAt", 0))
since = state.get("actedAt", 0) + SETTLE
if level and state.get("progressAt", 0) > since and state.get("clearAt", 0) > since:
log({"at": now, "event": "ladder-reset", "why": "progress since the last step", "rank": rank})
state["level"] = level = 0
# The last probe that saw progress (new places, or a higher rung than the last probe), kept across
# restarts and reboots so the stream's STUCK time counts the whole trap, not the last streak.
delta = (report.get("places") or {}).get("delta")
if type(at) is int and 0 <= now - at <= 600 and (
(type(delta) is int and delta > 0)
or (type(rank) is int and type(state.get("rank")) is int and rank > state["rank"])):
state["lastProgressAt"] = at
if type(rank) is int:
state["rank"] = rank
if (report.get("suspected") != 1 or type(at) is not int if (report.get("suspected") != 1 or type(at) is not int
or not 0 <= now - at <= 600 or report.get("action") != "none"): or not 0 <= now - at <= 600 or report.get("action") != "none"):
STATE.write_text(json.dumps({key: previous[key] for key in ("restarted_at",) if key in previous}) + "\n") state.pop("observedAt", None)
state["vetoes"] = 0
write_json(STATE, state)
return "not a fresh suspected loop" return "not a fresh suspected loop"
if "restarted_at" in previous and now - previous["restarted_at"] < COOLDOWN:
return "recovery cooldown" state["lastSuspectedAt"] = now
if previous.get("observed_at") == at: acted = state.get("actedAt", 0)
return "waiting for next probe" if at < acted + SETTLE:
if not previous.get("observed_at") or at - previous["observed_at"] < INTERVAL - 30: write_json(STATE, state)
STATE.write_text(json.dumps({"observed_at": at}) + "\n") return f"settling after {state.get('lastAction')}"
observed = state.get("observedAt")
if not observed or observed < acted + SETTLE:
state["observedAt"] = at
write_json(STATE, state)
return "waiting for second probe" return "waiting for second probe"
try: if at - observed < INTERVAL - 30:
approved = verdict(report) write_json(STATE, state)
except (OSError, ValueError, KeyError, IndexError) as error: return "waiting for next probe"
print("router unavailable or invalid:", type(error).__name__, file=sys.stderr)
return "router unavailable" resets_left = MAX_RESETS - len(state["resets"])
if not approved: action, target = plan(level, rank, state.get("bestRank", 0), resets_left, state.get("lastReset"))
return "router did not confirm" protected = action == "reset" and now - state.get("speciesAt", -PROTECT) < PROTECT
subprocess.run(["sudo", "-n", "systemctl", "restart", "flysim.service"], check=True) # Only a catch-protected reset is held (the level keeps its slot, so it never drops a rung deeper
STATE.write_text(json.dumps({"observed_at": at, "restarted_at": now}) + "\n") # while the window lasts, row 70). A step skipped because it would restore the archive just used
return "flysim restarted; checkpoint restore keeps the rung" # does climb, so the ladder reaches the rung below promptly.
held_reset = protected
if protected:
action, target = "restart", None
# Restarts are at least HOLD apart, also when the ladder has started over since the last one.
if action == "restart" and (level or state.get("lastAction") == "restart") and now - acted < HOLD:
write_json(STATE, state)
if protected:
return "holding: a species owned within the protection window, next restart after the hold"
if not level:
return "holding: the last restart was under three hours ago"
return "holding: no reset to take, next restart after the hold"
if protected:
log({"at": now, "event": "protect", "why": "a species owned within the protection window",
"speciesAt": state["speciesAt"], "rank": rank})
stuck, model = verdict(report)
if stuck is False and state.get("vetoes", 0) < VETO_LIMIT:
state["vetoes"] = state.get("vetoes", 0) + 1
write_json(STATE, state)
log({"at": now, "event": "veto", "model": model, "vetoes": state["vetoes"], "rank": rank})
return f"model {model} says not stuck ({state['vetoes']}/{VETO_LIMIT})"
why = {True: f"confirmed by {model}", False: "veto limit reached", None: "no model answer, watchdog alone"}[stuck]
base = {"v": 1, "id": f"{now}-{action}", "action": action,
"fromRung": rank, "fromLabel": (report.get("milestone") or {}).get("label"),
"reason": report.get("reason"), "loop": (report.get("sequence") or [])[:4],
"stuckSeconds": now - state["lastProgressAt"] if state.get("lastProgressAt")
else max(0, now - observed) + 600,
"announcedAt": now, "executeAt": now + COUNTDOWN}
if action == "reset":
base.update(toRung=target, toLabel=LADDER[target] if 0 <= target < len(LADDER) else None)
notice(base, "countdown", now)
sleep(COUNTDOWN)
started = int(clock())
# Recorded before acting, so a helper killed mid-step has still climbed (unless held) and spent the reset.
state.update(level=level if held_reset else level + 1, actedAt=started, lastAction=action, vetoes=0)
state.pop("observedAt", None)
if action == "reset":
state["resets"].append(started)
state.update(lastReset=target, lastResetAt=started)
write_json(STATE, state)
notice(base, "acting", started)
ok = act(action, target)
finished = int(clock())
if action == "reset" and not ok:
state.pop("lastReset", None) # not known to have been restored, so it may be tried again
notice(base, "done" if ok else "failed", finished)
state["actedAt"] = finished
write_json(STATE, state)
log({"at": finished, "event": action, "target": target, "ok": ok, "why": why, "rank": rank,
"level": level, "sequence": report.get("sequence"), "map": report.get("map")})
outcome = "flysim restarted" if action == "restart" else f"reset to rung {target}"
return f"{outcome} ({why})" if ok else f"{action} FAILED ({why})"
if __name__ == "__main__": if __name__ == "__main__":

172
infra/bin/fly-loop-reset Executable file
View file

@ -0,0 +1,172 @@
#!/usr/bin/env bash
# infra/bin/fly-loop-reset — the milestone step of fly-loop-recover's ladder, as root.
#
# fly-loop-recover runs as User=fly and reaches this through one NOPASSWD sudoers line
# (config/fly-sudoers). It does what infra/docs/runbook.md "Restart the run from a rung"
# does by hand: stop flysim, promote milestone-<N>.checkpoint with fly-reset-to-milestone,
# start flysim.
#
# Root never executes anything the fly account can write. The release tree under
# /opt/fly/releases is fly-owned, so the flysim run here is the root-owned copy 05-deploy
# installs at /opt/fly/sbin/flysim straight from the release tarball; without it every rung is
# refused and the ladder falls back to restarts. Paths are fixed (test overrides are honoured
# only when not root), and /etc/fly/fly.env is read as KEY=VALUE data, never sourced.
#
# fly-reset-to-milestone does not check that the build can restore the archive, and a flysim
# that refuses every checkpoint refuses to start: a black stream. So a rung is only used when
# its archive's compatibility string equals this build's, or differs only in an adapter id that
# FLY_ACCEPT_ADAPTERS names (05-deploy.sh's adapter_migration_accepted).
#
# fly-watchdog restarts a flysim whose /healthz fails, which during a reset would start it on a
# half-rewritten store; its timer is stopped for the reset and started again on every exit path.
#
# Usage: fly-loop-reset <rung> reset to that rung
# fly-loop-reset --list print the rungs this build can restore, one per line
set -euo pipefail
STATE_DIR=/srv/fly/state
ENV_FILE=/etc/fly/fly.env
FLYSIM=/opt/fly/sbin/flysim
RESET_BIN=/opt/fly/bin/fly-reset-to-milestone
if [ "$(id -u)" -ne 0 ]; then
STATE_DIR="${FLY_LOOP_RESET_TEST_STATE_DIR:-$STATE_DIR}"
ENV_FILE="${FLY_LOOP_RESET_TEST_ENV_FILE:-$ENV_FILE}"
FLYSIM="${FLY_LOOP_RESET_TEST_FLYSIM:-$FLYSIM}"
RESET_BIN="${FLY_LOOP_RESET_TEST_RESET_BIN:-$RESET_BIN}"
fi
SERVICE=flysim.service
WATCHDOG_TIMER=fly-watchdog.timer
WATCHDOG_SERVICE=fly-watchdog.service
readonly STATE_DIR ENV_FILE FLYSIM RESET_BIN SERVICE WATCHDOG_TIMER WATCHDOG_SERVICE
log() { echo "fly-loop-reset: $*" >&2; }
usage() { log "usage: fly-loop-reset <rung> | --list"; exit 2; }
LIST=0
RANK=""
[ "$#" -eq 1 ] || usage
if [ "$1" = --list ]; then
LIST=1
elif [[ "$1" =~ ^[0-9]{1,2}$ ]]; then
RANK="$1"
else
usage
fi
# FLY_* lines of fly.env as `env` arguments. Values may be quoted the systemd way; nothing
# is evaluated.
env_args=()
accepted=""
if [ -r "$ENV_FILE" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^(FLY_[A-Z0-9_]*)=(.*)$ ]] || continue
key="${BASH_REMATCH[1]}"
value="${BASH_REMATCH[2]}"
if [[ "$value" =~ ^\"(.*)\"$ ]] || [[ "$value" =~ ^\'(.*)\'$ ]]; then
value="${BASH_REMATCH[1]}"
fi
env_args+=("$key=$value")
if [ "$key" = FLY_ACCEPT_ADAPTERS ]; then
accepted="$value"
fi
done < "$ENV_FILE"
fi
clean_env() { env -i PATH=/usr/sbin:/usr/bin:/sbin:/bin HOME=/root "${env_args[@]}" "$@"; }
# The same rule as 05-deploy.sh: exactly one '/'-separated field differs, it is the adapter
# (index 1), and the archive's adapter id is listed.
migration_accepted() {
local old="$1" new="$2" i differing=0 index=-1 entry
local -a old_parts new_parts
IFS='/' read -r -a old_parts <<< "$old"
IFS='/' read -r -a new_parts <<< "$new"
[ "${#old_parts[@]}" -eq "${#new_parts[@]}" ] || return 1
for ((i = 0; i < ${#old_parts[@]}; i++)); do
if [ "${old_parts[$i]}" != "${new_parts[$i]}" ]; then
differing=$((differing + 1))
index=$i
fi
done
[ "$differing" -eq 1 ] && [ "$index" -eq 1 ] || return 1
for entry in ${accepted//,/ }; do
[ "$entry" = "${old_parts[1]}" ] && return 0
done
return 1
}
# The root copy must be the flysim that runs: a manual rollback of /opt/fly/current without a
# deploy would otherwise approve archives the running build refuses.
LIVE_FLYSIM=/opt/fly/current/flysim
[ "$(id -u)" -eq 0 ] || LIVE_FLYSIM="${FLY_LOOP_RESET_TEST_LIVE_FLYSIM:-$FLYSIM}"
same_build() {
[ -f "$LIVE_FLYSIM" ] \
&& [ "$(sha256sum < "$FLYSIM" | cut -d' ' -f1)" = "$(sha256sum < "$LIVE_FLYSIM" | cut -d' ' -f1)" ]
}
build_compat=""
if [ -x "$FLYSIM" ] && [ "$(stat -c %u "$FLYSIM")" = "$(id -u)" ] && same_build; then
build_compat="$(clean_env timeout 90 "$FLYSIM" --print-compatibility 2>/dev/null | tail -n1 || true)"
fi
if [ -z "$build_compat" ]; then
log "no compatibility string from $FLYSIM (missing, not owned by $(id -un), not the running build, or failed); no rung is restorable"
[ "$LIST" -eq 1 ] && exit 0
exit 3
fi
restorable() {
local archive="${STATE_DIR}/milestone-$1.checkpoint" compat
[ -f "$archive" ] || return 1
compat="$(head -c 262144 "$archive" 2>/dev/null | grep -a -o -m1 '"compatibility"[[:space:]]*:[[:space:]]*"[^"]*"' | head -n1 | cut -d'"' -f4 || true)"
[ -n "$compat" ] || return 1
[ "$compat" = "$build_compat" ] || migration_accepted "$compat" "$build_compat"
}
if [ "$LIST" -eq 1 ]; then
for archive in "${STATE_DIR}"/milestone-*.checkpoint; do
[ -e "$archive" ] || continue
rung="${archive##*/milestone-}"
rung="${rung%.checkpoint}"
if [[ "$rung" =~ ^[0-9]{1,2}$ ]] && restorable "$rung"; then
echo "$rung"
fi
done | sort -n
exit 0
fi
if ! restorable "$RANK"; then
log "rung ${RANK}'s archive is missing or not restorable by this build (FLY_ACCEPT_ADAPTERS='${accepted}'); nothing touched"
exit 3
fi
# shellcheck disable=SC2317 # invoked by the EXIT trap
finish() {
local status=$?
systemctl start "$SERVICE" || log "starting ${SERVICE} failed"
systemctl start "$WATCHDOG_TIMER" || log "starting ${WATCHDOG_TIMER} failed"
exit "$status"
}
trap finish EXIT
trap 'exit 143' TERM INT HUP
log "pausing ${WATCHDOG_TIMER} and stopping ${SERVICE} to reset to rung ${RANK}"
systemctl stop "$WATCHDOG_TIMER"
# A oneshot probe mid-run is "activating", which `is-active` does not count; wait on ActiveState.
watchdog_idle() {
case "$(systemctl show -p ActiveState --value "$WATCHDOG_SERVICE")" in
inactive|failed) return 0 ;;
*) return 1 ;;
esac
}
for _ in $(seq 1 60); do
watchdog_idle && break
sleep 1
done
if ! watchdog_idle; then
log "${WATCHDOG_SERVICE} still running after 60 s; not resetting"
exit 4
fi
systemctl stop "$SERVICE"
status=0
clean_env FLY_BIN="$FLYSIM" "$RESET_BIN" "$RANK" || status=$?
[ "$status" -eq 0 ] || log "fly-reset-to-milestone ${RANK} failed (exit ${status}); starting ${SERVICE} on the state it left"
exit "$status"

501
infra/bin/fly-runtime Executable file
View file

@ -0,0 +1,501 @@
#!/usr/bin/env bash
# infra/bin/fly-runtime — which runtime the live fly runs: the legacy loop (`flysim`) or the
# session runtime (`flysim-session`, SERVE-01).
#
# Usage (INSIDE the container, as root):
# fly-runtime status print `legacy` or `session` (and the session's transport), and
# what flysim.service runs
# fly-runtime session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation]
# fly-runtime session-bus [...] the same as `session --bus`
# fly-runtime legacy [--no-restart]
# fly-runtime fallback [reason] (run by fly-runtime-fallback.service, see below; idempotent)
#
# CUT-01 calls `fly-runtime session` after its zero-divergence shadow; `fly-runtime legacy` is
# the one-command rollback (port decisions, 2026-09-23). Neither migrates any data: both
# binaries read and write the same FLYSIM01 stores, event log, sugar journal and chat sidecar.
#
# The session's transport (BUS-01). `--local` (the default for a first switch) runs the session's
# participants in flysim-session's own process over the local lane. `--bus` runs them on the flybus
# router over Unix sockets: flysim-session (the router, the coordinator, the listeners) starts the
# agent and the world as child processes of the same unit (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release), in flysim.slice, on flysim's cpuset.
# The drop-in then carries `Environment=FLY_SESSION_TRANSPORT=bus`. Without either flag `session`
# keeps the transport the drop-in already has, so 05-deploy's `session --no-restart` refresh never
# changes it; `session --local` is the way back from the bus. Results, traces, checkpoints and the
# compatibility string are the same in both: only where the participants run changes. A switch onto
# the bus needs a shadow that ran the bus (`fly-shadow-run check --bus`), which the coordinator runs
# before this command, as for the first cutover. Everything below applies to both transports: one
# unit, OnFailure= falls back to LEGACY, the probation judges the session runtime either way.
#
# How the switch works. flysim.service stays the fly's one unit name, and the runtime it runs
# is chosen by one drop-in, ${DROPIN}:
#
# [Service]
# ExecStart=
# ExecStart=/opt/fly/current/flysim-session
# Environment=FLY_SESSION_DIR=/run/fly/session
#
# i.e. flysim-session.service's ExecStart and its one extra variable (the standalone unit and
# this drop-in are kept identical by infra/tests/lint.sh). Everything else that names
# flysim.service -- fly.target, flyedge.service's Requires=, fly-watchdog's checks and escalation,
# fly-loop-recover's `sudo systemctl restart flysim.service` and its sudoers line,
# fly-loop-reset, fly-reset-to-milestone, the unstick rule, `journalctl -u flysim`, the cpuset
# drop-in -- therefore keeps working unchanged, a reboot keeps the choice, and 05-deploy.sh (which
# converges unit files but never removes a drop-in) keeps it across deploys. 05-deploy.sh refuses
# a release without flysim-session while the drop-in is present.
#
# `session` refuses unless the release has flysim-session and its --print-compatibility equals
# flysim's (the store is shared, so the two must restore each other's checkpoints). After the
# restart it waits for /healthz (FLY_RUNTIME_HEALTH_TIMEOUT, default 300 s: the connectome load and
# the restore) and a snapshot that has advanced; if the session runtime does not come up healthy
# it switches back to legacy by itself and exits 1 (--no-fallback leaves it to the operator).
#
# The fallback survives the invocation (C1 of the SERVE-01 review). The drop-in also carries
#
# [Unit]
# OnFailure=fly-runtime-fallback.service
# StartLimitIntervalSec=600
# StartLimitBurst=3
# [Service]
# RestartMode=direct
#
# RestartMode=direct is essential (systemd >= 254; verified on 257): with the default
# RestartMode=normal the unit passes through `failed` before every Restart=always restart and
# OnFailure= fires on the FIRST crash, watchdog kill or start timeout. With `direct` the unit
# goes from one start straight to the next and only the start limit puts it in `failed`. So while the session runtime is selected, three starts of flysim.service inside ten minutes
# (crashes, watchdog kills, a start that never becomes ready, the restarts fly-watchdog and
# fly-loop-recover make for a stream that does not come up) end in the failed state, and systemd
# runs fly-runtime-fallback.service, i.e. `fly-runtime fallback`: write ${FELLBACK_FILE}, remove
# the drop-in, daemon-reload, restart flysim.service (now the legacy binary) and log a line. That
# holds across reboots, watchdog and loop-recover restarts and deploys, none of which go through
# `fly-runtime session`. It is idempotent (a lock, and a no-op once the drop-in is gone) and it
# keeps the drop-in when there is no executable legacy binary, so it never swaps one runtime that
# cannot start for another. `fly-runtime session` deletes the reason file; `status` shows it.
#
# During a switch fly-runtime traps INT, TERM and HUP (and any failure): an interrupted `session`
# puts the previous state back (drop-in removed, or the earlier one restored) and restarts
# flysim.service on it, so a dropped ssh never leaves a drop-in that was not health-checked.
#
# The speed probation (CUT-01). Operator decision 2026-09-30: the session runtime stays only if it
# sustains >= 1.0x real time on the release container. A `session` that restarted flysim and saw
# it healthy therefore starts infra/bin/fly-runtime-probation (fly-runtime-probation.timer, every
# 60 s for 30 minutes): a sustained speed failure ends in `fly-runtime fallback "speed: ..."`, the
# same fallback as above under the same lock. `legacy` and every fallback cancel it. `--no-restart`
# (05-deploy's refresh of the drop-in) and `--no-probation` (rehearsals) start none. If the
# probation cannot be started, `session` falls back: an unguarded cutover is not allowed.
#
# `session` also stops a running shadow and its guard (fly-shadow-run stop, no flysim restart) once
# flysim is healthy on the session runtime, so the procedure cannot be done wrong (review N1).
#
# Every switch is logged to the journal (tag fly-runtime) and appended to ${RUNTIME_LOG}.
set -euo pipefail
: "${FLY_RELEASE_DIR:=/opt/fly/current}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}"
: "${FLY_SERVICE:=flysim.service}"
: "${FLY_RUNTIME_HEALTH_TIMEOUT:=300}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
: "${FLY_SYSTEMD_DIR:=/etc/systemd/system}"
: "${FLY_RUNTIME_LOG:=/var/lib/fly/runtime.log}"
: "${FLY_RUNTIME_FELLBACK:=/run/fly/runtime-fellback.json}"
: "${FLY_RUNTIME_LOCK:=/run/fly/runtime.lock}"
: "${FLY_RUNTIME_LOCK_WAIT:=150}"
DROPIN_DIR="${FLY_SYSTEMD_DIR}/${FLY_SERVICE}.d"
DROPIN="${DROPIN_DIR}/10-runtime.conf"
RUNTIME_LOG="$FLY_RUNTIME_LOG"
FELLBACK_FILE="$FLY_RUNTIME_FELLBACK"
FALLBACK_UNIT=fly-runtime-fallback.service
SESSION_BIN="${FLY_RELEASE_DIR}/flysim-session"
WORKER_BIN="${FLY_RELEASE_DIR}/fly-session"
LEGACY_BIN="${FLY_RELEASE_DIR}/flysim"
SESSION_DIR=/run/fly/session
SHADOW_RUN_BIN="${FLY_SHADOW_RUN_BIN:-$(dirname "$(readlink -f "$0")")/fly-shadow-run}"
PROBATION_BIN="${FLY_PROBATION_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime-probation}"
log() { echo "fly-runtime: $*" >&2; }
# The speed probation's hooks (best effort except `start`, which the caller checks).
probation() {
[ -x "$PROBATION_BIN" ] || return 0
"$PROBATION_BIN" "$@" || log "fly-runtime-probation $1 failed"
}
die() { log "$*"; exit 1; }
# CUT-01 (review N1): once flysim runs the session runtime the shadow and its guard are over. The
# guard would judge the session against the legacy baseline and restart flysim on a trip; the
# session writes no trace. Stops both WITHOUT restarting flysim. Best effort, never fails the switch.
stop_shadow() {
if systemctl is-active --quiet flyshadow.service 2>/dev/null \
|| systemctl is-active --quiet flyshadow-guard.timer 2>/dev/null; then
if [ -x "$SHADOW_RUN_BIN" ] && "$SHADOW_RUN_BIN" stop; then
log "the shadow and its guard are stopped (flysim.service not restarted)"
else
log "WARNING: could not stop the shadow; run: fly-shadow-run stop (never with --restart-flysim)"
fi
fi
}
usage() {
echo "usage: fly-runtime status | session [--local|--bus] [--no-restart] [--no-fallback] [--no-probation] | session-bus [...] | legacy [--no-restart] | fallback [reason]" >&2
exit 2
}
current() {
if [ -f "$DROPIN" ]; then echo session; else echo legacy; fi
}
# The session's transport the drop-in selects: `bus` or `local` (also with no drop-in).
current_transport() {
if [ -f "$DROPIN" ] && grep -qx 'Environment=FLY_SESSION_TRANSPORT=bus' "$DROPIN"; then
echo bus
else
echo local
fi
}
# `legacy`, `session` or `session-bus`, for the runtime log.
current_label() {
if [ "$(current)" = session ] && [ "$(current_transport)" = bus ]; then echo session-bus; else current; fi
}
record() {
local line
line="$(date -u '+%Y-%m-%dT%H:%M:%SZ') $*"
if command -v logger >/dev/null 2>&1; then
logger -t fly-runtime -- "$*" || true
fi
mkdir -p "$(dirname "$RUNTIME_LOG")" 2>/dev/null || true
echo "$line" >>"$RUNTIME_LOG" 2>/dev/null || log "could not append to $RUNTIME_LOG"
}
# The compatibility string a binary would write, with the service's own environment: fly.env is
# systemd's EnvironmentFile syntax, read as KEY=VALUE lines rather than sourced as shell.
compat_of() {
local -a vars=()
local line key value
if [ -f "$FLY_ENV_FILE" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
key="${line%%=*}"
value="${line#*=}"
value="${value%\"}"
value="${value#\"}"
vars+=("${key}=${value}")
done <"$FLY_ENV_FILE"
fi
env "${vars[@]}" "$1" --print-compatibility 2>/dev/null | tr -d '\r'
}
write_dropin() {
mkdir -p "$DROPIN_DIR"
local tmp="${DROPIN}.tmp.$$"
cat >"$tmp" <<EOF
# Written by fly-runtime session (SERVE-01): flysim.service runs the session runtime.
# \`fly-runtime legacy\` removes this file, and so does fly-runtime-fallback.service (OnFailure=,
# after three starts in ten minutes). RestartMode=direct is what makes OnFailure= wait for the start
# limit: systemd >= 254 otherwise passes through the failed state (and OnFailure=) before EVERY auto-restart.
# Keep [Service] in step with units/flysim-session.service.
[Unit]
OnFailure=${FALLBACK_UNIT}
StartLimitIntervalSec=600
StartLimitBurst=3
[Service]
RestartMode=direct
ExecStart=
ExecStart=${SESSION_BIN}
Environment=FLY_SESSION_DIR=${SESSION_DIR}
Environment=MALLOC_ARENA_MAX=2
EOF
if [ "$transport" = bus ]; then
cat >>"$tmp" <<EOF
# BUS-01: the participants are child processes on the session router's Unix sockets.
Environment=FLY_SESSION_TRANSPORT=bus
EOF
fi
chmod 0644 "$tmp"
mv -f "$tmp" "$DROPIN"
}
# /healthz 200, then a snapshot whose frame moved: the loop is running, not just listening.
healthy() {
local deadline=$(( $(date +%s) + FLY_RUNTIME_HEALTH_TIMEOUT ))
local first=""
while [ "$(date +%s)" -lt "$deadline" ]; do
if [ -n "$old_invocation" ] \
&& [ "$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)" = "$old_invocation" ]; then
sleep 1
continue
fi
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
local frame
frame="$(curl -fsS "${FLY_CONTROL_URL}/status" 2>/dev/null \
| sed -n 's/.*"frame":\([0-9][0-9]*\).*/\1/p' | head -n1)"
if [ -n "$frame" ]; then
if [ -z "$first" ]; then
first="$frame"
elif [ "$frame" -gt "$first" ]; then
log "healthy: frame ${first} -> ${frame}"
return 0
fi
fi
fi
sleep 1
done
return 1
}
# One lock (${FLY_RUNTIME_LOCK}) serialises every change of the drop-in: `fallback`, `session`,
# `legacy` and the rollback in on_exit. A switch holds it from before it reads the current state
# until its restart has been queued (`restart --no-block`), and lets go before the health wait, so
# an OnFailure= fallback is never held up by a start that does not become ready. Re-entrant per
# process. Waits FLY_RUNTIME_LOCK_WAIT (150 s).
locked=0
take_lock() {
if [ "$locked" -eq 1 ]; then return 0; fi
mkdir -p "$(dirname "$FLY_RUNTIME_LOCK")" 2>/dev/null || true
exec 9>>"$FLY_RUNTIME_LOCK"
if flock -w "$FLY_RUNTIME_LOCK_WAIT" 9; then locked=1; return 0; fi
log "could not take ${FLY_RUNTIME_LOCK} within ${FLY_RUNTIME_LOCK_WAIT} s"
return 1
}
drop_lock() {
exec 9>&-
locked=0
}
restarted=0
old_invocation=""
restart_and_check() {
systemctl daemon-reload
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
log "restarting ${FLY_SERVICE} on the $(current) runtime"
restarted=1
# --no-block: a blocking restart of a unit that never becomes READY holds this process (and
# the lock) for minutes, starving the OnFailure= fallback. `healthy` therefore has to prove
# that it is talking to the NEW invocation, not the old process that is still shutting down.
old_invocation="$(systemctl show -p InvocationID --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
systemctl restart --no-block "$FLY_SERVICE" || { drop_lock; return 1; }
drop_lock
healthy
}
# The fallback to legacy, shared by `fly-runtime session` (its own health check) and by
# fly-runtime-fallback.service (OnFailure= in the drop-in). Idempotent and serialised: whoever
# gets the lock second finds the drop-in gone and does nothing. It never removes the drop-in
# unless legacy can start, and it puts the drop-in back if flysim.service cannot be restarted,
# so at least one runtime is always startable. Restarts with --no-block: the caller (or the
# watchdog) judges health, and a oneshot unit must not sit in a 90 s notify start.
do_fallback() {
local reason="$1" result nrestarts saved
take_lock || log "continuing without the lock"
if [ ! -f "$DROPIN" ]; then
log "fallback: the legacy runtime is already selected; nothing to do"
return 0
fi
if [ ! -x "$LEGACY_BIN" ]; then
record "fallback REFUSED (${reason}): no executable ${LEGACY_BIN}; the session drop-in stays"
return 1
fi
result="$(systemctl show -p Result --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
nrestarts="$(systemctl show -p NRestarts --value "$FLY_SERVICE" 2>/dev/null | head -n1 || true)"
reason="${reason//[\"\\]/}"
reason="${reason//$'\n'/ }"
mkdir -p "$(dirname "$FELLBACK_FILE")" 2>/dev/null || true
printf '{"at":"%s","from":"session","to":"legacy","reason":"%s","unitResult":"%s","nRestarts":"%s"}\n' \
"$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$reason" "${result:-unknown}" "${nrestarts:-}" \
>"${FELLBACK_FILE}.tmp.$$" 2>/dev/null || true
mv -f "${FELLBACK_FILE}.tmp.$$" "$FELLBACK_FILE" 2>/dev/null || log "could not write ${FELLBACK_FILE}"
saved="$(mktemp "${DROPIN}.saved.XXXXXX")"
cp -f "$DROPIN" "$saved"
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
probation cancel --quiet
record "legacy (automatic fallback: ${reason}; was session)"
systemctl daemon-reload || true
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
restarted=1
if systemctl restart --no-block "$FLY_SERVICE"; then
rm -f "$saved"
return 0
fi
# Could not even queue the restart: keep what was running, and say so.
mkdir -p "$DROPIN_DIR" && mv -f "$saved" "$DROPIN"
systemctl daemon-reload || true
rm -f "$FELLBACK_FILE"
record "fallback FAILED (${reason}): could not restart ${FLY_SERVICE}; the session drop-in is back"
return 1
}
# An interrupted or failed switch puts the previous state back. `switching` is 1 from just
# before the drop-in is touched until the switch has finished; `prev_dropin` is a copy of the
# drop-in that was there before (empty: none, i.e. legacy). The rollback runs under the lock and
# does nothing when a fallback has completed since the switch began (FELLBACK_FILE exists: the
# switch deleted it under the lock, only a finished fallback writes it): restoring the older
# drop-in then would strand the stream on the session runtime after it was taken off.
switching=0
switch_target=""
prev_dropin=""
# shellcheck disable=SC2317 # runs from the EXIT trap
on_exit() {
local rc=$?
trap - EXIT INT TERM HUP
if [ "$switching" -eq 1 ]; then
switching=0
take_lock || true
if [ "$switch_target" = session ] && [ -f "$FELLBACK_FILE" ]; then
record "legacy (switch to session interrupted or failed (exit ${rc}); a fallback completed meanwhile, not restoring the older drop-in)"
restarted=0
elif [ "$switch_target" = session ]; then
if [ -n "$prev_dropin" ] && [ -f "$prev_dropin" ]; then
mkdir -p "$DROPIN_DIR" && cp -f "$prev_dropin" "$DROPIN"
else
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
fi
record "$(current) (switch to session interrupted or failed (exit ${rc}); rolled back)"
else
record "$(current) (switch to legacy interrupted (exit ${rc}))"
fi
systemctl daemon-reload || true
if [ "$restarted" -eq 1 ]; then
systemctl reset-failed "$FLY_SERVICE" 2>/dev/null || true
systemctl restart --no-block "$FLY_SERVICE" || true
fi
fi
[ -z "$prev_dropin" ] || rm -f "$prev_dropin"
exit "$rc"
}
trap on_exit EXIT
trap 'exit 130' INT
trap 'exit 143' TERM
trap 'exit 129' HUP
[ $# -ge 1 ] || usage
command="$1"; shift
restart=1
fallback=1
probe=1
transport=""
fallback_reason=""
if [ "$command" = fallback ]; then fallback_reason="$*"; set --; fi
if [ "$command" = session-bus ]; then command=session; transport=bus; fi
for arg in "$@"; do
case "$arg" in
--no-restart) restart=0 ;;
--no-fallback) fallback=0 ;;
--no-probation) probe=0 ;;
--bus) [ "$command" = session ] || usage; transport=bus ;;
--local) [ "$command" = session ] || usage; transport=local ;;
*) usage ;;
esac
done
# No flag: keep the drop-in's transport (05-deploy's refresh); local for a first switch.
[ -n "$transport" ] || transport="$(current_transport)"
case "$command" in
status)
current
if [ "$(current)" = session ]; then echo " transport: $(current_transport)"; fi
if [ -f "$FELLBACK_FILE" ]; then echo " fell back to legacy: $(cat "$FELLBACK_FILE")"; fi
if [ -x "$PROBATION_BIN" ]; then "$PROBATION_BIN" status 2>/dev/null | sed 's/^/ /' || true; fi
systemctl show -p ExecStart --value "$FLY_SERVICE" 2>/dev/null | sed -n 's/.*path=\([^ ;]*\).*/ flysim.service runs \1/p' || true
exit 0
;;
session|session-bus|legacy) ;;
fallback)
[ "$(id -u)" -eq 0 ] || die "run as root"
do_fallback "${fallback_reason:-flysim.service failed on the session runtime (OnFailure=)}"
exit $?
;;
*) usage ;;
esac
[ "$(id -u)" -eq 0 ] || die "run as root (it writes ${DROPIN} and restarts ${FLY_SERVICE})"
if [ "$command" = session ]; then
[ -x "$SESSION_BIN" ] || die "this release has no ${SESSION_BIN}; the session runtime ships from SERVE-01 on"
[ -x "$LEGACY_BIN" ] || die "no ${LEGACY_BIN}"
if [ "$transport" = bus ] && [ ! -x "$WORKER_BIN" ]; then
die "this release has no ${WORKER_BIN}: the bus transport starts its participants from it"
fi
legacy_compat="$(compat_of "$LEGACY_BIN")"
session_compat="$(compat_of "$SESSION_BIN")"
[ -n "$session_compat" ] || die "${SESSION_BIN} --print-compatibility printed nothing (see its stderr); not switching"
if [ "$legacy_compat" != "$session_compat" ]; then
die "the two runtimes would write different checkpoints; not switching.
flysim: ${legacy_compat}
flysim-session: ${session_compat}"
fi
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
if [ -f "$DROPIN" ]; then
prev_dropin="$(mktemp "${DROPIN}.prev.XXXXXX")"
cp -f "$DROPIN" "$prev_dropin"
fi
switch_target=session
switching=1
rm -f "$FELLBACK_FILE"
write_dropin
record "$(current_label) (was ${before}); compatibility ${session_compat}"
if [ "$restart" -ne 1 ]; then
systemctl daemon-reload
switching=0
log "drop-in written; restart ${FLY_SERVICE} to apply"
exit 0
fi
if restart_and_check; then
# OnFailure= may have fallen back while we waited (a healthy legacy would pass the
# check above too): only report success if the session drop-in is still what runs.
if [ -f "$DROPIN" ] && [ ! -f "$FELLBACK_FILE" ]; then
switching=0
stop_shadow
if [ "$probe" -eq 1 ]; then
if [ ! -x "$PROBATION_BIN" ] || ! "$PROBATION_BIN" start; then
log "the speed probation could not be started; an unguarded cutover is not allowed"
if [ "$fallback" -eq 1 ]; then
do_fallback "the speed probation could not be started" || true
fi
exit 1
fi
log "flysim.service runs the session runtime, on probation: fly-runtime-probation status"
else
log "flysim.service runs the session runtime (no probation)"
fi
exit 0
fi
switching=0
log "the session runtime failed and ${FALLBACK_UNIT} fell back to legacy: $(cat "$FELLBACK_FILE" 2>/dev/null)"
exit 1
fi
log "the session runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s"
if [ "$fallback" -eq 1 ]; then
do_fallback "the session runtime was not healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s of the switch" || true
switching=0
if healthy; then
log "fell back to the legacy runtime; it is healthy"
else
log "fell back to the legacy runtime, and it is NOT healthy either: check journalctl -u ${FLY_SERVICE}"
fi
else
switching=0
fi
exit 1
fi
# legacy
take_lock || die "another fly-runtime holds ${FLY_RUNTIME_LOCK}; not switching"
before="$(current_label)"
switch_target=legacy
switching=1
rm -f "$DROPIN"
rmdir "$DROPIN_DIR" 2>/dev/null || true
probation cancel
record "legacy (was ${before})"
[ "$restart" -eq 1 ] || { systemctl daemon-reload; switching=0; log "drop-in removed; restart ${FLY_SERVICE} to apply"; exit 0; }
if restart_and_check; then
switching=0
log "flysim.service runs the legacy runtime"
exit 0
fi
switching=0
die "the legacy runtime did not come up healthy within ${FLY_RUNTIME_HEALTH_TIMEOUT}s: check journalctl -u ${FLY_SERVICE}"

299
infra/bin/fly-runtime-probation Executable file
View file

@ -0,0 +1,299 @@
#!/usr/bin/env bash
# infra/bin/fly-runtime-probation -- CUT-01's speed probation after `fly-runtime session`.
# Pushed to /opt/fly/bin by 05-deploy.sh. Root, inside the container. Normally nobody runs it by
# hand: `fly-runtime session` starts it, `fly-runtime legacy` and every fallback cancel it, and
# fly-runtime-probation.timer runs `tick` every 60 s.
#
# fly-runtime-probation start begin a probation (enables and starts the timer)
# fly-runtime-probation cancel end it without a verdict (disables the timer)
# fly-runtime-probation status state, latest samples, result
# fly-runtime-probation tick (timer) one sample and one decision
# fly-runtime-probation simulate CHECKS.jsonl the rule over recorded samples (lint)
#
# Operator decision 2026-09-30: cut over only if the session runtime sustains >= 1.0x real time on
# the release container. Only that box can measure it, so the switch is guarded. The rule:
# - A sample is one fly_realtime_factor mean over 10 one-second reads of flysim's /metrics (the
# same sampling as fly-shadow-run's guard), with fly_lag_seconds and fly_uptime_seconds.
# - Warm-up: a flysim process is not judged before it has been up FLY_PROBATION_WARMUP (300 s:
# the connectome load, the restore, the first minutes). A restart (uptime goes backwards)
# starts the window again; so does a paused or not running fly: it is not judged.
# - Window: the judged samples of the last FLY_PROBATION_WINDOW (600 s), at least
# FLY_PROBATION_MIN_SAMPLES (8). FAIL when the window's MEDIAN realtime factor is below
# FLY_PROBATION_MIN_RTF (0.97), or the lag grew by more than FLY_PROBATION_MAX_LAG_GROWTH
# (30 s) between the start and the end of the window (median of the first and of the last 3
# samples). The median is the same robust statistic fly-shadow-run's baseline uses: one
# stalled sample, or two, never fails it.
# - PASS when FLY_PROBATION_SECONDS (1800) have passed since `start` and the latest window is
# full and healthy. A probation that cannot fill a window within FLY_PROBATION_MAX_SECONDS
# (7200: a fly that never runs) fails as inconclusive: no proof of 1.0x, no cutover.
# FAIL runs `fly-runtime fallback "speed: ..."` (the ordinary fallback: lock, reason file
# /run/fly/runtime-fellback.json, journal line, flysim.service restarted on legacy). It is retried
# every minute until it succeeds. PASS writes ${RESULT} (passed: true) and disables the timer.
# Nothing judges the speed afterwards: the watchdog and the start-limit fallback are unchanged.
#
# State is ${DIR}/state.json (on disk, so a reboot resumes the probation: the timer is enabled,
# and OnBootSec= runs it after boot); ${DIR}/last.json keeps the last verdict.
set -euo pipefail
: "${FLY_PROBATION_DIR:=/var/lib/fly/probation}"
: "${FLY_PROBATION_RESULT:=/run/fly/runtime-probation.json}"
: "${FLY_PROBATION_TIMER:=fly-runtime-probation.timer}"
: "${FLY_PROBATION_READS:=10}"
: "${FLY_METRICS_URL:=http://127.0.0.1:9101}"
: "${FLY_CONTROL_URL:=http://127.0.0.1:7401}"
RUNTIME_BIN="${FLY_RUNTIME_BIN:-$(dirname "$(readlink -f "$0")")/fly-runtime}"
STATE="$FLY_PROBATION_DIR/state.json"
LAST="$FLY_PROBATION_DIR/last.json"
log() { echo "fly-runtime-probation: $*" >&2; }
die() { log "$*"; exit 1; }
journal() {
if command -v logger >/dev/null 2>&1; then logger -t fly-runtime -- "probation: $*" || true; fi
log "$*"
}
need_root() { [ "$(id -u)" = 0 ] || die "run as root"; }
take_lock() {
mkdir -p "$FLY_PROBATION_DIR"
exec 8>>"$FLY_PROBATION_DIR/lock"
flock -w 60 8 || die "could not take $FLY_PROBATION_DIR/lock"
}
drop_lock() { exec 8>&-; }
# One sample of the live fly: {t, status, rtMean, lag, uptime} (fly-shadow-run's format).
sample() {
python3 - "$FLY_METRICS_URL" "$FLY_CONTROL_URL" "$FLY_PROBATION_READS" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url, reads = sys.argv[1], sys.argv[2], int(sys.argv[3])
def metrics():
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
out = {}
for line in text.splitlines():
if line.startswith("#"):
continue
parts = line.split()
if len(parts) == 2:
try:
out[parts[0]] = float(parts[1])
except ValueError:
pass
return out
factors = []
for i in range(reads):
factors.append(metrics().get("fly_realtime_factor", 0.0))
if i + 1 < reads:
time.sleep(1)
m = metrics()
try:
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
status = None
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}
PROBATION_PY='
import json, os, sys
def env(name, default):
return type(default)(os.environ.get(name, default))
WARMUP = env("FLY_PROBATION_WARMUP", 300.0)
WINDOW = env("FLY_PROBATION_WINDOW", 600.0)
MIN_SAMPLES = env("FLY_PROBATION_MIN_SAMPLES", 8)
MIN_RTF = env("FLY_PROBATION_MIN_RTF", 0.97)
MAX_LAG_GROWTH = env("FLY_PROBATION_MAX_LAG_GROWTH", 30.0)
DURATION = env("FLY_PROBATION_SECONDS", 1800.0)
MAX_SECONDS = env("FLY_PROBATION_MAX_SECONDS", 7200.0)
def running(s):
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
def median(xs):
xs = sorted(xs)
n = len(xs)
return xs[n // 2] if n % 2 else (xs[n // 2 - 1] + xs[n // 2]) / 2
def step(state, s):
"""Returns (state, verdict, detail): verdict is wait, ok, pass or fail."""
started = state["startedAt"]
history = state.get("history", [])
elapsed = s["t"] - started
if not running(s):
return state, "wait", "flysim is %s: not judged" % s.get("status")
if history and s["uptime"] < history[-1]["uptime"]:
history = []
if s["uptime"] < WARMUP:
state["history"] = []
return state, "wait", "warming up (flysim up %.0f of %.0f s)" % (s["uptime"], WARMUP)
history = [h for h in history if h["t"] > s["t"] - WINDOW] + [s]
state["history"] = history
n = len(history)
if n < MIN_SAMPLES:
if elapsed >= MAX_SECONDS:
return state, "fail", "speed: probation inconclusive after %.0f s (%d judged samples in the window): no proof of 1.0x" % (elapsed, n)
return state, "wait", "collecting %d of %d samples" % (n, MIN_SAMPLES)
rtf = median([h["rtMean"] for h in history])
lag_growth = median([h["lag"] for h in history[-3:]]) - median([h["lag"] for h in history[:3]])
detail = "median realtime factor %.3f over %d samples, lag growth %+.1f s over %.0f s" % (
rtf, n, lag_growth, history[-1]["t"] - history[0]["t"])
state["last"] = {"medianRtf": rtf, "lagGrowth": lag_growth, "samples": n}
why = []
if rtf < MIN_RTF:
why.append("median realtime factor %.3f < %.2f" % (rtf, MIN_RTF))
if lag_growth > MAX_LAG_GROWTH:
why.append("lag grew %.1f s > %.0f s" % (lag_growth, MAX_LAG_GROWTH))
if why:
return state, "fail", "speed: " + ", ".join(why) + " over %d samples / %.0f s" % (
n, history[-1]["t"] - history[0]["t"])
if elapsed >= DURATION:
return state, "pass", detail
return state, "ok", detail + " (%.0f of %.0f s)" % (elapsed, DURATION)
mode = sys.argv[1]
if mode == "step":
state = json.load(open(sys.argv[2]))
state, verdict, detail = step(state, json.loads(sys.argv[3]))
json.dump(state, open(sys.argv[2], "w"))
print(verdict + " " + detail)
elif mode == "simulate":
samples = [json.loads(l) for l in open(sys.argv[2]) if l.strip()]
state = {"startedAt": samples[0]["t"] - 60, "history": []}
verdict, detail = "wait", ""
for n, s in enumerate(samples, 1):
state, verdict, detail = step(state, s)
if verdict in ("pass", "fail"):
print("%s at check %d: %s" % (verdict, n, detail))
sys.exit(0 if verdict == "pass" else 1)
print("undecided after %d checks: %s %s" % (len(samples), verdict, detail))
sys.exit(3)
'
now_iso() { date -u '+%Y-%m-%dT%H:%M:%SZ'; }
enabled_timer() { systemctl "$1" --now "$FLY_PROBATION_TIMER" >/dev/null 2>&1; }
start() {
need_root
take_lock
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
rm -f "$FLY_PROBATION_RESULT"
printf '{"startedAt":%s,"startedAtIso":"%s","history":[]}\n' "$(date +%s.%N)" "$(now_iso)" >"$STATE.tmp.$$"
mv -f "$STATE.tmp.$$" "$STATE"
if ! enabled_timer enable; then
rm -f "$STATE"
die "could not enable --now $FLY_PROBATION_TIMER (is the unit installed?)"
fi
journal "started: ${FLY_PROBATION_SECONDS:-1800} s, median realtime factor >= ${FLY_PROBATION_MIN_RTF:-0.97} over ${FLY_PROBATION_WINDOW:-600} s after ${FLY_PROBATION_WARMUP:-300} s warm-up, lag growth <= ${FLY_PROBATION_MAX_LAG_GROWTH:-30} s; else fallback to legacy"
}
cancel() {
local quiet=0
[ "${1:-}" = --quiet ] && quiet=1
need_root
take_lock
local had=0
if [ -f "$STATE" ]; then had=1; fi
rm -f "$STATE" "$FLY_PROBATION_RESULT"
enabled_timer disable || true
if [ "$had" -eq 1 ] || [ "$quiet" -eq 0 ]; then journal "cancelled"; fi
}
# The verdict, persisted in last.json (and in ${RESULT} on a pass).
finish() { # passed(true|false) detail state-file
local tmp="$LAST.tmp.$$"
python3 - "$1" "$2" "$3" >"$tmp" <<'PY'
import json, sys, datetime
passed, detail = sys.argv[1] == "true", sys.argv[2]
st = {}
try:
st = json.load(open(sys.argv[3]))
except Exception:
pass
out = {"passed": passed, "at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
"startedAt": st.get("startedAtIso"), "detail": detail}
out.update(st.get("last", {}))
print(json.dumps(out))
PY
mv -f "$tmp" "$LAST"
if [ "$1" = true ]; then
mkdir -p "$(dirname "$FLY_PROBATION_RESULT")" 2>/dev/null || true
cp -f "$LAST" "$FLY_PROBATION_RESULT"
fi
}
tick() {
need_root
local sample_json="" now out verdict detail rc
if [ "${1:-}" = --sample-json ]; then sample_json="$2"; fi # the test seam: a recorded sample
if [ ! -f "$STATE" ]; then
log "no probation: disabling $FLY_PROBATION_TIMER"
enabled_timer disable || true
exit 0
fi
# Only the session runtime is judged: a fallback, a legacy switch or a deploy that removed the
# drop-in ended it.
if [ "$("$RUNTIME_BIN" status 2>/dev/null | head -n1)" != session ]; then
journal "the session runtime is not selected; probation ends"
cancel --quiet
exit 0
fi
if [ -n "$sample_json" ]; then now="$sample_json"; else now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }; fi
take_lock
[ -f "$STATE" ] || { log "cancelled while sampling"; exit 0; }
rc=0
out="$(python3 -c "$PROBATION_PY" step "$STATE" "$now")" || rc=$?
[ "$rc" -eq 0 ] || die "probation rule failed: $out"
verdict="${out%% *}"
detail="${out#* }"
case "$verdict" in
wait|ok) drop_lock; log "$verdict: $detail" ;;
pass)
finish true "$detail" "$STATE"
rm -f "$STATE"
enabled_timer disable || true
journal "PASSED: $detail"
;;
fail)
cp -f "$STATE" "$STATE.failed.$$"
drop_lock
journal "FAILED: $detail; falling back to legacy"
if "$RUNTIME_BIN" fallback "$detail"; then
take_lock
finish false "$detail" "$STATE.failed.$$"
rm -f "$STATE" "$STATE.failed.$$"
enabled_timer disable || true
else
rm -f "$STATE.failed.$$"
log "fallback did not complete; probation stays and retries in a minute"
exit 1
fi
;;
*) die "unexpected verdict: $out" ;;
esac
}
status() {
if [ -f "$STATE" ]; then
python3 - "$STATE" <<'PY'
import json, sys
s = json.load(open(sys.argv[1]))
print("probation running since %s; %d judged samples in the window; last %s" % (
s.get("startedAtIso"), len(s.get("history", [])), json.dumps(s.get("last"))))
PY
else
echo "no probation running"
fi
if [ -f "$LAST" ]; then echo "last verdict: $(cat "$LAST")"; fi
if [ -f "$FLY_PROBATION_RESULT" ]; then echo "passed: $FLY_PROBATION_RESULT"; fi
}
cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
start) start ;;
cancel) cancel "$@" ;;
tick) tick "$@" ;;
status) status ;;
simulate) [ $# = 1 ] || die "simulate CHECKS.jsonl"; python3 -c "$PROBATION_PY" simulate "$1" ;;
*) echo "usage: fly-runtime-probation start|cancel|status|tick|simulate CHECKS.jsonl" >&2; exit 2 ;;
esac

630
infra/bin/fly-shadow-run Executable file
View file

@ -0,0 +1,630 @@
#!/usr/bin/env bash
# infra/bin/fly-shadow-run — start, stop, guard and read SHADOW-01's shadow run on the release
# container. Pushed to /opt/fly/bin/fly-shadow-run by 05-deploy.sh. Run as root inside the
# container, by the coordinator, with the container claimed in the host's agent claim log (one
# agent at a time).
#
# fly-shadow-run start baseline the live fly (10 min), turn flysim's trace on, start flyshadow.service
# and the live-impact guard, restart flysim once. The shadow runs on a
# build box (SHADOW-02, below); --local runs it on this container
# instead, which the live fly paid for on 2026-09-30 (RTF 0.999 -> 0.93)
# fly-shadow-run stop stop the shadow and the guard, turn the trace off (at flysim's next
# restart; --restart-flysim restarts it now), remove trace and spool
# fly-shadow-run status the verdict in one screen
# fly-shadow-run check CUT-01's hook: exit 0 only if the verdict allows the automatic cutover
# into the release /opt/fly/current points to, onto flysim-session.
# --bus also requires that the shadow ran the bus topology (BUS-01)
# fly-shadow-run guard (flyshadow-guard.timer, every 60 s) stop everything and restart flysim
# without the trace if the live fly pays for the shadow
# fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl the guard's rule over recorded samples
# fly-shadow-run baseline SAMPLES.jsonl the baseline those samples give
#
# The shadow is report-only (infra/units/flyshadow.service). `start` restarts flysim.service once,
# the same operator action as the unstick rule's restart: a restore keeps the rung and clears the
# ledgers. It is needed because flysim reads FLY_TRACE_DIR at start, and because the shadow can
# only follow a process from that process's own startup save.
#
# The trace cannot outlive the shadow: flysim starts no trace, and stops a running one within a
# minute, when the shadow's heartbeat (<trace dir>/consumer, every 30 s) is missing or older than
# 10 minutes; flysim also keeps the trace directory under 8 GiB, and the shadow deletes every file
# it has compared.
#
# The guard (SHADOW-01 review N2, recalibrated by round 2, G1). The live fly does not always run
# at real time (the release CT has run at a realtime factor of 0.66, and 0.77-0.99 after its cpuset
# rebalance), so the guard judges the live fly against ITSELF, before the shadow existed:
# - `start` first samples the live fly over FLY_SHADOW_BASELINE_SECONDS (600): sixty 10-s means
# of fly_realtime_factor and fly_lag_seconds. The BASELINE is robust: the median RTF, its
# spread (1.4826 x the median absolute deviation) and the lag growth rate over the most recent
# half (seconds of lag per wall second: about 1 - RTF when the loop is behind real time), so a
# step within the window neither sets the baseline nor widens the margin. It refuses to start
# on fewer than half the samples running.
# - Every 60 s the guard takes one 10-s sample. Over the last 5 samples of the same flysim
# process (a restart starts the window again) it compares the mean RTF and the lag growth
# rate with the baseline. The margin is max(0.05, 4 x the baseline spread / sqrt(5)), so it
# scales with how noisy this fly already was.
# - It TRIPS only on a SUSTAINED degradation: 3 checks in a row with the 5-sample mean RTF below
# the baseline mean minus the margin, or the lag growth rate above the baseline rate plus it.
# A paused, booting or recovering fly is not judged.
# `fly-shadow-run simulate BASELINE.jsonl CHECKS.jsonl` runs this rule over recorded samples;
# lint drives it over real and synthetic RTF traces (infra/tests/fixtures/shadow-guard/).
# Tripping stops flyshadow.service and the guard timer, removes the trace drop-in, restarts
# flysim.service without the trace, and writes /srv/fly/shadow/guard-tripped.json. When the shadow
# is no longer running (it diverged, passed and stopped, or crashed), the guard stops its own
# timer and changes nothing: it only ever acts against a running shadow. "No longer running" means
# ActiveState inactive or failed (systemctl show), never activating: the shadow's 10-s crash-restart
# delay must not switch the guard off. `check` also requires the guard timer active and baseline.json.
#
# THE BUS TOPOLOGY (BUS-01). `start --bus` runs the shadow's session the way `fly-runtime
# session --bus` runs the live one: the router, the coordinator and the task in the shadow's own
# process, the agent and the world as child processes (`fly-session legacy-agent`,
# `fly-session legacy-environment`, from the same release) on the router's Unix sockets. It sets
# FLY_SHADOW_MODE=bus/process in flyshadow.service's drop-in (mode.conf); a remote relay forwards it
# to the box (live.env), whose shadow reads it. The verdict records the topology
# (candidate.executionMode "process", candidate.transport "bus"), and `check --bus` refuses any
# verdict that did not run it. The live fly must run the LEGACY runtime while a shadow runs: only
# the legacy loop writes the trace (FLY_TRACE_DIR) the shadow follows, so `start` refuses while
# flysim.service runs the session runtime (fly-runtime status: session).
#
# REMOTE (SHADOW-02). With /etc/fly/shadow-remote.env present (the operator's private file:
# FLY_SHADOW_REMOTE=<user>@<box>, FLY_SHADOW_REMOTE_KEY, FLY_SHADOW_REMOTE_KNOWN_HOSTS, optional
# FLY_SHADOW_REMOTE_PORT), `start` gives flyshadow.service a drop-in (remote.conf) that runs
# `fly-shadow relay` instead of the shadow: a light process, normal scheduling, off flysim's CPUs,
# that streams the trace, the new saves and the sugar journal over one ssh connection to the box's
# `fly-shadow ingest` (the key's forced command) and writes the box shadow's verdict back to
# /srv/fly/shadow/verdict.json. The box runs the same release, at the same path, on its own cores
# (infra/box/flyshadow-remote.service). Everything else here is unchanged: the unit name, the
# guard, `check`, CUT-01. The relay keeps flysim's heartbeat fresh only while the box's shadow of
# THIS run (FLY_SHADOW_RUN_ID, the start's Unix ms) is alive and the box has everything that was on
# this disk a minute ago, so a dead box, shadow or network stops the trace like a dead local shadow.
# `check` in remote mode also needs /srv/fly/shadow/relay.json healthy, less than a minute old, of
# this run (the drop-in's id, which the verdict must carry too), without coverageLost (flysim
# stopped its trace for want of a consumer) and with a trace file written in the last 90 s.
#
# Files (all owned by fly):
# /srv/fly/shadow/trace/trace-<ms>-<pid>.jsonl flysim's per-process trace (4 GiB each, 8 in all)
# /srv/fly/shadow/trace/consumer the shadow's heartbeat
# /srv/fly/shadow/spool/ copies of the live saves, bounded (512 MiB)
# /srv/fly/shadow/verdict.json fly-shadow-verdict-v1 (the CUT-01 contract)
# /srv/fly/shadow/divergence.json the first divergence with its context
# /srv/fly/shadow/baseline.json the guard's baseline (and baseline-samples.jsonl)
# /srv/fly/shadow/guard-state.json the guard's recent samples
# /srv/fly/shadow/relay.json remote mode: the relay's health
set -euo pipefail
SHADOW_DIR="${FLY_SHADOW_DIR:-/srv/fly/shadow}"
DROPIN_DIR=/etc/systemd/system/flysim.service.d
DROPIN="$DROPIN_DIR/shadow-trace.conf"
REMOTE_ENV="${FLY_SHADOW_REMOTE_ENV:-/etc/fly/shadow-remote.env}"
REMOTE_DROPIN_DIR="${FLY_SHADOW_REMOTE_DROPIN_DIR:-/etc/systemd/system/flyshadow.service.d}"
REMOTE_DROPIN="$REMOTE_DROPIN_DIR/remote.conf"
MODE_DROPIN="$REMOTE_DROPIN_DIR/mode.conf"
RUNTIME_DROPIN="${FLY_RUNTIME_DROPIN:-$DROPIN_DIR/10-runtime.conf}"
# How long start waits for the first heartbeat (remote: at least 300 s, because the box's shadow
# restarts for the new run and the ingest hashes the release first).
HEARTBEAT_WAIT="${FLY_SHADOW_HEARTBEAT_WAIT_SECONDS:-60}"
BIN="${FLY_SHADOW_BIN:-/opt/fly/current/fly-shadow}"
METRICS_URL="${FLY_METRICS_URL:-http://127.0.0.1:9101}"
CONTROL_URL="${FLY_CONTROL_URL:-http://127.0.0.1:7401}"
# The ledger digest period in transitions: about one a second. Every boundary is proved in the
# offline rehearsal (the SHADOW-01 report); on the stream a digest a second bounds the extra work.
LEDGERS_EVERY="${FLY_SHADOW_LEDGERS_EVERY:-60}"
BASELINE_SECONDS="${FLY_SHADOW_BASELINE_SECONDS:-600}"
die() { echo "fly-shadow-run: $*" >&2; exit 2; }
log() { echo "fly-shadow-run: $*"; }
need_root() { [ "$(id -u)" = 0 ] || die "run as root (it installs a drop-in and restarts flysim)"; }
# One JSON sample of the live fly: {t, status, rtMean, lag, uptime}, the realtime factor averaged
# over 10 one-second reads.
sample() {
python3 - "$METRICS_URL" "$CONTROL_URL" <<'PY'
import json, sys, time, urllib.request
metrics_url, control_url = sys.argv[1], sys.argv[2]
def metrics():
text = urllib.request.urlopen(metrics_url + "/metrics", timeout=3).read().decode()
out = {}
for line in text.splitlines():
if line.startswith("#"):
continue
parts = line.split()
if len(parts) == 2:
try:
out[parts[0]] = float(parts[1])
except ValueError:
pass
return out
factors = []
for _ in range(10):
factors.append(metrics().get("fly_realtime_factor", 0.0))
time.sleep(1)
m = metrics()
try:
status = json.load(urllib.request.urlopen(control_url + "/status", timeout=3)).get("status")
except Exception:
status = None
print(json.dumps({"t": time.time(), "status": status, "rtMean": sum(factors) / len(factors),
"lag": m.get("fly_lag_seconds"), "uptime": m.get("fly_uptime_seconds")}))
PY
}
# The guard's rule, one definition for `baseline`, `decide` and `simulate`.
GUARD_PY='
import json, math, sys
WINDOW, SUSTAIN, MIN_MARGIN = 5, 3, 0.05
def running(s):
return s.get("status") == "running" and s.get("lag") is not None and s.get("uptime") is not None
def rate(samples):
"""Lag growth per wall second over the longest same-process run of samples."""
best, run = None, []
for s in samples:
if run and s["uptime"] < run[-1]["uptime"]:
run = []
run.append(s)
if len(run) >= 2 and (best is None or len(run) > len(best)):
best = list(run)
if not best or best[-1]["t"] <= best[0]["t"]:
return None
return max(0.0, (best[-1]["lag"] - best[0]["lag"]) / (best[-1]["t"] - best[0]["t"]))
def baseline(samples):
"""Robust statistics of the running samples: a step in the live fly within the window (its own
warm-up, a load coming or going) must neither set the baseline nor widen the margin, as long
as most of the window is on one side of it. The RTF is the median; its spread is 1.4826 x the
median absolute deviation, which estimates the standard deviation without the step; the lag
growth rate is taken over the most recent half, after any early step."""
ok = [s for s in samples if running(s)]
if len(ok) < max(3, len(samples) // 2):
raise SystemExit("baseline: only %d of %d samples running" % (len(ok), len(samples)))
recent = ok[len(ok) // 2:]
rtf = sorted(s["rtMean"] for s in ok)
median = rtf[len(rtf) // 2] if len(rtf) % 2 else (rtf[len(rtf) // 2 - 1] + rtf[len(rtf) // 2]) / 2
dev = sorted(abs(x - median) for x in rtf)
mad = dev[len(dev) // 2] if len(dev) % 2 else (dev[len(dev) // 2 - 1] + dev[len(dev) // 2]) / 2
sd = 1.4826 * mad
lag_rate = rate(recent)
return {"rtfMean": median, "rtfSd": sd, "lagRate": lag_rate if lag_rate is not None else 0.0,
"samples": len(ok), "margin": max(MIN_MARGIN, 4 * sd / math.sqrt(WINDOW))}
def decide(base, state, s):
"""Returns (state, verdict); the verdict starts with ok or trip."""
history, run = state.get("history", []), state.get("degradedRun", 0)
if not running(s):
return state, "ok (flysim is %s: not judged)" % s.get("status")
if history and s["uptime"] < history[-1]["uptime"]:
history, run = [], 0
history = (history + [s])[-WINDOW:]
state = {"history": history, "degradedRun": run}
if len(history) < WINDOW:
state["degradedRun"] = 0
return state, "ok (warming: %d of %d samples in this process)" % (len(history), WINDOW)
rtf = sum(h["rtMean"] for h in history) / WINDOW
lag_rate = rate(history) or 0.0
m = base["margin"]
why = []
if rtf < base["rtfMean"] - m:
why.append("realtime factor %.3f < baseline %.3f - %.3f" % (rtf, base["rtfMean"], m))
if lag_rate > base["lagRate"] + m:
why.append("lag growth %.3f s/s > baseline %.3f + %.3f" % (lag_rate, base["lagRate"], m))
state["degradedRun"] = run + 1 if why else 0
if state["degradedRun"] >= SUSTAIN:
return state, "trip " + "; ".join(why) + " (%d checks in a row)" % state["degradedRun"]
if why:
return state, "ok degraded %d/%d: %s" % (state["degradedRun"], SUSTAIN, "; ".join(why))
return state, "ok"
def load_jsonl(path):
return [json.loads(line) for line in open(path) if line.strip()]
mode = sys.argv[1]
if mode == "baseline":
print(json.dumps(baseline(load_jsonl(sys.argv[2]))))
elif mode == "decide":
base, state = json.load(open(sys.argv[2])), json.load(open(sys.argv[3]))
state, verdict = decide(base, state, json.load(open(sys.argv[4])))
json.dump(state, open(sys.argv[3], "w"))
print(verdict)
sys.exit(1 if verdict.startswith("trip") else 0)
elif mode == "simulate":
base = baseline(load_jsonl(sys.argv[2]))
state, n = {}, 0
for n, s in enumerate(load_jsonl(sys.argv[3]), 1):
state, verdict = decide(base, state, s)
if verdict.startswith("trip"):
print("trip at check %d: %s (baseline %s)" % (n, verdict, json.dumps(base)))
sys.exit(1)
print("no trip over %d checks (baseline %s)" % (n, json.dumps(base)))
'
# The shadow must never share a CPU with the live fly (review N2): refuse unless the unit's cpuset
# drop-in exists (05-deploy skips every cpuset drop-in when the CT conf and CPUSET disagree) and its
# AllowedCPUs is non-empty and disjoint from flysim.service's.
check_cpuset() {
local dropin="${FLY_SHADOW_CPUSET_DROPIN:-/etc/systemd/system/flyshadow.service.d/cpuset.conf}"
[ -f "$dropin" ] || die "$dropin is missing: flyshadow would run on every CPU, including flysim's. Run 05-deploy with CPUSET set; nothing started"
local shadow_cpus sim_cpus
shadow_cpus="$(systemctl show -p AllowedCPUs --value flyshadow.service 2>/dev/null || true)"
sim_cpus="$(systemctl show -p AllowedCPUs --value flysim.service 2>/dev/null || true)"
[ -n "$shadow_cpus" ] || die "flyshadow.service has an empty AllowedCPUs; nothing started"
[ -n "$sim_cpus" ] || die "flysim.service has an empty AllowedCPUs, so the shadow cannot be kept off it; nothing started"
local overlap rc=0
overlap="$(python3 -c '
import sys
def cpus(t):
out = set()
for part in t.replace(",", " ").split():
a, _, b = part.partition("-")
out.update(range(int(a), int(b or a) + 1))
return out
try:
both = cpus(sys.argv[1]) & cpus(sys.argv[2])
except ValueError:
sys.exit(2)
if both:
print(",".join(str(c) for c in sorted(both)))
sys.exit(1)
' "$shadow_cpus" "$sim_cpus" 2>/dev/null)" || rc=$?
case "$rc" in
0) ;;
1) die "flyshadow.service AllowedCPUs ($shadow_cpus) overlaps flysim.service's ($sim_cpus) on CPU $overlap; nothing started" ;;
*) die "cannot parse AllowedCPUs (flyshadow '$shadow_cpus', flysim '$sim_cpus'); nothing started" ;;
esac
}
# Remote mode's prerequisites, checked before anything changes.
check_remote() {
[ -r "$REMOTE_ENV" ] || die "$REMOTE_ENV is not readable"
local target key known
target="$(sed -n 's/^FLY_SHADOW_REMOTE=//p' "$REMOTE_ENV" | tail -n 1)"
key="$(sed -n 's/^FLY_SHADOW_REMOTE_KEY=//p' "$REMOTE_ENV" | tail -n 1)"
known="$(sed -n 's/^FLY_SHADOW_REMOTE_KNOWN_HOSTS=//p' "$REMOTE_ENV" | tail -n 1)"
[ -n "$target" ] || die "$REMOTE_ENV sets no FLY_SHADOW_REMOTE"
{ [ -n "$key" ] && [ -f "$key" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KEY ($key) is not a file"
{ [ -n "$known" ] && [ -f "$known" ]; } || die "$REMOTE_ENV: FLY_SHADOW_REMOTE_KNOWN_HOSTS ($known) is not a file"
[ "$(stat -c %U "$key")" = "${FLY_SHADOW_KEY_OWNER:-fly}" ] || die "$key must be owned by fly (the relay runs as fly)"
command -v ssh >/dev/null || die "no ssh client in this container (apt-get install openssh-client)"
}
start() {
need_root
local mode=remote arm=""
for arg in "$@"; do
case "$arg" in
--local) mode=local ;;
--bus) arm=bus/process ;;
*) die "start: unknown option $arg" ;;
esac
done
[ -x "$BIN" ] || die "$BIN is missing: this release predates SHADOW-01"
# Only the legacy loop writes the trace the shadow follows (FLY_TRACE_DIR); the session runtime
# ignores it, and every process it ran would be a coverage divergence.
[ ! -f "$RUNTIME_DROPIN" ] || die "flysim.service runs the session runtime, which writes no trace for a shadow to follow. Switch the live fly to legacy for the shadow window first (fly-runtime legacy), then start the shadow"
if [ -n "$arm" ]; then
[ -x "$(dirname "$(readlink -f "$BIN")")/fly-session" ] || die "the bus topology needs fly-session beside $BIN"
fi
systemctl is-active --quiet flyshadow.service && die "flyshadow.service is already running"
if [ "$mode" = remote ]; then
[ -f "$REMOTE_ENV" ] || die "no $REMOTE_ENV: the shadow runs on a build box (SHADOW-02; runbook). Pass --local to run it on this container instead, at the live fly's expense"
check_remote
fi
check_cpuset
install -d -o fly -g fly -m 0755 "$SHADOW_DIR" "$SHADOW_DIR/trace"
# A previous run's verdict is kept beside, never read as this run's.
if [ -f "$SHADOW_DIR/verdict.json" ]; then
mv "$SHADOW_DIR/verdict.json" "$SHADOW_DIR/verdict.$(date -u +%Y%m%dT%H%M%SZ).json"
fi
rm -f "$SHADOW_DIR/divergence.json" "$SHADOW_DIR/guard-tripped.json"
log "recording the live fly's baseline over ${BASELINE_SECONDS} s, before the shadow exists"
local n samples base
n=$(( BASELINE_SECONDS / 10 ))
[ "$n" -ge 3 ] || die "FLY_SHADOW_BASELINE_SECONDS must be at least 30"
samples="$SHADOW_DIR/baseline-samples.jsonl"
: > "$samples"
for _ in $(seq 1 "$n"); do
sample >> "$samples" || die "could not read flysim's metrics for the baseline"
done
base="$(python3 -c "$GUARD_PY" baseline "$samples")" \
|| die "flysim did not run normally during the baseline; not starting the shadow"
printf '%s\n' "$base" > "$SHADOW_DIR/baseline.json"
printf '{}\n' > "$SHADOW_DIR/guard-state.json"
chown fly:fly "$SHADOW_DIR/baseline.json" "$samples" "$SHADOW_DIR/guard-state.json"
log "baseline: $base"
mkdir -p "$DROPIN_DIR" "$REMOTE_DROPIN_DIR"
if [ -n "$arm" ]; then
cat > "$MODE_DROPIN" <<EOF
# written by fly-shadow-run start --bus (BUS-01); removed by fly-shadow-run stop and by its guard.
# The shadow's session runs the bus topology; a remote relay forwards this to the box.
[Service]
Environment=FLY_SHADOW_MODE=$arm
EOF
log "the shadow runs the bus topology ($arm)"
else
rm -f "$MODE_DROPIN"
fi
if [ "$mode" = remote ]; then
local run_id
run_id="$(date +%s%3N)"
[ "$HEARTBEAT_WAIT" -ge 300 ] || HEARTBEAT_WAIT=300
cat > "$REMOTE_DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-02); removed by fly-shadow-run stop and by its guard.
# The shadow runs on a build box; this unit is its relay: light, normal scheduling, off flysim's CPUs.
[Service]
EnvironmentFile=$REMOTE_ENV
Environment=FLY_SHADOW_RUN_ID=$run_id
ExecStart=
ExecStart=$BIN relay
CPUSchedulingPolicy=other
Nice=5
CPUWeight=50
IOSchedulingClass=best-effort
MemoryMax=1G
EOF
log "remote shadow, run $run_id: flyshadow.service relays to the build box in $REMOTE_ENV"
else
rm -f "$REMOTE_DROPIN"
log "LOCAL shadow on this container (--local)"
fi
cat > "$DROPIN" <<EOF
# written by fly-shadow-run start (SHADOW-01); removed by fly-shadow-run stop and by its guard.
[Service]
Environment=FLY_TRACE_DIR=$SHADOW_DIR/trace
Environment=FLY_TRACE_LEDGERS=$LEDGERS_EVERY
EOF
systemctl daemon-reload
rm -f "$SHADOW_DIR/relay.json" "$SHADOW_DIR/trace/consumer"
systemctl start flyshadow.service
# flysim starts no trace without a live consumer: wait for the shadow's heartbeat (remote: the
# relay writes it once the box's shadow of this run is alive and the sync is caught up).
for _ in $(seq 1 "$HEARTBEAT_WAIT"); do
[ -f "$SHADOW_DIR/trace/consumer" ] && break
sleep 1
done
[ -f "$SHADOW_DIR/trace/consumer" ] || { stop_all "the shadow wrote no heartbeat"; die "flyshadow.service did not come up (remote: journalctl -u flyshadow; $SHADOW_DIR/relay.json)"; }
log "flyshadow.service started; restarting flysim.service so the shadow follows it from its start"
systemctl restart flysim.service
systemctl start flyshadow-guard.timer
log "started, guarded every 60 s. Read progress with: fly-shadow-run status"
}
# Stops the shadow and the guard and turns the trace off. $1: why (logged).
stop_all() {
systemctl stop flyshadow-guard.timer 2>/dev/null || true
systemctl stop flyshadow.service 2>/dev/null || true
rm -f "$DROPIN" "$REMOTE_DROPIN" "$MODE_DROPIN"
systemctl daemon-reload
log "stopped the shadow: $1"
}
stop() {
need_root
local restart_flysim=0 keep=0
for arg in "$@"; do
case "$arg" in
--restart-flysim) restart_flysim=1 ;;
--keep) keep=1 ;;
*) die "stop: unknown option $arg" ;;
esac
done
stop_all "fly-shadow-run stop"
if [ "$restart_flysim" = 1 ]; then
systemctl restart flysim.service
log "flysim.service restarted without the trace"
else
log "flysim stops its current trace within a minute (no consumer) and starts none at its next restart"
fi
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
if [ "$keep" = 0 ]; then
rm -rf "$SHADOW_DIR/spool" "$SHADOW_DIR/work"
find "$SHADOW_DIR/trace" -name 'trace-*.jsonl' -delete 2>/dev/null || true
fi
log "the verdict stays in $SHADOW_DIR/verdict.json"
}
# "ActiveState/SubState" of a unit, from `systemctl show` (`is-active` cannot tell a crashed unit
# waiting out its restart delay, activating/auto-restart, from a stopped one).
unit_state() {
local out active
out="$(systemctl show -p ActiveState,SubState "$1" 2>/dev/null)" || true
active="$(printf '%s\n' "$out" | sed -n 's/^ActiveState=//p')"
# An unreadable state is not "stopped": the guard keeps running and judges the fly.
case "$active" in
active|inactive|failed|activating|deactivating|reloading) printf '%s\n' "$active" ;;
*) printf 'unknown\n' ;;
esac
}
guard() {
need_root
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
log "no baseline: nothing to guard"
systemctl stop flyshadow-guard.timer 2>/dev/null || true
exit 0
fi
# The guard acts only against a shadow that is up or on its way up. One that diverged, passed
# and stopped, or was stopped costs the live fly nothing more (ActiveState inactive/failed), and
# flysim stops its trace without the shadow's heartbeat. During the shadow's crash-restart delay
# (Restart=on-failure, RestartSec=10) the unit is `activating` (auto-restart): the guard must
# keep running, or the restarted shadow runs unguarded while `check` still allows a cutover
# (SHADOW-01 review round 3, G1-a).
local active_state
active_state="$(unit_state flyshadow.service)"
case "$active_state" in
inactive|failed)
log "flyshadow.service is $active_state: the guard stops itself and changes nothing"
systemctl stop flyshadow-guard.timer 2>/dev/null || true
exit 0
;;
esac
[ -f "$SHADOW_DIR/guard-state.json" ] || printf '{}\n' > "$SHADOW_DIR/guard-state.json"
local now tmp verdict
now="$(sample)" || { log "could not read flysim's metrics; not judged this minute"; exit 0; }
tmp="$(mktemp)"
printf '%s\n' "$now" > "$tmp"
if verdict="$(python3 -c "$GUARD_PY" decide "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json" "$tmp")"; then
rm -f "$tmp"
log "guard: $verdict ($now)"
exit 0
fi
rm -f "$tmp"
log "guard TRIPPED: $verdict ($now)"
stop_all "guard: $verdict"
rm -f "$SHADOW_DIR/baseline.json" "$SHADOW_DIR/guard-state.json"
python3 -c 'import json,sys,datetime; json.dump({"at": datetime.datetime.now(datetime.timezone.utc).isoformat(), "reason": sys.argv[1], "sample": json.loads(sys.argv[2])}, open(sys.argv[3], "w"))' \
"$verdict" "$now" "$SHADOW_DIR/guard-tripped.json"
systemctl restart flysim.service
log "flysim.service restarted without the trace; see $SHADOW_DIR/guard-tripped.json"
}
status() {
systemctl is-active flyshadow.service || true
systemctl is-active flyshadow-guard.timer || true
[ -f "$SHADOW_DIR/guard-tripped.json" ] && echo "GUARD TRIPPED: $(cat "$SHADOW_DIR/guard-tripped.json")"
if [ -f "$REMOTE_DROPIN" ] && [ -f "$SHADOW_DIR/relay.json" ]; then
python3 - "$SHADOW_DIR/relay.json" <<'PY'
import json, sys
r = json.load(open(sys.argv[1]))
print(f"remote relay: {'healthy' if r.get('healthy') else 'NOT HEALTHY'} (connected {r.get('connected')}, "
f"box shadow alive {r.get('remoteAlive')} {r.get('remoteWhy') or ''}); caught up "
f"{r.get('caughtUpSecondsAgo')} s ago; unsynced {r.get('unsyncedBytes')} B; updated {r.get('updatedAt')}")
PY
fi
[ -f "$SHADOW_DIR/verdict.json" ] || { echo "no verdict yet"; return 0; }
python3 - "$SHADOW_DIR/verdict.json" <<'PY'
import json, sys
v = json.load(open(sys.argv[1]))
c = v["compared"]
print(f"verdict {v['status']}: {v['reason']}")
print(f" compared {c['brainSeconds']:.0f} of {v['required']['brainSeconds']:.0f} brain s "
f"({c['transitions']} transitions, {c['segments']} segments); updated {v['updatedAt']}")
print(f" sugar {c['sugar']}, rewards {c['rewards']} {c['rewardKinds']}, macro events {c['macroEvents']}, "
f"slot saves {c['slotSaves']}, rollbacks {c['rollbacks']}, ledger checks {c['ledgerChecks']}")
print(f" checkpoints {c['checkpoints']}; skipped {v['skipped']}; spool evicted {v['spoolEvicted']}")
print(f" behind the live trace ~{v['lagTransitions']} transitions; live lag {v['liveLagSeconds']} s; cost {v['cost']}")
if v["firstDivergence"]:
print(f" FIRST DIVERGENCE: {json.dumps(v['firstDivergence'])}")
PY
}
check() {
# `--bus` (BUS-01): the cutover goes onto the bus topology, so the shadow must have run it.
local -a pass=()
local arg
for arg in "$@"; do
case "$arg" in
--bus) pass+=(--require-arm bus/process) ;;
*) pass+=("$arg") ;;
esac
done
set -- "${pass[@]}"
# Only the legacy loop writes the trace the shadow follows: if the live fly moved to the session
# runtime during the window, the verdict no longer covers what would be cut over.
if [ -f "$RUNTIME_DROPIN" ]; then
echo "cutover refused: flysim.service runs the session runtime, which writes no trace for a shadow to follow (switch the live fly to legacy for the shadow window: fly-runtime legacy)"
exit 1
fi
# A tripped guard, a shadow that is not running, or a run that no guard watched never allows a
# cutover, whatever the verdict file says: the guard timer must be active and its baseline
# present (G1-a).
if [ -f "$SHADOW_DIR/guard-tripped.json" ]; then
echo "cutover refused: the guard tripped ($(cat "$SHADOW_DIR/guard-tripped.json"))"
exit 1
fi
if ! systemctl is-active --quiet flyshadow.service; then
echo "cutover refused: flyshadow.service is not running"
exit 1
fi
if ! systemctl is-active --quiet flyshadow-guard.timer; then
echo "cutover refused: flyshadow-guard.timer is not active (this run is not guarded)"
exit 1
fi
if [ ! -f "$SHADOW_DIR/baseline.json" ]; then
echo "cutover refused: no baseline.json (this run was not baselined by fly-shadow-run start)"
exit 1
fi
# Remote (SHADOW-02): the relay must be healthy now (connected, the box's shadow of this run
# alive, the sync caught up), not just have relayed a pass lately; it must not have lost
# coverage (flysim stopped its trace for want of a consumer: review B1); the live trace must be
# being written; and the relay's, the verdict's and this run's drop-in's run ids must be one.
# A verdict that carries a run id is a remote run's: it never stands for a local shadow.
local why rc=0 run_id=""
[ -f "$REMOTE_DROPIN" ] && run_id="$(sed -n 's/^Environment=FLY_SHADOW_RUN_ID=//p' "$REMOTE_DROPIN" | tail -n 1)"
why="$(python3 - "$SHADOW_DIR/relay.json" "$SHADOW_DIR/verdict.json" "$([ -f "$REMOTE_DROPIN" ] && echo remote || echo local)" "$run_id" <<'PY'
import datetime, json, sys
relay_path, verdict_path, mode, run_id = sys.argv[1:5]
def refuse(msg):
print(msg); sys.exit(1)
try:
v = json.load(open(verdict_path))
except Exception:
v = {}
if mode == "local":
if v.get("runId") is not None:
refuse("the verdict is a remote run's (run %s) but this run is local: no remote drop-in" % v.get("runId"))
sys.exit(0)
if not run_id:
refuse("the remote drop-in names no FLY_SHADOW_RUN_ID")
try:
r = json.load(open(relay_path))
t = datetime.datetime.fromisoformat(r["updatedAt"].replace("Z", "+00:00"))
except Exception as e:
refuse("no readable relay.json (%s)" % e)
# updatedAt is the container's own clock (the relay writes it here), so skew between the two hosts
# does not reach this check; the verdict's own age check does (see the runbook: run NTP on both).
age = (datetime.datetime.now(datetime.timezone.utc) - t).total_seconds()
if not -60 <= age <= 60:
refuse("relay.json is %.0f s old" % age)
if r.get("runId") != run_id:
refuse("relay.json is for run %s, this run is %s" % (r.get("runId"), run_id))
if v.get("runId") != run_id:
refuse("the verdict is for run %s, this run is %s" % (v.get("runId"), run_id))
if v.get("window") is None:
refuse("the verdict does not say where its window starts (a shadow older than the B2 fix): a gap before it may be counted")
if r.get("coverageLost"):
refuse("coverage of the live fly was lost (%s): its trace stopped for want of a consumer and the rest of that process is uncompared" % json.dumps(r["coverageLost"]))
if not r.get("healthy"):
refuse("the relay is not healthy (connected %s, box shadow alive %s %s)" % (r.get("connected"), r.get("remoteAlive"), r.get("remoteWhy") or ""))
ta = r.get("traceAgeSeconds")
if ta is None:
refuse("no live trace file of this run")
if ta > 90:
refuse("the live trace has not been written for %d s while the shadow claims to follow it (flysim paused, or its trace stopped)" % ta)
PY
)" || rc=$?
if [ "$rc" != 0 ]; then
echo "cutover refused: remote shadow: $why"
exit 1
fi
[ -x "$BIN" ] || die "$BIN is missing"
# The live service's configuration, for its compatibility string. fly.env is systemd's
# EnvironmentFile syntax (GAME_TITLE=Pokemon Red is valid there), so it is read as KEY=VALUE
# lines, as fly-runtime does, never sourced as shell.
local line key value env_file="${FLY_ENV_FILE:-/etc/fly/fly.env}"
if [ -f "$env_file" ]; then
while IFS= read -r line || [ -n "$line" ]; do
[[ "$line" =~ ^[A-Za-z_][A-Za-z0-9_]*= ]] || continue
key="${line%%=*}"
value="${line#*=}"
value="${value%\"}"
value="${value#\"}"
export "${key}=${value}"
done <"$env_file"
fi
# The release CUT-01 switches into and the binary it switches to: SERVE-01's service there.
"$BIN" check --verdict "$SHADOW_DIR/verdict.json" --current "${FLY_CURRENT_DIR:-/opt/fly/current}" \
--binary flysim-session "$@"
}
cmd="${1:-}"
[ $# -gt 0 ] && shift
case "$cmd" in
start) start "$@" ;;
stop) stop "$@" ;;
status) status ;;
check) check "$@" ;;
guard) guard ;;
baseline) [ $# = 1 ] || die "baseline SAMPLES.jsonl"; python3 -c "$GUARD_PY" baseline "$1" ;;
simulate) [ $# = 2 ] || die "simulate BASELINE.jsonl CHECKS.jsonl"; python3 -c "$GUARD_PY" simulate "$1" "$2" ;;
*) echo "usage: fly-shadow-run start [--local]|stop [--restart-flysim] [--keep]|status|check [--max-age-seconds N]|guard|baseline SAMPLES.jsonl|simulate BASELINE.jsonl CHECKS.jsonl" >&2; exit 2 ;;
esac

View file

@ -48,6 +48,9 @@ log_info() {
# encoder actually opened (docs/design/gpu.md section 5). # encoder actually opened (docs/design/gpu.md section 5).
: "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}" : "${FLY_ENCODER_METRIC:=${TEXTFILE_DIR}/fly_encoder.prom}"
: "${FLY_ENV_FILE:=/etc/fly/fly.env}" : "${FLY_ENV_FILE:=/etc/fly/fly.env}"
# Written by the session worker (flybrain_core::lif::health): which hardware runs the LIF tick.
: "${FLY_BRAIN_BACKEND_METRIC:=${TEXTFILE_DIR}/fly_brain_backend.prom}"
: "${FLY_PROC_DIR:=/proc}"
# --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md --------- # --- check 9 (capture freeze) inputs, infra/docs/capture-freeze.md ---------
: "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments : "${FLY_REC_DIR:=/srv/fly/media/rec}" # flycast's 10-minute mpegts segments
: "${FFMPEG:=/usr/bin/ffmpeg}" : "${FFMPEG:=/usr/bin/ffmpeg}"
@ -72,6 +75,7 @@ log_info() {
: "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10) : "${WD_LOOP_MIN_EVENTS:=20}" # floor under the dominance rule (see check 10)
: "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57) : "${WD_LOOP_STALL_PCT:=90}" # decisions that ended refused/blocked/timeout: this share is a stall (row 57)
: "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58) : "${WD_LOOP_BUSY_MIN:=100}" # this many decisions with no reward and no new ground, two probes running, is busy going nowhere (row 58)
: "${WD_LOOP_FIGHT_MIN:=24}" # this many MOVE n decisions with no battle won and no new ground, two probes running, is battles lost on repeat (row 67)
: "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}" : "${WD_LOOP_REPORT:=${WD_RUN_DIR}/loop.json}"
mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR" mkdir -p "$WD_RUN_DIR" "$WD_STATE_DIR"
@ -155,7 +159,7 @@ write_textfile_metrics() {
{ {
echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)." echo "# HELP fly_watchdog_restarts_total Restarts issued because that unit's own check failed (cascade restarts from another unit's escalation are counted only in fly_watchdog_escalations_total, not here)."
echo "# TYPE fly_watchdog_restarts_total counter" echo "# TYPE fly_watchdog_restarts_total counter"
for unit in flysim flystage flycast mediamtx flypush flystage-web; do for unit in flysim flystage flycast mediamtx flypush flystage-web flyedge; do
echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")" echo "fly_watchdog_restarts_total{unit=\"${unit}\"} $(get_counter restarts_total "$unit")"
done done
# Check 7's own restart reason, kept as a separate labelset on the # Check 7's own restart reason, kept as a separate labelset on the
@ -173,6 +177,9 @@ write_textfile_metrics() {
echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all." echo "# HELP fly_watchdog_encoder_degraded 1 when flycast is running on a different video encoder than /etc/fly/fly.env asked for (i.e. the nvenc -> x264 fallback fired). -1 when the encoder state could not be read at all."
echo "# TYPE fly_watchdog_encoder_degraded gauge" echo "# TYPE fly_watchdog_encoder_degraded gauge"
echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)" echo "fly_watchdog_encoder_degraded $(cat "${WD_RUN_DIR}/encoder_degraded" 2>/dev/null || echo -1)"
echo "# HELP fly_watchdog_backend_degraded 1 when FLY_LIF_CUDA=1 asks for the GPU and the LIF tick runs on the CPU (the GPU fell back). -1 when no session worker has written fly_brain_backend."
echo "# TYPE fly_watchdog_backend_degraded gauge"
echo "fly_watchdog_backend_degraded $(cat "${WD_RUN_DIR}/backend_degraded" 2>/dev/null || echo -1)"
# Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames # Check 9 (infra/docs/capture-freeze.md). fly_capture_identical_frames
# is -1 until the first probe completes, the same "unknown, not # is -1 until the first probe completes, the same "unknown, not
# broken" convention fly_watchdog_encoder_degraded uses; a value at or # broken" convention fly_watchdog_encoder_degraded uses; a value at or
@ -192,7 +199,7 @@ write_textfile_metrics() {
# convention as fly_watchdog_encoder_degraded), while the flag itself # convention as fly_watchdog_encoder_degraded), while the flag itself
# starts at 0, because a 0/1 flag carrying -1 reads as a loop to every # starts at 0, because a 0/1 flag carrying -1 reads as a loop to every
# alert expression that would ever use it. # alert expression that would ever use it.
echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked) or completing nothing, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this." echo "# HELP fly_loop_suspected 1 when the last check-10 probe found a short macro cycle repeating, one macro dominating, or the decisions stalled (refused/blocked), completing nothing, earning nothing or winning no battle, with no growth in the exploration count. Report only: the watchdog never restarts or presses anything for this."
echo "# TYPE fly_loop_suspected gauge" echo "# TYPE fly_loop_suspected gauge"
echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" echo "fly_loop_suspected $(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)." echo "# HELP fly_loop_period Length in macro labels of the shortest repeating block found at the end of the window (0 when nothing repeats, -1 before the first probe)."
@ -221,6 +228,12 @@ write_textfile_metrics() {
echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)." echo "# HELP fly_loop_rewards Reward events in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_rewards gauge" echo "# TYPE fly_loop_rewards gauge"
echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)" echo "fly_loop_rewards $(cat "${WD_RUN_DIR}/loop.rewards" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_fights MOVE n decisions (a move chosen in a battle) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_fights gauge"
echo "fly_loop_fights $(cat "${WD_RUN_DIR}/loop.fights" 2>/dev/null || echo -1)"
echo "# HELP fly_loop_wins Battle-won reward events (rewardKind wildwin, trainer or badge) in the last check-10 window (-1 before the first probe)."
echo "# TYPE fly_loop_wins gauge"
echo "fly_loop_wins $(cat "${WD_RUN_DIR}/loop.wins" 2>/dev/null || echo -1)"
echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against." echo "# HELP fly_places_delta Growth in game.uniqueLocations (the exploration count) since the previous check-10 probe. -1 when there is no previous probe to compare against."
echo "# TYPE fly_places_delta gauge" echo "# TYPE fly_places_delta gauge"
echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)" echo "fly_places_delta $(cat "${WD_RUN_DIR}/loop.places_delta" 2>/dev/null || echo -1)"
@ -319,9 +332,30 @@ is_enabled() {
# ============================================================================ # ============================================================================
# Check 1: flysim — /healthz 200 and hot-state mtime age < 30s. # Check 1: flysim — /healthz 200 and hot-state mtime age < 30s.
# ============================================================================ # ============================================================================
# FLY_CONTROL_VIA from fly.env, lowercased ("direct" when absent).
control_via() {
local via=""
if [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_CONTROL_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
echo "${via:-direct}"
}
# flysim's own /healthz: :7401 when flysim serves it, and with FLY_CONTROL_VIA=bus
# (docs/design/flybus.md, "Control over the bus") flysim's read-only listener,
# which flysim serves itself in both modes -- so an edge that is down is check
# 1b's business and never restarts the fly.
flysim_health_url() {
if [ "$(control_via)" = "bus" ]; then
echo "${FLY_METRICS_URL}/healthz"
else
echo "${FLY_CONTROL_URL}/healthz"
fi
}
check_flysim() { check_flysim() {
local ok=1 local ok=1
if ! curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then if ! curl -fsS -o /dev/null "$(flysim_health_url)"; then
ok=0 ok=0
fi fi
if [ -e "$FLY_STATE_HOT" ]; then if [ -e "$FLY_STATE_HOT" ]; then
@ -339,6 +373,24 @@ check_flysim() {
fi fi
} }
# ============================================================================
# Check 1b: flycontrol-edge -- only with FLY_CONTROL_VIA=bus. :7401/healthz
# answered by the edge while flysim's own /healthz is fine; when the edge does
# not answer, restart the edge (never flysim, never a reboot: the fly is fine
# and the edge holds no state). With flysim itself down, check 1 owns it.
# ============================================================================
check_control_edge() {
[ "$(control_via)" = "bus" ] || return 0
curl -fsS -o /dev/null "${FLY_METRICS_URL}/healthz" || return 0
if curl -fsS -o /dev/null "${FLY_CONTROL_URL}/healthz"; then
record_ok flycontrol-edge
else
record_fail flycontrol-edge
log_err "flycontrol-edge: :7401 does not answer while flysim is healthy; restarting the edge"
restart_unit flycontrol-edge
fi
}
# ============================================================================ # ============================================================================
# Check 2: flystage — flysim's frames_sent_total / feed_clients from the # Check 2: flystage — flysim's frames_sent_total / feed_clients from the
# read-only metrics listener (infra.md section 5; not superseded by the # read-only metrics listener (infra.md section 5; not superseded by the
@ -350,25 +402,86 @@ check_flysim() {
# bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the # bus"), which exports them under the same names. FLY_FEED_METRICS_URL in the
# watchdog's own environment overrides both. # watchdog's own environment overrides both.
# ============================================================================ # ============================================================================
# `direct` or `bus`: who serves the feed RIGHT NOW. What fly.env says is what the next start of
# flysim does; what the running flysim started with (its environment: `fly-feed status` reads the
# same) is what is true. They differ between a deploy that changed FLY_FEED_VIA and the next
# restart, and judging the edge in that window would restart a flysim that is serving the feed
# itself. So: the running process when its environment can be read (flysim runs as the same user),
# else the file. Lowercased, because flysim reads the value case-insensitively; anything else, or
# no line, is direct.
feed_via() {
local via="" pid=""
pid="$(systemctl show -p MainPID --value flysim.service 2>/dev/null | head -n1 || true)"
if [ -n "$pid" ] && [ "$pid" != 0 ] && [ -r "${FLY_PROC_DIR}/${pid}/environ" ]; then
via="$(tr '\0' '\n' <"${FLY_PROC_DIR}/${pid}/environ" 2>/dev/null | awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
elif [ -f "$FLY_ENV_FILE" ]; then
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then echo bus; else echo direct; fi
}
feed_metrics_url() { feed_metrics_url() {
if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then if [ -n "${FLY_FEED_METRICS_URL:-}" ]; then
echo "$FLY_FEED_METRICS_URL" echo "$FLY_FEED_METRICS_URL"
return return
fi fi
local via="" if [ "$(feed_via)" = "bus" ]; then
if [ -f "$FLY_ENV_FILE" ]; then
# Lowercased: flysim reads the value case-insensitively, so `Bus` is bus mode.
via="$(awk -F= '/^FLY_FEED_VIA=/ { print $2; exit }' "$FLY_ENV_FILE" 2>/dev/null | tr -d ' \r"' | tr '[:upper:]' '[:lower:]' || true)"
fi
if [ "$via" = "bus" ]; then
echo "$FLY_EDGE_METRICS_URL" echo "$FLY_EDGE_METRICS_URL"
else else
echo "$FLY_METRICS_URL" echo "$FLY_METRICS_URL"
fi fi
} }
# Check 2a (FLY_FEED_VIA=bus only): the edge itself. flyedge.service active and its /healthz 200
# (subscribed to flysim's bus, a snapshot within the last 15 s). Not judged while flysim is down
# or restarting (check 1's business: the edge follows it by itself), and one failed pass is let go:
# a flysim that has only just answered may not have published yet. After that:
# 2nd consecutive failure restart flyedge (the escalation's restart)
# 3rd and the page and the encoder (escalate's chain)
# 4th the edge cannot be kept up: the feed goes back to flysim, `fly-feed
# direct --no-wait` (a restart of flysim, one stream gap, then the page
# is served again by the process that always worked). It is logged as
# an escalation and leaves FLY_FEED_VIA=direct until an operator
# switches again; this check then does nothing.
check_flyedge() {
if [ "$(feed_via)" != "bus" ]; then
record_ok flyedge
return 0
fi
if ! curl -fsS -o /dev/null --max-time 5 "${FLY_CONTROL_URL}/healthz" 2>/dev/null; then
return 0
fi
if is_active flyedge.service \
&& curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null; then
record_ok flyedge
return 0
fi
record_fail flyedge
local n
n="$(fail_count flyedge)"
# From the 4th consecutive failure on, whatever the time the failures were spread over (passes
# are skipped while flysim is down, so a flapping flysim stretches the run past any window): the
# fallback to direct comes first and a reboot is never the answer to an edge fault. Only
# n = 2 and 3 reach escalate (its reboot needs 5), and a failed `fly-feed direct` is retried on
# the next pass instead of falling through to it.
if [ "$n" -ge 4 ]; then
log_err "flyedge: ${n} consecutive failures, restarts did not bring it back: switching the feed to direct (fly-feed direct)"
inc_counter "escalations_total"
sudo /opt/fly/bin/fly-feed direct --no-wait || log_err "fly-feed direct FAILED; the edge stays down"
record_ok flyedge
elif [ "$n" -ge 2 ]; then
escalate flyedge flystage flycast
fi
}
check_flystage() { check_flystage() {
local metrics frames clients ok=1 local metrics frames clients ok=1 chain=(flycast)
if [ "$(feed_via)" = "bus" ] && [ -z "${FLY_FEED_METRICS_URL:-}" ]; then
# The edge serves the page. While it is down or silent that is check 2a's to fix, and a
# restarted page would only reconnect to nothing (and count towards a reboot).
curl -fsS -o /dev/null --max-time 5 "${FLY_EDGE_METRICS_URL}/healthz" 2>/dev/null || return 0
chain=(flyedge flycast)
fi
metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)" metrics="$(curl -fsS "$(feed_metrics_url)/metrics" 2>/dev/null || true)"
if [ -z "$metrics" ]; then if [ -z "$metrics" ]; then
ok=0 ok=0
@ -395,7 +508,7 @@ check_flystage() {
record_ok flystage record_ok flystage
else else
record_fail flystage record_fail flystage
escalate flystage flycast escalate flystage "${chain[@]}"
fi fi
} }
@ -603,6 +716,39 @@ check_encoder() {
"and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv" "and check: nvidia-smi --query-gpu=memory.used,utilization.encoder --format=csv"
} }
# ============================================================================
# Check 11: LIF backend (GPU-02 notes, runbook "FLY_LIF_CUDA"). Reads the
# fly_brain_backend series the session worker writes: when FLY_LIF_CUDA=1 asks
# for the card and the CPU is what runs, the GPU fell back (operator decision
# 2026-10-02: automatic, the stream keeps going, logged here, no paging).
#
# Like check 8 this takes NO remediation. A restart cannot repair a dead card
# and costs the run its in-memory state; the fallback is a CPU run from the
# last checkpoint, which is bit-exact. It logs, exports a gauge and leaves the
# card to a human. fly_brain_backend is not duplicated into this file's own
# .prom, for the reason check 8 gives.
# ============================================================================
check_backend() {
local wanted live fallbacks
if [ ! -f "$FLY_BRAIN_BACKEND_METRIC" ]; then
# No session worker has written it (the legacy loop, a CPU deploy, or not started yet).
echo -1 > "${WD_RUN_DIR}/backend_degraded"
return 0
fi
wanted="$(awk '/^fly_brain_backend_wanted / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
live="$(awk '/^fly_brain_backend\{/ && $NF == 1 {
if (match($0, /backend="[^"]+"/)) { print substr($0, RSTART + 9, RLENGTH - 10); exit } }' \
"$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
fallbacks="$(awk '/^fly_brain_backend_fallbacks_total / { print $2; exit }' "$FLY_BRAIN_BACKEND_METRIC" 2>/dev/null || true)"
if [ "$wanted" = 1 ] && [ "$live" = cpu ]; then
echo 1 > "${WD_RUN_DIR}/backend_degraded"
log_err "GPU backend degraded: FLY_LIF_CUDA=1 asks for the card but the LIF tick runs on the CPU (${fallbacks:-?} fallback(s) since flysim started)." \
"Automatic and bit-exact, from the last checkpoint; not restarting. Reason: journalctl -u flysim | grep LIF_GPU_FALLBACK. See docs/runbook.md 'FLY_LIF_CUDA'"
else
echo 0 > "${WD_RUN_DIR}/backend_degraded"
fi
}
# ============================================================================ # ============================================================================
# Check 9: capture freeze (infra/docs/capture-freeze.md). # Check 9: capture freeze (infra/docs/capture-freeze.md).
# #
@ -807,6 +953,22 @@ check_capture_freeze() {
# unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the # unrewarded — WD_LOOP_BUSY_MIN+ decisions and no reward event in the
# window, on this probe AND the previous one. # window, on this probe AND the previous one.
# #
# Row 67: the Pewter Gym, one trainer lost ~30 times in a row. The readout
# chose TAIL WHIP six turns in seven, Squirtle fainted every time, the fly
# whited out to Pewter and walked straight back in: MOVE 2 / NEXT / GO
# OBJECTIVE / TALK / NO, seven names, every macro `done`. Two stray tile
# rewards (a new tile of the gym on a whiteout's walk back) reset the
# unrewarded rule for ~45 minutes. What the window never had was a battle WON.
# So the reward lines carry their rewardKind, and one more rule reads them,
# behind the same gate:
# unwon-battles — WD_LOOP_FIGHT_MIN+ `MOVE n` decisions and no reward of
# kind wildwin, trainer or badge in the window, on this
# probe AND the previous one.
# The feed has no HP (docs/feed-protocol.md), so "a battle that makes no
# progress" is read as moves chosen and nothing won. Measured on the live log:
# healthy windows had 13-46 MOVE starts and 1-4 wins (the one 22-move window
# with no win also had new ground); the trap had 30-39 and none.
#
# The tile rule is what separates a loop from a legitimately repeating # The tile rule is what separates a loop from a legitimately repeating
# explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer # explorer (macros-traps.md: `GO FRONTIER` x19 over 93 tiles is a walk longer
# than the frame cap, not a trap), and the watchdog has no tile counter. The # than the frame cap, not a trap), and the watchdog has no tile counter. The
@ -857,7 +1019,7 @@ loop_status_fields() {
loop_macro_stream() { loop_macro_stream() {
[ -f "$FLY_EVENT_LOG" ] || return 0 [ -f "$FLY_EVENT_LOG" ] || return 0
tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \ tail -n "$WD_LOOP_TAIL_LINES" "$FLY_EVENT_LOG" 2>/dev/null \
| jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward") | "\(.brainMs)\t\(.label)\t\(.kind)"' -R 2>/dev/null \ | jq -r 'fromjson? // empty | select(.kind == "macro" or .kind == "reward" or .kind == "milestone") | "\(.brainMs)\t\(.label)\t\(.kind)\t\(.rewardKind // "")"' -R 2>/dev/null \
|| true || true
} }
@ -865,12 +1027,22 @@ loop_macro_stream() {
# #
# total US distinct US topCount US period US repeats US windowFrom US # total US distinct US topCount US period US repeats US windowFrom US
# windowTo US topName US block US tail US decisions US refused US blocked US # windowTo US topName US block US tail US decisions US refused US blocked US
# timeout US done US rewards # timeout US done US rewards US fights US wins US progress US species US keys
# #
# `total` counts start events inside the window, `decisions` starts plus # `total` counts start events inside the window, `decisions` starts plus
# refusals (the sequence, `distinct` and `topCount` are over decisions), and # refusals (the sequence, `distinct` and `topCount` are over decisions), and
# the next four count each outcome in the window, and `rewards` the reward # the next four count each outcome in the window, and `rewards` the reward
# events in it (row 58). `period`/`repeats` describe # events in it (row 58), `fights` the `MOVE n` decisions and `wins` the
# rewards of kind wildwin/trainer/badge (row 67). `progress` counts the lasting
# progress in the window (row 70): a `milestone` event (a new rung), or a reward of kind
# pokedex (a species owned for the first time), area (a map entered for the first time),
# trainer or badge -- each paid once per run, so a ring cannot earn them twice -- and
# `species` the pokedex ones alone. `keys` names each of them once as `kind:label`
# (`pokedex:OWNED #8`, `milestone:Reached MT. MOON`), RS-joined, at most 64: a milestone
# reset restores the reward ledger, so its replay pays the same rewards again, and only
# the names tell a replayed reward from a new one. They are reported, never read by a
# rule here: the recovery ladder uses them to tell a trap that follows real progress from
# one that outlived its last step. `period`/`repeats` describe
# the shortest repeating block at the END of the sequence (0/0 when nothing # the shortest repeating block at the END of the sequence (0/0 when nothing
# repeats), `block` is that block comma-joined, and `tail` is the last 12 # repeats), `block` is that block comma-joined, and `tail` is the last 12
# names for context. The window ends at the newest macro event's own brain # names for context. The window ends at the newest macro event's own brain
@ -879,14 +1051,29 @@ loop_analyze() {
awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" ' awk -F'\t' -v win="$WD_LOOP_WINDOW_MS" -v maxp="$WD_LOOP_MAX_PERIOD" '
# Reward lines are counted and nothing else: the window still ends at the # Reward lines are counted and nothing else: the window still ends at the
# newest macro event, as it always has. # newest macro event, as it always has.
$3 == "reward" { rms[++nr] = $1 + 0; next } $3 == "reward" { rms[++nr] = $1 + 0; rkind[nr] = $4; rlbl[nr] = $2; next }
$3 == "milestone" { rms[++nr] = $1 + 0; rkind[nr] = "milestone"; rlbl[nr] = $2; next }
{ ms[++n] = $1 + 0; lbl[n] = $2 } { ms[++n] = $1 + 0; lbl[n] = $2 }
END { END {
if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\n"; exit } if (n == 0) { printf "0\0370\0370\0370\0370\0370\0370\037\037\037\0370\0370\0370\0370\0370\0370\0370\0370\0370\0370\037\n"; exit }
to = ms[n]; from = to - win to = ms[n]; from = to - win
k = 0; distinct = 0; topn = 0; top = "" k = 0; distinct = 0; topn = 0; top = ""
starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0 starts = 0; refused = 0; blocked = 0; timeout = 0; done = 0; rewards = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) rewards++ fights = 0; wins = 0; progress = 0; species = 0; keys = ""; nkeys = 0
for (q = 1; q <= nr; q++) if (rms[q] >= from) {
lasting = rkind[q] == "milestone" || rkind[q] == "pokedex" || rkind[q] == "area" \
|| rkind[q] == "trainer" || rkind[q] == "badge"
if (lasting) {
progress++
key = rkind[q] ":" rlbl[q]
gsub(/[\036\037]/, " ", key)
if (!(key in seenkey) && nkeys < 64) { seenkey[key] = 1; keys = keys (nkeys++ ? "\036" : "") key }
}
if (rkind[q] == "milestone") continue
rewards++
if (rkind[q] == "wildwin" || rkind[q] == "trainer" || rkind[q] == "badge") wins++
if (rkind[q] == "pokedex") species++
}
for (i = 1; i <= n; i++) { for (i = 1; i <= n; i++) {
if (ms[i] < from) continue if (ms[i] < from) continue
if (lbl[i] ~ / blocked$/) { blocked++; continue } if (lbl[i] ~ / blocked$/) { blocked++; continue }
@ -897,6 +1084,7 @@ loop_analyze() {
else continue else continue
name = lbl[i]; sub(/ (start|refused)$/, "", name) name = lbl[i]; sub(/ (start|refused)$/, "", name)
seq[++k] = name seq[++k] = name
if (name ~ /^MOVE [1-4]$/) fights++
if (!(name in cnt)) { cnt[name] = 0; distinct++ } if (!(name in cnt)) { cnt[name] = 0; distinct++ }
cnt[name]++ cnt[name]++
if (cnt[name] > topn) { topn = cnt[name]; top = name } if (cnt[name] > topn) { topn = cnt[name]; top = name }
@ -919,9 +1107,9 @@ loop_analyze() {
tailstr = "" tailstr = ""
start = k - 11; if (start < 1) start = 1 start = k - 11; if (start < 1) start = 1
for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j] for (j = start; j <= k; j++) tailstr = tailstr (tailstr == "" ? "" : ", ") seq[j]
printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\n", \ printf "%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\037%s\037%s\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%d\037%s\n", \
starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \ starts, distinct, topn, period, repeats, from, to, top, block, tailstr, \
k, refused, blocked, timeout, done, rewards k, refused, blocked, timeout, done, rewards, fights, wins, progress, species, keys
}' }'
} }
@ -979,14 +1167,15 @@ check_loop() {
echo "$delta" > "${WD_RUN_DIR}/loop.places_delta" echo "$delta" > "${WD_RUN_DIR}/loop.places_delta"
local analysis total distinct topn period repeats win_from win_to top block tailstr local analysis total distinct topn period repeats win_from win_to top block tailstr
local decisions refused blocked timeouts completed rewards local decisions refused blocked timeouts completed rewards fights wins progress species keys
analysis="$(loop_macro_stream | loop_analyze)" analysis="$(loop_macro_stream | loop_analyze)"
IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \ IFS=$'\037' read -r total distinct topn period repeats win_from win_to top block tailstr \
decisions refused blocked timeouts completed rewards <<< "$analysis" decisions refused blocked timeouts completed rewards fights wins progress species keys <<< "$analysis"
total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}" total="${total:-0}"; distinct="${distinct:-0}"; topn="${topn:-0}"
period="${period:-0}"; repeats="${repeats:-0}" period="${period:-0}"; repeats="${repeats:-0}"
decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}" decisions="${decisions:-0}"; refused="${refused:-0}"; blocked="${blocked:-0}"
timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}" timeouts="${timeouts:-0}"; completed="${completed:-0}"; rewards="${rewards:-0}"
fights="${fights:-0}"; wins="${wins:-0}"; progress="${progress:-0}"; species="${species:-0}"
echo "$distinct" > "${WD_RUN_DIR}/loop.distinct" echo "$distinct" > "${WD_RUN_DIR}/loop.distinct"
echo "$period" > "${WD_RUN_DIR}/loop.period" echo "$period" > "${WD_RUN_DIR}/loop.period"
echo "$repeats" > "${WD_RUN_DIR}/loop.repeats" echo "$repeats" > "${WD_RUN_DIR}/loop.repeats"
@ -994,6 +1183,8 @@ check_loop() {
echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked" echo "$(( blocked + timeouts ))" > "${WD_RUN_DIR}/loop.blocked"
echo "$completed" > "${WD_RUN_DIR}/loop.done" echo "$completed" > "${WD_RUN_DIR}/loop.done"
echo "$rewards" > "${WD_RUN_DIR}/loop.rewards" echo "$rewards" > "${WD_RUN_DIR}/loop.rewards"
echo "$fights" > "${WD_RUN_DIR}/loop.fights"
echo "$wins" > "${WD_RUN_DIR}/loop.wins"
local prev_suspected=0 local prev_suspected=0
[ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)" [ -f "${WD_RUN_DIR}/loop.suspected" ] && prev_suspected="$(cat "${WD_RUN_DIR}/loop.suspected" 2>/dev/null || echo 0)"
@ -1022,6 +1213,14 @@ check_loop() {
[ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1 [ "$decisions" -ge "$WD_LOOP_BUSY_MIN" ] && [ "$rewards" -eq 0 ] && [ "$grown" -eq 0 ] && busy=1
echo "$busy" > "$busy_file" echo "$busy" > "$busy_file"
# Battles lost on repeat (row 67), judged over two probes like the two
# above: moves chosen, no battle won, no new ground.
local unwon_file="${WD_RUN_DIR}/loop.prev_unwon" prev_unwon=0 unwon=0
[ -f "$unwon_file" ] && prev_unwon="$(cat "$unwon_file" 2>/dev/null || echo 0)"
case "${prev_unwon:-}" in ''|*[!0-9]*) prev_unwon=0 ;; esac
[ "$fights" -ge "$WD_LOOP_FIGHT_MIN" ] && [ "$wins" -eq 0 ] && [ "$grown" -eq 0 ] && unwon=1
echo "$unwon" > "$unwon_file"
local failed=$(( refused + blocked + timeouts )) local failed=$(( refused + blocked + timeouts ))
local suspected=0 reason="" local suspected=0 reason=""
if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then if [ "$decisions" -gt 0 ] && [ "$grown" -eq 0 ]; then
@ -1051,6 +1250,11 @@ check_loop() {
# completes, none of them earns anything, and the ground stays put. # completes, none of them earns anything, and the ground stays put.
suspected=1 suspected=1
reason="unrewarded" reason="unrewarded"
elif [ "$unwon" -eq 1 ] && [ "$prev_unwon" -eq 1 ]; then
# Row 67: every macro completes and the odd tile reward keeps the
# window from reading unrewarded, but no battle is ever won.
suspected=1
reason="unwon-battles"
fi fi
fi fi
echo "$suspected" > "${WD_RUN_DIR}/loop.suspected" echo "$suspected" > "${WD_RUN_DIR}/loop.suspected"
@ -1083,6 +1287,11 @@ check_loop() {
--argjson timeouts "$timeouts" \ --argjson timeouts "$timeouts" \
--argjson completed "$completed" \ --argjson completed "$completed" \
--argjson rewards "$rewards" \ --argjson rewards "$rewards" \
--argjson fights "$fights" \
--argjson wins "$wins" \
--argjson progress "$progress" \
--argjson species "$species" \
--arg keys "${keys:-}" \
--argjson windowFrom "${win_from:-0}" \ --argjson windowFrom "${win_from:-0}" \
--argjson windowTo "${win_to:-0}" \ --argjson windowTo "${win_to:-0}" \
--argjson windowMs "$WD_LOOP_WINDOW_MS" \ --argjson windowMs "$WD_LOOP_WINDOW_MS" \
@ -1112,6 +1321,10 @@ check_loop() {
decisions: $decisions, decisions: $decisions,
outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused }, outcomes: { done: $completed, blocked: $blocked, timeout: $timeouts, refused: $refused },
rewards: $rewards, rewards: $rewards,
fights: $fights,
wins: $wins,
progress: { lasting: $progress, species: $species,
keys: (if $keys == "" then [] else ($keys | split("\u001e")) end) },
tail: (if $tail == "" then [] else ($tail | split(", ")) end) tail: (if $tail == "" then [] else ($tail | split(", ")) end)
}, },
dominant: { name: (if $dominant == "" then null else $dominant end), dominant: { name: (if $dominant == "" then null else $dominant end),
@ -1137,6 +1350,8 @@ check_loop() {
if [ "$suspected" -eq 1 ]; then if [ "$suspected" -eq 1 ]; then
if [ "$reason" = "unrewarded" ]; then if [ "$reason" = "unrewarded" ]; then
log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (unrewarded): ${decisions} decisions and no reward event in the last ${mins} brain minutes, two probes running — ${completed} done, top [${top}] x${topn}, ${distinct} distinct name(s), tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — macros that complete and earn nothing are an undo pair or a ring. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "unwon-battles" ]; then
log_err "loop suspected (unwon-battles): ${fights} moves chosen in battle and no battle won in the last ${mins} brain minutes, two probes running — ${decisions} decisions, ${rewards} reward event(s), top [${top}] x${topn}, tail [${tailstr}], exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — battles lost on repeat are a readout choice or a pad that offers no winning move. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then elif [ "$reason" = "stalled" ] || [ "$reason" = "zero-progress" ]; then
log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'." log_err "loop suspected (${reason}): [${shown}] — ${decisions} decisions in the last ${mins} brain minutes, ${total} started, ${completed} done, ${refused} refused, $(( blocked + timeouts )) blocked or timed out, exploration count ${places:-?} unchanged (delta ${delta}), rung ${rank:-?} '${mlabel:-?}' for ${since:-?}s. NOT acting: nothing restarted, nothing pressed, the game untouched — a pad whose buttons cannot run is a macro bug. Report: ${WD_LOOP_REPORT}; see infra/docs/runbook.md 'loop suspected'."
elif [ "$reason" = "sequence" ]; then elif [ "$reason" = "sequence" ]; then
@ -1151,9 +1366,12 @@ check_loop() {
main() { main() {
check_flysim check_flysim
check_flyedge
check_control_edge
check_flystage check_flystage
check_flycast check_flycast
check_encoder check_encoder
check_backend
check_mediamtx check_mediamtx
check_flypush check_flypush
check_disk check_disk

147
infra/box/fly-shadow-remote-setup Executable file
View file

@ -0,0 +1,147 @@
#!/usr/bin/env bash
# infra/box/fly-shadow-remote-setup — prepare a BUILD BOX to run the remote shadow (SHADOW-02).
# Run as root ON THE BOX (never on the release container, never on the host), by the coordinator.
# Idempotent: re-run it for every release the container runs.
#
# fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]
#
# RELEASE_TARBALL the exact flybrain-<version>.tar.gz deployed to the release container. It is
# installed at the SAME path, /opt/fly/releases/<version>, MANIFEST-verified,
# root-owned, and /opt/fly/current points to it: the shadow's verdict names
# that directory and the SHA-256 of its binaries, and `fly-shadow ingest`
# refuses a relay whose release differs.
# ROM_FILE the cartridge; its SHA-256 must be the container's ROM_SHA256.
# RELAY_PUBKEY the public half of the relay's key (the private half lives only on the
# release container, /etc/fly/shadow-remote/id_ed25519, owned by fly).
# --from ADDRS REQUIRED: restricts the key to the container's address (authorized_keys from=).
# --cpus LIST AllowedCPUs for the shadow, a drop-in: its own cores, never shared with the
# live fly's NUMA node.
# --threads N the shadow's sweep threads (default 4; one per core in --cpus). It must run
# clearly faster than real time: see the runbook's "Which box".
#
# What it sets up:
# - user flyshadow, the mirror /srv/fly-shadow-remote (flyshadow's; 0750) and, apart from it, the
# user's home /srv/fly-shadow-remote-home, ROOT-owned with a root-owned .ssh: flyshadow can
# neither change nor rename the key file (in a home it owned, it could rename .ssh);
# - /srv/fly-shadow-remote-home/.ssh/authorized_keys, ROOT-owned, with one
# line: restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="..." <key>. restrict turns off forwarding, agent, X11 and the pty; the forced command
# ignores what the client asks for; the ingest writes nothing outside the mirror;
# - /etc/fly/fly-shadow-remote.env: FLY_ROM, FLY_DATASET (this box's paths);
# - flyshadow-remote.service and flyshadow-remote.path (enabled; the service starts at the first
# run id the relay brings).
# A re-run never follows a symlink under the mirror (flyshadow owns it and could plant one): it
# refuses if any of the mirror's paths is a symlink, and leaves an existing directory as it is.
# The release container's address is only in authorized_keys (from=); the relay dials out to the box.
set -euo pipefail
die() { echo "fly-shadow-remote-setup: $*" >&2; exit 2; }
log() { echo "fly-shadow-remote-setup: $*"; }
[ "$(id -u)" = 0 ] || die "run as root on the build box"
[ $# -ge 3 ] || die "usage: fly-shadow-remote-setup RELEASE_TARBALL ROM_FILE RELAY_PUBKEY --from ADDRS [--cpus LIST] [--threads N]"
tarball="$1"; rom="$2"; pubkey="$3"; shift 3
from=""; cpus=""; threads=4
while [ $# -gt 0 ]; do
case "$1" in
--from) from="$2"; shift 2 ;;
--cpus) cpus="$2"; shift 2 ;;
--threads) threads="$2"; shift 2 ;;
*) die "unknown option $1" ;;
esac
done
here="$(cd "$(dirname "$0")" && pwd)"
ROOT=/srv/fly-shadow-remote
HOME_DIR=/srv/fly-shadow-remote-home
[ -n "$from" ] || die "--from is required: the relay key must be restricted to the container's address"
[ -f "$tarball" ] || die "no tarball $tarball"
[ -f "$rom" ] || die "no ROM $rom"
[ -f "$pubkey" ] || die "no public key $pubkey"
base="$(basename "$tarball")"; version="${base#flybrain-}"; version="${version%.tar.gz}"
[[ "$version" =~ ^[A-Za-z0-9._-]+$ ]] || die "cannot parse a version from $base"
[[ "$from" =~ ^[0-9A-Fa-f.:,/*]*$ ]] || die "--from takes addresses or patterns only"
[[ "$cpus" =~ ^[0-9,-]*$ ]] || die "--cpus takes a CPU list"
[[ "$threads" =~ ^[1-9][0-9]?$ ]] || die "--threads takes a number"
key="$(head -n 1 "$pubkey")"
[[ "$key" =~ ^ssh-(ed25519|rsa)\ [A-Za-z0-9+/=]+( [^\"]*)?$ ]] || die "$pubkey is not one ssh public key line"
command -v sshd >/dev/null || [ -x /usr/sbin/sshd ] || die "this box has no sshd"
# The release, exactly as 05-deploy installs it on the container (but root-owned here).
release="/opt/fly/releases/${version}"
if [ -f "$release/MANIFEST" ]; then
log "release $version already at $release"
else
install -d -m 0755 "$release"
tar -xzf "$tarball" -C "$release"
chown -R root:root "$release"
fi
(cd "$release" && sha256sum -c MANIFEST --quiet) || die "MANIFEST verification failed for $release"
[ -x "$release/fly-shadow" ] || die "$release has no fly-shadow: this release predates SHADOW-01"
# The bare subcommand exits 2 (usage); under pipefail a pipe into grep would fail on that, so capture.
probe="$("$release/fly-shadow" ingest 2>&1 || true)"
printf '%s' "$probe" | grep -q 'needs --root' \
|| die "$release/fly-shadow has no ingest: this release predates SHADOW-02"
ln -sfn "$release" /opt/fly/current.tmp && mv -T /opt/fly/current.tmp /opt/fly/current
log "/opt/fly/current -> $release"
# The user, the mirror and the user's home. The home and its .ssh are root's; the mirror is
# flyshadow's, so nothing in it is trusted: no symlink is followed there, as root.
[ -L "$ROOT" ] && die "$ROOT is a symlink: refusing to follow it"
[ -L "$HOME_DIR" ] && die "$HOME_DIR is a symlink: refusing to follow it"
if id flyshadow >/dev/null 2>&1; then
[ "$(getent passwd flyshadow | cut -d: -f6)" = "$HOME_DIR" ] || usermod --home "$HOME_DIR" flyshadow
else
useradd --system --home-dir "$HOME_DIR" --no-create-home --shell /bin/sh --user-group flyshadow
fi
if [ -e "$ROOT" ]; then
[ -d "$ROOT" ] || die "$ROOT is not a directory"
else
mkdir -m 0750 "$ROOT"
chown -h flyshadow:flyshadow "$ROOT"
fi
for d in trace hot durable out; do
[ -L "$ROOT/$d" ] && die "$ROOT/$d is a symlink: refusing to follow it"
if [ -e "$ROOT/$d" ]; then
[ -d "$ROOT/$d" ] || die "$ROOT/$d is not a directory"
else
mkdir -m 0750 "$ROOT/$d"
chown -h flyshadow:flyshadow "$ROOT/$d"
fi
done
# An earlier version of this script kept .ssh in the mirror, where flyshadow could rename it.
if [ -e "$ROOT/.ssh" ] || [ -L "$ROOT/.ssh" ]; then rm -rf "$ROOT/.ssh"; fi
if [ -L "$HOME_DIR/.ssh" ]; then rm -f "$HOME_DIR/.ssh"; fi
install -d -o root -g root -m 0755 "$HOME_DIR"
install -d -o root -g root -m 0755 "$HOME_DIR/.ssh"
line="restrict,command=\"/opt/fly/current/fly-shadow ingest --root $ROOT\",from=\"$from\""
printf '%s %s\n' "$line" "$key" > "$HOME_DIR/.ssh/authorized_keys.new"
chown root:root "$HOME_DIR/.ssh/authorized_keys.new"; chmod 0644 "$HOME_DIR/.ssh/authorized_keys.new"
mv -f "$HOME_DIR/.ssh/authorized_keys.new" "$HOME_DIR/.ssh/authorized_keys"
log "authorized_keys: the relay key may run only the ingest"
# The cartridge and this box's paths.
rom_sha="$(sha256sum "$rom" | cut -d' ' -f1)"
install -d -m 0755 /srv/fly/rom
install -o root -g flyshadow -m 0640 "$rom" "/srv/fly/rom/${rom_sha}.gb"
install -d -m 0755 /etc/fly
cat > /etc/fly/fly-shadow-remote.env <<ENV
# written by infra/box/fly-shadow-remote-setup (SHADOW-02): this box's paths for the remote shadow.
FLY_ROM=/srv/fly/rom/${rom_sha}.gb
FLY_DATASET=/opt/fly/current/data/fafb-v783
ENV
log "ROM sha256 $rom_sha (must equal the container's ROM_SHA256)"
# The units.
install -m 0644 "$here/flyshadow-remote.service" /etc/systemd/system/flyshadow-remote.service
install -m 0644 "$here/flyshadow-remote.path" /etc/systemd/system/flyshadow-remote.path
install -d -m 0755 /etc/systemd/system/flyshadow-remote.service.d
{
printf '# written by fly-shadow-remote-setup\n[Service]\nEnvironment=FLY_SHADOW_THREADS=%s\n' "$threads"
[ -n "$cpus" ] && printf 'AllowedCPUs=%s\n' "$cpus"
} > /etc/systemd/system/flyshadow-remote.service.d/10-cores.conf
log "${threads} threads${cpus:+ on CPUs $cpus}"
systemctl daemon-reload
systemctl enable --now flyshadow-remote.path
systemctl enable flyshadow-remote.service
# A running shadow of an older release restarts on this one (the relay's next run resets anyway).
systemctl try-restart flyshadow-remote.service || true
log "ready: the container's fly-shadow-run start brings the first run id"

View file

@ -0,0 +1,13 @@
# infra/box/flyshadow-remote.path — installed on a BUILD BOX with flyshadow-remote.service
# (SHADOW-02). A new run id (the container's `fly-shadow-run start`, written by the ingest) starts
# the shadow when it is down: the first run, or after a divergence (exit 3 is not restarted). A
# running shadow restarts itself on the change (exit 4, Restart=always).
[Unit]
Description=Start the remote shadow for a new run (SHADOW-02)
[Path]
PathChanged=/srv/fly-shadow-remote/run-id
Unit=flyshadow-remote.service
[Install]
WantedBy=multi-user.target

View file

@ -0,0 +1,55 @@
# infra/box/flyshadow-remote.service — installed on a BUILD BOX, never on the release container,
# by infra/box/fly-shadow-remote-setup (SHADOW-02).
#
# The shadow run (SHADOW-01, legacy-gameboy-v1 section 18) moved off the release container: there it
# cost the live fly real time (2026-09-30: RTF 0.999 -> 0.93-0.98 with the shadow SCHED_IDLE on the
# page and encoder CPUs, 27 ms of shadow per frame, falling further behind every hour). Here it runs
# the SAME release (installed from the same tarball at the same /opt/fly/releases/<version> path,
# so the verdict's release and binary hashes are the container's), on this box's own cores, at
# normal priority.
#
# Its input is the mirror /srv/fly-shadow-remote, written by `fly-shadow ingest`, the forced
# command of the one key the container's relay (`fly-shadow relay`, flyshadow.service there) holds;
# the relay writes this shadow's verdict back to the container, where `fly-shadow-run check`, its
# guard and CUT-01 read it as before. REPORT-ONLY: it reads the mirror, writes <root>/out and its
# runtime directory, and serves nothing.
#
# The run: `fly-shadow-run start` on the container gives each run an id; the ingest writes it to
# <root>/run-id (after resetting the mirror). A running shadow sees the change within 5 s and exits
# with status 4, and Restart=always starts the new run; a shadow that is down (it diverged: exit 3,
# which is not restarted, so the diverged verdict stays) is started by flyshadow-remote.path.
[Unit]
Description=flyshadow-remote: the session runtime shadowing the live fly from a build box (SHADOW-02, report only)
ConditionPathExists=/opt/fly/current/fly-shadow
ConditionPathExists=/srv/fly-shadow-remote/run-id
[Service]
Type=simple
User=flyshadow
# The live composition's settings, as the relay forwarded them (game, macro mode, accepted
# adapters, pins; never a path or a secret), then this box's own paths: FLY_ROM (the cartridge,
# with the container's ROM_SHA256) and FLY_DATASET (the release's connectome).
EnvironmentFile=-/srv/fly-shadow-remote/live.env
EnvironmentFile=/etc/fly/fly-shadow-remote.env
Environment=FLY_TRACE_DIR=/srv/fly-shadow-remote/trace
Environment=FLY_STATE_HOT=/srv/fly-shadow-remote/hot
Environment=FLY_STATE=/srv/fly-shadow-remote/durable
Environment=FLY_SHADOW_DIR=/srv/fly-shadow-remote/out
Environment=FLY_SHADOW_WORK=/run/flyshadow-remote
RuntimeDirectory=flyshadow-remote
# 3 sweep threads (the SHADOW-01 measurements: 13-15 ms a frame against 16.7 ms of real time).
Environment=FLY_SHADOW_THREADS=3
# No lag back-off: the live fly is on another machine. The spool holds a long catch-up.
ExecStart=/opt/fly/current/fly-shadow run --run-id-file /srv/fly-shadow-remote/run-id --lag-guard-margin 0 --spool-max-mib 4096
Restart=always
RestartSec=2
RestartPreventExitStatus=3
# Dedicated cores (fly-shadow-remote-setup --cpus writes AllowedCPUs= in a drop-in) at a weight
# above anything else on the box: a build must not starve the shadow.
CPUWeight=1000
Nice=-5
MemoryMax=6G
TimeoutStopSec=30
[Install]
WantedBy=multi-user.target

View file

@ -85,6 +85,16 @@ log "building in $crate_dir for target-cpu=haswell (the host is E5-2660 v3, Hasw
# without a rebuild. It lands next to OUT_PATH, where package-release.sh # without a rebuild. It lands next to OUT_PATH, where package-release.sh
# looks for it. # looks for it.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-edge
# fly-control-edge (FLY_CONTROL_VIA=bus, CTRL-01): the control API served from
# flysim's control services on the bus. Same reasons, same place.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin fly-control-edge
# flysim-session (SERVE-01): the live fly on the session runtime, a drop-in for flysim
# that `fly-runtime session` points flysim.service at; fly-shadow (SHADOW-01,
# infra/units/flyshadow.service): the session runtime shadowing the live fly; and
# fly-session, their worker program (FLY_SESSION_MODE=process only). Same features as flysim,
# built every time so a release can switch runtimes without a rebuild. All land next to
# OUT_PATH, where package-release.sh looks for them.
RUSTFLAGS="-C target-cpu=haswell" cargo build --release --target "$CARGO_TARGET" --bin flysim-session --bin fly-shadow --bin fly-session "${features_args[@]}"
) )
built="${crate_dir}/target/${CARGO_TARGET}/release/flysim" built="${crate_dir}/target/${CARGO_TARGET}/release/flysim"
@ -118,4 +128,18 @@ edge_out="$(dirname "$OUT_PATH")/fly-edge"
cp "$edge_built" "$edge_out" cp "$edge_built" "$edge_out"
chmod 0755 "$edge_out" chmod 0755 "$edge_out"
log "built $edge_out ($(du -h "$edge_out" | cut -f1))" log "built $edge_out ($(du -h "$edge_out" | cut -f1))"
control_edge_built="${crate_dir}/target/${CARGO_TARGET}/release/fly-control-edge"
[ -x "$control_edge_built" ] || die "expected binary not found after build: $control_edge_built"
control_edge_out="$(dirname "$OUT_PATH")/fly-control-edge"
cp "$control_edge_built" "$control_edge_out"
chmod 0755 "$control_edge_out"
log "built $control_edge_out ($(du -h "$control_edge_out" | cut -f1))"
for extra in flysim-session fly-shadow fly-session; do
extra_built="${crate_dir}/target/${CARGO_TARGET}/release/${extra}"
[ -x "$extra_built" ] || die "expected binary not found after build: $extra_built"
extra_out="$(dirname "$OUT_PATH")/${extra}"
cp "$extra_built" "$extra_out"
chmod 0755 "$extra_out"
log "built $extra_out ($(du -h "$extra_out" | cut -f1))"
done
log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>" log "next: infra/build/package-release.sh VERSION $OUT_PATH <stage-dir> <bridge-dir> <out-dir>"

View file

@ -14,6 +14,14 @@
# fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh # fly-edge (the feed-bus edge, mode 0755, when build-flysim.sh
# left one beside FLYSIM_BIN; flyedge.service stays # left one beside FLYSIM_BIN; flyedge.service stays
# inactive on a release without it) # inactive on a release without it)
# fly-control-edge (the control-bus edge, CTRL-01, likewise;
# flycontrol-edge.service stays inactive without it)
# flysim-session (the session runtime, SERVE-01, and fly-session, its
# fly-shadow worker program; mode 0755, when build-flysim.sh left
# fly-session them beside FLYSIM_BIN. `fly-runtime session` refuses
# a release without flysim-session. fly-shadow is
# SHADOW-01's shadow; flyshadow.service stays inactive
# on a release without it)
# stage/... (apps/stage's build output) # stage/... (apps/stage's build output)
# bridge/... (services/bridge + node_modules) # bridge/... (services/bridge + node_modules)
# data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here) # data/fafb-v783/... (the connectome, from the repo; FLY_DATASET points here)
@ -82,6 +90,25 @@ if [ -x "$EDGE_BIN" ]; then
else else
log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)" log "no fly-edge beside $FLYSIM_BIN; packaging without it (FLY_FEED_VIA=bus unavailable in this release)"
fi fi
CONTROL_EDGE_BIN="$(dirname "$FLYSIM_BIN")/fly-control-edge"
if [ -x "$CONTROL_EDGE_BIN" ]; then
cp "$CONTROL_EDGE_BIN" "${release_dir}/fly-control-edge"
chmod 0755 "${release_dir}/fly-control-edge"
else
log "no fly-control-edge beside $FLYSIM_BIN; packaging without it (FLY_CONTROL_VIA=bus unavailable in this release)"
fi
for extra in flysim-session fly-shadow fly-session; do
EXTRA_BIN="$(dirname "$FLYSIM_BIN")/${extra}"
if [ -x "$EXTRA_BIN" ]; then
cp "$EXTRA_BIN" "${release_dir}/${extra}"
chmod 0755 "${release_dir}/${extra}"
else
case "$extra" in
fly-shadow) log "no ${extra} beside $FLYSIM_BIN; packaging without it (no shadow run in this release)" ;;
*) log "no ${extra} beside $FLYSIM_BIN; packaging without it (fly-runtime session unavailable in this release)" ;;
esac
fi
done
cp -a "$STAGE_DIR" "${release_dir}/stage" cp -a "$STAGE_DIR" "${release_dir}/stage"
cp -a "$BRIDGE_DIR" "${release_dir}/bridge" cp -a "$BRIDGE_DIR" "${release_dir}/bridge"

View file

@ -38,6 +38,19 @@ branch="$(git rev-parse --abbrev-ref HEAD)"
if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then if git rev-parse -q --verify "refs/tags/${TAG}" >/dev/null; then
die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})" die "refusing to tag: ${TAG} already exists (git tag -l ${TAG})"
fi fi
# A tag is published with its whole history, so the privacy scan runs first and fails
# closed: without the operator's private pattern list ($FLY_PII_PATTERNS) it cannot see
# host names, people's names, the channel or pass entry names, and a tag is not cut blind.
# It checks the tree being tagged and every line added since the previous tag.
log "running tools/pii-scan.sh (private pattern list required)"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --tree HEAD \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in the tree (or its private pattern list is missing) — see above"
prev_tag="$(git describe --tags --abbrev=0 --match 'v[0-9]*' HEAD 2>/dev/null || true)"
pii_range="HEAD"
[ -z "$prev_tag" ] || pii_range="${prev_tag}..HEAD"
"${REPO_DIR}/tools/pii-scan.sh" --require-private --range "$pii_range" \
|| die "refusing to tag: tools/pii-scan.sh found identifying strings in commits since ${prev_tag:-the root} (a tag publishes them even if a later commit removed them) — see above"
git fetch --tags >/dev/null 2>&1 \ git fetch --tags >/dev/null 2>&1 \
&& log "fetched tags from the remote" \ && log "fetched tags from the remote" \
|| log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state" || log "WARNING: git fetch --tags failed (no remote configured, or offline) — checking only against local tag state"
@ -56,7 +69,19 @@ if [ -d "$flysim_dir" ]; then
# --release, not debug (Makefile's `rust:` target and the reason it gives): the flysim # --release, not debug (Makefile's `rust:` target and the reason it gives): the flysim
# integration test that asserts the feed's 30 Hz contract only reaches ~9.5-10.4 Hz in a debug # integration test that asserts the feed's 30 Hz contract only reaches ~9.5-10.4 Hz in a debug
# build, so a debug run would fail or flake that gate. # build, so a debug run would fail or flake that gate.
log "running cargo test --workspace --release in services/flysim" # The ROM suites (tests/rom_*.rs) return early and count as PASSED when FLY_ROM or their
# checkpoint variable is unset, so a gate run without them proves nothing about the macros.
# v0.6.4's gate ran that way. Refuse without the ROM; name every checkpoint suite skipped.
if [ -z "${FLY_ROM:-}" ] || [ ! -r "${FLY_ROM}" ]; then
die "FLY_ROM is unset or unreadable: the ROM test suites would pass without running. Export FLY_ROM and the FLY_*_CHECKPOINT variables (the operator's rom env) first."
fi
skipped=""
while IFS= read -r var; do
[ -n "${!var:-}" ] || skipped="${skipped} ${var}"
done < <(grep -rhoE 'var_os\("FLY_[A-Z0-9_]*_CHECKPOINT"\)' "$flysim_dir"/crates/*/tests/rom_*.rs \
| sed -E 's/.*"(FLY_[A-Z0-9_]*)".*/\1/' | sort -u)
[ -z "$skipped" ] || log "WARNING: ROM checkpoint suites that will pass WITHOUT running (unset):${skipped}"
log "running cargo test --workspace --release in services/flysim (FLY_ROM set)"
(cd "$flysim_dir" && cargo test --workspace --release) (cd "$flysim_dir" && cargo test --workspace --release)
else else
log "WARNING: services/flysim does not exist in this checkout — skipping cargo test --workspace" log "WARNING: services/flysim does not exist in this checkout — skipping cargo test --workspace"

View file

@ -6,13 +6,22 @@
# <unit>` and, on the 5-consecutive-failure escalation, a container # <unit>` and, on the 5-consecutive-failure escalation, a container
# reboot. This is the minimum NOPASSWD surface for exactly what # reboot. This is the minimum NOPASSWD surface for exactly what
# bin/fly-watchdog's checks actually restart (flysim, flystage, flycast, # bin/fly-watchdog's checks actually restart (flysim, flystage, flycast,
# mediamtx, flypush), plus reboot. No `systemctl stop`, no # mediamtx, flypush, flyedge in bus mode, flycontrol-edge when FLY_CONTROL_VIA=bus), plus reboot. No `systemctl stop`, no
# `enable`/`disable`, no arbitrary unit name, and no units this script # `enable`/`disable`, no arbitrary unit name, and no units this script
# does not itself restart (xvfb, pulse, flystage-web are never touched by # does not itself restart (xvfb, pulse, flystage-web are never touched by
# fly-watchdog's checks, so they are not granted here). # fly-watchdog's checks, so they are not granted here).
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flysim.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flystage.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flyedge.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycast.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart mediamtx.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flypush.service
fly ALL=(root) NOPASSWD: /usr/bin/systemctl restart flycontrol-edge.service
fly ALL=(root) NOPASSWD: /usr/sbin/reboot fly ALL=(root) NOPASSWD: /usr/sbin/reboot
# fly-loop-recover.service (also User=fly): its ladder restarts flysim (granted above) and
# resets to a milestone archive through this one root wrapper, which validates the rung,
# stops/resets/starts flysim and nothing else (infra/docs/loop-recovery.md).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-loop-reset
# Watchdog check 2a (FLY_FEED_VIA=bus): an edge that restarts cannot fix puts the feed back on
# flysim, with exactly these arguments and nothing else (infra/bin/fly-feed).
fly ALL=(root) NOPASSWD: /opt/fly/bin/fly-feed direct --no-wait

View file

@ -9,6 +9,8 @@ d /run/fly/wd 0750 fly fly -
# ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's # ADDED: the feed bus (FLY_FEED_VIA=bus, docs/design/flybus.md): flysim's
# router socket and artifact store. flysim also creates it, 0700, on start. # router socket and artifact store. flysim also creates it, 0700, on start.
d /run/fly/bus 0700 fly fly - d /run/fly/bus 0700 fly fly -
# The session runtime's router store and worker sockets (SERVE-01, flysim-session).
d /run/fly/session 0700 fly fly -
d /var/lib/fly 0750 fly fly - d /var/lib/fly 0750 fly fly -
d /var/lib/fly/chrome 0700 fly fly - d /var/lib/fly/chrome 0700 fly fly -
d /srv/fly/state 0750 fly fly - d /srv/fly/state 0750 fly fly -

View file

@ -9,6 +9,14 @@
// on flystage-web.service). Deliberately not a general-purpose server: // on flystage-web.service). Deliberately not a general-purpose server:
// no directory listing, no symlink following outside root, no range // no directory listing, no symlink following outside root, no range
// requests (the page is a handful of static assets, not video). // requests (the page is a handful of static assets, not video).
//
// One route is not a file under root: GET /recovery-notice.json returns the
// auto-recovery helper's notice (infra/bin/fly-loop-recover writes it to
// /run/fly/wd/recovery-notice.json, FLY_RECOVERY_NOTICE overrides), which the
// page's recovery splash polls once a second. It is served from here and not
// from flysim because flysim is the thing being restarted. 200 with the file's
// bytes, or 204 when there is no (readable, small, regular) file; the page does
// all of the validation (apps/stage/src/lib/recovery.ts).
import { createServer } from 'node:http'; import { createServer } from 'node:http';
import { readFile, stat } from 'node:fs/promises'; import { readFile, stat } from 'node:fs/promises';
import { join, normalize, extname } from 'node:path'; import { join, normalize, extname } from 'node:path';
@ -17,6 +25,27 @@ const root = process.argv[2] ?? new URL('.', import.meta.url).pathname;
const host = process.argv[3] ?? '127.0.0.1'; const host = process.argv[3] ?? '127.0.0.1';
const port = Number(process.argv[4] ?? 7402); const port = Number(process.argv[4] ?? 7402);
const RECOVERY_ROUTE = '/recovery-notice.json';
const RECOVERY_PATH = process.env.FLY_RECOVERY_NOTICE || '/run/fly/wd/recovery-notice.json';
const RECOVERY_MAX_BYTES = 16384;
async function serveRecoveryNotice(res) {
const headers = { 'cache-control': 'no-store' };
const st = await stat(RECOVERY_PATH).catch(() => null);
if (!st?.isFile() || st.size === 0 || st.size > RECOVERY_MAX_BYTES) {
res.writeHead(204, headers).end();
return;
}
const body = await readFile(RECOVERY_PATH).catch(() => null);
if (!body) { res.writeHead(204, headers).end(); return; }
res.writeHead(200, {
...headers,
'content-type': 'application/json; charset=utf-8',
'content-length': body.length,
});
res.end(body);
}
const TYPES = { const TYPES = {
'.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8',
'.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.mjs': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8',
@ -27,6 +56,7 @@ const TYPES = {
const server = createServer(async (req, res) => { const server = createServer(async (req, res) => {
try { try {
if (req.url.split('?')[0] === RECOVERY_ROUTE) { await serveRecoveryNotice(res); return; }
const urlPath = normalize(decodeURIComponent(req.url.split('?')[0])); const urlPath = normalize(decodeURIComponent(req.url.split('?')[0]));
if (urlPath.includes('..')) { res.writeHead(400).end('bad path'); return; } if (urlPath.includes('..')) { res.writeHead(400).end('bad path'); return; }
let path = join(root, urlPath === '/' ? 'index.html' : urlPath); let path = join(root, urlPath === '/' ? 'index.html' : urlPath);
@ -47,5 +77,5 @@ const server = createServer(async (req, res) => {
}); });
server.listen(port, host, () => { server.listen(port, host, () => {
console.log(`flystage-web: serving ${root} on http://${host}:${port}/`); console.log(`flystage-web: serving ${root} on http://${host}:${server.address().port}/`);
}); });

View file

@ -1,29 +1,135 @@
# Automated loop recovery # Automated loop recovery
`fly-watchdog` remains report-only. The separate `fly-loop-recover.timer` checks its `fly-watchdog` remains report-only. The separate `fly-loop-recover.timer` reads its
`/run/fly/wd/loop.json` every five minutes. Two fresh suspected reports from `/run/fly/wd/loop.json` every minute and unsticks a confirmed trap on its own, climbing
separate watchdog probes, at least ~5 minutes apart, cause **only** a a ladder one step per trap that outlives the previous step:
`flysim.service` restart. The ordinary checkpoint restore keeps the current
rung and learned brain state, but clears session macro ledgers. This does not
press buttons or promote a milestone archive. A successful restart imposes a
one-hour cooldown, including across intervening clear reports. The timer's
journal records every decision; inspect it with
`journalctl -u fly-loop-recover.service`. Disable the timer to stop automatic
recovery: `systemctl disable --now fly-loop-recover.timer`.
By default confirmation is deterministic, using watchdog's existing signal. | level | step | cost |
An optional OpenAI-compatible local router can veto a recovery: provision a |---|---|---|
root-managed `/etc/fly/loop-recovery.env` readable by the `fly` account, | 0 | `systemctl restart flysim.service` | none: the restore keeps the rung and learned state, clears session macro ledgers |
containing `FLY_LOOP_ROUTER_URL` (base URL ending in `/v1`) and | 1 | reset to the current rung's milestone archive | progress since the rung was first reached |
`FLY_LOOP_MODEL` (an available free-tier model). A private router can additionally | 2+ | reset to the archive below the best rung (never lower) | one visible rung |
use `FLY_LOOP_ROUTER_KEY`; provision it outside this public checkout and limit
file permissions to `0640 root:fly`. Never put credentials in the unit or the
repository. When either router setting is present, both must be set; malformed or
unavailable responses prevent recovery. The model may only return `{"stuck": true|false}` and cannot
choose commands, buttons, or checkpoint paths. Confirm the model actually
exists and is reachable from the release container before configuring it.
This is an unstick mechanism, not a macro bug fix. A recurring trap still needs - **Confirmed** means two fresh suspected watchdog reports (at most 10 minutes old, `action: none`)
the checkpoint-based loop review in `docs/loop-review.md`. The live recovery from separate probes about 5 minutes apart. A clear report in between starts the count again.
must be recorded in the host claim log by the operator reviewing the unit - **Outlives** means the reports that confirm it again are at least 20 minutes after the step, so
journal; the unit itself has no host claim-log access. their 10-brain-minute window lies after it. The helper waits that long after every step.
- **Budget:** at most two milestone resets per 24 hours. With the budget spent the step is a
restart, at most every three hours, until a reset is free again. The same three-hour spacing applies
when a reset level finds no restorable rung and restarts instead, and between any two restarts in a
row, also when the ladder has started over in between.
- **Starting over:** the ladder returns to level 0 when the fly reaches a new best rung, after
six hours with no suspected report, or when the fly makes new lasting progress more than
20 minutes after the last step and a clear probe shows the old trap let go (row 70). Lasting
progress is the watchdog's `window.progress`: a rung reached, a species owned, a map entered, or
a trainer or badge beaten, each named in `window.progress.keys` as `kind:label` (`pokedex:OWNED
#41`). A ring cannot earn them twice, but a milestone reset restores the reward ledger, so its
replay pays the archive's rewards again. Progress is therefore measured against every name the
ladder has seen (`progressSeen` in the state file, the last 2,000), not against the restored
archive: a replay re-earning what the run had before the reset is not progress, and the ladder
climbs on to the rung below as it did before row 70. A trap that follows new progress is a new
trap, and it starts again from a restart. A catch made while the fly stays flagged is not a new
trap. With a watchdog that reports no names, the counts are used as before.
Names the ladder never saw (before this version was deployed, or while an older one ran) count
as new once.
- **Protected catches:** a milestone reset never erases a species first owned in the last two hours
(`PROTECT`, a `pokedex:` name not seen before). A species a reset's replay owns again was the fly's
before the reset and was protected then, so it does not open a second window. Within that window the step is a restart, spaced by
the hold like a spent budget, and `history.jsonl` records a `protect` event. A reset turned into a
restart this way does not climb the ladder: the level keeps its slot and the reset comes, at the
same rung, once the window ends. Evolution also counts as a species owned.
- **No archive twice in a row:** a reset never restores the same archive as the last reset,
until a new best rung is reached or twelve hours have passed (`AGAIN`; a trap no restart clears
is reset again in bounded time, no later than before this rule). Such a step does climb, so the rung below is reached promptly. A restore is deterministic, so the same archive replays the
same run into the same trap. Row 70's second reset to rung 11 matched the first one event for
event: the same Zubat caught, the same trap an hour later, and the catch erased. That step is
a restart instead. A reset that fails does not mark its archive: it is not known to have been
restored, so the next reset may try it again.
A milestone step only uses an archive the running build can restore. `fly-loop-reset --list`
compares each archive's compatibility string with `flysim --print-compatibility` and accepts an
adapter-only difference that `FLY_ACCEPT_ADAPTERS` in `/etc/fly/fly.env` names (the rule
`05-deploy.sh` applies). A flysim that refuses every checkpoint refuses to start, so a step whose
rung is not restorable is a restart instead, never a lower rung. Keep `FLY_ACCEPT_ADAPTERS` in the
release env file so a deploy does not drop it.
The step runs `/opt/fly/bin/fly-loop-reset <rung>` through sudo (the one line in
`config/fly-sudoers`). As root it:
- runs only the root-owned `/opt/fly/sbin/flysim`, and only while it is byte-identical to the
flysim `/opt/fly/current` points to, that `05-deploy.sh` installs from the release
tarball after checking it against the tarball's MANIFEST (never the fly-owned release tree).
Without that copy (an infra-only deploy, or a manual rollback) no rung is restorable and the
ladder only restarts; after a release deploy, check as `fly` that
`sudo -n /opt/fly/bin/fly-loop-reset --list` names the current rung;
- reads `fly.env` as `KEY=VALUE` data, never sources it, and ignores the caller's environment;
- stops `fly-watchdog.timer` and waits for a running probe to finish, so the watchdog cannot
start flysim on a half-rewritten store; stops flysim; runs `fly-reset-to-milestone`; and on every
exit path starts flysim and the watchdog timer again.
The reset copies both stores to `/srv/fly/state.reset-<UTC>` first, as in the runbook, and
clears milestone archives above the rung. After each step the helper waits up to four minutes for
`/status` to report `running` (and the target rank for a reset). Otherwise the step is recorded
as failed and the ladder still climbs. The step is recorded before it runs, so a helper killed
mid-step has still climbed and spent the reset. Do not stop `fly-loop-recover.service` during a
step: that kills the reset too, and the wrapper's exit trap starts flysim on whatever state is
left.
## On stream
Every step is announced 60 seconds ahead (`FLY_LOOP_COUNTDOWN`) in
`/run/fly/wd/recovery-notice.json` (`FLY_RECOVERY_NOTICE`), which the stage's recovery splash
reads. It holds the contract below, written atomically, mode 0644:
```json
{"v": 1, "id": "1790629095-reset", "phase": "countdown|acting|done|failed",
"action": "restart|reset", "fromRung": 12, "fromLabel": "MT. MOON",
"toRung": 11, "toLabel": "BOULDER BADGE", "reason": "unrewarded",
"loop": ["GO OBJECTIVE", "GO WARP"], "stuckSeconds": 900,
"announcedAt": 1790629095, "executeAt": 1790629155, "updatedAt": 1790629160}
```
`toRung`/`toLabel` are present for a reset only; every write refreshes `updatedAt`, and the
helper never deletes the file. `flystage-web` serves it at `/recovery-notice.json` (204 when
absent) and the page's recovery splash polls it once a second (`apps/stage/README.md`, "Recovery
splash"). The page ignores a notice more than 15 minutes old, shows `done` for 8 s and `failed`
for 20 s, and stops covering the game 10 minutes after an `acting` write that nothing followed.
A milestone step pauses the watchdog, so Chromium is not restarted under the splash; a plain
restart is short enough that a watchdog pass rarely lands in it.
## Model confirmation
An OpenAI-compatible router can be asked before each step. The model may only answer
`{"stuck": true|false}` (the reply may wrap it in prose; the first such object counts). It cannot
choose commands, rungs or buttons. `false` delays the step by one probe, at most three times in a
row; then the step goes ahead. If no model answers (unset, rate-limited, down, malformed), the
watchdog's confirmation stands alone. A model can delay recovery by about 15 minutes, never deny
it.
Provision a root-managed `/etc/fly/loop-recovery.env`, mode `0640 root:fly`, outside this public
checkout:
```
FLY_LOOP_ROUTER_URL=<base URL ending in /v1>
FLY_LOOP_ROUTER_KEY=<router key>
FLY_LOOP_MODELS=<model>,<fallback model>,...
```
Models are tried in order within a 90-second budget. Prefer fast free-tier chat models, and put
providers with generous free limits first: free OpenRouter models share a small daily quota and
the router's circuit breaker can close the whole provider for a while. Check each model against
a stuck and a healthy report before listing it. `FLY_LOOP_MODEL` (one model) is still read when
`FLY_LOOP_MODELS` is unset.
## Operating it
- Decisions: `journalctl -u fly-loop-recover.service`. Every step, veto and ladder restart is also
appended to `/var/lib/fly-loop-recover/history.jsonl`.
- Ladder state: `/var/lib/fly-loop-recover/state.json` (the unit's `StateDirectory`, so it
survives a reboot). Deleting it starts the ladder over.
- Stop automatic recovery: `systemctl disable --now fly-loop-recover.timer`.
- Record automatic steps you find in the journal in the host claim log when you next claim the
container; the unit has no access to that log.
This is an unstick mechanism, not a macro bug fix. A recurring trap still needs the
checkpoint-based loop review in `docs/loop-review.md`.

View file

@ -3051,3 +3051,747 @@ On `main` `510727c` (v0.6.1, row 59 merged):
- `npm test` 663 passed; `npm run typecheck` clean; `infra/tests/lint.sh` ALL CHECKS PASSED. - `npm test` 663 passed; `npm run typecheck` clean; `infra/tests/lint.sh` ALL CHECKS PASSED.
- `flysim --print-compatibility`, raw and macros: 648 bytes, sha256 `8ce67b97...a8f68`, the same - `flysim --print-compatibility`, raw and macros: 648 bytes, sha256 `8ce67b97...a8f68`, the same
as `main`. Decoder, reward catalog, adapter version and roles untouched. as `main`. Decoder, reward catalog, adapter version and roles untouched.
## 2026-09-24, row 62: the shop, the balls and the nurse, withheld
### What was live
v0.6.2, the fresh run since the operator's reset to milestone 1, about eleven and a half hours:
rung 12 (MT. MOON) with the Boulder Badge, 16 trainer wins, 86 wild wins. In the whole event log
(70,357 macro events) `GO SHOP` twice (the parcel errand), then no `BUY`, no `THROW BALL`, no
`GO HEAL`, `HEAL` or nurse's YES, 72 `TALK`. Rung 12 took 3.5 hours: the fly whited out in Mt.
Moon again and again and walked back from the south. The live checkpoint reads one Pokémon at
54/80, 508 money (every whiteout halves it), no ball, the Viridian and Pewter marts and the Mt.
Moon centre in the lifetime map ledger, the Pewter centre not, and **`wLastBlackoutMap` (`$d719`)
= `$00`, Pallet Town**: only the nurse's YES writes it (`SetLastBlackoutMap`), and the fly had never
said it.
### The survey: what the pad dealt
`FLY_PROBE_CATCH=offers` in `examples/scene_probe.rs` (new): 71,673 frames of the service's frame
behind a uniform stub, per decidable frame (a playable scene, a pad, no macro running) which
watched buttons are dealt, and the cartridge beside it. From the live checkpoint on `main`, twenty
brain minutes in Mt. Moon: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION` and `THROW BALL`
on **0** of 32,178 decidable frames. From row 59's checkpoint inside the Mt. Moon centre at 10/70:
`HEAL` on 31 frames of 28,069, never in that centre. With the chain's buttons preferred (a
survey's driver), from the rung-11 Pewter checkpoint: `GO SHOP` never dealt on `main`; on the
branch before the purchase fix, `BUY BALL` 55 starts, 55 `done`, the wallet at 1,606 throughout.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 62 | section 13's errand is paid on entering, also by a visit on which the counter could do nothing (Oak's parcel at the Viridian mart, a centre entered with a full party), and with the lifetime map ledger since row 54 `GO SHOP` / `GO HEAL` never came back for the run | every town after its first visit; live, the whole run after the parcel | `go_heal_comes_back_for_a_hurt_party_after_the_errand_is_paid`, `go_shop_comes_back_while_the_bag_has_no_ball_and_the_money_covers_one`, `row62_go_shop_comes_back_with_no_ball_and_buy_ball_rings_up_a_ball` (ROM) | **fixed**: `palette::service_needed` (a centre while the party needs rest; a mart while the bag has no ball, the wallet covers one and no Oak's parcel is carried); `GO SHOP` / `GO HEAL` aim at the area's building while the errand or the need holds. Self-satisfying. `docs/design/macros.md` 12.26 |
| 62b | a counter person this session had talked to or reached is retired from `TALK` and the counter walk for the session | a second visit to a counter in one session | `a_counter_the_fly_has_a_use_for_opens_again_after_this_session_has_talked_to_it`, `a_declined_heal_writes_the_nurse_into_the_talked_ledger` | **fixed**: with the need, the walk and `TALK` (`facing_service`) ignore talked and reached; blocked kept; a rested party still has no `TALK` at the nurse (12.12) |
| 62c | `HEAL`'s goals were `counter_aims`, which drops the tile already facing the nurse and a nurse `GO HEAL` has reached (ten minutes) | at the counter, and after every `GO HEAL` | `heal_is_dealt_facing_the_nurse_and_after_go_heal_has_reached_her` | **fixed**: `HEAL`'s aims keep the facing tile and read neither ledger |
| 62d | from a centre's door (3, 7) the nurse at (3, 1) is off the screen, so the drawn sprites hold nobody behind the counter: `HEAL`, `GO HEAL` and the counter suppression off on arrival, the way out on the pad | every centre entry | `the_nurse_is_found_from_the_door_when_the_screen_does_not_draw_her` | **fixed**: the counter person is read from the drawn and the off-screen sprites (row 58's `offscreen_npcs`) |
| 62e | Route 4's centre (`$44`) was on no table: no `HEAL` in it, no errand to it | the last centre before Mt. Moon | `the_mt_moon_pokecenter_is_a_centre_and_route_4s`, `row62_heal_is_dealt_in_the_mt_moon_center_and_moves_the_whiteout_map` (ROM) | **fixed**: `MT_MOON_POKECENTER` in LINKS, Route 4's west piece and AMENITIES; Mt. Moon 1F's area is Route 4 |
| 62f | `BUY …` pressed its last A while the price line was still up: after the quantity the mart prints "That will be" and waits for a press (a `cont`), then draws the YES/NO box; the macro reported `done` with nothing bought and the box left to the next hold | every purchase | `a_purchase_answers_the_price_box_once_the_cartridge_has_drawn_it`, the three purchase tests, `row62_go_shop_…` (ROM) | **fixed**: `Step::Prompt` pulses A until the box is drawn, YES, `Step::Paid` waits for the wallet to drop; running out is `blocked` |
| 62g | `THROW BALL` | -- | -- | **not a trap**: off with no ball, dealt on 385 of 1,070 wild-battle frames with one (both arms), catches when pressed. The live run had no ball because 62/62f left no way to buy one |
| 62h | the nurse's YES is dealt only for a hurt party, so a full party passing a centre never moves `wLastBlackoutMap` | a centre visited healthy | -- | **left, operator's**: the prompt's other effect is the whiteout map, which no macro reads; 12.12 keeps the full-party ring closed. With 62/62c/62d a hurt fly heals and moves it (9 of 10 branch surveys) |
### Before and after
Ten uniform-stub surveys per arm, 71,673 frames each (twenty brain minutes), `main` `862e343` vs
branch, seeds 20260924 and 7. Checkpoints: `live` the row-62 live one (Mt. Moon 1F); `mtmoonpc`
row 59's, inside the Mt. Moon centre at 10/70; `viridian` the milestone-5 one carried to rung 8
(Viridian centre, 3,175, before the parcel); `pewter` row 59's rung-11 survey checkpoint (Pewter
gym, 1,606, no ball, errands paid); `route2ball` the 2026-09-22 rung-9 one (Route 2, one Poké Ball).
Cells are "frames dealt / starts".
| run (checkpoint-arm-seed) | decidable | HEAL dealt/started | GO HEAL dealt/started | GO SHOP dealt/started | BUY BALL dealt/started | BUY POTION dealt/started | THROW BALL dealt/started | heals | balls bought | thrown | catches | whiteouts | blackout map |
| live-base-s20260924 | 32178 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 0 | 0x00 |
| live-base-s7 | 23494 | 0/0 | 48/3 | 1/1 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| live-branch-s20260924 | 31387 | 2/0 | 541/16 | 0/0 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 0 | 0x0f |
| live-branch-s7 | 28546 | 7/0 | 405/8 | 178/6 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x02 |
| mtmoonpc-base-s20260924 | 28069 | 31/0 | 75/3 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| mtmoonpc-base-s7 | 27696 | 9/0 | 11/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| mtmoonpc-branch-s20260924 | 35812 | 4/0 | 356/9 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 1 | 0x0f |
| mtmoonpc-branch-s7 | 35128 | 25/2 | 634/7 | 0/0 | 0/0 | 0/0 | 0/0 | 2 | 0 | 0 | 0 | 0 | 0x0f |
| pewter-base-s20260924 | 35351 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| pewter-base-s7 | 33628 | 0/0 | 1/1 | 0/0 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| pewter-branch-s20260924 | 33541 | 1/1 | 42/3 | 72/5 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x02 |
| pewter-branch-s7 | 35554 | 0/0 | 30/1 | 29/2 | 0/0 | 0/0 | 0/0 | 0 | 0 | 0 | 0 | 1 | 0x00 |
| route2ball-base-s20260924 | 32315 | 0/0 | 2/0 | 1/1 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 |
| route2ball-base-s7 | 39135 | 0/0 | 0/0 | 0/0 | 0/0 | 0/0 | 385/6 | 0 | 0 | 1 | 0 | 1 | 0x00 |
| route2ball-branch-s20260924 | 30993 | 41/0 | 209/6 | 38/2 | 9/0 | 9/1 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x02 |
| route2ball-branch-s7 | 32296 | 1/1 | 57/2 | 0/0 | 0/0 | 0/0 | 385/6 | 1 | 0 | 1 | 0 | 1 | 0x01 |
| viridian-base-s20260924 | 24307 | 2/1 | 2/0 | 34/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 3 | 0x01 |
| viridian-base-s7 | 29710 | 1/1 | 1/0 | 65/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 4 | 0x01 |
| viridian-branch-s20260924 | 34564 | 3/0 | 25/1 | 158/3 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 1 | 0x01 |
| viridian-branch-s7 | 30238 | 1/1 | 1/0 | 94/2 | 0/0 | 0/0 | 0/0 | 1 | 0 | 0 | 0 | 2 | 0x01 |
Totals, base -> branch: decidable frames 305,883 -> 328,059; `HEAL` dealt 43 -> 85; `GO HEAL`
dealt 140 -> 2,300 (starts 8 -> 53); `GO SHOP` dealt 101 -> 569 (starts 6 -> 20); heals 2 -> 12;
whiteout map off Pallet Town in 2 -> 9 runs; whiteouts 14 -> 9; `THROW BALL` identical (770 / 12,
two thrown). No ball bought under the uniform stub on either arm: the counter opens only on
`TALK`, then `CONFIRM`, then `BUY BALL`, and the stub rarely picks the three in a row. That is
the fly's choice; with the chain preferred, the branch buys (Pewter: 1,606 -> 1,406, one ball) and
`main` cannot (no `GO SHOP`, and a `BUY BALL` that ends before its box). The ROM tests fail on
`main` (`HEAL` never dealt in 3,000 frames in the Mt. Moon centre; `GO SHOP` not on Pewter's pad)
and pass on the branch (healed in 587 frames, `wLastBlackoutMap` `$0f`; one ball, 200 paid).
The live event log's choices against the pad the survey measured from the live checkpoint on
`main`: `HEAL`, `GO HEAL`, `GO SHOP`, `BUY BALL`, `BUY POTION`, `THROW BALL` dealt on 0 frames and
chosen 0 times, except `GO SHOP` (2 starts in eleven hours, both the parcel errand, dealt only
before it was paid). None of it was the fly's choice.
**Review round 2** (two blocking findings, fixed in the macros; `docs/design/macros.md` 12.26).
(1) Route 4's centre was dealt as `GO HEAL` (and as the errand under `GO OBJECTIVE`) from Route 4's
east side and B1F's exit chamber, both in Route 4's area, and the road to it runs through B2F, in
no area: the button dropped one hop in, opposite the road to Cerulean. A building is now the area's
only where the route to it stays in the area (`geography::route_within`). ROM, from the live
B2F checkpoint stepped up the ladder: the first round deals `GO HEAL` on 642 of 2,492 hurt frames
east of the mountain and walks back down into B2F; the fix deals it on none (`main` none, no row).
(2) Row 58's gym test failed on the first round (6 arrivals, 4 straight back out, by `GO HEAL` and
`GO SHOP`): a service is not wanted while the rung's own target stands in the room (row 29's rule),
and it passes (2 arrivals, 0 out, the badge won). The live Mt. Moon B2F trap at the ladder (row 64)
is not this mechanism: from its checkpoint all three arms stay on B2F for twenty brain minutes,
identically, and on `main` there is no Route 4 centre to route to.
## 2026-09-24, row 63: Mt. Moon B2F, ITEM, BACK, BACK
### What was live
Map 61 (Mt. Moon B2F), rung 12, v0.6.2, wild battles, about 03:05 to 03:15 UTC: per ten minutes
`BACK` 62, `ITEM` 28, `RUN` 21, `MOVE 1` 10, no game event. The log: ITEM, BACK, BACK, ITEM, BACK
... RUN, and MOVE 1, BACK, RUN. The checkpoint is a wild Geodude L9 with the battle bag open:
Wartortle L28 at 8/86, BITE, TAIL WHIP and BUBBLE at 0 PP and WATER GUN at 25; the bag an
Antidote, a Potion, TM34.
### The survey
`scene_probe` `FLY_PROBE_CATCH=bag` (uniform pick among dealt buttons, trace per macro) and
`=potion` (the Potion pressed by hand, then A tried after every delay 0..120 in a rollback).
- The cartridge's `ItemUsePtrTable` says the Potion would be taken, the Antidote not (nobody
poisoned), TM34 never in a battle. `ITEM` is dealt correctly (hurt, a Potion).
- `ITEM` presses ITEM, the Potion, and the party list opens on the frame after the pulse with
the one Pokémon under the cursor; the script's confirm goes in at once and the list stays up.
`ITEM done`; `BACK` closes the list (`UseItem` fails, back to the bag); `BACK` closes the bag.
- By rollback: A lost for 22 frames after the pulse, answered from then on; `hJoyLast` (and the
three joypad bytes after it) the only bytes that separate the two.
- `MOVE 1` is dealt over the menu with slot one spent beside slot four; it opens the list, whose
`BACK` closes it.
- With the confirm fixed: RUN's A is taken, the menu's box stays for up to sixteen frames with
`hJoyLast` = A, and a macro dealt there (the survey: `MOVE 4` after every `RUN` from FIGHT's
column, 324 of 324) presses at a menu that is gone and blocks for 180 frames.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 63 | a cursor step's confirming A goes into a list that reads open before the cartridge has let go of the A that opened it; the press is no edge, the macro reports done over a waiting list, and `BACK` twice undoes it | any list opened by an A whose target is under the cursor at once; the Potion's party list with one Pokémon | `items_last_press_waits_for_the_cartridge_to_let_go_of_the_potions_a`, `row63_item_uses_the_potion_and_the_battle_menu_deals_no_list_it_only_opens` (ROM) | **fixed**: `state::a_latched` (`hJoyLast`, `$FFB1`); the confirm waits while it holds. `docs/design/macros.md` 12.27 |
| 63b | `MOVE 1` over the battle menu with slot one spent beside a usable move only opens the list its `BACK` closes | a spent first move | `move_one_is_not_fights_backstop_beside_a_usable_move`, the ROM test's second drive | **fixed**: the backstop only while no move is usable |
| 63c | a battle menu the cartridge has taken an A on stays on screen; a macro dealt on it presses at a menu already gone | RUN, and any answer whose box lingers | `a_battle_menu_the_cartridge_still_holds_an_a_on_deals_no_pad` | **fixed**: no own-turn pad while `hJoyLast` holds A |
| 63d | `ITEM` is dealt while the cartridge would refuse the Potion | none reached: `hurt` implies it is taken | `item_is_off_the_pad_while_the_cartridge_would_refuse_the_potion`, `the_row_63_bag_holds_one_item_the_cartridge_would_take` | **guarded**: `state::battle_item_use` from `ItemUsePtrTable` (`$03:$55E1`) |
| 63e | a party list opened by an item reads as the battle's party list: its pad is `SWITCH`, `BACK`, and `SWITCH` there would use the item on the healthiest other Pokémon | only if `ITEM` stops before its last press; not reached with 63 fixed | -- | **left**: `ITEM` now finishes; naming the item's list is a seam change for when it is reached |
### Before and after
Ten seeds per arm, 71,673 frames each (20 brain minutes), uniform pick among the dealt buttons,
from the row-63 checkpoint. Base: `main` plus the seam reader and the probe; branch: the fix.
`build/loop-row63/survey-summary.md` has the per-seed table.
| | base | branch |
| --- | ---: | ---: |
| `ITEM` starts | 244 | 10 (each one used the Potion) |
| `BACK` starts | 559 | 0 |
| `MOVE 1` starts | 173 | 0 |
| longest ITEM/BACK run | 6 | 0 |
| battle macros blocked | 0 | 0 |
| battles | 392 | 343 |
| battle frames | 448,282 | 366,049 |
| mean / longest battle | 1,144 / 2,006 | 1,067 / 1,651 |
| wins (enemy seen at 0 HP) | 185 | 166 |
| rewards: battle / exploration / boundary+item | 67 / 3 / 0 | 73 / 19 / 24 |
ROM-gated, `row63_item_uses_the_potion_and_the_battle_menu_deals_no_list_it_only_opens`: base,
pressing `ITEM` whenever dealt, 12,000 frames in the one battle, `ITEM` 119 and `BACK` 119, the
party list left waiting 119 times, the Potion never used, and pressing `BACK` then `MOVE 1`
whenever dealt, `MOVE 1` 125 and `BACK` 125, the battle never ends: **fails**. Branch: the Potion
used (8 to 28 HP) and the battle over in 555 frames; `MOVE 4` and the battle over in 773: passes.
## 2026-09-28, row 64: Mt. Moon's far side, a ladder underfoot and three ledges down
### What was live
v0.6.2/v0.6.4 binary, adapter `pokered-unique8-v7`, macros mode, rank 12 (MT. MOON), objective
Cerulean City, from 2026-09-26 to 09-28. The watchdog flagged it as `unrewarded`: about 750 macro
decisions per ten brain minutes, all `done`, no reward, places delta 0. The 09-28 event log has
`GO OBJECTIVE` 41,990 starts, `GO WARP` 25,554, `GO FRONTIER refused` 27 (about one per restore),
and nothing else: no battle and no step. Forty-eight hourly flysim restarts did not clear it. The
milestone-12 reset of 09-26 bought hours; nobs had recorded a "GO OUT / GO OBJECTIVE" pad just
before that reset.
### Reproduction (the pulled checkpoint, hot generation 218910)
The fly is on Mt. Moon B2F (`$3d`) at (5, 7), which is warp 3, the ladder up to B1F's exit chamber
(23, 3). With the ledgers **empty** the pad is `GO OBJECTIVE`, `GO WARP`, `GO FRONTIER`:
- `objective_goals` is `Exit(Warp(3))` at (5, 7), and `ways(Passage)` is `[Warp(3)]` (tier 2,
toward the objective).
- `GO FRONTIER` is refused `no route` and the map is marked exhausted. Correctly: all 452 reachable
tiles are stood on, and the 439 unstood ones are in B2F's north and south pieces and the border.
- Per-frame trace: `GO OBJECTIVE` runs 27 frames with mask `0x00` on every one (a `Settle` arrival
on the tile underfoot) and ends `done`. The next hold does the same. Route survey on main,
20,000 frames: `GO OBJECTIVE` 205 and `GO WARP` 211 `done`, all on (5, 7).
With the ledgers rebuilt (`EXHAUSTED=1`, `STOOD=1`) the pad is `GO OBJECTIVE`, `GO WARP` from frame
0. **The coordinator's lead (`GO WARP` and `GO FRONTIER` exhausted) is refuted.** The frontier mark
is correct, and `GO WARP` is never withheld: it is dealt the whole time, at the ladder underfoot.
No ledger removes the way on. Both ways on execute as no-ops.
**Why it came back after the reset.** Off the ladder (a raw right/left step, then the drive), the
fly goes B1F exit chamber, then (27, 3), then Route 4 (24, 6). There `GO OBJECTIVE` is refused
`no route`, because every road from there to Cerulean's west edge crosses a ledge: the column at
x = 62 on rows 10-15, and the rows at y = 5 and 9. The route search read a ledge as a wall both
ways. The east edge rests, and `GO ITEM` or `GO FRONTIER` walk back into the cave mouth (24, 5).
The fly lands on B1F (27, 3), where `GO OBJECTIVE` settles in place (618 times in 30,000 frames),
or on B2F (5, 7) after a walk over (23, 3). The geometry re-creates the ring; nothing persisted.
### Fix (three commits)
1. `014d869`: a walk that starts on its own step-fired warp steps onto free ground beside it (never
another warp) and back on (`CheckWarpsNoCollision` runs only after a step).
2. `e10f48e`: `LedgeTiles` hops. The grid marks them (OVERWORLD tileset only, lower-left anchor
tiles). The route search takes a hop from above as one press that lands two tiles on. The walk
holds while `HandleLedges` carries the fly, so the hop is not written as a push-back.
3. `83e842a` (general, separable): a `Settle` on an exit key that leaves the fly on its map ends
`blocked`. From the tile it pressed from, row 57's refused-from-here ledger also holds the
button off for the window.
Ablations from the checkpoint:
- 1 alone becomes a B1F/Route 4 ring (`GO OBJECTIVE` done on Route 4 151 times, `GO ROUTE` on B1F
150).
- 3 alone breaks the in-place ring (1,500 done in place drops to 0 in 72,000 frames), but the fly
does not reach Cerulean.
- 1 + 2 reach Cerulean at frame 1,972.
### Before and after
Route survey from the live checkpoint, 72,000 frames per arm, `main` `eecd574` vs the branch:
| driver | base | branch |
| --- | --- | --- |
| prefer GO OBJECTIVE, GO WARP | rank 12, 3,290 tiles, 1,500 of 1,500 done on B2F | rank 13 CERULEAN, 3,434 tiles, Cerulean f1973 |
| uniform, seed 7 | rank 12, 3,290, 1,499/1,500 | rank 15 NUGGET BRIDGE, 3,551, Cerulean f3331 |
| uniform, seed 12345 | rank 12, 3,290, 1,499/1,500 | rank 13, 3,436, Cerulean f3041 |
| uniform, default seed | rank 12, 3,290, 1,499/1,500 | rank 13, 3,447, Cerulean f1973 |
ROM test `the_fly_takes_the_ladder_it_stands_on_and_hops_down_to_cerulean_from_mt_moons_far_side`
(`FLY_ROW64_CHECKPOINT`):
- base: 167 done in place, never leaves B2F, **fails**;
- branch: the first `GO OBJECTIVE` goes to B1F, 80 hop frames under a walk on Route 4, Cerulean at
f1972, pushed ledger empty, passes.
### Why nothing inside the fly broke it, and the general guarantee
The in-place ring wrote no ledger. `Done` records nothing, and every ledger with a window was
empty after a restore anyway. The per-macro form of 12.2's rule had no case for a warp underfoot.
Commit 3 makes the rule structural for every way out.
Rows 58, 59 and 61 were rings in which each macro crossed a door, so no effect-based rule sees
them. A repetition budget keyed on the fly's own starts was considered and not built. It is a rule
about the choice, not knowledge in a macro, and it would turn a ring into a wait or a wander
without adding the missing fact. Those rings stay guarded outside the fly: the watchdog, the
recovery ladder, and the ROM road tests.
## 2026-09-29, row 65: the release merge's Mt. Moon door ring, and the Cerulean badge house's yard
### What was found
Not live: both came from the row-64 review, before v0.6.5 shipped (`docs/design/macros.md` 12.29).
- **The merge.** On the staging tree (rows 63, 62 and 64 merged), row 59's ROM test
`the_fly_goes_into_mt_moon_from_the_live_route_4_checkpoint` crossed Route 4's west doors 34
times against a bound of 25. Any two of the three rows pass (3 to 18).
- **The yard.** The row-64 route survey, seed 7: `GO OUT` in the Cerulean badge house took its back
door onto Cerulean (9, 9). That is the door tile of a closed yard of 33 tiles. The pad stayed empty
from f40,753 to the end of the run, about 32,000 frames.
### Reproduction
- Row 59's test on the staging tree, traced: arrive on 1F's mouth (14, 35), `GO OUT` or `GO HEAL`
out, arrive on Route 4 (18, 6), `GO ROUTE` or `GO OBJECTIVE` back in. Each leg takes 70 to 80
frames, and there were 17 round trips. `GO HEAL` walks a hurt fly back to the mouth from deep in
the cave. `GO OUT`'s tier-3 fallback deals the mouth itself, because on 1F Route 4 is visited and
not toward the rung. The test's stub rotation was swept over eight offsets on the staging tree:
24 to 44 crossings, three of the eight over the bound. The count depends on where the rotation
stands when the fly arrives, and that is why the pairs passed.
- The yard came back on the staging tree with seed 99 (`FLY_PROBE_CATCH=route FLY_PROBE_RNG=99`
from `FLY_ROW64_CHECKPOINT`). It was saved at f31178, when the fly stood on the door, as
`survey-rank15-row65-yard.checkpoint` (`FLY_ROW65_YARD_CHECKPOINT`, not committed). The
per-frame trace of an underfoot fallback that used row 64's step-off shows the fly stepping
left and back right onto (9, 9). No warp fires, because the tile is no door tile and a sideways
step has no carpet in front.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 65 | `GO OUT`'s "a room has to be leavable" fallback deals the way back out of a cave floor whose road on is a ladder, one step from the arrival tile. Route 4's side walks straight back in | Mt. Moon 1F's mouth. `GO HEAL` (row 62) brings a hurt fly back to it | `a_floor_whose_way_on_is_a_passage_deals_no_go_out_back_the_way_it_came`, row 59's ROM test on the merged tree | **fixed**: no tier-3 `GO OUT` while an unrested passage leads toward the objective |
| 65b | the exit walks set a step-fired door underfoot aside while any other exit is listed, reachable or not | a closed yard whose one door the fly stands on | `a_door_underfoot_is_taken_when_no_other_way_out_can_be_walked_to`, `row65_the_fly_leaves_the_cerulean_badge_houses_back_yard` | **fixed**: fall back on it once every listed goal has failed the route search |
| 65c | a warp whose own tile is no door fires only through `ExtraWarpCheck`. On the OVERWORLD tileset that needs a warp carpet in front, so row 64's sideways step-off does nothing | the badge house's back door | `a_door_underfoot_that_fires_on_a_bump_is_bumped_and_not_stepped_off`, `a_warp_carpet_in_front_is_marked_where_extra_warp_check_reads_it` | **fixed**: the grid marks carpets on the maps whose check reads them. A walk takes a warp underfoot by bumping toward one when it can |
| 65d | Cerulean was one node while its ground is two pieces. The badge house was off the graph, so its two doors were one door to `GO OUT`, the nearest | the house entered by either door | `cerulean_is_a_town_and_a_yard_and_the_badge_houses_back_door_is_the_yards` | **fixed**: the house on `LINKS`, and the yard as a `SPLIT` piece |
| 65e | on a split map, the other pieces' doors and edges are candidates. Each `no route` refusal from the small piece rests that exit for the whole map | out of the yard, the town's exits resting: an empty pad outside the front door for the rest of the window (survey, seed 3) | `a_way_out_on_another_piece_of_a_split_map_is_not_a_way_out_of_this_one` | **fixed**: `path::exits` keeps the fly's own piece. A door no piece lists is not claimed |
| 65f | the 12.28 guarantee read the tile the walk settled on, so a same-map teleport would read as a way out that did not fire | the Saffron Gym's pads, Silph Co. (not reached) | `a_same_map_teleport_is_somewhere_the_way_out_took_the_fly` | **fixed**: `blocked` only while the fly still stands where it settled |
| 65g | the frontier's exhausted mark is per map, so a fly that has covered the yard marks all of Cerulean | the yard, after the fly has stood on all of it | -- | **left, named**: the yard is now reached only when the objective has no route through the front door, and a restart clears the mark |
| 65h | a hurt fly on 1F's mouth has `GO HEAL` out, and on Route 4 has `GO HEAL` and the cave side by side | row 62's service while the party is below full | -- | **left, the fly's**: both lead somewhere real (row 62 round 2, the same tug) |
### Before and after
Row 59's ROM test on the stub rotation, over eight rotation offsets (0, 5, 11, 17, 23, 29, 37, 41):
| tree | crossings | pass |
| --- | --- | --- |
| staging `release/v0.6.5` `19d295d` | 34 28 24 24 44 24 24 24 | 5 of 8 |
| row 65, road rule off (piece filter on) | 10 19 19 23 21 25 19 27 | 6 of 8 |
| row 65, piece filter off (road rule on) | 4 4 18 13 6 4 8 8 | 8 of 8 |
| row 65 | 2 4 4 4 4 4 7 5 | 8 of 8 |
At offset 0, which is the test as it ships, the result is 34 before and 2 after. Every run reached
Mt. Moon.
The same checkpoint on the uniform route survey (72,000 frames, seeds 7, 11, 12345, 99) gives base
20, 8, 19, 20 against branch 14, 16, 5, 6. The branch's remaining crossings are row 65h.
`row65_the_fly_leaves_the_cerulean_badge_houses_back_yard` (`FLY_ROW65_YARD_CHECKPOINT`, 24,000
frames, stub rotation):
- staging: never leaves the yard, with an empty pad for 21,448 frames running. **Fails.**
- branch: in the town at f266, then the gym, Pallet after a whiteout and on. The pad is never empty
in the yard. **Passes.**
Each of 65b through 65e alone lets this rotation out of the yard, so the ROM test does not separate
them; the unit mutants do. The route survey from the yard checkpoint (six seeds, 36,000 frames)
gives these results:
- **staging**: every seed is back on the door by f2,560, through the house and out of its back door
again, with an empty pad from there to the end of the run.
- **65b and 65c, no split**: a house-and-yard door ring, `GO ROUTE` bumping in and `GO OUT` taking
the back door out, hundreds of times.
- **65b to 65d**: out, but seed 3 then stands outside the front door with an empty pad for the rest
of the window (65e).
- **branch**: all six leave with no empty pad, and three win the Cascade Badge.
## 2026-09-29, row 66: shop, Poké Balls and catching from the rung-8 restart
### What was found
The operator restarted the live run from the rung-8 archive (VIRIDIAN CITY) on v0.6.5 to watch
shopping and catching. In the first 35 minutes: `GO SHOP` done 33, `TALK` 5, `BUY BALL` never
dealt, `THROW BALL` 0, no catch. The sequences after `GO SHOP` were `GO SHOP`, `GO OUT`, `GO SHOP`,
`GO OUT` (`docs/design/macros.md` 12.30).
### Reproduction
- `survey-rank8-row66-viridian-mart.checkpoint` (`FLY_ROW66_MART_CHECKPOINT`, not committed) was
saved by the offers survey (`FLY_PROBE_SAVE_MART=2a`, `FLY_PROBE_SAVE_AFTER=3000`) from
`survey-rank7-row62` on the frame the fly walked into the Viridian mart after delivering the
parcel: 793 in the wallet, no ball.
- The connectome from it (`trap_hunt`, `FLY_TRAP_LOG_MACROS=1`): `GO SHOP` from the door to the
clerk, `GO OBJECTIVE` out of the door, `GO SHOP` from the street. Three laps in 18 brain seconds.
`TALK` was on the pad at the counter every time and was never chosen.
- A catch on the stub survey (`FLY_PROBE_SCREEN_*` dumps): from "All right! WEEDLE was caught!"
to the end of the battle, 6,900 frames under a pad of `BACK` and `THROW BALL`. `THROW BALL`'s A
said YES to the nickname and typed AAAAAAAAAA.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 66 | row 62's service walk is dealt again whenever the service is needed, with no window, so a fly that walks away from the counter is walked straight back | the Viridian mart after the parcel, no ball, money for one | `a_counter_the_fly_walked_away_from_is_not_walked_back_to_for_the_window`, `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` | **fixed**: a completed `GO SHOP` / `GO HEAL` facing the counter records `TargetKey::Counter` on the building's map. The service walk toward it is withheld for the reached window |
| 66b | a purchase took four choices in a row at the counter (`TALK`, the greeting, `CONFIRM`, `BUY BALL`). The connectome never chose `TALK` there | any mart | `buy_ball_is_offered_from_a_marts_floor_only_while_a_ball_can_be_bought`, `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | **operator decision, built**: `BUY BALL` is also one button from the mart's floor, like `HEAL`. It walks to the clerk, talks, opens BUY, buys the first row and is done when paid. It is offered only in Viridian (after Oak has the parcel), Pewter and Cerulean, with no ball, 200 in the wallet, no parcel, and the clerk not blocked |
| 66c | `wListMenuID` outlives the battle bag, so every frame after a throw read as an open bag | a catch (the Pokédex page, the nickname, the naming screen) and the text after any throw or potion | `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends`, the state unit test | **fixed**: the bag is the bag only while its box (4, 2)-(19, 12) is drawn |
| 66d | after a catch, `NEXT` says YES to the nickname offer and names the Pokémon with A's | every catch | -- | **left, named**: offering the box's two answers in a battle is a pad change for the operator |
| 66e | the connectome did not choose `THROW BALL` in any wild battle with a ball (35 decisions over seven battles, three runs) | Viridian Forest with a ball bought by 66b | -- | **left, the fly's**: dealt as designed (12.9). Whether to make throwing likelier is the operator's |
| 66f | whiteouts halve the wallet: 3,175 to 793 to 396 to 0 on one stub run before Pewter | early fights lost | -- | **left**: the cartridge's rule. It is why the restart rung matters |
| 66g | `rom_catch`'s `BALL` is the button's tag (`MB·BALL`), not its channel, so the lean sets a rate nobody reads | the test's drive | -- | **left, documented**: that drive is the one that catches from `FLY_CATCH_CHECKPOINT`. Both tests now retry from idle offsets, because one ball misses about two throws in three |
### Before and after
ROM tests (rom-env sourced):
| test | v0.6.5 | branch |
| --- | --- | --- |
| `row66_a_counter_walked_away_from_is_not_walked_back_to_by_go_shop` (10,000 frames, the drive declines the counter) | 31 street `GO SHOP`s, 31 walks back in. **Fails** | 0 and 0. Passes |
| `row66_buy_ball_from_the_marts_floor_rings_up_a_ball` | `BUY BALL` never dealt on the floor, no ball. **Fails** | dealt, started, done. One ball, 793 to 593, at f491. Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | `THROW BALL` dealt on 666 frames after the catch, pad `BACK`/`THROW BALL`. **Fails** | 0, pad `NEXT`, battle over 1,463 frames after the catch. Passes |
With the connectome (`trap_hunt`, one sweep thread). `FLY_TRAP_SEED` seeds only the palette, and
three seeds from one checkpoint were byte-identical. So the runs vary the starting state: three
post-parcel Viridian mart entrances saved from stub seeds 1, 3 and 5, and the Pewter gym
(`survey-rank11-row59`, 1,606 in the wallet). A decision is a macro start whose pad held the
button.
| run | brain min | counter `TALK` dealt / chosen | floor `BUY BALL` dealt / chosen / done | balls bought | `THROW BALL` dealt / chosen |
| --- | ---: | ---: | ---: | ---: | ---: |
| base, Viridian mart (s1 entrance) | 5 | 4 / 0 | -- | 0 | 0 / 0 |
| branch, Viridian mart (s1 entrance) | 5 | 1 / 0 | 2 / 0 / 0 | 0 | 0 / 0 |
| branch, Viridian mart (s3 entrance) | 5 | 3 / 0 | 3 / 1 / 1 | 1 (431 to 231) | 4 / 0 |
| branch, Viridian mart (s5 entrance) | 5 | 3 / 0 | 4 / 1 / 1 | 1 (1,587 to 1,387) | 16 / 0 |
| branch, Pewter gym, then the Pewter mart | 10 | 1 / 0 | 4 / 1 / 1 | 1 (1,606 to 1,406) | 15 / 0 |
`TALK` at a counter: 0 of 12 decisions on either arm. The floor `BUY BALL`: chosen 3 of 13, and
done (paid) all 3 times. The ring: 4 mart entries in 16 brain seconds on base, one visit on the
branch.
## 2026-09-29, row 67: the Pewter Gym trainer, lost on repeat
### What was live
v0.6.5, macros mode, reset to rung 8 at 12:16Z and back at PEWTER CITY by 13:40. The fly
entered the Pewter Gym (map 54) at 13:41, talked to the guide (#3) and to the Jr. Trainer
(#2). For the next hour and a half the pad read `battle` most of the time.
Per 3,000 events: `NEXT` 1,332, `MOVE 2` 83, `MOVE 3` 13, `MOVE 1` 0, `GO OBJECTIVE` 30, `NO` 17,
`GO FRONTIER` 13, `TALK` 7. There was no battle-won reward, only two tile rewards on map 54. Check
10 stayed clear.
### Reproduction (the pulled checkpoint, hot generation 230739)
- The checkpoint is on the walk back, not in a battle: Pewter City (18, 13), `wIsInBattle` 0,
`wLastBlackoutMap` `$02`, money 0, no badge, `EVENT_BEAT_PEWTER_GYM_TRAINER_0` clear. The party
is one Squirtle L11, 34/34: TACKLE 35/35, TAIL WHIP 30/30, BUBBLE 30/30.
- The opponent is `wTrainerClass` `$05` (Jr. Trainer♂) #1, `wEnemyPartyCount` 2: Diglett L11 and
Sandshrew L11, both Ground (`wEnemyMonType1` `$04`).
- Driven with the real palette and the live readout's measured favourite (TAIL WHIP 87%, else
BUBBLE), the cycle is the live one. `GO OBJECTIVE` into the gym, then `TALK` and the guide's
YES/NO. Then the trainer's challenge starts the battle. The own-turn pad is `MOVE 1, MOVE 2, MOVE 3`
on every turn, and each turn resolves in about 530 frames. Squirtle falls 34 → 29 → 24 → 19
→ 11 → 6 → 0 while Diglett's DEFENSE falls to -6. Then `wIsInBattle` `$ff`, `wBattleResult` 1,
the whiteout to Pewter (13, 26) with PP back to 30, and the walk back. One battle takes about
4,500 frames.
- Live, per battle (29 battles, from the event log): TAIL WHIP 155, BUBBLE 23, TACKLE 0, and 5 to 8
moves each. Where TAIL WHIP ran out of effect before the faint, 12.23 withheld it and the fly
pressed BUBBLE (`22222233`).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 67 | a readout that favours TAIL WHIP loses every battle against a trainer it could beat; the whiteout heals the party, so PP never runs out and the ring never ends | the Pewter Gym's Jr. Trainer, Squirtle alone | `row67_the_gym_trainer_is_beaten_from_what_the_pad_deals` | **left, the fly's**: the pad offers every move with PP and an effect on every own-turn frame (0 missing in 932) and a uniform choice wins. Options for the operator below |
| 67b | check 10 did not flag: a stray tile reward (a new gym tile on a walk back) every ~20 minutes reset `unrewarded`, and battles are not a sequence of four names | a whiteout ring with a walk in it | `lint.sh` check 10 case 8 | **fixed**: `unwon-battles` (24+ `MOVE n`, no `wildwin`/`trainer`/`badge` reward, two probes, no new ground) |
| 67c | the no-PP ROM test asserted "more than one button" on a trainer battle whose only honest button is `MOVE 1` (12.8's backstop); it was red on main and skipped without `FLY_NOPP_CHECKPOINT` | the no-PP checkpoint | `macros_mode_ends_a_turn_with_no_move_left_on_the_cartridge` | **fixed (test)**: at least one button, and the battle ends (Struggle, 1,487 frames) |
### The options, measured
From the live checkpoint, 60,000 frames per arm (16.7 brain minutes), real palette. The driver
is harness choice, not the fly's:
| arm | trainer battles (L lost, W won) | trainer beaten | Brock beaten |
| --- | --- | --- | --- |
| live favourite (TAIL WHIP 87%), seed 1 | LLLLLLLLL | no | no |
| live favourite, seed 2 | LLLLLLLL | no | no |
| uniform over the pad, seeds 1 / 2 / 3 | LLW / LLLLW / LLLW | f32,940 / f46,293 / f41,030 | seed 1 |
| BUBBLE whenever dealt | W | f12,234 | yes |
| TACKLE whenever dealt | LLLLLW | f59,253 | no |
| live favourite, stat-down move withheld once the target's stage is -1 or lower, seeds 1 / 2 | W / W | f9,165 / f9,304 | yes / yes |
| the same at -2, seeds 1 / 2 | LW / LW | f17,053 / f19,033 | yes / yes |
| the same at -3, seed 1 | LLLLLW | f54,551 | no |
- **Withhold a move with no effect on this target** (12.23's rule): it already applies, and TAIL
WHIP has an effect until -6. The fly faints at about that turn, so the rule changes nothing here.
- **Withhold a stat-lowering move once it has done something**: the -1 arm wins the first battle
on both seeds and then beats Brock. It is a pad rule about which move is good, not about what
the cartridge refuses, so it is a doctrine change for the operator. It would also hide GROWL,
SAND-ATTACK and similar moves after one use in every battle.
- **Reward damage dealt**: this is a reward-catalog change, out of scope for loop review, and it
cannot be measured without the brain. Nothing in the current catalog separates BUBBLE from
TAIL WHIP until a battle is won, and none is.
- **Watchdog detection plus the recovery ladder**: shipped (67b). Replayed probe by probe on the
live log with uniqueLocations proxied from the tile rewards, base check 10 first flags at 14:46
(`unrewarded`). The branch flags `unwon-battles` at 14:01, 14:16, 14:21, 14:36 and 14:41; a
tile reward at 14:06 and 14:26 clears one probe each. The healthy windows before the gym
(13 to 46 `MOVE n`, 1 to 4 wins each) are not flagged. The ladder's restart does not change the
readout, and a reset to PEWTER CITY replays the same gym. Only the reset to the rung below adds
forest battles, and whether that is enough was not measured.
## 2026-09-29, row 69: throw on low HP only, and the fly names its catch
### What was asked
Two operator decisions after row 66 (`docs/design/macros.md` 12.32). Row 66 measured the connectome
choosing `THROW BALL` 0 times in 35 decisions with a ball in the bag (66e), and every catch named
`AAAAAAAAAA`: `NEXT` answered the nickname offer YES and its A presses typed on the keyboard (66d).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 69 | at low HP the ball sat beside four moves, `SWITCH` and `RUN`, and the fly never chose it (66e) | a wild battle with a ball, the enemy at a third of its HP | `row69_at_low_hp_in_a_wild_battle_the_ball_is_the_only_attack` and four more unit tests, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` (`FLY_ROW69_CHECKPOINT`) | **operator decision, built**: with `THROW BALL` dealt and `ItemUseBall`'s HP factor saturated (`W >= 255`), the moves, `SWITCH`, `RUN` and the bag's `BACK` are withheld; `ITEM` stays for a hurt thrower |
| 69b | the keyboard read as the battle's between-turns frame, so `NEXT` typed the name (66d) | every catch | `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends`, `the_naming_screen_is_its_menu_and_its_box_and_its_underscores` | **operator decision, built**: the keyboard reads `Unknown` and its pad is the fly's own D-pad, A, B and START |
| 69c | a keyboard nobody ends is a stall: B never leaves it and A stops typing at ten letters | a fly that does not press ED or START | `row69_a_fly_that_types_nothing_is_ended_by_the_bound`, `row69_confirm_on_the_keyboard_presses_start_until_it_closes` | **fixed**: once the name is full or sixty brain seconds have run, `CONFIRM` alone, which presses START until the keyboard closes (`blocked` after 160 frames) |
| 69d | row 66's `unknown_pads_with_no_box` counted the bound's `CONFIRM` on the keyboard, which is drawn without the text font | the rung-10 Pewter gym drive, which buys a ball and catches | `the_fly_reaches_the_pewter_gym_from_the_rung_ten_checkpoint` | **fixed in the test**: the keyboard is a drawn screen |
| 69e | the catch checkpoint's lead one-shots every forest Pokémon, so no wild HP is ever low there | `FLY_CATCH_CHECKPOINT` | -- | **left, named**: the low-HP ROM test uses a rung-9 Route 2 checkpoint (rung-9 A below: a Bulbasaur at 5/30, one ball) as `FLY_ROW69_CHECKPOINT` |
### Before and after
ROM tests (rom-env sourced, the build box), a69a258 against the branch:
| test | a69a258 | branch |
| --- | --- | --- |
| `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | 664 low-HP frames with the ball dealt, pad `MOVE 1`, `MOVE 2`, `MOVE 3`, `THROW BALL`. **Fails** | 58 frames, pad `THROW BALL` alone, thrown. Passes |
| `row69_after_a_catch_the_keyboard_is_the_flys_own_buttons_and_it_ends` | keyboard 511 frames, 11 `NEXT` starts, 0 raw frames, name `AAAAAAAAAA`. **Fails** | keyboard 1,516 frames, no macro, 1,516 frames of the fly's buttons, 7 letters at most, name `RIJ?`, closed by the fly (ED). Passes |
| `row69_a_fly_that_types_nothing_is_ended_by_the_bound` | `NEXT` types ten A's and ED. **Fails** | nothing typed; `CONFIRM` dealt once at the bound, span 3,587 frames, name empty (the species' own). Passes |
| `row66_after_a_catch_the_pad_is_not_the_bag_and_the_battle_ends` | passes | passes (battle over 2,468 frames after the catch) |
With the connectome (`trap_hunt`, one sweep thread, 15 brain minutes, macro log). The runs vary the
starting state, as row 66's did: four rung-9 checkpoints with one ball each.
| checkpoint (lead, balls) | arm | wild battles with a ball | `THROW BALL` dealt frames / chosen | the throw's pad (frames) | catches | keyboard | rung, tiles, windows flagged |
| --- | --- | ---: | ---: | ---: | ---: | --- | --- |
| rung-9 A, Route 2 (Bulbasaur 5/30, 1) | a69a258 | 5 | 414 / 0 | -- | 0 | -- | 10, 520, 40 |
| | branch | 2 | 96 / 1, at low HP from the pad `THROW BALL` alone | 32 | 1 | 16.8 brain s, A 32, B 30, longest 1, name empty (the species'), ended by the fly (ED) | 10, 482, 51 |
| rung-9 B, Route 2 (Wartortle 9/70, 1) | a69a258 | 1 | 32 / 1, at full HP on the first frame | 0 | 1 | `NEXT` | 9, 300, 46 |
| | branch | 1 | 32 / 1, the same throw | 0 | 1 | 28.1 brain s, A 55, B 52, longest 1, name empty, ended by the fly (ED) | 9, 236, 43 |
| rung-9 C, the forest (`FLY_CATCH_CHECKPOINT`, Wartortle 18/70, 1) | both, identical | 1 | 32 / 1, at full HP, missed | 0 | 0 | -- | 9, 278, 18 |
| rung-9 D, the forest (the no-PP state, Bulbasaur 6/34, 1) | both, identical | 2 | 282 / 0 | 0 (never low with the ball dealt) | 0 | -- | 9, 285, 21 |
- **Throws and catches.** Three balls thrown in four runs on the branch, two catches; on a69a258
two thrown and one catch. The one run where they differ is the one whose wild HP passed a third
with the ball dealt: the fly threw from the throw's pad at once and caught. Two of the throws
were the fly's own choice from the ordinary pad on a battle's first frame, on both arms.
- **Names.** Both keyboards were ended by the fly's own A on ED, in 17 and 28 brain seconds, well
inside the bound. The brain's A and B fire at nearly the same rate there, so each letter it typed
it deleted again and both names came out empty, which the cartridge turns into the species'
name. That is the fly's spelling, kept as it is.
- **Stalls.** None from this row. Every run ends its battles; no keyboard reached the bound. The
flagged windows are `NEXT` runs through battle text on both arms (and on the branch's rung-9 A run
five `GO ROUTE, GO HEAL` windows, row 62's tug, 65h). The branch's rung-9 B run covers fewer tiles
after the keyboard because its frames after the catch differ from a69a258's (the keyboard took
28 brain seconds instead of `NEXT`'s few), not because anything waited: 635 macros started, 633
done, one refusal and one timeout, against 803, 802, one and one.
## 2026-09-29, row 68: the damage reward, the catalog's answer to row 67
Row 67 (the Pewter Gym's Jr. Trainer lost on repeat, TAIL WHIP 155 / BUBBLE 23 / TACKLE 0) is a
readout choice, not a pad fault. The operator chose a catalog change over a pad rule: `damage`,
adapter `pokered-unique8-v8` (`docs/rewards-learning.md`, "Damage rewards"). It pays for the HP the
fly's own attack removes; it does not touch the pad.
### The survey
The real brain, macros mode, from the row 67 checkpoint, 120 brain minutes per arm, `v7` (main)
against `v8` (the rule), on the stream's own frame (`LegacyFrame`). The palette seed turned out not
to diversify a run (seeds 1, 2 and 3 were identical per arm), so the three pairs are three starts:
the checkpoint as it is, and the checkpoint with the game run 7 and 19 frames ahead of the brain.
Each pair is identical until the first damage payout.
| start | arm | trainer battles | won | BUBBLE share, first 40 / last 40 min | damage paid | rung |
| --- | --- | ---: | ---: | --- | ---: | --- |
| +0 | v7 | 68 | 0 | 14% / 17% | -- | 10 |
| +0 | v8 | 58 | 3 (Jr. Trainer at 101 min, Brock at 107, a Route 3 trainer at 112) | 15% / 20% | 6.01 | **11, BOULDER BADGE** |
| +7 | v7 | 65 | 0 | 16% / 21% | -- | 10 |
| +7 | v8 | 67 | 0 | 14% / 14% | 3.41 | 10 |
| +19 | v7 | 60 | 0 | 15% / 24% | -- | 10 |
| +19 | v8 | 59 | 1 (Jr. Trainer at 119.6 min) | 16% / 22% | 6.74 | 10 |
TACKLE stayed at 0 to 2 choices a run in every arm.
**What it shows.** The rule fires where it should: every `v8` arm was paid for BUBBLE's hits and
nothing for TAIL WHIP's, 3.4 to 6.7 over two hours, capped per battle. `v8` beat the trainer in 2
of 3 starts and `v7` in 0 of 3 (and the live run 0 of 29). **What it does not show** is the
mechanism the rule is for: the move choice did not move more under `v8` than under `v7`. BUBBLE
drifted from about 15% to about 20% in both arms, and TAIL WHIP stayed near 80% everywhere. So
inside two brain hours the wins are not explained by a learned preference; a paid hit also changes
the brain's activity (the PAM stimulation) and the trajectory, and three starts cannot tell a small
real effect from luck. Learning is too slow to show in this window, or not happening, and the
survey cannot say which.
**Status: shipped as the operator decided, not a fix.** The trap is still possible under it: one of
three `v8` starts never won. Row 67's watchdog check 10 (`unwon-battles`, on its branch) is the
detector, and the pad rule the operator declined is the lever that still exists.
## 2026-09-30, row 70: Mt. Moon, the SHIFT offer's party list, and the ladder that took the catch
### What was live
On v0.7.0 with adapter v8, the ladder reset the run to rung 11 at 16:54Z. The rung-11 archive
replayed deterministically: Route 3's trainers, Mt. Moon (rung 12) at 17:40, a Poké Ball bought,
thrown, and a Zubat caught at 17:47 (`OWNED #41`, `CAUGHT #107`). At 17:52 a Lass's battle on 1F
started. From then on the log was `NEXT start/done` every 0.8 brain seconds and nothing else: no
reward and no other macro for 58 brain minutes. Check 10 flagged `dominant`/`sequence` (`NEXT`
100%). At 18:50 the ladder, at level 2 since the 16:54 reset, reset the run to rung 11 again and
erased the catch. The replay after that reset matched the one before it event for event (the same
`brainMs`), so it was heading into the same trap at about 19:48.
### Reproduction (durable generation 250877, pulled from the reset's archive)
`wIsInBattle` 2 and the Lass (`wTrainerClass` 3), with Oddish beaten and Bellsprout L11 next.
Wartortle L19 was at 0/58, Zubat L8 at 24/26 and out. The party list was open with
`wPartyMenuTypeOrMessageID` = BATTLE_PARTY_MENU and the cursor on the Zubat. The screen read
"ZUBAT is already out!". The seam read `forced_switch`, so the pad was `SWITCH, NEXT`, and `SWITCH`
had no healthy Pokémon to go to. Driven from the checkpoint on v0.7.0, the pad was `NEXT` on
6,000 of 6,000 frames: 125 `NEXT` starts, every one "already out" and the list again.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 70 | the SHIFT style's "Will <mon> change POKéMON?" offer opens the party list with BATTLE_PARTY_MENU, which the seam read as `ChooseNextMon`'s forced switch. Its pad `SWITCH, NEXT` had no B; `NEXT` on the Pokémon already out rings forever | any trainer battle with two or more Pokémon in the party, the fly answering YES (the first catch made it possible) | `the_shift_offers_party_list_is_the_flys_turn_and_its_way_out_is_back`, `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` (`FLY_ROW70_CHECKPOINT`), `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` (`FLY_ROW70_FORCED_CHECKPOINT`) | **fixed**: forced switch = BATTLE_PARTY_MENU **and** the active battler at 0 HP (`docs/design/macros.md` 12.33). The offer is the fly's turn, and its pad is `SWITCH` (when someone can go out) and `BACK` |
ROM tests on the build box (rom-env sourced):
| test | v0.7.0 | branch |
| --- | --- | --- |
| `row70_the_shift_offers_party_list_is_declined_and_the_battle_goes_on` | 6,000 frames in the list, `NEXT` on all of them, `BACK` on none, never left. **Fails** | `BACK` from f3. "LASS sent out BELLSPROUT!", then the fly's turn at f194. Passes |
| `row70_the_list_after_a_faint_is_still_a_forced_switch_and_is_answered` | passes | 881 forced frames, all read as forced, `SWITCH` on all of them, `BACK` on none. The Zubat goes out, and the fly's turn comes at f1,102. Passes |
The stub reaches row 70 by itself. From the live rung-12 archive (Mt. Moon's mouth, one ball),
three uniform-stub seeds each catch a Zubat within 4,000 frames and meet the same Lass. There
Wartortle faints at f27,361, f34,656 and f35,284.
### The watchdog and the ladder: every act was on a real trap
The day's six acts, replayed probe by probe through check 10 and the ladder from the live logs
(open loop; uniqueLocations proxied from the tile rewards). The base replay reproduces the live
history: restarts at 05:55, 08:55 and 11:55, and resets to rung 11 at 16:50 and 18:49 (live:
16:54 and 18:50).
| live act | window | what the fly was doing |
| --- | --- | --- |
| restarts 05:57, 08:58, 11:59 (map 59) | `unwon-battles`, 05:50 to 13:50 | Row 67 again, against a Lass on Mt. Moon 1F. `MOVE 2` (TAIL WHIP) on six turns in seven, BUBBLE doing 5 to 8 to her Oddish, 34 to 48 moves per window, no battle won, whiteout and back. Beaten after the 11:59 restart (13:54, then the other 1F trainers, B2F's and the Super Nerd) |
| reset to 11, 16:54 (map 61, B2F) | `unrewarded`, 15:05 to 16:50 | A wild encounter every ~20 s, `RUN` every time (220), `GO FRONTIER`/`GO WARP` between them, and no new tile or reward for 1 h 50 min. The battles were ending and the fly was moving between them, but on ground it had already covered. Mechanism not established: no checkpoint from before 16:54 survives (row 64/65 territory, B2F's far side) |
| reset to 11, 18:50 (map 59) | `dominant`/`sequence`, 17:59 on | Row 70's list: `NEXT` alone for 58 brain minutes |
So check 10 read no cave as a trap. Healthy cave windows (17:04 to 17:54: Route 3 and Mt. Moon
battles won, a catch, new areas) peaked at 94% `NEXT`, and the tile gate kept them clear. Two
suggested relaxations are **not** supported by the evidence:
- "Battles ending and the fly moving between them": the 16:54 window was exactly that for
1 h 50 min, with nothing new.
- Counting the damage reward's KO as a win: the Lass ring had 45 KOs of her first Pokémon in
eight hours and never won.
The watchdog's flags are unchanged. Every replayed log (rows 58, 60 to 64, 67, 70) flags on the
same probes with the same reasons, base and branch.
What went wrong was the ladder. It stayed at level 3 to 4 from the morning's ring through a
rung-11 reset and a full, rewarded climb back to Mt. Moon. The 18:50 reset then restored the
same rung-11 archive as the 16:54 one. A restore is deterministic: the replay after it matched
the one before event for event (1,138 of 1,138, same `brainMs`). So the reset erased the catch
and walked back into the same list about an hour later. It also could not have helped: row 70's
trap is in the game state, not the ledgers, so neither a restart nor a replay clears it.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 70b | the ladder never started over after real progress. A trap after a reset and a rewarded climb back was treated as the old trap outliving its step | a reset, then progress, then any trap | `test_progress_after_the_last_step_starts_the_ladder_over`, `test_progress_while_a_step_settles_does_not_start_the_ladder_over` | **fixed**: `window.progress` in loop.json (report only; `lint.sh` check 10 case 9). New lasting progress more than `SETTLE` after the step, once a clear probe shows the trap let go, returns the ladder to level 0 (see 70f) |
| 70c | a reset restored the same archive as the last reset, which replays deterministically into the same trap | level 2 and above, where every step targets the rung below the best | `test_the_last_resets_archive_is_not_restored_again`, `test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it` | **fixed**: that step is a restart |
| 70d | a reset erased a catch made an hour earlier | any reset after a catch | `test_a_species_owned_recently_is_never_reset_away`, `test_a_probe_that_owns_a_species_starts_the_protection` | **fixed**: within two hours of a species first owned, a reset is a restart (held three hours apart) |
| 70f | (review r3) a reset's replay counted as progress. The restored reward ledger pays the archive's areas, trainers, species and rung again, so 70b started the ladder over after every reset, and a replayed catch opened a second protection window. A trap only the rung below escapes took 5.6 h (6.8 h after a catch) to reach it, against 2.1 h in v0.7.0 | a reset whose replay re-earns rewards, then traps | `test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over`, `test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected`, `test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over`, `test_a_trap_only_the_rung_below_escapes_is_reached_promptly`, `test_restarts_are_a_hold_apart_in_every_closed_loop` | **fixed**: `window.progress.keys` names each lasting reward (`lint.sh` check 10 case 9); progress and protection count only names the ladder has not seen (`progressSeen`). 2.1 h (3.3 h after a catch). Restarts stay three hours apart, and a failed reset does not mark its archive |
| 70e | the B2F wander: `RUN` from every encounter, walks on covered ground, nothing new for 1 h 50 min | Mt. Moon B2F after the Super Nerd | -- | **left, named**: no checkpoint survived. The next occurrence should be pulled before any reset |
Ladder replay of the day (the same logs and the same start state, base against branch):
- **Base**: restarts at 01:30, 05:55, 08:55, 11:55 and 15:10; resets to 11 at 16:50 and 18:49.
- **Branch**: restarts at 01:30, 05:55, 07:15, 10:30, 13:30 and 15:10; a reset to 12 (the
current rung, not 11) at 16:50; a restart at 18:04.
- 07:15: AREA 60 at 06:48 started the ladder over.
- 18:04: the climb after 16:50 started the ladder over.
- After 18:04, no reset. The Zubat was owned at 17:46 and rung 12 was the last reset's
archive, so the branch holds to restarts three hours apart.
- **Review r3** (names, from a live-like 00:00 state, then the post-16:54 log with the state carried
over): restarts at 01:30, 05:55, 08:55, 11:55 and 15:10, as live; a reset to 12 at 16:50 (the
13:54 to 14:20 trainers were new, so the ladder had started over). After 16:54 the Route 3
trainers, AREA 59, OWNED #8 and the rung are the replay's and do not count; OWNED #41 (the
Zubat, 17:46) is new, so a restart at 18:04 and then the protection hold through 18:54, no reset.
The replay is open loop: the log after 16:50 is what the base's reset produced.
## 2026-10-01, row 71: Route 25, a ball past the bag's window
### What was live
v0.7.3 legacy, adapter v8, rung 15 (NUGGET BRIDGE), map 36 (Route 25), two badges. After the
Route 25 trainers, a wild battle began. The pad held `THROW BALL` alone and every start was
`blocked`: 131 of 131 in ten minutes, about two hours in all. A flysim restart restored a hot
generation from inside the same battle with the same bag open, so the trap came back at once. The
coordinator then reset the run to milestone 15.
### Reproduction (hot generation 263767, inside the trap)
- The state: `wIsInBattle` 1 (wild, not a trainer), a wild Oddish L13 at 8/36, Wartortle L35 at
21/105 with PP left (only GROWL at 0).
- The bag: TM34, HELIX FOSSIL, NUGGET, TM45, POKé BALL x2. Party of 2, Oddish not in it.
- The bag was open with `wListScrollOffset` 3, so the window showed TM45, POKé BALL and CANCEL,
with the arrow on row 1, the ball.
- Row 69's rule (enemy HP low for the ball) withheld everything but the ball.
- `THROW BALL` aims at bag index 4. The seam reported the window row (0..2) as the cursor, so the
cursor step walked between rows 1 and 2 until its budget ran out.
The hypotheses in the brief were all checked:
- **A trainer battle.** No, it is wild.
- **No balls in the bag.** No, there are two.
- **The ball counted wrong.** Its index was right; the cursor reading was wrong.
- **RUN, or PP.** Not involved.
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 71 | the battle bag's cursor was read as the window's row, so a bag entry past the third could never be reached; with row 69's low-HP rule, `THROW BALL` alone on the pad and blocked for ever | any wild battle against a species not in the party at low HP, with the ball fourth or later in the bag (`ITEM`'s Potion likewise, without the trap) | `a_battle_frame_with_a_cursor_accepting_input_is_the_flys_turn`, `row71_a_ball_past_the_bags_window_is_thrown` (`FLY_ROW71_CHECKPOINT`), `row71_the_list_scroll_offset_is_where_the_cartridge_reads_it` | **fixed**: cursor = `wCurrentMenuItem + wListScrollOffset` (`$CC36`, pinned from the cartridge; `docs/design/macros.md` 12.34). The mart's lists read the same way; `MART_CURSOR_ROWS` stays |
| test | 390d118 | branch |
| --- | --- | --- |
| `row71_a_ball_past_the_bags_window_is_thrown` | 11 starts, 10 `blocked`, nothing thrown in 3,000 frames. **Fails** | thrown, Oddish caught (`wCapturedMonSpecies`) by f350, 0 `blocked`. Passes |
| `a_catch_on_the_cartridge_pays_the_catch_rule_once_with_the_species_in_its_label`, `row69_at_low_hp_a_wild_battles_pad_is_the_ball` | pass | pass (balls in the window's first rows, unscrolled) |
Trap hunt, 10 brain minutes with the real connectome from the trap checkpoint:
- **390d118:** 33 of 33 windows flagged, 1 tile, `THROW BALL` 131 starts and 131 `blocked`. That
matches the live count exactly.
- **Branch:** 1 of 33 flagged. That window is the opening battle text, with 71 tiles in it. The
ball is thrown on the first hold and the Oddish is caught at 0.10 min. The fly ends the keyboard
itself, and the run reaches 91 tiles.
The watchdog and the ladder flagged the trap correctly. The restart could not help, because the
trap is in the game state and the hot checkpoint is inside it (row 70's lesson again). Only a reset
or the fix ends it.
## 2026-10-02, row 73: Route 25 and Bill's house, a PC no macro could press, and Cerulean's south
### What was live
v0.7.5, rung 15 (NUGGET BRIDGE), Route 24/25. After row 71's battle trap was fixed the fly kept a
busy ring with no progress: `GO ROUTE` into Bill's house (`$58`, door (45, 3)), `GO OBJECTIVE` or
`GO OUT` straight back out. Scout B3 measured it from the live checkpoint: on six seeds (2.8
brain hours) the pad in the house was always `GO OBJECTIVE, GO OUT, GO NPC, GO FRONTIER`, `GO OUT`
16-51 and `GO OBJECTIVE` 16-60 starts per ten brain minutes, `GO NPC` 0 in about 600 starts, and
new tiles 2527 to 2531 in 35 minutes. Rung 16 was never earned.
### Mechanism
- **Rung 16's place was the route.** `RUNG_PLACES[16]` was `at(ROUTE_25)`. A fly on Route 25 was
already there, so in the house `GO OBJECTIVE` was an exit into the objective's map: the same
door as `GO OUT`.
- **The errand's middle step was unpressable.** The ticket is Bill's errand
(`scripts/BillsHouse.asm`): talk to Bill as a Pokémon, press the cell separator's PC at (1, 4)
facing up, talk to Bill when he steps out. The PC is a hidden event (`wNumSigns` 0, one sprite),
and no macro aimed at hidden events or dealt `TALK` in front of one. Scout B3 confirmed the
press on the cartridge by hand.
- **After the ticket, the town is two pieces.** Cerulean's town ground ends at row 28; Route 5 is
on the ground behind the trashed house (`$3e`), in by its front door and out by the hole in its
back wall. The house was off the map graph, so `GO OBJECTIVE` toward Vermilion ended `blocked`
at (17, 28) and the fly rang between the town and its houses (scout: 0 of 6 seeds past row 28 in
43 brain minutes each, from a carry-forward made by scripted presses).
| # | trap | trigger | test | fix, or why it is left |
| --- | --- | --- | --- | --- |
| 73 | rung 16's place was Route 25, so inside Bill's house `GO OBJECTIVE` and `GO OUT` were both the door; the errand's PC is a hidden event no macro could press; after the ticket, Cerulean's south was off the graph | rung 15 on Route 25 (live), and any fly with the ticket in Cerulean | `an_errand_is_its_people_first_and_the_room_is_not_left_while_one_is_waiting`, `a_hidden_event_is_the_errands_next_step_once_no_person_is_left_and_it_is_faced_from_its_side`, `a_hidden_event_is_nobody_elses_target`, `the_road_south_out_of_cerulean_is_through_the_trashed_house`; `row73_*` in `rom_macros_mode.rs` (`FLY_ROW73_DOOR_CHECKPOINT`, `FLY_ROW73_PC_CHECKPOINT`, `FLY_ROW71_CHECKPOINT`, `FLY_ROW73_SOUTH_CHECKPOINT`, `FLY_ROW73_TRASHED_CHECKPOINT`, `FLY_ROW73_TICKET_CHECKPOINT`) | **fixed**: rung 16 is `errand(BILLS_HOUSE)`, people then things; hidden events read from the cartridge's own table (`$11:$6A40`/`$6A96`), only ever as the errand's next step, faced from the side the entry names (`docs/design/macros.md` 12.35, `macros-wram.md` 17); Cerulean's third piece and the trashed house on the graph |
| 73a | the road from Route 5 to Vermilion is plain map edges through Saffron, whose gates are guarded until the drink; the Underground Path's houses are off the graph | a fly on Route 5 with rung 17 next | none yet | **left**: predicted, not reached by the scout; the branch hunt's flies reach Route 5's gate (`$46`) and the Underground Path house (`$47`). Needs its own checkpoint and row |
| test (stub rotation) | 74a3c12 | branch |
| --- | --- | --- |
| `row73_the_fly_earns_the_ss_ticket_from_inside_the_ring_at_bills_door` | no ticket in 36,000 frames, out of the house and the Route 24/25 ring. **Fails** | ticket at 4,743 frames, never out of the house. Passes |
| `row73_the_cell_separator_pc_is_pressed_and_bill_hands_over_the_ticket` | no ticket in 36,000 frames. **Fails** | ticket at 2,116 frames. Passes |
| `row73_the_fly_walks_from_the_live_route_25_checkpoint_to_the_ss_ticket` | no ticket in 216,000 frames (60 brain minutes), 1,019 times into the house and 1,019 out. **Fails** | ticket at 9,876 frames. Passes |
| `row73_the_objective_south_of_cerulean_is_the_trashed_houses_two_doors` | aims at the town's bottom row (unreachable). **Fails** | the house's front door, then the hole in its back wall. Passes |
| `row73_the_fly_takes_the_trashed_house_south_to_route_5` | trashed house 54,442; ticket carry-forward not in 48,000 (63,880). **Fails** | 52,081 and 27,067. Passes |
| `row73_the_hidden_event_table_is_the_cartridges_and_bills_pc_is_in_it` | does not compile (new seam) | passes |
Trap hunt, real connectome, 15 brain minutes per seed, six seeds per arm. The palette seed does not
make runs differ (row 68), so the seeds are the game run 0, 7, 19, 41, 97 and 211 frames ahead of
the brain before the first hold (scout B3's `FLY_TRAP_AHEAD`, a scratch patch, not committed):
| from | arm | rung 16 | distinct (map, tile) | Bill's-house ring (`GO ROUTE` / `GO OUT` / `GO OBJECTIVE` at net 0) | reached Route 5 |
| --- | --- | --- | --- | --- | --- |
| live row-71 checkpoint (rung 15, Route 25) | 74a3c12 | 0 of 6 | 83-105 | 36-47 / 18-22 / 18-27 per seed | 0 of 6 |
| live row-71 checkpoint | branch | **6 of 6**, at 2.0-2.3 brain minutes | 200-517 | 2-24 / 3-30 / none at net 0 (the walks go somewhere) | 3 of 6 inside the 15 minutes |
| ticket carry-forward (rung 16, Bill's house) | 74a3c12 | (has it) | 328-400 | -- | 0 of 6 (ends in the town, the bike shop or the centre) |
| ticket carry-forward | branch | (has it) | 273-439 | -- | **5 of 6**; four of them on into Route 5's gate (`$46`) or the Underground Path house (`$47`) |
The two-minute window flags do not measure this trap: the ring crosses more than four tiles, so
the base arm flags only the opening battle text (1 of 53), and the branch arm's flags (28-49 of 53)
are `NEXT` runs inside long battles it now reaches -- the Rocket in the yard behind the trashed
house and Route 24/5 trainers (one battle 23,954 frames and 462 macros; the base's ticket seed 19
has the same 17,235-frame battle). Every one ended; none is a ring. Route 5 is counted from the
hunt's text-box maps and its final map, so it is a floor.

View file

@ -193,6 +193,8 @@ ssh the host pct exec <release-ctid> -- curl -s 127.0.0.1:7410/metrics | grep fl
| Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. | | Repeating `FATAL:` + `transport_limit` for more than ~10 min | Something else is holding this account's websocket transports (a second bridge, a dev box, a stale `tools/mock-twitch.sh`) | Find and stop the other client. `GET https://api.twitch.tv/helix/eventsub/subscriptions` with the broadcaster token lists them; delete the strays. |
| Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. | | Repeating `FATAL:` + `create failure ... missing scope` | The token lost a scope (re-authorized with the wrong `--role`, or Twitch revoked it) | Re-run `tools/authorize.mts` — see "Rotate the bot token" below. The bridge will NOT recover from this on its own; restarting cannot add a scope. |
| Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. | | Repeating `FATAL:` + `revoked (authorization_revoked)` | The channel or the user revoked the app | Re-authorize. Same as above. |
| Repeating `FATAL: Twitch refused to refresh the <role> token ... (HTTP 400 "Invalid refresh token")` at startup | That role's refresh token is revoked or invalid (password change, app disconnected, re-authorized elsewhere) | Re-authorize that `--role` — "Rotate the bot token" below. Restarting cannot help; systemd keeps retrying every 15 s with one refresh request per role until the file is fixed. |
| `the stored <role> access token has expired; refreshing it` or `rejected the stored <role> access token (401); refreshing it once`, then a normal start | The bridge was down longer than an access token lives (~4 h), or Twitch invalidated it early | Nothing: it refreshed and persisted the new token itself. |
| One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. | | One `FATAL:` then a quiet, `chatSubscriptionHealthy: true` bridge | It healed. | Nothing. Note it in the status log if it was during a stream. |
| `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. | | `active (running)`, `chatSubscriptionHealthy: false`, and NO `FATAL:` line after more than 2 min | The watchdog itself is not running — an old bundle | Check `/opt/fly/current/bridge/index.js` is from a release that has it, then `systemctl restart flybridge`. |
@ -203,13 +205,30 @@ unit, so chat can never take the fly down.
## Rotate the bot token (flybridge) ## Rotate the bot token (flybridge)
Not yet applicable until flybridge exists and is wired up (P3, `docs/design/infra.md` Access tokens live about 4 h; refresh tokens until revoked. The bridge refreshes on its own:
section 7). Once it is: re-run `tools/authorize.mts` (`docs/design/stage-bridge.md` at runtime through `RefreshingAuthProvider`, and ON LOAD (`prepareStartupTokens` in
section B1) on the operator box to get a fresh refresh token, which `services/bridge/src/auth.ts`) — a stored access token that has expired, or that Twitch's
`RefreshingAuthProvider`'s `onRefresh` persists to `/var/lib/fly/bridge/tokens.json` validate endpoint rejects with 401, is refreshed with its refresh token before the bridge gives
automatically from then on — a one-time manual step, not a recurring one. The up, for both roles, and each refreshed token is written back to `/var/lib/flybridge/tokens.json`
`twitch-app` credential (client id/secret) only needs rotating if the app itself is under its own role (tmp file + rename, mode 0600), also when the bot and the broadcaster are one
compromised; follow the same `06-secrets.sh` pattern as the stream key. account. So an outage longer than an access token's life no longer needs a hand refresh
(2026-09-28: it used to crash-loop on 401 at `validate`).
Re-authorizing is needed only when the journal says
`flybridge: FATAL: Twitch refused to refresh the <role> token for user <id> (HTTP 400 "Invalid refresh token")`,
or a scope is missing (the table in "Chat dead" above). Then, on the operator box:
1. `npx tsx tools/authorize.mts --role <role> --tokens-file <local copy of tokens.json>`
(`services/bridge`, `docs/design/stage-bridge.md` section B1). It rewrites only that role's
entry and keeps the other.
2. Push the file to the release container as `/var/lib/flybridge/tokens.json`, owned by the
service user, mode 0600 (it is a secret; never in a release artifact or in git).
3. `systemctl restart flybridge` and read the journal for the startup notice line.
Never paste a token or the client secret into a log, a ticket or chat: the bridge itself prints
neither (Twitch errors are logged by status and message only, URLs redacted). The `twitch-app`
credential (client id/secret) only needs rotating if the app itself is compromised; follow the
same `06-secrets.sh` pattern as the stream key.
## Restore a checkpoint locally ## Restore a checkpoint locally
@ -263,7 +282,7 @@ pct exec $CTID -- /opt/fly/bin/fly-reset-to-milestone $N
# (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5. # (a) the running release already wrote that checkpoint -> nothing to deploy, skip to 5.
# (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's # (b) the new build bumps the ADAPTER VERSION and nothing else -> name the checkpoint's
# adapter so the gate and flysim both migrate instead of refusing: # adapter so the gate and flysim both migrate instead of refusing:
FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 infra/05-deploy.sh <release-env> <release-tarball> FLY_ACCEPT_ADAPTERS=pokered-unique8-v7 infra/05-deploy.sh <release-env> <release-tarball>
# The gate logs "the adapter version is the only difference, and it is named; the run is KEPT # The gate logs "the adapter version is the only difference, and it is named; the run is KEPT
# and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the # and migrated", and writes FLY_ACCEPT_ADAPTERS into /etc/fly/fly.env so flysim applies the
# same rule at restore. Anything else about the string differing is still a refusal. # same rule at restore. Anything else about the string differing is still a refusal.
@ -424,6 +443,612 @@ One `ln -sfn` plus a restart, per `docs/design/infra.md` section 2. Nothing else
touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`. touching: `flycast`/`flypush`/`mediamtx` do not read anything under `/opt/fly/current`.
On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above. On the release container, `<previous-version>` is a tag (e.g. `v0.1.0`) — "Cutting a release" above.
## Switch the runtime (legacy loop or session runtime)
Two binaries in every release from SERVE-01 on run the same fly: `flysim`, the legacy loop, and
`flysim-session`, the same composition on the session framework (agent, Game Boy environment and
macro task as participants). They read the same `/etc/fly/fly.env`, write the same checkpoint
stores, event log, sugar journal and chat sidecar, and serve the same feed, control API and
metrics through the same listener code, so nothing else on the container can tell them apart.
`flysim.service` is the fly's one unit name either way; which binary it runs is one drop-in,
written and removed by `fly-runtime` (`infra/bin/fly-runtime`, installed to `/opt/fly/bin`).
```
pct exec $CTID -- /opt/fly/bin/fly-runtime status # legacy | session
pct exec $CTID -- /opt/fly/bin/fly-runtime session # CUT-01, after the shadow's verdict (starts the speed probation)
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy # the one-command rollback
```
- **What it does.** `session` writes `/etc/systemd/system/flysim.service.d/10-runtime.conf`
(`ExecStart=/opt/fly/current/flysim-session`, `FLY_SESSION_DIR=/run/fly/session`),
daemon-reloads and restarts `flysim.service`; `legacy` deletes the file and does the same. No
data moves: the store is shared, and each runtime restores the other's checkpoints.
- **What it checks.** `session` refuses a release without `flysim-session`, and refuses when
`flysim --print-compatibility` and `flysim-session --print-compatibility` differ. After the
restart both wait for `/healthz` and a `/status` frame that advances
(`FLY_RUNTIME_HEALTH_TIMEOUT`, 300 s). If the session runtime does not come up healthy, it
switches back to legacy by itself and exits 1 (`--no-fallback` leaves it to the operator).
Every switch is logged (`journalctl -t fly-runtime`, `/var/lib/fly/runtime.log`).
- **The fallback outlives the switch (C1).** While the session runtime is selected, the drop-in
also sets `OnFailure=fly-runtime-fallback.service`, `StartLimitBurst=3`,
`StartLimitIntervalSec=600` and `RestartMode=direct`, and `MALLOC_ARENA_MAX=2` (glibc arena
fragmentation was the whole of the 5-8 MB/h RSS growth). `RestartMode=direct` is what makes the
limit real: since systemd 254 the default (`normal`) sends the unit through the `failed` state
before every `Restart=always` restart, so `OnFailure=` would fire on the first crash, watchdog
kill or start timeout (seen on systemd 257, the container's). With `direct` the unit goes from
one start to the next and only hitting the start limit fails it. Three starts of `flysim.service` within ten minutes, from any
cause and any caller (a reboot, the watchdog or `fly-loop-recover` restarting it, a deploy, a
binary that crashes, hangs before READY or is killed by `WatchdogSec`) make systemd run
`fly-runtime fallback`: it writes `/run/fly/runtime-fellback.json` (time, reason, unit result),
deletes the drop-in, daemon-reloads and restarts `flysim.service` on the legacy binary, and logs
a `fly-runtime` journal line. It is idempotent, and it does nothing if the release has no
executable `flysim`. Look with `fly-runtime status` (it prints the reason) or
`cat /run/fly/runtime-fellback.json`; the container is then on legacy until an operator runs
`fly-runtime session` again, which clears the reason file. Restarts you make yourself count
too, and once the limit is reached systemd refuses the next start and runs the fallback. Three legitimate restarts in ten
minutes count the same as three crashes: after that many, prefer `fly-runtime legacy`, do the
work, then switch back.
- **Interrupted switches roll back.** `fly-runtime` traps INT, TERM and HUP (an ssh that drops
mid-switch): an unfinished `session` removes the drop-in again (or restores the one that was
there) and restarts `flysim.service` on that state, so a drop-in that never passed its health
check is never left behind. `session`, `legacy`, `fallback` and that rollback all take one lock
(`/run/fly/runtime.lock`); a switch holds it while it changes the drop-in and queues the restart
(`systemctl restart --no-block`, so a unit that never becomes READY cannot hold it) and releases
it for the health wait. The rollback does nothing when a fallback finished after the switch began (the
reason file exists), so it can never put back an older drop-in over a fallback.
- **What stays the same.** Everything that names `flysim.service` keeps working unchanged:
`fly.target`, `flyedge.service`'s `Requires=`, the watchdog, `fly-loop-recover`'s restart and
its sudoers line, `fly-loop-reset`, `fly-reset-to-milestone` (run with the service stopped, on
the shared store), the unstick rule's `systemctl restart flysim.service`, `journalctl -u
flysim`, the cpuset drop-in. The choice survives a reboot and a deploy: `05-deploy.sh`
converges unit files but never removes a drop-in (it rewrites it in place from the current
template, without a restart), and it refuses a release without `flysim-session` or with a
different compatibility string while the drop-in is present (`fly-runtime legacy` first to
deploy one). **Policy (C2, operator decision 2026-09-29, "Session stays, trust gates"):** a
deploy keeps the chosen runtime on the new release's `flysim-session`, without re-running the
shadow for it. The trust gates before the release vouch for the binary, and the persistent
fallback above protects a bad one.
- **What differs, by declaration.** `POST /reward` is always 403 on the session runtime (the
operator pulse has no session-framework counterpart, `legacy-gameboy-v1` section 15); a
fresh start publishes no audio for its one setup frame; `FLY_TRACE` and
`FLY_PROFILE_SECONDS` are legacy-loop tools (the session runtime logs a `session profile`
line of per-phase timings every minute instead). The sugar journal's boot header says
`runtime: fly-session`.
- **The standalone unit.** `flysim-session.service` is the same service as a unit of its own
(flysim's limits, cpuset and environment; `Conflicts=flysim.service`; no `[Install]`, so it
cannot be enabled). It is for a rehearsal or a soak on a container whose `flysim.service` is
stopped, not for switching the stream.
- **The session on the bus (BUS-01).** `fly-runtime session --bus` (or `session-bus`) runs the
session's participants on the flybus router over Unix sockets: `flysim-session` (the router, the
coordinator, the listeners) starts `fly-session legacy-agent` and `fly-session legacy-environment`
as children of the same unit, in `flysim.slice`, on flysim's CPUs. The drop-in gains
`Environment=FLY_SESSION_TRANSPORT=bus`; `fly-runtime status` prints `session` and then
` transport: bus`. `fly-runtime session` without a flag (05-deploy's refresh) keeps the transport
the drop-in has; `fly-runtime session --local` goes back to the in-process lane, and
`fly-runtime legacy` to legacy. The fallback, the probation, the watchdog and the unstick rule's
restart are the same on either transport: one unit, restarted as a whole, children included
(`ps -o pid,args --ppid $(systemctl show -p MainPID --value flysim)` lists them). A deploy
refuses a release without `fly-session` while the drop-in says `bus`. **Before switching onto the
bus, run a shadow of it** (Shadow run below): with the live fly on legacy (`fly-runtime legacy`),
`fly-shadow-run start --bus`, three hours, then `fly-shadow-run check --bus && fly-runtime
session --bus`. Watch `fly_frame_work_mean_ms` and `fly_frame_work_p99_ms` on `/metrics` (the
loop's compute time per frame, without its pacing sleep, over the last 3,600 frames; the budget
at real time is 16.74 ms): they show the headroom that a realtime factor of 1.0 hides.
- **Per-frame compute time, both runtimes.** `/metrics` exports `fly_frame_work_mean_ms`,
`fly_frame_work_p99_ms`, `fly_frame_work_max_ms` and `fly_frame_work_frames` for the legacy loop
and the session runtime alike: everything one running iteration does except the pacing sleep.
Headroom is `1 - mean / 16.74` at real time.
## Feed over the bus (EDGE-02)
`ws://127.0.0.1:7400/feed` is served either by `flysim` itself (`direct`, how every release before
EDGE-01 did it, and the default) or by `fly-edge` from flysim's embedded feed bus (`bus`,
`docs/design/flybus.md` "Feed over the bus"). The WebSocket contract is the same bytes either way
(`docs/feed-protocol.md`); nothing about the fly, the readout or the compatibility string changes,
on either runtime (`flysim` or `flysim-session`, `fly-runtime`). The stage, the bridge and the
capture never see the difference.
**One switch, one line.** `FLY_FEED_VIA` in `/etc/fly/fly.env` (written by every deploy from the
env file's `FLY_FEED_VIA`, default `direct`). flysim reads it, `flyedge.service` runs only when it
says `bus` (`ExecCondition=`; in direct mode the unit starts as "skipped", inactive and not
failed), and `flysim.service` has `Wants=flyedge.service`, so **every** start of flysim brings the
edge up in bus mode, whoever starts it: a reboot, the unstick rule's restart, `fly-loop-reset`'s
stop and start, `fly-reset-to-milestone`, a crash-restart. There is nothing to enable or start by
hand, and flysim and the edge cannot disagree.
```
pct exec $CTID -- /opt/fly/bin/fly-feed status # configured / running / the edge and its counters
pct exec $CTID -- /opt/fly/bin/fly-feed bus # switch (restarts flysim; rolls itself back if unhealthy)
pct exec $CTID -- /opt/fly/bin/fly-feed direct # the way back
```
### The live procedure
Preconditions: the release has `fly-edge` (v0.7.6 and later; `ls /opt/fly/current/fly-edge`),
`fly-feed` is installed (`/opt/fly/bin/fly-feed`, converged by the deploy), the container is
claimed in the host log as for any host work, and `fly-feed status` says `configured: direct`,
`running: direct`. Pick a moment you would also pick for the unstick rule's restart: **the switch
restarts flysim**, so the stream shows the stage's reconnect screen for about a minute (the
restore, the warm-up and the page's reconnect; the rehearsal measured it, below), and the run
continues from the last checkpoint. It counts as one start against `flysim.service`'s start limit
(3 in 10 minutes on the session runtime), two if it rolls back: do not switch within ten minutes
of two other restarts.
```
# 1. Before: the baseline to compare with (keep the output).
pct exec $CTID -- /opt/fly/bin/fly-feed status
pct exec $CTID -- sh -c 'curl -s 127.0.0.1:9101/metrics | grep -E "^fly_(realtime_factor|lag_seconds|feed_clients|frames_sent_total) "'
pct exec $CTID -- fly-cpu-confine status # PERF-02: the sim's cpus are the sim's
# 2. Switch. Blocks until the page is on the feed again (FLY_FEED_HEALTH_TIMEOUT, 300 s) and prints
# "healthy (bus): the page is on the feed and frames are moving", exit 0.
pct exec $CTID -- /opt/fly/bin/fly-feed bus
# 3. Make it permanent for the next deploy: FLY_FEED_VIA=bus in the operator's env file for this
# container. (A deploy that finds fly.env and the env file disagreeing warns loudly and writes the
# env file's value; flysim applies it at its next restart.)
# 4. Look at it (below) for a few minutes, then at the end of the first hour and the first day.
pct exec $CTID -- /opt/fly/bin/fly-feed status
```
What `fly-feed bus` does, in order: refuses unless the release has `fly-edge`, takes
`/run/fly/feed.lock`, rewrites the one `FLY_FEED_VIA` line (every other line, the mode and the owner
kept), restarts `flysim.service` (`--no-block`, then waits for a **new** invocation's `/healthz`),
waits for the edge's `/healthz` (subscribed to the bus, a snapshot within 15 s) and, while
`flystage.service` is active, for the page: `fly_feed_clients >= 1` on the edge's counters with
`fly_frames_sent_total` advancing. Anything short of that within the timeout puts `FLY_FEED_VIA`
back to `direct`, restarts flysim again, checks it the same way and exits 1 (`--no-rollback`
leaves the failed switch in place for the operator; an interrupted `bus`, ssh dropped or INT, TERM
or HUP, rolls back too). `direct` is the safe terminal state and is never rolled back: an interrupted
`fly-feed direct` leaves `FLY_FEED_VIA=direct` and restarts flysim so the running process matches. Every switch is in the journal (`journalctl -t fly-feed`) and
`/var/lib/fly/feed.log`.
### What to watch
| Where | Healthy in bus mode | Wrong looks like |
| --- | --- | --- |
| `fly-feed status` | `configured: bus`, `running: bus`, `edge healthz: ok`, snapshot age under a second, `bus lost` and `bind failures` not growing | `running` differs from `configured` (a deploy wrote a new value; the next flysim start applies it); `edge healthz: NOT OK` |
| edge `:9102/metrics` (loopback for the watchdog; the same address answers on the container's network for the dashboard) | `fly_edge_bus_connected 1`, `fly_edge_snapshot_age_seconds` under 1, `fly_feed_clients 1` (the page; the bridge or a test adds more), `fly_frames_sent_total` rising about 30 a second, `fly_edge_decode_failures_total 0`, `fly_edge_bind_failures_total 0` | `bus_connected 0` (flysim down, or restarting), `bind_failures_total` rising (something else holds :7400: a flysim still in direct mode, a stale process), `decode_failures_total` rising (a mismatched flysim and fly-edge: deploy one release) |
| flysim `:9101/metrics` | `fly_bus_published_total` rising at the snapshot rate, `fly_bus_publish_failures_total` flat 0; `fly_feed_clients` and `fly_frames_sent_total` read **0 here in bus mode** (the counters belong to the edge) | publish failures rising: the store is full or the edge's seat is stuck; read `journalctl -u flysim -g "feed bus"` |
| `fly_realtime_factor`, `fly_lag_seconds` | the same as the baseline from step 1, within the usual noise: the publisher is about 2 ms of CPU per snapshot (10x the direct websocket write), so with `SESSION_AUX_CPUS=1` it runs on its own CPU and the number is unchanged; without it, expect a loss of 1 to 2 ms of the 3.7 to 5.7 ms of headroom per frame | a drop that persists for the hour: switch back (`fly-feed direct`) and compare |
| `ps -L -o pid,psr,comm -p $(pidof fly-edge)` / `grep Cpus_allowed_list /proc/$(pidof fly-edge)/status` | the page CPUs (`flyedge.service.d/cpuset.conf`, written by the deploy), never the sim's | an edge on the sim's CPUs: the cpuset drop-in is missing; re-run the deploy |
| `ls -R /run/fly/bus/store | wc -l`, `du -sk /run/fly/bus` | a few files, under 1 MB, flat for days (the router keeps one retained snapshot and what the edge is still reading) | growth: report it, restart flysim, switch back |
| `journalctl -u flyedge -u flysim -g "bus|feed|edge"`, `journalctl -t fly-watchdog -g flyedge` | `serving the feed from the bus` once per flysim start | `the feed bus went away` outside a flysim restart; a watchdog line `flyedge: ... failures` |
| the stream | the page is up, frames moving | the page on its reconnect screen: `fly-feed status`; if the edge is down `systemctl status flyedge`; `fly-feed direct` is the one-command answer |
The watchdog follows the **running** mode (the running flysim's own environment, so a deploy that
changed `FLY_FEED_VIA` but has not restarted flysim is not an outage). Check 2 reads the feed
counters from the edge in bus mode; a new check 2a judges the edge itself, only while flysim answers
`/healthz` (a down flysim is check 1's): active and `/healthz` 200, one failed pass let go, then
the second pass restarts `flyedge`, the third restarts the page and the encoder as well, and the
fourth **puts the feed back on flysim** (`fly-feed direct --no-wait`, granted in sudoers with exactly
those arguments): one more flysim restart, and `FLY_FEED_VIA=direct` stays until an operator
switches again (put it in the env file too). Check 2 in bus mode leaves a silent edge to 2a rather
than restarting a page that has nothing to connect to, and its chain ends with the edge and the
encoder.
### Rolling back
- `fly-feed direct`: writes `direct`, restarts flysim, waits until the page is on flysim's own
feed, stops a lingering edge. It needs nothing from the release (it works on one without
`fly-edge`), and it is the way back if anything above looks wrong. It restarts flysim again, so
count it against the start limit.
- Automatic: a switch that does not become healthy (above), the watchdog's fourth failed pass, and
`fly-runtime fallback` (to legacy) all leave `FLY_FEED_VIA` alone: the setting is the same on both
runtimes.
- A deploy of a release **without** `fly-edge` is refused (before `/opt/fly/current` moves) while
the env file says `bus` or the container is in bus mode: `fly-feed direct` and set
`FLY_FEED_VIA=direct` in the env file first, then roll back or deploy.
- A reboot keeps whatever `fly.env` says.
### What the rehearsal measured
Before the first live switch (EDGE-02, 2026-10-02): the real fly (session runtime, real connectome,
macros mode, sim on four CPUs and the page and edge on two others, as on the container), the real
stage page in headless Chromium consuming through `fly-edge`, plus the repo's own units, `fly-feed`
and watchdog under a real systemd. The build box was shared and loaded (load average 8 to 30), so
**real-time factor is not comparable between the two runs**; the numbers below are the ones load does
not move much. The live switch is the real A/B: take the step 1 baseline and compare.
| Measure | direct | bus |
| --- | --- | --- |
| WebSocket content, speed 0.25 so every frame is published, 4,261 and 5,406 frames compared | reference | frame, audio and spike attachments byte-equal on every frame; headers equal except a wall-clock "checkpoint saved" event that lands on different frames in any two runs |
| Latency, snapshot stamped by the sim to received by a local client (median / p95) | 1 / 3 ms | 7 / 14 ms (two hops: seal into the store, read out) |
| CPU per snapshot | 0.24 ms (flysim's websocket thread, on the host CPU) | 2.4 ms in flysim (`flysim-bus` publisher: on the aux CPU with `SESSION_AUX_CPUS`, else on the host CPU with the sim's dispatcher, about 7% of a CPU at 30 Hz and on the critical path) and 1.1 ms in the edge (page CPUs) |
| Edge CPU and placement | n/a | 1.3% mean, 2.8% p95, only on the page CPUs |
| Router store | n/a | 116 KB steady (median), 238 KB peak, 6 to 9 files, flat over the run |
| Memory over 35 min plus the restarts | flysim 72 to 78 MB | flysim 65 to 69 MB, edge 8.3 to 9.6 MB; the page grows the same in both |
| Snapshots dropped on the way (heavy load) | none seen by a local client | 0.28% sequence gaps at the recorder (the edge sits on CPUs Chromium saturates); none on a quiet box |
| Page | 0 decode errors | 0 decode errors, gaps only under that load |
Recovery, with the page (a reconnecting stage) as the witness: `kill -9 fly-edge`, a SIGTERM
restart of it, and two kills 0.1 s apart (the router's one seat for the edge is released at once)
each had the page streaming again in 0.7 to 0.9 s; a `kill -9` of flysim (router, publisher and
sim) had the edge serving the new router 3 s later and the page 3.4 s later; a SIGTERM restart of
flysim (the unstick rule) 4 and 5.3 s (the page's retries are 0.3 to 1 s apart, the sim restores
from its hot ring). Under the real systemd: `fly-feed bus` took 6 s from command to "page on the
feed", `fly-feed direct` 6 s, a `fly-feed bus` with a broken `fly-edge` rolled itself back after
the 40 s test timeout and left the page on flysim, a stop and start of flysim brought the edge
back by itself, and the watchdog's fourth failed pass switched a permanently broken edge back to
direct with the page connected again. The live restart is longer than these 6 s by the real
restore and warm-up; use the unstick rule's usual time.
### Notes
- **Dashboards.** In bus mode flysim's `:9101` reports `fly_feed_clients` and
`fly_frames_sent_total` as 0. Scrape the edge's `:9102` too (same names, plus the `fly_edge_*`
series); the metrics address is on every interface, as `:9101` is, and exposes nothing but
counters.
- **CPUs.** `flyedge.service` is confined to the page CPUs by the deploy's drop-in; the router and
the publisher run inside flysim, on its `flysim-bus` runtime: two threads plus tokio's blocking
pool, which does the artifact copies. **Give it a CPU of its own** (`SESSION_AUX_CPUS=1` in the
operator's env file, a page CPU added to `flysim.slice`; the deploy writes it to `fly.env` as
`FLY_SESSION_AUX_CPUS`, and the session pins the bus runtime there and the sweep and dispatcher to
the rest). Without it the runtime shares the host CPU with the sim's dispatcher, which costs about
1 ms per frame measured (the publisher is 1.3 to 2.5 ms of CPU per snapshot, 30 a second, on the
critical path; the barrier stalls behind it). Check: `grep Cpus_allowed_list /proc/$(pidof
flysim-session)/task/*/status` for the `flysim-bus` threads shows the aux CPU alone. Set it, run the
deploy, restart flysim, and only then `fly-feed bus`.
- **The store** is `/run/fly/bus` (tmpfs, `fly` 0700, 32 MiB cap, in practice under 0.5 MB). A
reboot empties it; a crashed flysim's directory is removed by the next one.
- **Control (`:7401`)** stays in flysim and is not part of this switch.
## Shadow run (SHADOW-01)
The session runtime, run beside the live fly as the gate for the automatic cutover (CUT-01). The
contract is `docs/design/session-framework/legacy-gameboy-v1.md` section 18. The shadow is
report-only: it presses no button, serves no port, and only reads flysim's stores and trace. Claim
the release container in the host log first, as for any host work.
```
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run start # baseline, trace on, remote shadow + guard, one flysim restart
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run status # the verdict, the relay (and a guard trip) in one screen
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run check # CUT-01's hook: exit 0 = cutover allowed
pct exec <ctid> -- /opt/fly/bin/fly-shadow-run stop --restart-flysim # shadow, guard and trace off
```
- **A shadow of the bus topology (BUS-01).** `start --bus` runs the box's shadow session with its
agent and world as child processes on its router's sockets (`FLY_SHADOW_MODE=bus/process`, which
the relay forwards); `check --bus` also requires that the verdict ran that topology
(`candidate.transport` `bus`, `executionMode` `process`). The live fly must be on the legacy
runtime for any shadow: only the legacy loop writes the trace, and `start` refuses otherwise.
- **Where it runs (SHADOW-02).** On a build box, not on the release container: there it cost the
live fly real time (2026-09-30: the realtime factor fell from 0.9998 to 0.93-0.98 and came back
to 0.999-1.0 the moment the shadow stopped), and at about 27 ms a frame on shared CPUs it fell
further behind every hour. `start` refuses without the remote configuration below; `start --local`
runs it on the container anyway. In remote mode `flyshadow.service` on the container is the
*relay* (`fly-shadow relay`, from a drop-in `start` writes): normal scheduling off flysim's CPUs,
a few file reads and one outbound ssh stream that carries the trace, the new saves and the sugar
journal to the box and brings the box shadow's verdict back to `/srv/fly/shadow/verdict.json`.
The guard, `check` and CUT-01 see the unit and the files they always did. Set-up below
("Remote shadow set-up").
- **Start** first records the live fly's baseline for 10 minutes, before the shadow exists: sixty
10-s means of `fly_realtime_factor` (their mean and spread) and the `fly_lag_seconds` growth
rate. It refuses unless flysim ran normally for most of that time. Then it:
1. installs `flysim.service.d/shadow-trace.conf` (`FLY_TRACE_DIR=/srv/fly/shadow/trace`,
`FLY_TRACE_LEDGERS=60`) and, remote, `flyshadow.service.d/remote.conf` (the relay, and this
run's id: the start's Unix ms);
2. starts `flyshadow.service` and waits for its heartbeat (remote: up to 5 minutes, while the
box resets its mirror, restarts its shadow for the new run and reports it alive);
3. restarts `flysim.service` once;
4. starts `flyshadow-guard.timer`.
`FLY_SHADOW_BASELINE_SECONDS` shortens the baseline, for tests only. The restart is the same one
the unstick rule uses: the rung is kept and the ledgers are cleared. A previous `verdict.json`
is kept beside the new one, renamed with its time.
- **The guard** runs every 60 s, automatically, and judges the live fly against its own baseline,
not against real time. A fly that already ran at 0.66 is fine at 0.66. It trips only on a
sustained degradation: 3 checks in a row in which the last 5 samples of the same flysim process
fall below the baseline, or grow lag faster than it, by more than the margin. The margin is
max(0.05, 4 x the baseline spread / sqrt 5). A trip is at the earliest about 7 minutes after a
real degradation begins. A tripped guard stops the shadow and the guard, removes the drop-in and
restarts flysim without the trace. It records why in `/srv/fly/shadow/guard-tripped.json`, and
`status` shows it. A paused fly is not judged, and a restarted one starts its window again.
Once the shadow is down for good (`ActiveState` inactive or failed: diverged, stopped, given up),
the guard stops itself and changes nothing. While the shadow waits out its 10-s crash-restart delay
(`activating`) the guard keeps running. A trip is not a divergence: fix the resources, then `start` again.
- **While it runs**, every later flysim restart (the unstick rule, the watchdog,
`fly-loop-recover`, `fly-reset-to-milestone`) starts a new trace file. The shadow follows it on
its own; nothing needs doing. The 3 h window is live *brain* time summed over those processes.
Stopping or restarting `flyshadow.service` itself starts the window again.
- **Pass**: `status` shows `verdict pass` once both of these hold with zero divergence:
- 10,800 brain seconds are compared;
- at least one live save per 10 brain minutes has been compared byte for byte.
The shadow keeps following, and the verdict stays `pass` only while nothing diverges. CUT-01
runs `check` at the moment it cuts over. `check` also requires all of these:
- at least 10,800 brain seconds, whatever window the shadow was started with;
- the guard has not tripped, `flyshadow.service` is running, `flyshadow-guard.timer` is active and
`baseline.json` exists (a run no guard watched is never cut over);
- remote: `/srv/fly/shadow/relay.json` is less than a minute old and `healthy` (connected, the
box's shadow of this run alive, the sync caught up), and the verdict is this run's (`runId`);
its `lagTransitions` counts the live trace not yet on the box as well;
- the verdict is for the release `/opt/fly/current` points to, with `flysim-session` and every
other shadowed binary unchanged;
- the shadow is caught up (at most about a minute behind);
- remote: `relay.json` is this run's (its `runId`, the verdict's and the drop-in's are one), has
no `coverageLost`, and its `traceAgeSeconds` (the newest live trace file's age) is at most 90 s:
a trace that is not being written while the shadow claims to follow refuses the check (a paused
flysim refuses too, until it runs);
- remote, the two hosts' clocks agree: the verdict's `updatedAt` is the box's clock and the check
bounds its age to within 60 s, so clock skew between the container and the box makes `check`
refuse (safe, not silent). Run NTP on both;
- the verdict's `updatedAt` is neither older than the max age nor more than 60 s in the future
(a clock stepped back must not keep an old pass fresh);
- no segment was skipped for a reason other than the live side's own.
- **Divergence**: the shadow stops itself (exit status 3; the unit does not restart it). A failure
of the session runtime itself counts: it did not start, the restore gate refused the live save,
or a step failed. The shadow leaves `verdict.json` at `diverged` and
`/srv/fly/shadow/divergence.json` with the field, both values and the 30 transitions before it.
On a checkpoint difference it also leaves both checkpoint files. It removes its heartbeat, so
flysim stops tracing within a minute. The live fly is untouched. Run `stop --keep`, pull the
files for the review, and do not cut over.
- **The trace cannot outlive the shadow.** flysim starts no trace without the shadow's fresh
heartbeat (`/srv/fly/shadow/trace/consumer`), and stops a running trace within a minute once the
heartbeat is more than 10 minutes old. That happens when the shadow crashed, diverged, was
stopped, or the guard tripped. flysim keeps the trace directory under 8 GiB, and the shadow
deletes every file it has compared (remote: the box deletes its copy, and the relay then deletes
the container's). Remote, the heartbeat is the relay's, and it is written only while the relay is
healthy: a dead box, a dead box shadow, a broken link or a sync more than a minute behind all stop
it, and flysim then stops its trace as for a dead local shadow. A trace that stops that way while
the shadow follows it is a `coverage` divergence: that process can no longer be compared. A
network blip shorter than the 10 minutes costs nothing for the trace: the relay resumes where
the box's copy ends. The hot saves queued in the relay (400 MiB, about 12 minutes) cover the same
window; beyond it a save may be missed, which the unavailable-checkpoint allowance absorbs.
**A stop that did happen is never forgotten** (review B1): after an outage of more than 10 minutes
flysim stops its trace (`no-consumer`) and runs on untraced. When the link heals the box is alive
and, counted in trace lines, soon caught up, long before its shadow reaches that stop. The relay
therefore scans the trace bytes it forwards for the stop and sets `coverageLost` in
`/srv/fly/shadow/relay.json`; it reports itself not healthy (no heartbeat) and `check` refuses
until the box's shadow reaches the stop and diverges (`coverage`), or ends its window at that
stop. **A stop ends the window** (B2): a trace that stopped (no consumer, byte cap) is a coverage
gap, never a skip. The shadow discards the brain time and saves compared before it
(`window.ends` in the verdict says how much), and a `pass` needs the whole 10,800 s after the
last gap. A box shadow that restarts after a gap replays the stopped trace, counts it, and drops
the count at its stop, so the pass still comes 10,800 s after the gap. `check` refuses while
`coverageLost` is set (it closes only when the verdict's `window.lastStopTrace` is that trace or
a later one) and for a verdict without a `window`. Catching up and restarting never clear it.
The relay flags a byte-cap stop exactly like a no-consumer one. A reward pulse (a declared skip)
does not hide a later stop in the same trace: the shadow reads on for it and the stop still ends
the window. After a window end the verdict's `status` is `running` again (not `pass`) until the
new window has compared the required time.
**After a long outage (more than the 10 minutes) the run cannot recover in practice**: the shadow
would have to restart while the stopped trace is still the newest file and reach its stop before
any flysim restart, and flysim's next boot is untraced (no heartbeat) so the shadow diverges
(`coverage`). Do not try to nurse it. The operator starts a new run (as root in the release
container, `pct exec <release-ctid> --` in front): `/opt/fly/bin/fly-shadow-run stop
--restart-flysim && /opt/fly/bin/fly-shadow-run start`. The old verdict is kept beside the new
one.
**Restarting the relay (`systemctl restart flyshadow`) mid-run** removes the heartbeat. If the
restart is faster than flysim's next minute check nothing is lost, otherwise flysim stops tracing
and the run is lost (safe: start a new run as above); do not rely on the fast case.
`coverageLost` is synced to disk before the chunk with the stop is forwarded.
- **Resources**: the shadow is a second whole brain, at about the live fly's CPU per frame.
Remote, it runs on the box's own cores at normal priority (`flyshadow-remote.service`), and the
container pays the relay (about 0.5 % of a core, measured; about 2.1 GB an hour over the network:
the hot save every 5 s is 2.7 MB, the trace about 140 MB an hour) and the trace writer inside
flysim: about 1.3 ms of the sim thread a frame (measured unpaced on a build box's Haswell, 3
threads: 11.1 to 12.5 ms). The guard's baseline is taken before the trace is on, so that cost
counts against it; if the guard trips on a remote run, the trace alone is too much for the live
fly's headroom. `--local` runs it `SCHED_IDLE` on the page and encoder CPUs, never on flysim's (05-deploy.sh
writes its `cpuset.conf`), pausing for a minute while flysim's lag grows faster than its
baseline rate. Disk on the container: the trace until the box has compared it (under 8 GiB);
on the box: the mirrored saves (under 3 GiB) and a spool of at most 4 GiB.
- **Start** refuses, and starts nothing, unless `flyshadow.service.d/cpuset.conf` exists and the
unit's `AllowedCPUs` (`systemctl show`) is disjoint from flysim.service's (05-deploy skips every
cpuset drop-in when the CT conf and CPUSET disagree).
- **Stop** stops the unit and the guard, removes the drop-ins, and deletes the trace and the spool
(`--keep` keeps them). Without `--restart-flysim`, the running flysim stops its current trace
within a minute, because its consumer is gone. Remote, the box's shadow keeps running idle until
the next `start`, which resets its mirror and restarts it for the new run.
- **Remote divergence**: the box's shadow stops (exit 3); the relay brings `divergence.json` and
both checkpoint files back to `/srv/fly/shadow/`, writes the diverged verdict and exits with
status 3 (the unit stays stopped, the guard stops itself). Pull the files from the container as
for a local divergence.
### Remote shadow set-up (SHADOW-02)
Once per build box, and again for every release the container runs. The real values (the box's
address, the key's path) go in the operator's private files, never in this repository. Nothing
on the build box can reach the release container: the container dials out.
1. **The relay's key**, on the release container (as root, claimed):
`install -d -o root -g fly -m 0750 /etc/fly/shadow-remote`, then
`ssh-keygen -t ed25519 -N '' -C fly-shadow-relay -f /etc/fly/shadow-remote/id_ed25519` and
`chown fly:fly /etc/fly/shadow-remote/id_ed25519*`. The private half never leaves the container.
The container needs an ssh client (`openssh-client`; `02-base.sh` installs it) and no sshd.
2. **The box** (as root on the box): copy the release tarball the container runs, the cartridge,
`infra/box/` and the public key there, then
`infra/box/fly-shadow-remote-setup flybrain-<version>.tar.gz <rom> id_ed25519.pub --from <container address> --cpus <its cores> --threads <one per core>`.
It installs the release at the same `/opt/fly/releases/<version>` path (MANIFEST-verified,
root-owned), a `flyshadow` user whose home is a root-owned `/srv/fly-shadow-remote-home` (so the
user cannot rename `.ssh`; the mirror `/srv/fly-shadow-remote` is the user's and is never
followed through a symlink on a re-run), a root-owned `authorized_keys` whose only line is
`restrict,command="/opt/fly/current/fly-shadow ingest --root /srv/fly-shadow-remote",from="…" <key>`,
`/etc/fly/fly-shadow-remote.env` (the box's `FLY_ROM`, `FLY_DATASET`), and
`flyshadow-remote.service` + `.path` (enabled). Put the box's host key into
`/etc/fly/shadow-remote/known_hosts` on the container (`ssh-keyscan` from the host, checked by
hand).
3. **The container's remote file**, `/etc/fly/shadow-remote.env` (root, 0600):
`FLY_SHADOW_REMOTE=flyshadow@<box address>`,
`FLY_SHADOW_REMOTE_KEY=/etc/fly/shadow-remote/id_ed25519`,
`FLY_SHADOW_REMOTE_KNOWN_HOSTS=/etc/fly/shadow-remote/known_hosts`
(and `FLY_SHADOW_REMOTE_PORT` if the box's sshd is not on 22). `fly-shadow-run start` finds
it and runs in remote mode.
4. `fly-shadow-run start` as above. **Then watch the live fly's realtime factor by hand for the
first hour** (`fly_realtime_factor` on the metrics endpoint): stop the shadow if its 30-minute
median is below 0.99. The guard's floor is a 5 % margin on the baseline and cannot see the
trace's cost (about 1.3 ms a frame, 2 to 3 %); on the rehearsal it tripped only by chance,
after an hour. The ingest refuses a relay whose release directory or binaries
differ from the box's (another release on the container: re-run step 2 with its tarball);
`journalctl -u flyshadow` on the container shows it.
Which box: never one on the live fly's NUMA node (flysim is memory-bandwidth-bound: in the
SHADOW-02 rehearsal an unpaced flysim on a neighbouring box of the same node took a paced one from
1.0 to 0.68-0.88). The shadow must also run clearly faster than real time (16.7 ms a frame) to
catch up after a restart; measured per frame (mean, unthrottled replay): 11.8 ms on the second
host's box with 4 threads, 11.9-12.2 ms on the build boxes of the release host's other node with
6 threads (13-14 ms with 3-4). Give it 4 cores (second host) or all 6 (same host, other node)
with `--cpus` and `--threads`; keep other heavy work (bx) off that box
for the 3 h (the shadow runs at `CPUWeight=1000`, `Nice=-5`).
## Cutover to the session runtime (CUT-01)
Operator decision (2026-09-30): the stream moves to the session runtime only if that runtime
sustains at least 1.0x real time on the release container, otherwise it stays on legacy. Only the
release container can measure that, so the switch is guarded by a **probation**. Claim the
container in the host log first, as for any host work.
```
# 1. Deploy v0.7.0 with flysim-session installed but NOT selected (no drop-in): the ordinary deploy.
# The container keeps running legacy; nothing else changes. (fly-runtime status: legacy)
# 2. Shadow, 3 h of brain time, zero divergence, guarded against live impact; on a build box
# (Remote shadow set-up above, once per box and release):
pct exec $CTID -- /opt/fly/bin/fly-shadow-run start
pct exec $CTID -- /opt/fly/bin/fly-shadow-run status # until: verdict pass
# 3. Cutover: the shadow's gate, then the switch. One command line:
pct exec $CTID -- sh -c '/opt/fly/bin/fly-shadow-run check && /opt/fly/bin/fly-runtime session'
# 4. Watch the probation (30 minutes after the switch):
pct exec $CTID -- /opt/fly/bin/fly-runtime-probation status
pct exec $CTID -- /opt/fly/bin/fly-runtime status
# 5. Pass, or automatic fallback (below). Nothing to stop: step 3 already stopped the shadow.
# Manual rollback, any time (cancels the probation too):
pct exec $CTID -- /opt/fly/bin/fly-runtime legacy
```
- **Step 3 in detail.** `check` refuses unless the verdict, the guard and the release all line
up (Shadow run above). `session` then does what "Switch the runtime" describes (compatibility
check, drop-in, restart, health wait) and, once flysim is healthy on the session runtime, starts
the probation. `session` returns 0 at that point: the probation is judged later, by the timer.
`session` also stops the shadow and its guard (`fly-shadow-run stop`, never
`--restart-flysim`) as soon as flysim is healthy on the session runtime, before the probation
starts. A guard left running would judge the session runtime against the legacy baseline and
restart flysim on a trip (a second start inside the 600 s start-limit window, and a reset
warm-up), and the session writes no trace, so the shadow has nothing to follow. If you stop the
shadow by hand at any time during the probation, do it without `--restart-flysim`.
- **The probation** (`infra/bin/fly-runtime-probation`, `fly-runtime-probation.timer` every 60 s,
root). Each tick takes one sample of flysim's `/metrics` (`fly_realtime_factor` averaged over 10
one-second reads, `fly_lag_seconds`, `fly_uptime_seconds`; the same sampling as the shadow
guard). It judges the session runtime only:
- *Warm-up.* A flysim process is not judged before it has been up 300 s (connectome load,
restore, first minutes). A restart, a pause or a fly that is not `running` starts the window
again; it is never counted as slow.
- *Failure*, sustained and not one sample: over the judged samples of the last 10 minutes (at
least 8 of them) the **median** realtime factor is below **0.97**, or the lag grew by more than
**30 s** from the window's start to its end (median of the first and of the last three
samples). The median is the robust statistic the shadow guard's baseline uses: one or two
stalled minutes do not fail it, a steady 0.85x does, at the earliest about 13 minutes after the
switch (5 min warm-up, 8 samples). A lag step of more than 30 s inside the window counts as
lag growth.
- *Pass*: 30 minutes since the switch, and the latest window is full and healthy. A probation
that cannot fill a window within 2 h (a fly that never runs) fails as inconclusive: no proof
of 1.0x, no cutover. `FLY_PROBATION_*` variables tune every number (tests and rehearsals only).
- **On failure** it runs `fly-runtime fallback "speed: ..."`, exactly the fallback of "Switch
the runtime": under the same lock, `/run/fly/runtime-fellback.json` with the reason
(`"speed: median realtime factor 0.850 < 0.97 ..."`), the drop-in removed, flysim restarted on
legacy, a `fly-runtime` journal line (`journalctl -t fly-runtime`,
`/var/lib/fly/runtime.log`), and the probation ended (`/var/lib/fly/probation/last.json`
says `passed: false`). If that fallback cannot complete (no executable `flysim`) it is retried
every minute. The container is then on legacy and the decision is "no cutover": do not retry
`session` without a fix (or a new measurement) for the cause.
- **On pass** it writes `/run/fly/runtime-probation.json` (`{"passed": true, "at", "startedAt",
"medianRtf", "lagGrowth", "samples", "detail"}`; also kept in
`/var/lib/fly/probation/last.json` because `/run` is cleared by a reboot) and disables its
timer. **Nothing judges the speed afterwards.** A continuous guard would make a passing
cutover fall back at 03:00 on one noisy hour, on a stream that has proven itself, and the
watchdog already covers a stuck or dead loop. The start-limit fallback also stays as it is.
- **Cancel and resume.** `fly-runtime legacy` cancels the probation, as does every fallback
(including the start-limit one), and a tick that finds the legacy runtime selected ends it
without a verdict. The state is `/var/lib/fly/probation/state.json` and the timer is enabled while
a probation runs (`[Install] WantedBy=timers.target`; nothing else enables it), so a reboot
during the probation resumes it: `OnBootSec=90s` runs the first tick, flysim's new process
starts a new warm-up and window, and the 30 minutes keep counting from the original switch.
`fly-runtime session --no-restart` (05-deploy's refresh of the drop-in) starts no probation;
`fly-runtime session --no-probation` is for rehearsals. A `session` that cannot start the
probation (helper or timer unit missing) falls back: an unguarded cutover is not allowed.
- **Reading the result honestly.** The probation is absolute, as decided: a container on which the
legacy loop itself runs below 0.97x (the release container has been measured at 0.66, and 0.77-0.99
after its cpuset rebalance) will fail it, and the session runtime was measured at 1.25-1.35x
legacy's time per frame on the dev box. A fallback with reason `speed` therefore means "this box
cannot hold real time on the session runtime", not necessarily "the session runtime is
broken"; compare with `fly-shadow-run`'s baseline (`/srv/fly/shadow/baseline.json`) before
anything else. The `check` before it measures the live fly against itself; this measures it
against the clock.
- **Rehearsal** without a host: `fly-runtime-probation simulate CHECKS.jsonl` runs the rule over
recorded samples (`{t, status, rtMean, lag, uptime}`, one a minute); `infra/tests/lint.sh` drives
the real `fly-runtime` and the probation over synthetic traces (healthy, 0.85x, a stall, lag
growth, a restore, a restart, legacy cancel), and the unit wiring has been run under a real
systemd 257 user manager (state, timer enable/disable, `OnFailure`-style fallback, resume).
## Control over the bus (CTRL-01)
`FLY_CONTROL_VIA` picks who serves `http://127.0.0.1:7401`: `direct` (the default; flysim binds
it) or `bus`. In bus mode flysim registers the control API as RPC services on its embedded flybus
router, and `flycontrol-edge.service` serves the same HTTP bytes on `:7401` by calling them
(`docs/design/flybus.md`, "Control over the bus"). Clients do not change: the bridge, the stage's
health wait, the watchdog, `fly-runtime`, the probation and shadow guards, `fly-loop-recover`,
the stream check and `curl` still talk to `:7401`. It works under either runtime, independently
of `FLY_FEED_VIA`. Claim the container in the host log first, as for any host work.
**Prerequisites.** The release ships `fly-control-edge` (`ls /opt/fly/current/fly-control-edge`).
The env file has `FLY_CONTROL_VIA=bus`, deployed with `05-deploy.sh`. The deploy only rewrites
`/etc/fly/fly.env` and pushes the unit; it neither enables the edge nor restarts flysim, so the
box keeps serving `:7401` directly until step 2.
```
# 1. Before: what the switch must preserve.
pct exec $CTID -- grep -E '^FLY_(CONTROL|FEED)_VIA=' /etc/fly/fly.env # FLY_CONTROL_VIA=bus
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status, .checkpoint'
pct exec $CTID -- curl -s -X POST 127.0.0.1:7401/checkpoint # a fresh generation to restart from
# 2. The switch: flysim stops binding :7401 and registers the services; the edge (Wants= of
# flysim.service, started with it because fly.env says bus) binds :7401 once they answer.
# Between the two, :7401 refuses connections, exactly as during any flysim restart.
# There is nothing to enable: the unit has no [Install] section.
pct exec $CTID -- systemctl restart flysim.service
# 3. Verify.
pct exec $CTID -- ss -ltnp | grep ':7401' # users:(("fly-control-edg"...
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz # {"status":"ok"}
pct exec $CTID -- curl -s 127.0.0.1:7401/status | jq '.frame, .status' # the frame moves
pct exec $CTID -- curl -s 127.0.0.1:9103/metrics | grep -E '^fly_control_edge_(bus_connected|calls_total|call_failures_total)'
pct exec $CTID -- journalctl -u flysim -b --since -5min | grep -E 'control services registered|bus listening'
pct exec $CTID -- ls /run/fly/bus/control-edge.sock /run/fly/bus/control/
pct exec $CTID -- curl -s 127.0.0.1:7410/health | jq . # the bridge: sim reachable
```
- **Healthy looks like:** `fly_control_edge_bus_connected 1`, `calls_total` rising (the bridge and
the watchdog poll it), `call_failures_total` flat, no `fly-watchdog:` restart lines, and the next
real channel-points sugar fulfilled as before. Do not fire a test sugar or chat line on the live
stream to prove it; both are visible on screen.
- **Watchdog.** With `FLY_CONTROL_VIA=bus`, check 1 reads flysim's own `/healthz` on `:9101`, so a
dead edge never restarts the fly. Check 1b restarts `flycontrol-edge` alone when `:7401` fails
while flysim is healthy (the sudoers file grants exactly that restart).
- **Restarts.** `flysim.service` has `Wants=flycontrol-edge.service` and the edge has `Requires=`
on flysim plus an `ExecCondition=` on `FLY_CONTROL_VIA`, so the edge follows flysim in bus mode
and stays off ("skipped", not failed) in direct mode. A `restart`, and a `stop` then `start`
(`fly-loop-reset`, `fly-reset-to-milestone`, the milestone-reset rung of the unstick rule) all
bring `:7401` back with flysim; nothing needs a separate `start` of the edge. A crash-restart of flysim needs nothing: the edge
unbinds `:7401`, reconnects every 500 ms and binds again once the new services answer.
**Rollback** (any time, no release change):
```
pct exec $CTID -- sed -i 's/^FLY_CONTROL_VIA=.*/FLY_CONTROL_VIA=direct/' /etc/fly/fly.env
pct exec $CTID -- systemctl restart flysim.service # binds :7401 itself; the edge is skipped
pct exec $CTID -- curl -s 127.0.0.1:7401/healthz
# then set FLY_CONTROL_VIA=direct in the env file too, or the next 05-deploy.sh writes bus back.
```
- **Rolling back to a release from before CTRL-01 while in bus mode** is safe. The older flysim
does not know `FLY_CONTROL_VIA`, so it binds `:7401` itself. The edge unit's
`ConditionPathExists=` keeps it inactive on a release without the binary, and the older
watchdog reads `:7401` as before. Switch to direct first anyway, so the env file says what
runs.
- **If the edge cannot bind** (`fly_control_edge_bind_failures_total` rising, "the control port
cannot be bound" in its journal), flysim is still in direct mode. `fly.env` says bus but flysim
was not restarted after the deploy. Restart flysim (step 2).
- **Upgrading a container that had the edge enabled** (before this wiring): an
old `fly.target.wants/flycontrol-edge.service` symlink is harmless (the condition decides), but
run `systemctl disable flycontrol-edge.service` once so `systemctl is-enabled` says what is true.
## CPU partition (cpuset) ## CPU partition (cpuset)
`05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit `05-deploy.sh` derives the in-guest `AllowedCPUs=` drop-ins for every app unit
@ -473,6 +1098,78 @@ not a constant, and live in the operator's infra repo
ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh` ENCODER_CORES` reproduces the split from those three numbers; `infra/tests/lint.sh`
checks it against both the current shape and the earlier, narrower one. checks it against both the current shape and the earlier, narrower one.
### The sim's CPUs are exclusive to the sim (PERF-02 review N1)
The session runtime pins its sweep workers one per CPU. A pinned worker cannot leave its CPU, so
any sustained CPU-bound process that is allowed on a worker's CPU stalls every barrier: measured
**0.14x real time** with a plain busy loop (0.68x at nice 19; `SCHED_IDLE` was harmless; the
floating, unpinned runtimes held 0.86-0.94x under the same hog). Priorities cannot fix that, so
the partition above is completed by making the sim's CPUs exclusive:
- `flysim.service` and `flysim-session.service` run in **`flysim.slice`** (`units/flysim.slice`),
whose `AllowedCPUs=` is the sim's set (`flysim.slice.d/cpuset.conf`, written by `05-deploy.sh` from
`lib/common.sh`'s `cpuset_dropin_plan`, the same call that writes every other drop-in).
- `bin/fly-cpu-confine apply` sets `AllowedCPUs=` the **non-sim** CPUs on `system.slice` (every
other service, cron, apt, sshd), `user.slice` (every login session) and `init.scope`, and writes
the same list to `/sys/fs/cgroup/.lxc/cpuset.cpus` (where `pct exec` / `pct enter` processes land,
see below). It runs as
both sim units' `ExecStartPre` (root, failure never blocks the start), so it is re-applied after
every boot and every restart. The lists come from `/etc/fly/cpuset.env`, which the deploy writes.
- The slice is named without a dash on purpose: systemd nests `a-b.slice` under `a.slice`, and a
child's cpuset is bounded by its parent's (cgroup v2: effective cpus = own cpus intersected with
the parent's, and the parent's when that is empty). `flysim.slice` sits beside `system.slice`
under the root slice, so nothing above it excludes its CPUs.
- **Ordering rule.** Shrinking `system.slice` under a flysim that still sits in `system.slice` (a
unit started before this change, not yet restarted) would leave its own `AllowedCPUs=` outside the
parent's set and silently make it float over the page CPUs. So `apply` refuses (exit 3, nothing
changed) while a sim unit's cgroup is not under `/flysim.slice/`. A deploy therefore changes
nothing on a running sim; the confinement starts with the next `flysim` (re)start, which is the
first moment it is safe. `fly-cpu-confine status` shows the result.
- `fly-recap` and `fly-retention` also run at `CPUSchedulingPolicy=idle`, which the review measured
harmless beside the pinned workers (defence in depth for the batch jobs).
- **No partition, no pinning.** With `CPUSET` unset (or the container conf not matching it) there
is no confinement, so `05-deploy.sh` writes `FLY_SESSION_PIN=0` to `/etc/fly/fly.env` and the
session runtime's threads float, as before PERF-02. With the partition in force it writes
`FLY_SESSION_PIN=1`. (The runtime treats exactly `0` as off.)
- **`pct exec` / `pct enter`:** `lxc-attach` puts its processes in the cgroup `/.lxc` (or
`/.lxc-N`), a sibling of `system.slice` that systemd does not manage. `apply` writes the non-sim
list into the `cpuset.cpus` of every such cgroup that already exists (it never creates one; lxc
owns it). Where that file is not writable it logs a warning and carries on: `apply` never fails
the sim's start. In that case run long operator jobs through
`pct exec <ctid> -- systemd-run --scope --slice=system.slice -- <command>`. A `.lxc-N` created
after `apply` is not covered until the next sim start. `fly-cpu-confine check` lists every
process outside `flysim.slice` that may run on a sim CPU (exit 1 if there is one); its own
process and the shell chain it was started from are printed as a note and not counted, so it
exits 0 on a healthy container when run through `pct exec`.
- **After the first deploy (once):** restart the sim so the confinement is applied, then read it.
`apply` is refused while flysim still runs outside `flysim.slice`, so nothing changes until then.
```
pct exec <ctid> -- systemctl restart flysim.service
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine status # system.slice, user.slice, init.scope and /.lxc = the non-sim cpus; flysim.slice = the sim's; flysim ControlGroup under /flysim.slice/
pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine check # exit 0: "ok: only flysim.slice can reach ..."
pct exec <ctid> -- systemctl show -p AllowedCPUs flycast.service xvfb.service # still the drop-in values
```
Then watch the probation RTF. A `check` that names a process is a hog to move or stop.
- **If lag grows on the session runtime**: `fly-cpu-confine check`, then `top -H` for a stray hog on
the sim's CPUs. `FLY_SESSION_PIN=0` (a drop-in) restores floating.
- `fly-cpu-confine release` undoes the runtime confinement (until the next sim start); it sets
`system.slice`, `user.slice`, `init.scope` and `/.lxc` back to the container's whole cpuset
explicitly, because systemd keeps the old mask for an empty `AllowedCPUs=` while the cpuset
controller stays on for another unit. (Tested in `tests/lint.sh` against a fake cgroup tree.)
- **Rollback by re-running an older infra tree's `05-deploy.sh`** (rather than the symlink flip in
"Roll back a release", which is fine): an infra tree older than this change has no
`Slice=flysim.slice`, so flysim restarts into `system.slice`, which is still confined to the
non-sim CPUs. Its `AllowedCPUs=` then does not intersect that set and it floats over the page and
encoder CPUs while the sim's own CPUs sit idle (the slow shape again, not a black stream). After
such a rollback run `pct exec <ctid> -- /opt/fly/bin/fly-cpu-confine release` (or reboot), then
restart flysim.
Verified on a real-systemd box (4 CPUs, the sim as a unit in `flysim.slice` on 3 of them, 3 sweep
threads, paced at 0.55x): confined or not, with no hog the session holds 0.55; five busy loops (three
as system services, two from a user shell) unconfined sit on the sim's CPUs and the session drops to
0.37; confined by the unit's own `ExecStartPre`, every loop samples on CPU 0 only, the sim's threads
keep their CPUs and the session holds 0.54-0.55.
### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition ### `FLY_LIF_CUDA` — the LIF tick on the GPU, and what it does to the partition
`FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into `FLY_LIF_CUDA=1` in an env file makes `05-deploy.sh` write `FLY_LIF_CUDA=1` into
@ -485,13 +1182,49 @@ loud which backend is configured. Two separate switches, deliberately:
| build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed | | build | `FLY_CARGO_FEATURES=cuda` | `build-flysim.sh` | the backend is *compiled in*, `libcuda` still only `dlopen`ed |
| run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* | | run | `FLY_LIF_CUDA=1` | the env file → `/etc/fly/fly.env` | the backend is *attached* |
A binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the A `flysim` binary without the feature ignores `FLY_LIF_CUDA=1` **silently**, so confirm the
backend from flysim's own log, not from the env file: backend from flysim's own log, not from the env file:
```sh ```sh
pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend' pct exec <ctid> -- journalctl -u flysim -b --no-pager | grep -i 'cuda\|lif backend'
``` ```
The session runtime (`flysim-session`, `fly-shadow`, GPU-02) reads the same two variables
(`FLY_LIF_CUDA`, `FLY_LIF_CUDA_DEVICE`, a device ordinal) in its agent worker. A build without
the feature that is asked for the GPU is a misconfiguration and fails `Agent.Initialize` with
`BACKEND_FAILURE`; a build with it logs `LIF backend cuda:<n> attached, device-owned state` when
the worker starts. It steps one game frame per GPU call and keeps `membrane` and `refractory` on the
card, copying them back only for a checkpoint, so per frame only the inputs (noise draws, visual
drive, plastic gains, about 110 KB) go up and the spike lists come down. Build all binaries with the
feature: `FLY_CARGO_FEATURES=cuda` now reaches `flysim-session`, `fly-shadow` and `fly-session` too.
**A GPU failure falls back to the CPU and the stream keeps going** (operator, 2026-10-02; no
paging). The first failure makes the GPU unusable for that process's lifetime, so nothing re-attaches
a dead card in a loop:
- A CUDA error on a frame whose host state was current (the first frame after a start or a
restore) finishes that frame on the CPU in place, bit-exact, and the agent goes on there.
- Any other CUDA error mid-run fails the agent (the device held the only current copy of the
membrane). Recovery restores the last checkpoint into a **replacement worker, which is created on
the CPU**, and replays from there. Checkpoints are backend-neutral and the GPU tick is bit-exact,
so the CPU run equals one that never had a GPU.
- A CUDA init that fails (a lost device, or a driver that is gone after a restart) is a warning and
a CPU worker, not a failed `Agent.Initialize`.
- The fallback lasts until `flysim.service` restarts, which tries the card again; if it is still
dead, that attach is another fallback. Restart is therefore also the way back onto a repaired GPU.
Where it shows: the journal line `LIF_GPU_FALLBACK: the GPU is unusable ...` (once per failure,
with the reason); `fly_brain_backend{backend="cpu|cuda"}` (1 on the backend that runs),
`fly_brain_backend_wanted` and `fly_brain_backend_fallbacks_total`, written by the worker to the
textfile `FLY_BRAIN_BACKEND_PROM` points at (the deploy sets it beside `fly_encoder.prom`); and
`fly-watchdog` check 11, which logs `GPU backend degraded:` and raises
`fly_watchdog_backend_degraded` when `FLY_LIF_CUDA=1` asks for the card and the CPU is running. It
takes no remediation and pages no one (a restart cannot fix a dead card and would cost the
run a rollback); look at `journalctl -u flysim | grep LIF_GPU_FALLBACK`, `nvidia-smi` on the host,
and the driver-lockstep section below. The CPU run is slower per thread count, so `RAYON_THREADS=2`
(see below) is below real time on the CPU: after a fallback, set it back to 3 with `FLY_LIF_CUDA=0`
and redeploy if the card is not coming back soon.
It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the It needs `GPU=1` (the `/dev/nvidia*` device block plus the userspace driver in the
container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX container — `docs/design/gpu.md` sections 1 and 2) and the card the committed PTX
targets, `sm_75`. targets, `sm_75`.
@ -603,13 +1336,17 @@ pct exec <ctid> -- cat /run/fly/wd/loop.json | jq .
| `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window | | `fly_loop_blocked` | macros that ended `blocked` or `timeout` in the window |
| `fly_loop_done` | macros that ended `done` in the window | | `fly_loop_done` | macros that ended `done` in the window |
| `fly_loop_rewards` | reward events in the window | | `fly_loop_rewards` | reward events in the window |
| `fly_loop_fights` | `MOVE n` decisions (a move chosen in a battle) in the window |
| `fly_loop_wins` | battle-won reward events (`wildwin`, `trainer`, `badge`) in the window |
The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+ The flag needs **both** halves: at most 3 distinct macro names with the block repeating 20+
times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused, times, one macro at 95%+ of the window's decisions, 90%+ of 20+ decisions ending refused,
blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row blocked or timed out (`stalled`), or decisions with no `done` among them on two probes in a row
(`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row (`zero-progress`), or 100+ decisions with no reward event among them on two probes in a row
(`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other (`unrewarded`, row 58: `GO OBJECTIVE` in and `GO OUT` out of one door, diluted by eight other
names, every macro `done`) — **and** no growth in the exploration count. A decision is a `start` or a names, every macro `done`), or 24+ `MOVE n` decisions and no battle won on two probes in a row
(`unwon-battles`, row 67: one Pewter Gym trainer lost thirty times, whiteout and back, with a
stray tile reward now and then keeping `unrewarded` quiet) — **and** no growth in the exploration count. A decision is a `start` or a
`refused`: a refused press starts nothing, which is why counting starts alone read row 57's `refused`: a refused press starts nothing, which is why counting starts alone read row 57's
pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and pad (`GO ROUTE refused` ~740 times in ten brain minutes, `macros-traps.md`) as one start and
one name. A one name. A
@ -726,6 +1463,50 @@ The card is shared with **the neighbouring GPU container (`ml`, the GPU workload
mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let mode stays `Default`; never set `nvidia-smi -c EXCLUSIVE_PROCESS`, which would let
whichever container got there first lock the card out from under the other. whichever container got there first lock the card out from under the other.
## GPU on a build box (dev and benchmarks)
A build box is a container with the host's `/dev/nvidia*` device nodes passed through but no
userspace driver installed — used for the `cuda` feature tests and the GPU benchmarks. The
release container follows the lockstep runbook above; this path is only for build boxes,
no root, no system install, one userspace per test run.
**Get the host's module version** — the .run must match exactly:
```sh
ssh the host cat /proc/driver/nvidia/version # the "Kernel Module" line
# or: ssh the host cat /sys/module/nvidia/version
```
**Install under your home.** Download the matching `NVIDIA-Linux-x86_64-<ver>.run`, verify
its SHA256 against the checksum NVIDIA publishes, and `--extract-only`:
```sh
VER=580.76.05 # whatever the host module reports
mkdir -p ~/tmp/nvidia-$VER && cd ~/tmp/nvidia-$VER
U=https://download.nvidia.com/XFree86/Linux-x86_64/$VER/NVIDIA-Linux-x86_64-$VER.run
curl -fSLO $U && curl -fSLO $U.sha256sum
sha256sum -c NVIDIA-Linux-x86_64-$VER.run.sha256sum # must print OK
sh NVIDIA-Linux-x86_64-$VER.run --extract-only --target ~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
```
**Use it only for the test run.** Prepend the extracted directory to `LD_LIBRARY_PATH`
(`libcuda.so`, `libnvidia-ptxjitcompiler.so`) and `PATH` (`nvidia-smi`); the kernel
modules are the host's, so nothing else is needed:
```sh
NV=~/tmp/nvidia-$VER/NVIDIA-Linux-x86_64-$VER
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH FLY_CARGO_FEATURES=cuda \
cargo test --release -p flybrain-core --features cuda
LD_LIBRARY_PATH=$NV:$LD_LIBRARY_PATH PATH=$NV:$PATH \
cargo run --release -p flybrain-core --features cuda --example cuda_bench
```
**Shared card.** The build box shares the GPU with the LLM workload. Before and after each
timing run, `nvidia-smi` for other compute processes on the device; re-run flagged timings
(benchmarks yield to the other workload — a contended run is not a measurement).
**Never on the release container** — that path is the lockstep one above.
## The host reboot order ## The host reboot order
Fly containers have no special reboot ordering requirement relative to each other Fly containers have no special reboot ordering requirement relative to each other

View file

@ -49,7 +49,7 @@ a credential. Full list:
| # | shape matched | path | commits (first → last touching) | verdict | | # | shape matched | path | commits (first → last touching) | verdict |
| --- | --- | --- | --- | --- | | --- | --- | --- | --- | --- |
| 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/fly-pokemon-key`), not a secret. | | 1 | `pass show "$PASS_KEY"` shell pipelines, 4 blobs | `infra/06-secrets.sh` | `0d1a762` → `69816e6` | **False positive.** The script's whole job is to pipe `pass show` into `systemd-creds` on the container; the value never lands in a file and never in git. `PASS_KEY` holds a pass *entry name* (`twitch/<channel>-key`), not a secret. |
| 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. | | 2 | `pass show … \| head -c8` in a verify helper, 6 blobs | `infra/verify.sh` | `0d1a762` → `57276d4` | **False positive.** Reads the first 8 bytes of the stored key to compare a prefix against what the container holds. The prefix is computed at run time and printed nowhere that is committed. |
| 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. | | 3 | `accessToken:` / `refreshToken:` struct fields, 3 blobs | `services/bridge/src/auth.ts` | `d9f00b6` → `48cd40a` | **False positive.** Twurple `AccessToken` field names in code (`accessToken: token.accessToken`). No literal values. |
| 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. | | 4 | `accessToken:` / `refreshToken:` struct fields, 1 blob | `services/bridge/tools/authorize.mts` | `77f5892` | **False positive.** Same: the interactive authorize tool writes the token it just fetched to a path outside the repo. |

4
infra/env/README.md vendored
View file

@ -53,6 +53,8 @@ requires `CTID`, `HOSTNAME`, `IP`, `GAME` and `PUSH_TARGET`; `ROLE` defaults to
Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app Secrets. `PASS_KEY` holds the **name** of a `pass` entry, never a key. The Twitch app
id/secret arrive as the systemd credential `twitch-app`, installed by id/secret arrive as the systemd credential `twitch-app`, installed by
`infra/06-secrets.sh` from `pass` on the operator box; the OAuth tokens live in the `infra/06-secrets.sh` from `pass` on the operator box, reading the two entry **names** from
`BRIDGE_ID_KEY` and `BRIDGE_SECRET_KEY` in the real env file (it skips `twitch-app` with a
warning when they are unset); the OAuth tokens live in the
container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and container as `/var/lib/flybridge/tokens.json`, mode 0600. `ROM_SHA256` is a digest, and
the ROM it describes is never committed, copied into the repo, or shown on stream. the ROM it describes is never committed, copied into the repo, or shown on stream.

37
infra/env/example.env vendored
View file

@ -138,6 +138,12 @@ RAYON_THREADS=3
# cpuset_partition (default 2 when unset). flycast gets its own group rather # cpuset_partition (default 2 when unset). flycast gets its own group rather
# than sharing the page group — see lib/common.sh's cpuset_partition header. # than sharing the page group — see lib/common.sh's cpuset_partition header.
ENCODER_CORES=2 ENCODER_CORES=2
# SESSION_AUX_CPUS: how many page cpus (taken from the end of the page group) flysim.slice gets in
# addition to the sim's, for the session runtime's bus threads (the feed publisher and router when
# FLY_FEED_VIA / FLY_CONTROL_VIA is bus). The sweep and its dispatcher never use them, the page and the
# encoder never see them. Default 0 (none): the bus threads then share the sim's host cpu, which costs
# +1 to 2 ms per frame (EDGE-02 review N1). Set 1 on a partitioned container before `fly-feed bus`.
SESSION_AUX_CPUS=0
# --- CUDA LIF backend ------------------------------------------------------- # --- CUDA LIF backend -------------------------------------------------------
# 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what # 1 makes 05-deploy.sh write FLY_LIF_CUDA=1 into /etc/fly/fly.env, which is what
@ -216,6 +222,11 @@ TWITCH_CHANNEL=<twitch-channel>
# never is. 06-secrets.sh reads it on the operator box and installs it as a # never is. 06-secrets.sh reads it on the operator box and installs it as a
# systemd credential. # systemd credential.
PASS_KEY=twitch/<channel>-key PASS_KEY=twitch/<channel>-key
# The `pass` entries holding the Twitch app client id and secret (names only).
# 06-secrets.sh installs them together as the twitch-app credential; unset means
# it skips twitch-app with a warning.
BRIDGE_ID_KEY=twitch/<app>-client-id
BRIDGE_SECRET_KEY=twitch/<app>-client-secret
# --- flybridge (services/bridge/src/config.ts) ------------------------------ # --- flybridge (services/bridge/src/config.ts) ------------------------------
# 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads # 05-deploy.sh writes these into /etc/fly/fly.env, which flybridge.service reads
@ -316,9 +327,21 @@ FLY_MACRO_MODE=raw
# Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the # Who serves ws://127.0.0.1:7400/feed (docs/design/flybus.md, "Feed over the
# bus"). direct: flysim binds it, as always. bus: flysim publishes every # bus"). direct: flysim binds it, as always. bus: flysim publishes every
# snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves # snapshot on its embedded feed bus (/run/fly/bus) and flyedge.service serves
# the same bytes; enable that unit by hand (its header has the steps). # the same bytes. This line (written into fly.env by every deploy) is the only
# Watchdog check 2 follows this setting to the edge's counters by itself. # switch: flysim.service wants the edge, which starts only in bus mode.
# On a live container switch with `fly-feed bus` / `fly-feed direct` (restarts
# flysim, checks the page is back, rolls back by itself) and put the same value
# here afterwards, or the next deploy warns that it writes the old one back.
# Watchdog check 2 follows the running mode to the edge's counters by itself.
# Runbook: "Feed over the bus".
FLY_FEED_VIA=direct FLY_FEED_VIA=direct
# --- control path -------------------------------------------------------------
# Who serves http://127.0.0.1:7401 (docs/control-api.md; docs/design/flybus.md,
# "Control over the bus"). direct: flysim binds it, as always. bus: flysim
# registers the control services on its embedded bus (/run/fly/bus) and
# flycontrol-edge.service serves the same bytes; enable that unit by hand
# (infra/docs/runbook.md, "Control over the bus"). Independent of FLY_FEED_VIA.
FLY_CONTROL_VIA=direct
# How long a macro leaves a target alone after a walk to it aborted "blocked" or # How long a macro leaves a target alone after a walk to it aborted "blocked" or
# "timeout" (macros.md section 12.1). Session state, so a restart offers every # "timeout" (macros.md section 12.1). Session state, so a restart offers every
# target once more. Unset means the default, 10. # target once more. Unset means the default, 10.
@ -335,9 +358,13 @@ FLY_FEED_VIA=direct
# two strings AND the new build's adapter declares a migration from that one. A # two strings AND the new build's adapter declares a migration from that one. A
# dataset, kernel, plasticity, emulator or state-format difference is still a # dataset, kernel, plasticity, emulator or state-format difference is still a
# refusal. Set it for the one deploy that needs it and leave it out afterwards; # refusal. Set it for the one deploy that needs it and leave it out afterwards;
# 05-deploy writes it into /etc/fly/fly.env only while it is set. The v0.6.0 # 05-deploy writes it into /etc/fly/fly.env only while it is set. The deploy
# deploy (pokered-unique8-v7, the engagement rewards) is the one that needs: # of pokered-unique8-v8 (the damage reward) over the live v7 run needs:
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v6 # FLY_ACCEPT_ADAPTERS=pokered-unique8-v7
# and, to keep the milestone archives written before v0.6.0 restorable as
# fallbacks and fly-reset-to-milestone targets, also names v6 (v8 reads both):
# FLY_ACCEPT_ADAPTERS=pokered-unique8-v7,pokered-unique8-v6
# (v0.6.0's, pokered-unique8-v7 over v6, needed pokered-unique8-v6.)
# --- push mode -------------------------------------------------------------- # --- push mode --------------------------------------------------------------
# local: flypush.service stays disabled, everything else identical to prod. # local: flypush.service stays disabled, everything else identical to prod.

View file

@ -168,6 +168,19 @@ feed_via_normalize() {
esac esac
} }
# control_via_normalize VALUE — FLY_CONTROL_VIA as feed_via_normalize does FLY_FEED_VIA:
# lowercased (empty means "direct"), or return 1 for anything but direct|bus. flysim refuses
# anything else at boot; 05-deploy.sh refuses it at deploy and writes the lowercased word, which
# the watchdog reads to know who serves :7401 (docs/design/flybus.md, "Control over the bus").
control_via_normalize() {
local via
via="$(printf '%s' "${1:-direct}" | tr '[:upper:]' '[:lower:]')"
case "$via" in
direct|bus) printf '%s\n' "$via" ;;
*) return 1 ;;
esac
}
cpuset_partition() { cpuset_partition() {
local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}" local cpuset="$1" rayon_threads="$2" encoder_cores="${3:-2}"
local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus local sim_cpus remainder remainder_count page_count page_cpus encoder_cpus
@ -189,6 +202,69 @@ cpuset_partition() {
echo "$sim_cpus $page_cpus $encoder_cpus" echo "$sim_cpus $page_cpus $encoder_cpus"
} }
# cpuset_aux_split PAGE_CPUS COUNT — take the LAST COUNT cpus of the page group for flysim's
# auxiliary threads (EDGE-02 review N1: the bus runtime, which must not share the sim's
# dispatcher cpu). Echoes "PAGE_REST AUX"; dies if that would leave no page cpu.
cpuset_aux_split() {
local page="$1" count="$2" n
n="$(echo "$page" | awk -F, '{print NF}')"
if [ "$count" -ge "$n" ]; then
die "cpuset_aux_split: SESSION_AUX_CPUS=${count} leaves no page cpu out of '${page}'. Widen CPUSET or lower SESSION_AUX_CPUS."
fi
echo "$(echo "$page" | cut -d, -f1-"$(( n - count ))") $(echo "$page" | cut -d, -f"$(( n - count + 1 ))"-)"
}
# cpuset_dropin_plan CPUSET RAYON_THREADS [ENCODER_CORES] [AUX_COUNT] — print one "UNIT-NAME CPUS" line for every
# AllowedCPUs= drop-in 05-deploy.sh writes (UNIT-NAME includes its suffix, e.g. flysim.service,
# flysim.slice), and then the two lines that name the confinement lists for bin/fly-cpu-confine:
#
# flysim.slice the sim's CPUs plus AUX_COUNT page cpus (default 0) taken from the end of the
# page group for flysim's bus threads, exclusive to flysim like the rest (flysim.service and flysim-session.service run in it);
# flysim.service, flysim-session.service the same set (belt and braces: a unit outside the
# slice is still bounded);
# xvfb, flystage, flystage-web, pulse, mediamtx, flyedge, flycontrol-edge the page CPUs;
# flycast the encoder CPUs;
# flyshadow page + encoder (never the sim's);
# FLY_AUX_CPUS= only with AUX_COUNT > 0: the aux cpus (fly.env's FLY_SESSION_AUX_CPUS);
# FLY_SIM_CPUS / FLY_OTHER_CPUS "=": the lists /etc/fly/cpuset.env carries; OTHER is every CPU
# of CPUSET that is not the sim's, in CPUSET order.
#
# One function so the deploy and infra/tests/lint.sh cannot disagree about the plan. Dies like
# cpuset_partition does.
cpuset_dropin_plan() {
local cpuset="$1" rayon="$2" encoder="${3:-2}" aux_count="${4:-0}" sim page enc u aux="" slice_cpus
local out
out="$(cpuset_partition "$cpuset" "$rayon" "$encoder")" || return 1
read -r sim page enc <<< "$out"
if [ "$aux_count" -gt 0 ]; then
# not `read <<< "$(...)"`: die inside the substitution would only end the subshell
out="$(cpuset_aux_split "$page" "$aux_count")" || return 1
read -r page aux <<< "$out"
fi
slice_cpus="$sim"
[ -n "$aux" ] && slice_cpus="${sim},${aux}"
echo "flysim.slice $slice_cpus"
for u in flysim flysim-session; do echo "${u}.service $slice_cpus"; done
for u in xvfb flystage flystage-web pulse mediamtx flyedge flycontrol-edge; do echo "${u}.service $page"; done
echo "flycast.service $enc"
echo "flyshadow.service ${page},${enc}"
echo "FLY_SIM_CPUS= $slice_cpus"
echo "FLY_OTHER_CPUS= ${page},${enc}"
[ -n "$aux" ] && echo "FLY_AUX_CPUS= $aux"
return 0
}
# cpuset_dropin_text UNIT-NAME CPUS ENV_LABEL — the AllowedCPUs= drop-in 05-deploy.sh converges to
# /etc/systemd/system/UNIT-NAME.d/cpuset.conf ([Slice] for a .slice, [Service] otherwise).
cpuset_dropin_text() {
local unit="$1" cpus="$2" label="$3" section="Service"
case "$unit" in *.slice) section="Slice" ;; esac
echo "# generated by infra/05-deploy.sh from CPUSET in ${label} — do not hand-edit."
echo "# infra/README.md step 4 and infra/docs/p0-measurements.md run 2 measurement 4."
echo "[${section}]"
echo "AllowedCPUs=${cpus}"
}
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------
# operator-box guard # operator-box guard
# --------------------------------------------------------------------------- # ---------------------------------------------------------------------------

View file

@ -1,33 +1,32 @@
# infra/tests/de-pii-allow.txt — the mentions infra/tests/lint.sh's de-PII # infra/tests/de-pii-allow.txt — the mentions tools/pii-scan.sh (run by
# guard (section 5) is allowed to find. # infra/tests/lint.sh section 5, infra/build/tag-release.sh and the pre-push hook)
# is allowed to find.
# #
# Format, whitespace-separated: # Format, whitespace-separated:
# #
# <path> <pattern-name> # reason # <path> <pattern-name> # reason
# #
# <path> is a repo-relative path, a directory prefix ending in `/`, or a glob. # <path> is a repo-relative path, a directory prefix ending in `/`, or a glob.
# <pattern-name> is one of the guard's own names (host-proxmox, host-backup, # <pattern-name> is a pattern name: a generic one from tools/pii-scan.sh
# host-llm, operator-name, lan-address, container-id, host-root-path, # (`tools/pii-scan.sh --list`), one from the operator's private pattern list
# home-path, twitch-account, claim-log-name, forge-name, infra-repo-name, # (operator-name, forge-name, ...), or `*` for every pattern.
# mac-address, email-address, pass-entry-path), or `*` for every pattern.
# #
# EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead — # EVERY LINE NEEDS A REASON. The right fix is almost always to redact instead —
# the rules and the per-file verdicts live in the operator's infra repo. # the rules and the per-file verdicts live in the operator's infra repo.
# An entry here says "this string is not identifying", not "this is grandfathered". # An entry here says "this string is not identifying", not "this is grandfathered".
# #
# The literals in the comments below are spelled with one bracketed character, for # Comments below describe what a mention is, never the private string itself: an
# the same reason lint.sh spells its patterns that way: an allowlist that carried the # allowlist that carried the plaintext would be the leak it is meant to prevent.
# plaintext would be the leak it is meant to prevent.
# --- chat-username fixtures ------------------------------------------------- # --- chat-username fixtures -------------------------------------------------
# Lowercase `"alex"` is the chat-username fixture the sanitizer, deny-list, # A lowercase first name is the chat-username fixture the sanitizer, deny-list,
# rate-limiter, ticker and store tests are written against; the de-PII sprint # rate-limiter, ticker and store tests are written against; the de-PII sprint
# leaves test fixture names alone. The guard's operator-name pattern is # leaves test fixture names alone. The operator-name pattern is case-sensitive
# case-sensitive precisely so capitalised `Al[e]x` in prose still fails, and # precisely so the capitalised name in prose still fails, and the real handle
# `al[e]x_camilo` (the real handle shape) was replaced with `fly_fan_42`. These # was replaced with `fly_fan_42`. These entries exist only for the few places a
# entries exist only for the few places a fixture is lowercase-with-a-boundary # fixture is lowercase-with-a-boundary that the pattern would still catch via
# that the case-sensitive pattern would still catch via another alternative. # another alternative.
apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures apps/stage/tests/unit/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures services/flysim/crates/flysim/tests/ operator-name # lowercase chat-username fixtures
services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file services/flysim/crates/flysim/src/chat.rs operator-name # sanitizer unit-test fixtures in the same file
@ -35,12 +34,12 @@ services/flysim/crates/flysim/src/eventlog.rs operator-name # ticker fixture in
services/bridge/tests/ operator-name # lowercase chat-username fixtures services/bridge/tests/ operator-name # lowercase chat-username fixtures
# --- container-side paths --------------------------------------------------- # --- container-side paths ---------------------------------------------------
# `/ro[o]t/nvidia.run`, `/ro[o]t/virtualgl.deb` and `/ro[o]t/nv.run` are paths INSIDE # `nvidia.run`, `virtualgl.deb` and `nv.run` under root's home are paths INSIDE
# a container: root's home on a stock Debian guest, not an operator-chosen # a container: root's home on a stock Debian guest, not an operator-chosen
# location, and not specific to this network. Host-side staging paths are # location, and not specific to this network. Host-side staging paths are
# parameterised instead (HOST_STAGE_DIR / `<host-stage>`). # parameterised instead (HOST_STAGE_DIR / `<host-stage>`).
infra/02-base.sh host-root-path # /ro[o]t/nvidia.run and /ro[o]t/virtualgl.deb are inside the guest infra/02-base.sh host-root-path # the two installer paths under root's home are inside the guest
docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ro[o]t/... which is procfs, not /root docs/design/gpu.md host-root-path # same two paths, plus /proc/<pid>/ root links, which are procfs
# --- documentation examples ------------------------------------------------- # --- documentation examples -------------------------------------------------
# A made-up MAC in a worked example of the compatibility string. Real MACs are # A made-up MAC in a worked example of the compatibility string. Real MACs are
@ -51,11 +50,16 @@ services/flysim/crates/flybrain-gb/src/compatibility.rs mac-address # aa:bb:...
# Third-party addresses and handles: upstream projects, not this network. # Third-party addresses and handles: upstream projects, not this network.
# (None currently; keep the section so the next one lands in the right place.) # (None currently; keep the section so the next one lands in the right place.)
apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit apps/stage/public/fonts/ email-address # SIL OFL licence text from upstream font projects; not ours to edit
infra/tests/lint.sh email-address # `lint@ex[a]mple.invalid`, the git identity for the throwaway test repos infra/tests/lint.sh email-address # the example.invalid git identity for the throwaway test repos
infra/tests/pii-scan-test.sh email-address # same example.invalid identity for the scanner's throwaway repos
# --- publish pack ------------------------------------------------------------ # --- publish pack ------------------------------------------------------------
NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred NOTICE operator-name # the copyright holder's legal name, chosen by the operator 2026-09-17; change here if an entity is preferred
LICENSES.md operator-name # same copyright line, mirrored LICENSES.md operator-name # same copyright line, mirrored
.forgejo/workflows/ci.yml forge-name # the product name of the CI runner (F[o]rgejo Actions), not the operator's forge .forgejo/workflows/ci.yml forge-name # the product name of the CI runner, not the operator's forge
.github/workflows/ci.yml forge-name # a comment naming the F[o]rgejo copy of this workflow .github/workflows/ci.yml forge-name # a comment naming the sibling copy of this workflow
infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path infra/docs/secrets-history-scan.md forge-name # names the two workflow files by path
infra/tests/de-pii-allow.txt forge-name # this file names the .f[o]rgejo/ workflow directory in the two entries above infra/tests/de-pii-allow.txt forge-name # this file names that workflow directory in the entry above
# --- fixtures ----------------------------------------------------------------
apps/stage/tests/unit/query.test.ts private-address # made-up address in a feed-URL parsing fixture
services/bridge/tests/ secret-assignment # fake client id/secret fixtures ("test-client-secret-DO-NOT-LOG")

View file

@ -0,0 +1,19 @@
# Recorded live-fly samples for `fly-shadow-run`'s guard
These samples come from a real `flysim` (legacy, FAFB, macros mode, at real time) on a shared build
box on 2026-09-30. They are in `fly-shadow-run`'s own format and cadence:
- `baseline.jsonl` holds 60 samples 10 s apart;
- `checks.jsonl` holds 20 samples a minute apart, after the same flysim restart that `start` does.
`lint.sh` runs `fly-shadow-run simulate` over each case and holds it to `expect`:
| Case | Setup | Expect |
| --- | --- | --- |
| `slow-alone` | 1 cpu, 1 thread; no shadow | pass |
| `slow-shadow-same` | the same fly, with a real `fly-shadow` following it at normal priority on the same cpu. The live fly dropped from 0.66 to 0.44-0.60 | trip |
| `fast-shadow-idle` | 3 cpus, 3 threads; a real `fly-shadow` at `SCHED_IDLE` on other cpus. The box was already loaded, and the fly ran at 0.4-0.85 | pass |
| `fast-alone` | 3 cpus, 3 threads; no shadow | pass |
The box's own load moved the fly between 0.4 and 1.0 during some baselines. Those steps are why
the baseline is robust: the median, and the spread taken as the MAD.

View file

@ -0,0 +1,60 @@
{"t": 1790738128.362942, "status": "running", "rtMean": 0.7588339770286441, "lag": 33.479, "uptime": 71.223399881}
{"t": 1790738138.4285393, "status": "running", "rtMean": 1.0036906365382738, "lag": 33.479, "uptime": 81.293069051}
{"t": 1790738148.4962938, "status": "running", "rtMean": 0.9970303099114692, "lag": 33.479, "uptime": 91.408291997}
{"t": 1790738158.5748143, "status": "running", "rtMean": 0.9957513747669762, "lag": 33.479, "uptime": 101.483131764}
{"t": 1790738168.9591897, "status": "running", "rtMean": 0.819013893871745, "lag": 35.496, "uptime": 111.869185712}
{"t": 1790738179.0497794, "status": "running", "rtMean": 0.955720505211804, "lag": 35.496, "uptime": 121.957242118}
{"t": 1790738189.13739, "status": "running", "rtMean": 0.8799930137133124, "lag": 36.498, "uptime": 132.018380479}
{"t": 1790738199.2148638, "status": "running", "rtMean": 0.8902680060117365, "lag": 37.521, "uptime": 142.113434378}
{"t": 1790738209.3021023, "status": "running", "rtMean": 0.8803874146669992, "lag": 38.524, "uptime": 152.181022738}
{"t": 1790738219.3764796, "status": "running", "rtMean": 0.8658710279839296, "lag": 40.54, "uptime": 162.284831945}
{"t": 1790738229.4663715, "status": "running", "rtMean": 0.8894453486450183, "lag": 41.541, "uptime": 172.367967371}
{"t": 1790738239.553954, "status": "running", "rtMean": 0.9052554309116678, "lag": 42.543, "uptime": 182.460932044}
{"t": 1790738249.6388013, "status": "running", "rtMean": 0.9129316585556161, "lag": 43.544, "uptime": 192.526870399}
{"t": 1790738259.7050216, "status": "running", "rtMean": 0.9999965689074697, "lag": 43.544, "uptime": 202.609470103}
{"t": 1790738269.7767544, "status": "running", "rtMean": 0.9378600900744024, "lag": 43.544, "uptime": 212.690426315}
{"t": 1790738279.8516681, "status": "running", "rtMean": 0.7973579434723355, "lag": 45.556, "uptime": 222.761268128}
{"t": 1790738289.9210968, "status": "running", "rtMean": 0.9352522067409303, "lag": 46.571, "uptime": 232.836669514}
{"t": 1790738300.0552127, "status": "running", "rtMean": 0.7150556877963433, "lag": 49.584, "uptime": 242.963564523}
{"t": 1790738310.2007082, "status": "running", "rtMean": 1.0059437251512073, "lag": 49.584, "uptime": 253.109498917}
{"t": 1790738320.2790272, "status": "running", "rtMean": 1.00373183915971, "lag": 49.584, "uptime": 263.195154054}
{"t": 1790738330.3444412, "status": "running", "rtMean": 0.9972521469939926, "lag": 49.584, "uptime": 273.255265175}
{"t": 1790738340.4204133, "status": "running", "rtMean": 0.8495939168264007, "lag": 50.586, "uptime": 283.330032566}
{"t": 1790738350.5301325, "status": "running", "rtMean": 0.7839208383476353, "lag": 52.599, "uptime": 293.439062795}
{"t": 1790738360.6693776, "status": "running", "rtMean": 0.9653471893141468, "lag": 53.6, "uptime": 303.576346295}
{"t": 1790738370.8137631, "status": "running", "rtMean": 0.6241158180206947, "lag": 57.623, "uptime": 313.699656832}
{"t": 1790738380.9961703, "status": "running", "rtMean": 0.5687473149333804, "lag": 61.68, "uptime": 323.912074763}
{"t": 1790738391.089262, "status": "running", "rtMean": 0.5804323097526403, "lag": 65.706, "uptime": 333.967914558}
{"t": 1790738401.19394, "status": "running", "rtMean": 0.5362910197658861, "lag": 70.779, "uptime": 344.048343544}
{"t": 1790738411.3023837, "status": "running", "rtMean": 0.5510464052357773, "lag": 74.845, "uptime": 354.205680506}
{"t": 1790738421.4007213, "status": "running", "rtMean": 0.5652293538813947, "lag": 79.905, "uptime": 364.315364667}
{"t": 1790738431.503473, "status": "running", "rtMean": 0.57359026862898, "lag": 83.964, "uptime": 374.377908576}
{"t": 1790738441.6479023, "status": "running", "rtMean": 0.5540343187796515, "lag": 87.999, "uptime": 384.55919851}
{"t": 1790738451.7651033, "status": "running", "rtMean": 0.6037429716311573, "lag": 92.018, "uptime": 394.673360423}
{"t": 1790738461.8663146, "status": "running", "rtMean": 0.6985130182613225, "lag": 95.095, "uptime": 404.755070174}
{"t": 1790738471.9642298, "status": "running", "rtMean": 0.7594984860121092, "lag": 98.14, "uptime": 414.851205955}
{"t": 1790738482.0506132, "status": "running", "rtMean": 0.8166532570546075, "lag": 99.145, "uptime": 424.958463239}
{"t": 1790738492.1384304, "status": "running", "rtMean": 0.8807780226062987, "lag": 100.145, "uptime": 434.992925627}
{"t": 1790738502.2033277, "status": "running", "rtMean": 1.0802703218851182, "lag": 100.145, "uptime": 445.108112717}
{"t": 1790738512.273309, "status": "running", "rtMean": 0.9857221768324773, "lag": 100.145, "uptime": 455.179728346}
{"t": 1790738522.3412535, "status": "running", "rtMean": 1.0008941796078314, "lag": 100.145, "uptime": 465.243065017}
{"t": 1790738532.4065015, "status": "running", "rtMean": 1.0144037951650158, "lag": 100.145, "uptime": 475.316217749}
{"t": 1790738542.4878814, "status": "running", "rtMean": 0.995240358864496, "lag": 100.145, "uptime": 485.400446119}
{"t": 1790738552.5522985, "status": "running", "rtMean": 0.9958695819760208, "lag": 100.145, "uptime": 495.331048011}
{"t": 1790738562.6135433, "status": "running", "rtMean": 0.9990484834746928, "lag": 100.145, "uptime": 505.518260558}
{"t": 1790738572.6848962, "status": "running", "rtMean": 0.9999101070487516, "lag": 100.145, "uptime": 515.603359756}
{"t": 1790738582.7517495, "status": "running", "rtMean": 1.0067915374872096, "lag": 100.145, "uptime": 525.63843004}
{"t": 1790738592.8203006, "status": "running", "rtMean": 0.9933226593909843, "lag": 100.145, "uptime": 535.714625602}
{"t": 1790738602.8871908, "status": "running", "rtMean": 0.9997146956682066, "lag": 100.145, "uptime": 545.76592055}
{"t": 1790738612.9580173, "status": "running", "rtMean": 0.9995574815559497, "lag": 100.145, "uptime": 555.842376949}
{"t": 1790738623.0309892, "status": "running", "rtMean": 1.0009077839472587, "lag": 100.145, "uptime": 565.932440918}
{"t": 1790738633.1058488, "status": "running", "rtMean": 0.905700103566834, "lag": 101.148, "uptime": 576.014824329}
{"t": 1790738643.2241693, "status": "running", "rtMean": 0.9002632818253182, "lag": 102.159, "uptime": 586.12547679}
{"t": 1790738653.3037221, "status": "running", "rtMean": 1.001384402969126, "lag": 102.159, "uptime": 596.212798092}
{"t": 1790738663.377194, "status": "running", "rtMean": 1.0025847949946505, "lag": 102.159, "uptime": 606.291720522}
{"t": 1790738673.450081, "status": "running", "rtMean": 0.9982495351402143, "lag": 102.159, "uptime": 616.368169968}
{"t": 1790738683.5147092, "status": "running", "rtMean": 1.000470259093377, "lag": 102.159, "uptime": 626.427550974}
{"t": 1790738693.5863135, "status": "running", "rtMean": 0.9966639708181871, "lag": 102.159, "uptime": 636.458204371}
{"t": 1790738703.651422, "status": "running", "rtMean": 0.9994712074317433, "lag": 102.159, "uptime": 646.54138456}
{"t": 1790738713.7201247, "status": "running", "rtMean": 0.9965700494189607, "lag": 102.159, "uptime": 656.631814013}
{"t": 1790738723.7912498, "status": "running", "rtMean": 1.0007973265331749, "lag": 102.159, "uptime": 666.694264297}

View file

@ -0,0 +1,20 @@
{"t": 1790738735.0354905, "status": "running", "rtMean": 0.999484237762719, "lag": 0.0, "uptime": 11.07355663}
{"t": 1790738795.1101537, "status": "running", "rtMean": 0.998153021033785, "lag": 0.0, "uptime": 71.129215866}
{"t": 1790738855.1800184, "status": "running", "rtMean": 0.9926228160612285, "lag": 0.0, "uptime": 131.202241399}
{"t": 1790738915.249556, "status": "running", "rtMean": 0.9992177109183569, "lag": 0.0, "uptime": 191.273914994}
{"t": 1790738975.3090174, "status": "running", "rtMean": 1.0004807207169564, "lag": 0.0, "uptime": 251.312728385}
{"t": 1790739035.3770518, "status": "running", "rtMean": 0.99729025135176, "lag": 0.0, "uptime": 311.41256314}
{"t": 1790739095.4512274, "status": "running", "rtMean": 0.9963104110487839, "lag": 0.0, "uptime": 371.442377297}
{"t": 1790739155.5106263, "status": "running", "rtMean": 0.9986795197502222, "lag": 0.0, "uptime": 431.514951288}
{"t": 1790739215.5753255, "status": "running", "rtMean": 0.998777006263299, "lag": 0.0, "uptime": 491.615126509}
{"t": 1790739275.6377265, "status": "running", "rtMean": 0.9993828850549406, "lag": 0.0, "uptime": 551.643819315}
{"t": 1790739335.6982403, "status": "running", "rtMean": 0.9998689452246822, "lag": 0.0, "uptime": 611.710123532}
{"t": 1790739395.7690253, "status": "running", "rtMean": 1.0066090326463777, "lag": 0.0, "uptime": 671.806084883}
{"t": 1790739455.8361878, "status": "running", "rtMean": 0.9991477060779191, "lag": 0.0, "uptime": 731.837495033}
{"t": 1790739515.8999934, "status": "running", "rtMean": 0.9968497132252894, "lag": 0.0, "uptime": 791.918687829}
{"t": 1790739575.9599848, "status": "running", "rtMean": 0.9993416499626159, "lag": 0.0, "uptime": 851.966694729}
{"t": 1790739636.031231, "status": "running", "rtMean": 0.9997509681411471, "lag": 0.0, "uptime": 912.047324838}
{"t": 1790739696.1082256, "status": "running", "rtMean": 0.9993880587210896, "lag": 0.0, "uptime": 972.143571488}
{"t": 1790739756.1715124, "status": "running", "rtMean": 0.9978257533955007, "lag": 0.0, "uptime": 1032.192931507}
{"t": 1790739816.2371426, "status": "running", "rtMean": 1.0003866207887322, "lag": 0.0, "uptime": 1092.269950437}
{"t": 1790739876.297765, "status": "running", "rtMean": 0.9997339122145353, "lag": 0.0, "uptime": 1152.311864977}

View file

@ -0,0 +1 @@
pass

View file

@ -0,0 +1,60 @@
{"t": 1790736255.1832466, "status": "running", "rtMean": 0.44899475378270337, "lag": 40.531, "uptime": 71.111642723}
{"t": 1790736265.3486006, "status": "running", "rtMean": 0.40737226174421837, "lag": 46.58, "uptime": 81.296028671}
{"t": 1790736275.462523, "status": "running", "rtMean": 0.43926524622884744, "lag": 51.607, "uptime": 91.41614284}
{"t": 1790736285.5483737, "status": "running", "rtMean": 0.4992672422167786, "lag": 57.668, "uptime": 101.49334599}
{"t": 1790736295.691844, "status": "running", "rtMean": 0.4722833612045654, "lag": 62.729, "uptime": 111.631919513}
{"t": 1790736305.8359153, "status": "running", "rtMean": 0.49364414852989763, "lag": 67.756, "uptime": 121.766530366}
{"t": 1790736316.0044537, "status": "running", "rtMean": 0.4592358802945983, "lag": 72.814, "uptime": 131.934151579}
{"t": 1790736326.1091528, "status": "running", "rtMean": 0.4414601438247983, "lag": 78.84, "uptime": 142.0534588}
{"t": 1790736336.2525842, "status": "running", "rtMean": 0.4540765983005316, "lag": 83.88, "uptime": 152.198379259}
{"t": 1790736346.4600585, "status": "running", "rtMean": 0.4173426800525677, "lag": 89.957, "uptime": 162.413446602}
{"t": 1790736356.5611305, "status": "running", "rtMean": 0.4606621035712305, "lag": 96.016, "uptime": 172.491203687}
{"t": 1790736366.7702422, "status": "running", "rtMean": 0.46203321509514217, "lag": 101.071, "uptime": 182.696019242}
{"t": 1790736376.9394329, "status": "running", "rtMean": 0.4863329297033063, "lag": 106.126, "uptime": 192.889038592}
{"t": 1790736387.0649624, "status": "running", "rtMean": 0.4495199219435465, "lag": 112.232, "uptime": 203.013465866}
{"t": 1790736397.1682742, "status": "running", "rtMean": 0.42863654848005284, "lag": 118.286, "uptime": 213.12621802}
{"t": 1790736407.2758026, "status": "running", "rtMean": 0.4139101392220675, "lag": 123.367, "uptime": 223.208709667}
{"t": 1790736417.43286, "status": "running", "rtMean": 0.43302060621434524, "lag": 129.445, "uptime": 233.357393123}
{"t": 1790736427.5712192, "status": "running", "rtMean": 0.43801120859089393, "lag": 135.505, "uptime": 243.507406013}
{"t": 1790736437.7151752, "status": "running", "rtMean": 0.4402615997407782, "lag": 140.554, "uptime": 253.661724645}
{"t": 1790736447.85799, "status": "running", "rtMean": 0.48112727487436235, "lag": 146.635, "uptime": 263.813400946}
{"t": 1790736458.0452223, "status": "running", "rtMean": 0.4318712743090674, "lag": 151.707, "uptime": 273.954505321}
{"t": 1790736468.1886797, "status": "running", "rtMean": 0.42247469989908265, "lag": 157.751, "uptime": 284.121781118}
{"t": 1790736478.3070867, "status": "running", "rtMean": 0.414255858741203, "lag": 163.851, "uptime": 294.242313229}
{"t": 1790736488.4334955, "status": "running", "rtMean": 0.42798509497809467, "lag": 169.928, "uptime": 304.374179381}
{"t": 1790736498.598869, "status": "running", "rtMean": 0.6973435620918129, "lag": 171.95, "uptime": 314.520569518}
{"t": 1790736508.6862988, "status": "running", "rtMean": 0.8506385364177339, "lag": 173.964, "uptime": 324.645689838}
{"t": 1790736518.7639382, "status": "running", "rtMean": 0.6393757799420648, "lag": 176.98, "uptime": 334.702167477}
{"t": 1790736528.8444629, "status": "running", "rtMean": 0.7563780548037421, "lag": 179.995, "uptime": 344.767409573}
{"t": 1790736538.9335213, "status": "running", "rtMean": 0.7299449362518324, "lag": 183.099, "uptime": 354.892773648}
{"t": 1790736549.0587013, "status": "running", "rtMean": 0.7495898580324455, "lag": 185.1, "uptime": 365.018206452}
{"t": 1790736559.125795, "status": "running", "rtMean": 0.7466250548943967, "lag": 188.191, "uptime": 375.072270628}
{"t": 1790736569.2290745, "status": "running", "rtMean": 0.7135159366386999, "lag": 191.217, "uptime": 385.16395309}
{"t": 1790736579.3221574, "status": "running", "rtMean": 0.6444057032246826, "lag": 194.311, "uptime": 395.24551542}
{"t": 1790736589.387774, "status": "running", "rtMean": 0.7078500629057103, "lag": 197.356, "uptime": 405.328315223}
{"t": 1790736599.457208, "status": "running", "rtMean": 0.7724222621426244, "lag": 199.41, "uptime": 415.395630334}
{"t": 1790736609.5669358, "status": "running", "rtMean": 0.7238637707089501, "lag": 202.432, "uptime": 425.523861591}
{"t": 1790736619.667222, "status": "running", "rtMean": 0.636988015566429, "lag": 206.491, "uptime": 435.596000401}
{"t": 1790736629.7565455, "status": "running", "rtMean": 0.6846194839249449, "lag": 209.511, "uptime": 445.705233095}
{"t": 1790736639.9320571, "status": "running", "rtMean": 0.5775285955158141, "lag": 213.527, "uptime": 455.875805326}
{"t": 1790736650.1127295, "status": "running", "rtMean": 0.6874672985502784, "lag": 216.574, "uptime": 466.047794887}
{"t": 1790736660.23605, "status": "running", "rtMean": 0.7980788454806589, "lag": 218.599, "uptime": 476.191578571}
{"t": 1790736670.3181207, "status": "running", "rtMean": 0.8373465907575423, "lag": 220.629, "uptime": 486.259561672}
{"t": 1790736680.5240602, "status": "running", "rtMean": 0.5739965775984952, "lag": 224.72, "uptime": 496.479775337}
{"t": 1790736690.6629243, "status": "running", "rtMean": 0.5286072075517942, "lag": 229.778, "uptime": 506.594493598}
{"t": 1790736700.8302114, "status": "running", "rtMean": 0.6743407053708753, "lag": 232.792, "uptime": 516.784837195}
{"t": 1790736710.9810565, "status": "running", "rtMean": 0.4833175202797613, "lag": 237.843, "uptime": 526.927338551}
{"t": 1790736721.1076307, "status": "running", "rtMean": 0.5049205359243616, "lag": 242.912, "uptime": 537.054603691}
{"t": 1790736731.2034523, "status": "running", "rtMean": 0.4861911891792873, "lag": 248.95, "uptime": 547.101045326}
{"t": 1790736741.3109553, "status": "running", "rtMean": 0.4845765517462596, "lag": 254.061, "uptime": 557.246782973}
{"t": 1790736751.4774404, "status": "running", "rtMean": 0.5333230355802153, "lag": 258.103, "uptime": 567.418066384}
{"t": 1790736761.652144, "status": "running", "rtMean": 0.49627891829609305, "lag": 264.173, "uptime": 577.572329582}
{"t": 1790736771.8544915, "status": "running", "rtMean": 0.5215276573927089, "lag": 268.2, "uptime": 587.79709649}
{"t": 1790736781.9649491, "status": "running", "rtMean": 0.5216891717973449, "lag": 273.234, "uptime": 597.898939598}
{"t": 1790736792.0599647, "status": "running", "rtMean": 0.5310205891816586, "lag": 278.266, "uptime": 607.982986102}
{"t": 1790736802.1870968, "status": "running", "rtMean": 0.49618279364312484, "lag": 283.316, "uptime": 618.117053029}
{"t": 1790736812.290842, "status": "running", "rtMean": 0.49072671618430486, "lag": 288.404, "uptime": 628.23818419}
{"t": 1790736822.4333866, "status": "running", "rtMean": 0.5402747673446865, "lag": 292.418, "uptime": 638.367153256}
{"t": 1790736832.613669, "status": "running", "rtMean": 0.8329938906374317, "lag": 294.42, "uptime": 648.537882771}
{"t": 1790736842.6835933, "status": "running", "rtMean": 0.7430173560600793, "lag": 297.448, "uptime": 658.629022047}
{"t": 1790736852.755823, "status": "running", "rtMean": 0.8578215877131159, "lag": 298.448, "uptime": 668.694834509}

View file

@ -0,0 +1,20 @@
{"t": 1790736864.4256852, "status": "running", "rtMean": 0.6099898319965826, "lag": 3.091, "uptime": 11.07909019}
{"t": 1790736924.501681, "status": "running", "rtMean": 0.5411932741082821, "lag": 20.265, "uptime": 71.155545456}
{"t": 1790736984.5807962, "status": "running", "rtMean": 0.7295306018507262, "lag": 35.328, "uptime": 131.199399778}
{"t": 1790737044.6489198, "status": "running", "rtMean": 0.8067884564857175, "lag": 46.47, "uptime": 191.29805351}
{"t": 1790737104.7270966, "status": "running", "rtMean": 0.8192565712279218, "lag": 58.542, "uptime": 251.37716607}
{"t": 1790737164.7932363, "status": "running", "rtMean": 0.8487114702728498, "lag": 69.618, "uptime": 311.44889619}
{"t": 1790737224.91049, "status": "running", "rtMean": 0.42516908835738415, "lag": 101.107, "uptime": 371.522769005}
{"t": 1790737285.0996652, "status": "running", "rtMean": 0.41299332249218484, "lag": 136.493, "uptime": 431.719907398}
{"t": 1790737345.3437996, "status": "running", "rtMean": 0.4410892921905215, "lag": 171.04, "uptime": 491.980527036}
{"t": 1790737405.5281327, "status": "running", "rtMean": 0.4454430216668691, "lag": 204.353, "uptime": 552.14783058}
{"t": 1790737465.838257, "status": "running", "rtMean": 0.5991416565682315, "lag": 227.769, "uptime": 612.473422449}
{"t": 1790737525.9655414, "status": "running", "rtMean": 0.6857160494879407, "lag": 246.844, "uptime": 672.619024119}
{"t": 1790737586.045057, "status": "running", "rtMean": 0.6537634570200577, "lag": 265.963, "uptime": 732.678449214}
{"t": 1790737646.1301575, "status": "running", "rtMean": 0.6473194011694912, "lag": 290.309, "uptime": 792.775859726}
{"t": 1790737706.2470899, "status": "running", "rtMean": 0.474484017045933, "lag": 319.566, "uptime": 852.890865845}
{"t": 1790737766.4071772, "status": "running", "rtMean": 0.5316840402693012, "lag": 349.947, "uptime": 913.037081082}
{"t": 1790737826.488124, "status": "running", "rtMean": 0.7651768950839182, "lag": 371.253, "uptime": 973.141837869}
{"t": 1790737886.652113, "status": "running", "rtMean": 0.4461005912444415, "lag": 403.681, "uptime": 1033.302886448}
{"t": 1790737946.764796, "status": "running", "rtMean": 0.4610048048396617, "lag": 438.093, "uptime": 1093.383696514}
{"t": 1790738006.857649, "status": "running", "rtMean": 0.44882468186134916, "lag": 471.382, "uptime": 1153.477095415}

View file

@ -0,0 +1 @@
pass

View file

@ -0,0 +1,60 @@
{"t": 1790732513.9182734, "status": "running", "rtMean": 0.8924521636213212, "lag": 14.055, "uptime": 71.036299234}
{"t": 1790732524.0150237, "status": "running", "rtMean": 0.8353274823796196, "lag": 16.062, "uptime": 81.13323077}
{"t": 1790732534.1210978, "status": "running", "rtMean": 0.8500748093099013, "lag": 17.063, "uptime": 91.228242756}
{"t": 1790732544.215337, "status": "running", "rtMean": 0.8468167790642429, "lag": 19.065, "uptime": 101.324762382}
{"t": 1790732554.322073, "status": "running", "rtMean": 0.8195776032071418, "lag": 21.069, "uptime": 111.432768959}
{"t": 1790732564.4171112, "status": "running", "rtMean": 0.8132396801449534, "lag": 23.128, "uptime": 121.51184336}
{"t": 1790732574.6153316, "status": "running", "rtMean": 0.7620145427014579, "lag": 25.169, "uptime": 131.725135168}
{"t": 1790732584.921327, "status": "running", "rtMean": 0.8332397110903376, "lag": 27.171, "uptime": 142.033873438}
{"t": 1790732595.01128, "status": "running", "rtMean": 0.870312035539666, "lag": 28.172, "uptime": 152.095917692}
{"t": 1790732605.1342888, "status": "running", "rtMean": 0.8533222405905535, "lag": 29.174, "uptime": 162.233917268}
{"t": 1790732615.2172267, "status": "running", "rtMean": 0.8613640091999233, "lag": 31.183, "uptime": 172.332574842}
{"t": 1790732625.292268, "status": "running", "rtMean": 0.8522988744218247, "lag": 32.186, "uptime": 182.413805105}
{"t": 1790732635.3641157, "status": "running", "rtMean": 0.9357131448898743, "lag": 33.188, "uptime": 192.485818904}
{"t": 1790732645.4261112, "status": "running", "rtMean": 1.0206119648139633, "lag": 33.188, "uptime": 202.528181723}
{"t": 1790732655.4861393, "status": "running", "rtMean": 0.9996233335893017, "lag": 33.188, "uptime": 212.597230658}
{"t": 1790732665.5481722, "status": "running", "rtMean": 0.9988689561123472, "lag": 33.188, "uptime": 222.643138786}
{"t": 1790732675.6082208, "status": "running", "rtMean": 0.9720518244342236, "lag": 33.188, "uptime": 232.688977534}
{"t": 1790732685.6701753, "status": "running", "rtMean": 0.9535516201508779, "lag": 33.188, "uptime": 242.776975854}
{"t": 1790732695.7341325, "status": "running", "rtMean": 1.0629078918872632, "lag": 33.188, "uptime": 252.850174728}
{"t": 1790732705.8101525, "status": "running", "rtMean": 0.9727389888242601, "lag": 33.188, "uptime": 262.903659566}
{"t": 1790732715.8741817, "status": "running", "rtMean": 1.0273735099933976, "lag": 33.188, "uptime": 272.974337275}
{"t": 1790732725.938133, "status": "running", "rtMean": 1.0004052294537187, "lag": 33.188, "uptime": 283.049608446}
{"t": 1790732735.998134, "status": "running", "rtMean": 0.9949238477466771, "lag": 33.188, "uptime": 293.095921712}
{"t": 1790732746.058181, "status": "running", "rtMean": 1.001717860791771, "lag": 33.188, "uptime": 303.168958273}
{"t": 1790732756.1181643, "status": "running", "rtMean": 0.9904886517209306, "lag": 33.188, "uptime": 313.212038344}
{"t": 1790732766.1781104, "status": "running", "rtMean": 1.0019464588045806, "lag": 33.188, "uptime": 323.27335596}
{"t": 1790732776.2361557, "status": "running", "rtMean": 0.9964762908263903, "lag": 33.188, "uptime": 333.345377532}
{"t": 1790732786.2971303, "status": "running", "rtMean": 0.9919143606076284, "lag": 33.188, "uptime": 343.415231522}
{"t": 1790732796.356171, "status": "running", "rtMean": 0.9987406877370043, "lag": 33.188, "uptime": 353.453194803}
{"t": 1790732806.4211473, "status": "running", "rtMean": 0.9606955955830612, "lag": 33.188, "uptime": 363.51066889}
{"t": 1790732816.4811146, "status": "running", "rtMean": 1.0365607476649523, "lag": 33.188, "uptime": 373.577335699}
{"t": 1790732826.5412261, "status": "running", "rtMean": 0.9998410565989371, "lag": 33.188, "uptime": 383.641038325}
{"t": 1790732836.6022642, "status": "running", "rtMean": 1.0000077033831407, "lag": 33.188, "uptime": 393.71493795}
{"t": 1790732846.66412, "status": "running", "rtMean": 1.000194713414025, "lag": 33.188, "uptime": 403.778353067}
{"t": 1790732856.7631304, "status": "running", "rtMean": 0.9963137515722961, "lag": 33.188, "uptime": 413.843209009}
{"t": 1790732866.8251379, "status": "running", "rtMean": 1.0024279700647742, "lag": 33.188, "uptime": 423.939536235}
{"t": 1790732876.8881218, "status": "running", "rtMean": 0.9998292141625301, "lag": 33.188, "uptime": 434.00196051}
{"t": 1790732886.9481704, "status": "running", "rtMean": 1.000376047514638, "lag": 33.188, "uptime": 444.041568588}
{"t": 1790732897.0131807, "status": "running", "rtMean": 0.9650577242433412, "lag": 33.188, "uptime": 454.116318252}
{"t": 1790732907.0751567, "status": "running", "rtMean": 1.0144244685102852, "lag": 33.188, "uptime": 464.167010558}
{"t": 1790732917.135163, "status": "running", "rtMean": 1.0205380747863821, "lag": 33.188, "uptime": 474.251702386}
{"t": 1790732927.2051454, "status": "running", "rtMean": 1.0000612465292147, "lag": 33.188, "uptime": 484.315901269}
{"t": 1790732937.2681184, "status": "running", "rtMean": 0.9994207833538337, "lag": 33.188, "uptime": 494.376673004}
{"t": 1790732947.3331046, "status": "running", "rtMean": 1.000304521129079, "lag": 33.188, "uptime": 504.439961234}
{"t": 1790732957.3971682, "status": "running", "rtMean": 1.0002162260543621, "lag": 33.188, "uptime": 514.506681195}
{"t": 1790732967.4561813, "status": "running", "rtMean": 0.9940778699094166, "lag": 33.188, "uptime": 524.546264956}
{"t": 1790732977.5141263, "status": "running", "rtMean": 0.9996073475880696, "lag": 33.188, "uptime": 534.609522709}
{"t": 1790732987.574194, "status": "running", "rtMean": 1.0002335793712973, "lag": 33.188, "uptime": 544.681525736}
{"t": 1790732997.63819, "status": "running", "rtMean": 0.9719075938039292, "lag": 33.188, "uptime": 554.746296519}
{"t": 1790733007.6981711, "status": "running", "rtMean": 0.9642994644579728, "lag": 33.188, "uptime": 564.819180783}
{"t": 1790733017.758178, "status": "running", "rtMean": 1.018785781616432, "lag": 33.188, "uptime": 574.863920385}
{"t": 1790733027.8201568, "status": "running", "rtMean": 1.0126053016171566, "lag": 33.188, "uptime": 584.931657624}
{"t": 1790733037.8801777, "status": "running", "rtMean": 1.0288813388578921, "lag": 33.188, "uptime": 595.000913192}
{"t": 1790733047.9401584, "status": "running", "rtMean": 0.9993726786826045, "lag": 33.188, "uptime": 605.062362454}
{"t": 1790733058.0032334, "status": "running", "rtMean": 1.0003288362459641, "lag": 33.188, "uptime": 615.100685166}
{"t": 1790733068.0701303, "status": "running", "rtMean": 0.996323054395049, "lag": 33.188, "uptime": 625.182391179}
{"t": 1790733078.1311688, "status": "running", "rtMean": 0.9986121232113987, "lag": 33.188, "uptime": 635.237969741}
{"t": 1790733088.194169, "status": "running", "rtMean": 0.9998456257825143, "lag": 33.188, "uptime": 645.294446623}
{"t": 1790733098.254364, "status": "running", "rtMean": 0.9990527607429407, "lag": 33.188, "uptime": 655.371233565}
{"t": 1790733108.3171723, "status": "running", "rtMean": 0.9801059046785113, "lag": 33.188, "uptime": 665.424268239}

View file

@ -0,0 +1,20 @@
{"t": 1790733119.441622, "status": "running", "rtMean": 0.999626145847037, "lag": 0.0, "uptime": 11.03453719}
{"t": 1790733179.5021126, "status": "running", "rtMean": 0.996429238965645, "lag": 0.0, "uptime": 71.109465871}
{"t": 1790733239.563163, "status": "running", "rtMean": 1.0001344530283525, "lag": 0.0, "uptime": 131.161767319}
{"t": 1790733299.6230712, "status": "running", "rtMean": 1.0051819085367752, "lag": 0.0, "uptime": 191.213566544}
{"t": 1790733359.684059, "status": "running", "rtMean": 0.9994857841966536, "lag": 0.0, "uptime": 251.305985353}
{"t": 1790733419.744106, "status": "running", "rtMean": 0.9309339263307287, "lag": 1.016, "uptime": 311.343539702}
{"t": 1790733479.8072605, "status": "running", "rtMean": 0.9914113663325995, "lag": 1.016, "uptime": 371.420558771}
{"t": 1790733539.874109, "status": "running", "rtMean": 1.0150616406858766, "lag": 1.016, "uptime": 431.469758515}
{"t": 1790733599.934255, "status": "running", "rtMean": 0.9990854925925501, "lag": 1.016, "uptime": 491.554715659}
{"t": 1790733659.998115, "status": "running", "rtMean": 0.9992033155394792, "lag": 1.016, "uptime": 551.614612008}
{"t": 1790733720.0581028, "status": "running", "rtMean": 1.0002394824346315, "lag": 1.016, "uptime": 611.653389874}
{"t": 1790733780.121188, "status": "running", "rtMean": 1.002487894172868, "lag": 1.016, "uptime": 671.727773294}
{"t": 1790733840.1851053, "status": "running", "rtMean": 1.000530724113054, "lag": 1.016, "uptime": 731.80678409}
{"t": 1790733900.2461364, "status": "running", "rtMean": 1.000644782810976, "lag": 1.016, "uptime": 791.842628622}
{"t": 1790733960.3072183, "status": "running", "rtMean": 0.999652205983927, "lag": 1.016, "uptime": 851.922688196}
{"t": 1790734020.3681173, "status": "running", "rtMean": 0.9946548155046125, "lag": 1.016, "uptime": 911.968050417}
{"t": 1790734080.4291067, "status": "running", "rtMean": 1.0009058823044212, "lag": 1.016, "uptime": 972.041325345}
{"t": 1790734140.4912531, "status": "running", "rtMean": 0.9902809817215064, "lag": 1.016, "uptime": 1032.085088126}
{"t": 1790734200.550132, "status": "running", "rtMean": 1.0136589528338944, "lag": 1.016, "uptime": 1092.153292688}
{"t": 1790734260.6101415, "status": "running", "rtMean": 0.997751864835789, "lag": 1.016, "uptime": 1152.230885469}

View file

@ -0,0 +1 @@
pass

View file

@ -0,0 +1,60 @@
{"t": 1790734381.7911441, "status": "running", "rtMean": 0.9991690302798031, "lag": 0.0, "uptime": 71.04094778}
{"t": 1790734391.863173, "status": "running", "rtMean": 0.9995511232186312, "lag": 0.0, "uptime": 81.137648009}
{"t": 1790734401.9251318, "status": "running", "rtMean": 1.004411393451764, "lag": 0.0, "uptime": 91.179846024}
{"t": 1790734411.9851615, "status": "running", "rtMean": 1.0061548832920237, "lag": 0.0, "uptime": 101.244880286}
{"t": 1790734422.045158, "status": "running", "rtMean": 1.0009389826422062, "lag": 0.0, "uptime": 111.322533823}
{"t": 1790734432.1231213, "status": "running", "rtMean": 0.9994054188236428, "lag": 0.0, "uptime": 121.386590467}
{"t": 1790734442.1821327, "status": "running", "rtMean": 1.0019091973172163, "lag": 0.0, "uptime": 131.434675409}
{"t": 1790734452.2411315, "status": "running", "rtMean": 1.0003511147658264, "lag": 0.0, "uptime": 141.510042108}
{"t": 1790734462.3011394, "status": "running", "rtMean": 0.9998128330113216, "lag": 0.0, "uptime": 151.571854176}
{"t": 1790734472.3611345, "status": "running", "rtMean": 0.9995342276541852, "lag": 0.0, "uptime": 161.611024691}
{"t": 1790734482.435045, "status": "running", "rtMean": 0.9922858838781137, "lag": 0.0, "uptime": 171.712414098}
{"t": 1790734492.4924283, "status": "running", "rtMean": 1.0077000502536002, "lag": 0.0, "uptime": 181.768296008}
{"t": 1790734502.590251, "status": "running", "rtMean": 0.688659978029653, "lag": 3.02, "uptime": 191.845836083}
{"t": 1790734512.7063384, "status": "running", "rtMean": 0.6918570039489707, "lag": 6.031, "uptime": 201.972741056}
{"t": 1790734522.8416302, "status": "running", "rtMean": 0.6636996350321189, "lag": 9.061, "uptime": 212.118463031}
{"t": 1790734532.9413493, "status": "running", "rtMean": 0.677691555064422, "lag": 13.117, "uptime": 222.217638708}
{"t": 1790734543.0511246, "status": "running", "rtMean": 0.6687714298956552, "lag": 16.132, "uptime": 232.330293687}
{"t": 1790734553.214297, "status": "running", "rtMean": 0.6610843395024606, "lag": 19.139, "uptime": 242.48895228}
{"t": 1790734563.3515842, "status": "running", "rtMean": 0.652060892547814, "lag": 23.162, "uptime": 252.608110328}
{"t": 1790734573.4900045, "status": "running", "rtMean": 0.6695512645097088, "lag": 26.172, "uptime": 262.753496555}
{"t": 1790734583.676419, "status": "running", "rtMean": 0.672729094430949, "lag": 30.189, "uptime": 272.933415929}
{"t": 1790734593.8542893, "status": "running", "rtMean": 0.6751609713074462, "lag": 33.199, "uptime": 283.119763313}
{"t": 1790734603.9855552, "status": "running", "rtMean": 0.6532184360045333, "lag": 36.247, "uptime": 293.24006575}
{"t": 1790734614.107205, "status": "running", "rtMean": 0.6660828397073446, "lag": 40.264, "uptime": 303.373977854}
{"t": 1790734624.218526, "status": "running", "rtMean": 0.6077386619823459, "lag": 44.344, "uptime": 313.467368475}
{"t": 1790734634.3447165, "status": "running", "rtMean": 0.6539609074261248, "lag": 47.354, "uptime": 323.602496592}
{"t": 1790734644.4728997, "status": "running", "rtMean": 0.6660933740022716, "lag": 50.368, "uptime": 333.740179276}
{"t": 1790734654.5995867, "status": "running", "rtMean": 0.6500636748816758, "lag": 54.395, "uptime": 343.847346535}
{"t": 1790734664.7299855, "status": "running", "rtMean": 0.6705859566600052, "lag": 57.409, "uptime": 354.005911843}
{"t": 1790734674.917639, "status": "running", "rtMean": 0.6740430368306463, "lag": 61.419, "uptime": 364.191797413}
{"t": 1790734685.0660818, "status": "running", "rtMean": 0.6643961460479318, "lag": 64.428, "uptime": 374.341795785}
{"t": 1790734695.265925, "status": "running", "rtMean": 0.6579653102367324, "lag": 68.437, "uptime": 384.519988281}
{"t": 1790734705.472841, "status": "running", "rtMean": 0.6547900490878023, "lag": 71.446, "uptime": 394.730676243}
{"t": 1790734715.6600814, "status": "running", "rtMean": 0.6530533406133286, "lag": 75.466, "uptime": 404.896364288}
{"t": 1790734725.7730033, "status": "running", "rtMean": 0.6672820515708326, "lag": 78.47, "uptime": 415.037219103}
{"t": 1790734735.8823855, "status": "running", "rtMean": 0.6604279690960906, "lag": 81.507, "uptime": 425.141484166}
{"t": 1790734746.0059605, "status": "running", "rtMean": 0.669876056664904, "lag": 85.525, "uptime": 435.241624797}
{"t": 1790734756.16065, "status": "running", "rtMean": 0.6669554325713298, "lag": 88.532, "uptime": 445.424510067}
{"t": 1790734766.2961965, "status": "running", "rtMean": 0.6789691324390087, "lag": 91.546, "uptime": 455.562624387}
{"t": 1790734776.4270732, "status": "running", "rtMean": 0.6764526659523141, "lag": 95.567, "uptime": 465.699227051}
{"t": 1790734786.5895793, "status": "running", "rtMean": 0.6530891711548452, "lag": 98.603, "uptime": 475.850685381}
{"t": 1790734796.7317367, "status": "running", "rtMean": 0.6406146952722656, "lag": 102.675, "uptime": 486.00189116}
{"t": 1790734806.8721528, "status": "running", "rtMean": 0.6453060329257198, "lag": 105.69, "uptime": 496.149729812}
{"t": 1790734817.0070937, "status": "running", "rtMean": 0.6454966448957478, "lag": 109.706, "uptime": 506.283307741}
{"t": 1790734827.1343982, "status": "running", "rtMean": 0.6448485469528062, "lag": 112.72, "uptime": 516.409124389}
{"t": 1790734837.2881198, "status": "running", "rtMean": 0.6535926679887758, "lag": 116.748, "uptime": 526.560442848}
{"t": 1790734847.4209673, "status": "running", "rtMean": 0.6425044322629614, "lag": 119.784, "uptime": 536.693837434}
{"t": 1790734857.5829508, "status": "running", "rtMean": 0.6452458464522223, "lag": 123.802, "uptime": 546.8305001}
{"t": 1790734867.7133708, "status": "running", "rtMean": 0.6302281366614498, "lag": 127.82, "uptime": 556.984448186}
{"t": 1790734877.8158286, "status": "running", "rtMean": 0.6629500748501092, "lag": 130.844, "uptime": 567.072718764}
{"t": 1790734887.943275, "status": "running", "rtMean": 0.6648674424022735, "lag": 133.854, "uptime": 577.200347159}
{"t": 1790734898.06847, "status": "running", "rtMean": 0.6593429199106378, "lag": 137.876, "uptime": 587.328798352}
{"t": 1790734908.210695, "status": "running", "rtMean": 0.662979366140112, "lag": 140.891, "uptime": 597.465073525}
{"t": 1790734918.3496716, "status": "running", "rtMean": 0.6614754105222075, "lag": 144.914, "uptime": 607.619842905}
{"t": 1790734928.486646, "status": "running", "rtMean": 0.6692348242211306, "lag": 147.924, "uptime": 617.724273337}
{"t": 1790734938.6051722, "status": "running", "rtMean": 0.6733974004623173, "lag": 150.942, "uptime": 627.874978882}
{"t": 1790734948.703509, "status": "running", "rtMean": 0.6484292959854895, "lag": 154.965, "uptime": 637.96851242}
{"t": 1790734958.9605355, "status": "running", "rtMean": 0.6326829212607562, "lag": 158.977, "uptime": 648.224285288}
{"t": 1790734969.0924904, "status": "running", "rtMean": 0.6743317584475094, "lag": 162.001, "uptime": 658.352731683}
{"t": 1790734979.512936, "status": "running", "rtMean": 0.66105927868997, "lag": 165.016, "uptime": 668.754929041}

View file

@ -0,0 +1,20 @@
{"t": 1790734991.7640753, "status": "running", "rtMean": 0.6359105463426694, "lag": 3.008, "uptime": 11.070042764}
{"t": 1790735051.931584, "status": "running", "rtMean": 0.4413866438713924, "lag": 31.225, "uptime": 71.270223818}
{"t": 1790735112.0636158, "status": "running", "rtMean": 0.528275325797771, "lag": 56.478, "uptime": 131.388274947}
{"t": 1790735172.2191246, "status": "running", "rtMean": 0.5653650170639056, "lag": 85.705, "uptime": 191.513860632}
{"t": 1790735232.3440776, "status": "running", "rtMean": 0.598275320104138, "lag": 110.037, "uptime": 251.674657096}
{"t": 1790735292.5060995, "status": "running", "rtMean": 0.6030301486902879, "lag": 134.326, "uptime": 311.836161733}
{"t": 1790735352.646486, "status": "running", "rtMean": 0.6475849197046364, "lag": 156.459, "uptime": 371.966818709}
{"t": 1790735412.780515, "status": "running", "rtMean": 0.5770778494664259, "lag": 179.892, "uptime": 432.08998512}
{"t": 1790735472.8577662, "status": "running", "rtMean": 0.6886656579593289, "lag": 198.051, "uptime": 492.201636495}
{"t": 1790735532.9329088, "status": "running", "rtMean": 0.7616039578620443, "lag": 210.17, "uptime": 552.275859184}
{"t": 1790735592.995646, "status": "running", "rtMean": 0.8492741277663118, "lag": 225.508, "uptime": 612.316843322}
{"t": 1790735653.0601382, "status": "running", "rtMean": 0.8233088403353765, "lag": 232.541, "uptime": 672.386139571}
{"t": 1790735713.1299574, "status": "running", "rtMean": 0.8821898469526929, "lag": 239.649, "uptime": 732.468014006}
{"t": 1790735773.1924357, "status": "running", "rtMean": 0.9074726134753647, "lag": 243.655, "uptime": 792.527038261}
{"t": 1790735833.2571187, "status": "running", "rtMean": 0.899453016514728, "lag": 250.877, "uptime": 852.593245225}
{"t": 1790735893.3221343, "status": "running", "rtMean": 0.6620087337657867, "lag": 258.043, "uptime": 912.634830266}
{"t": 1790735953.5102656, "status": "running", "rtMean": 0.4740061480416233, "lag": 290.508, "uptime": 972.827598732}
{"t": 1790736013.6372716, "status": "running", "rtMean": 0.552244625226687, "lag": 321.774, "uptime": 1032.942900792}
{"t": 1790736073.7192469, "status": "running", "rtMean": 0.5496939405024359, "lag": 348.997, "uptime": 1093.015463153}
{"t": 1790736133.779931, "status": "running", "rtMean": 0.8831947829035597, "lag": 362.15, "uptime": 1153.096169148}

View file

@ -0,0 +1 @@
trip

File diff suppressed because it is too large Load diff

180
infra/tests/pii-scan-test.sh Executable file
View file

@ -0,0 +1,180 @@
#!/usr/bin/env bash
# infra/tests/pii-scan-test.sh — tests for tools/pii-scan.sh and tools/install-hooks.sh.
#
# Everything runs in throwaway repos under a temp dir, against a throwaway private pattern
# list. The fake identifying values are assembled at run time from pieces, so no complete
# fake value (and no real one) appears in this file for the tree scan to trip over.
set -euo pipefail
REPO="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
T="$(mktemp -d)"
trap 'rm -rf "$T"' EXIT
FAILS=0
ok() { echo "ok - $*"; }
bad() { echo "FAIL - $*"; FAILS=$((FAILS + 1)); }
# expect RC DESC -- CMD...: run CMD, capture output in $OUT, check the exit code
# the tree scan covers TRACKED files (git grep), like the guard it replaced
track() { git -C "$W" add -A; }
expect() {
local want="$1" desc="$2"; shift 3
local rc=0
OUT="$("$@" 2>&1)" || rc=$?
if [ "$rc" -eq "$want" ]; then ok "$desc"; else bad "$desc (exit $rc, wanted $want)"; printf '%s\n' "$OUT" | sed 's/^/ /'; fi
}
contains() { case "$OUT" in *"$1"*) ok "$2" ;; *) bad "$2 (missing '$1')"; printf '%s\n' "$OUT" | sed 's/^/ /' ;; esac; }
not_contains() { case "$OUT" in *"$1"*) bad "$2 (output leaks '$1')" ;; *) ok "$2" ;; esac; }
# --- fake private values, built from pieces -------------------------------------------
HOST="zorb""lequin" # a "host name"
PERSON="Quen""tavius" # a "person"
SECRET="fk""Q7pL2xV9""mZ4rT8wY""1nB6" # a "router key"
LAN="192.168"".77.21"
MAIL="someone""@""example.org"
mkdir -p "$T/private"
printf 'FAKE_ROUTER_KEY=%s\nSHORT=abc\n' "$SECRET" > "$T/private/router.env"
cat > "$T/private/patterns.txt" <<EOF
# test list
house-host -i ${HOST}
operator-name - \\b${PERSON}\\b
@values $T/private/router.env
EOF
export FLY_PII_PATTERNS="$T/private/patterns.txt"
# --- a throwaway repo with the scanner in it ------------------------------------------
W="$T/work"
git init -q -b main "$W"
git -C "$W" config user.name lint
git -C "$W" config user.email lint@example.invalid
mkdir -p "$W/tools" "$W/infra/tests" "$W/src"
cp "$REPO/tools/pii-scan.sh" "$REPO/tools/install-hooks.sh" "$W/tools/"
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
echo "hello" > "$W/src/a.txt"
git -C "$W" add -A && git -C "$W" commit -qm "init"
SCAN="$W/tools/pii-scan.sh"
expect 0 "clean tree passes" -- "$SCAN" --tree
contains "private list loaded" "private list is reported loaded"
expect 0 "--list prints names" -- "$SCAN" --list
contains "house-host" "--list includes private names"
not_contains "$HOST" "--list never prints a private regex"
# generic pattern
echo "feed at ws://${LAN}:7400" > "$W/src/b.txt"
track
expect 1 "LAN address in the tree fails" -- "$SCAN" --tree
contains "lan-address: src/b.txt:1:" "finding names the pattern and the location"
not_contains "$LAN" "the address itself is not echoed"
git -C "$W" rm -qf src/b.txt
# private noun, case-insensitive
echo "ssh root@$(echo "$HOST" | tr a-z A-Z).example" > "$W/src/c.txt"
track
expect 1 "private host name fails" -- "$SCAN" --tree
contains "house-host: src/c.txt:1:" "private name reported by its pattern name"
not_contains "$HOST" "private host name is not echoed"
git -C "$W" rm -qf src/c.txt
# case-sensitive private pattern: lowercase fixture passes, capitalised fails
echo "user: $(echo "$PERSON" | tr A-Z a-z)" > "$W/src/d.txt"
track
expect 0 "case-sensitive pattern ignores the lowercase fixture" -- "$SCAN" --tree
echo "by ${PERSON}" > "$W/src/d.txt"
track
expect 1 "case-sensitive pattern catches the capitalised name" -- "$SCAN" --tree
git -C "$W" rm -qf src/d.txt
# literal secret value from @values
echo "KEY=${SECRET}" > "$W/src/e.env"
track
expect 1 "a literal secret value fails" -- "$SCAN" --tree
contains "secret-value:FAKE_ROUTER_KEY: src/e.env:1:" "value finding names the env KEY"
not_contains "${SECRET:0:6}" "secret value is fully redacted"
git -C "$W" rm -qf src/e.env
# credential shape
echo "export STREAM_KEY=\"live_123456""7_abcdefghijABCDEFGHIJ123\"" > "$W/src/f.sh"
track
expect 1 "stream-key shape fails" -- "$SCAN" --tree
contains "secret-twitch" "stream key reported as secret-twitch"
git -C "$W" rm -qf src/f.sh
# allowlist
echo "contact ${MAIL}" > "$W/src/g.txt"
track
expect 1 "e-mail address fails" -- "$SCAN" --tree
printf 'src/g.txt email-address # upstream licence contact\n' >> "$W/infra/tests/de-pii-allow.txt"
expect 0 "allowlisted path/name pair passes" -- "$SCAN" --tree
printf 'src/ house-host # a different name does not excuse\n' >> "$W/infra/tests/de-pii-allow.txt"
echo "${LAN}" > "$W/src/g2.txt"
track
expect 1 "an allow entry excuses only its own pattern name" -- "$SCAN" --tree
git -C "$W" rm -qf src/g.txt src/g2.txt
printf '# allowlist\n' > "$W/infra/tests/de-pii-allow.txt"
# fail closed / open
expect 2 "--require-private without the list exits 2" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --require-private --tree
contains "private pattern list not found" "missing list is named"
expect 0 "without --require-private a missing list is a NOTE" -- env FLY_PII_PATTERNS="$T/nope" "$SCAN" --tree
contains "NOTE: no private pattern list" "NOTE printed"
printf 'broken-line\n' > "$T/private/broken.txt"
expect 2 "a malformed private list is an error, not a silent pass" -- env FLY_PII_PATTERNS="$T/private/broken.txt" "$SCAN" --tree
# range: added then removed is still published history
base="$(git -C "$W" rev-parse HEAD)"
echo "on ${HOST} today" > "$W/src/h.txt"; git -C "$W" add -A; git -C "$W" commit -qm "add h"
git -C "$W" rm -q src/h.txt; git -C "$W" commit -qm "remove h"
expect 0 "tree is clean after the removal" -- "$SCAN" --tree
expect 1 "range still finds the line a commit added" -- "$SCAN" --range "${base}..HEAD"
contains "house-host:" "range finding names the pattern"
contains "src/h.txt:1" "range finding names path and line"
git -C "$W" commit -q --allow-empty -m "deploy to ${HOST}"
expect 1 "range scans commit messages" -- "$SCAN" --range "HEAD~1..HEAD"
contains "<commit-message>:1" "message finding is marked"
git -C "$W" reset -q --hard "$base"
git -C "$W" status --porcelain | grep -q . && bad "work repo not clean before the hook tests" || true
# --- pre-push hook ---------------------------------------------------------------------
git init -q --bare "$T/pub.git"
git init -q --bare "$T/priv.git"
git -C "$W" remote add github "$T/pub.git"
git -C "$W" remote add origin "$T/priv.git"
expect 0 "install-hooks installs" -- "$W/tools/install-hooks.sh"
[ -x "$W/.git/hooks/pre-push" ] && ok "hook is executable" || bad "hook missing"
expect 0 "install-hooks is idempotent" -- "$W/tools/install-hooks.sh"
expect 0 "clean push to github is accepted" -- git -C "$W" push -q github main
echo "at ${LAN}" > "$W/src/i.txt"; git -C "$W" add -A; git -C "$W" commit -qm "i"
expect 1 "push with PII to github is refused" -- git -C "$W" push -q github main
contains "refusing to publish" "hook explains the refusal"
expect 0 "push to a private remote is not scanned" -- git -C "$W" push -q origin main
git -C "$W" rm -q src/i.txt; git -C "$W" commit -qm "rm i"
expect 1 "removing it in a later commit does not unblock the push" -- git -C "$W" push -q github main
git -C "$W" reset -q --hard github/main
git -C "$W" tag -a v9.9.9 -m "release for ${HOST}"
expect 1 "annotated tag message is scanned" -- git -C "$W" push -q github v9.9.9
contains "<tag-message>" "tag finding is marked"
git -C "$W" tag -d v9.9.9 >/dev/null
git -C "$W" tag -a v9.9.8 -m "release"
expect 0 "clean annotated tag is accepted" -- git -C "$W" push -q github v9.9.8
git -C "$W" commit -q --allow-empty -m "clean"
expect 1 "push is refused when the private list is missing" -- env FLY_PII_PATTERNS="$T/nope" git -C "$W" push -q github main
git -C "$W" checkout -q -b old "$base"
rm -f "$W/tools/pii-scan.sh"
echo "x ${HOST}" > "$W/src/j.txt"; git -C "$W" add -A; git -C "$W" commit -qm "j"
expect 1 "a branch without tools/pii-scan.sh is scanned by the hook's own copy" -- git -C "$W" push -q github old
printf 'exit 0\n' > "$T/other-hook"
git -C "$W" checkout -q main
cp "$T/other-hook" "$W/.git/hooks/pre-push"
expect 1 "install-hooks refuses to clobber a foreign hook" -- "$W/tools/install-hooks.sh"
# --- review-pii-guard N2/N3 (2026-09-29) ----------------------------------------------
printf 'broken - (unclosed\n' > "$T/private/bad-patterns.txt"
expect 2 "an invalid private regex refuses to scan (never 'clean')" -- env FLY_PII_PATTERNS="$T/private/bad-patterns.txt" "$SCAN" --tree
printf '++ %s\n' "$LAN" > "$W/src/plusplus.txt"
git -C "$W" add -A && git -C "$W" commit -qm "a line that starts with ++"
expect 1 "an added line starting '++ ' is still scanned" -- "$SCAN" --range HEAD~1..HEAD
git -C "$W" rm -qf src/plusplus.txt && git -C "$W" commit -qm "drop it"
echo "==="
if [ "$FAILS" -eq 0 ]; then echo "pii-scan-test: ALL PASSED"; else echo "pii-scan-test: ${FAILS} FAILED"; exit 1; fi

View file

@ -0,0 +1,136 @@
#!/usr/bin/env python3
"""Synthetic live-fly RTF traces for fly-shadow-run's guard (SHADOW-01 review round 2, G1).
shadow_guard_traces.py OUTDIR
Writes <case>/baseline.jsonl and <case>/checks.jsonl in fly-shadow-run's sample format
({t, status, rtMean, lag, uptime}) and prints one line per case: `<case> <expect>`, where
<expect> is `pass` (the guard must not trip) or `trip` (it must). The baseline is 60 samples 10 s
apart (start's 10 minutes); the checks are one sample a minute for the given length.
The lag follows flysim's pacer: a fly behind real time owes (1 - rtf) seconds per second, and the
pacer books it as lag only in chunks of more than a second (`pacing::MAX_CATCHUP`).
The cases come from the release container's own numbers (the coordinator's samples, agents.log
2026-09-30 00:08Z): a flat 0.66 before the cpuset rebalance, 0.77-0.99 noisy after it, plus a fly
at real time; each alone (must pass), and each with a genuine degradation after the start (must
trip).
"""
import json
import os
import random
import sys
class Fly:
def __init__(self, seed):
self.rng = random.Random(seed)
self.t, self.uptime, self.lag, self.debt = 1_790_000_000.0, 3600.0, 12.0, 0.0
def run(self, seconds, rtf_of):
"""Advances `seconds` of wall time at the realtime factors `rtf_of()` gives per second."""
rtfs = []
for _ in range(int(seconds)):
rtf = rtf_of(self.rng)
rtfs.append(rtf)
self.debt += max(0.0, 1.0 - rtf)
if self.debt > 1.0:
self.lag += self.debt
self.debt = 0.0
self.t += 1
self.uptime += 1
return rtfs
def sample(self, rtf_of, status="running"):
rtfs = self.run(10, rtf_of)
return {"t": self.t, "status": status, "rtMean": sum(rtfs) / len(rtfs),
"lag": round(self.lag, 3), "uptime": self.uptime}
def restart(self):
self.uptime, self.lag, self.debt = 5.0, 0.0, 0.0
def flat(v, jitter=0.01):
return lambda rng: v + rng.uniform(-jitter, jitter)
def noisy(lo, hi):
return lambda rng: rng.uniform(lo, hi)
def noisy_windows(lo, hi):
"""Noise at the sample level: each 10 s holds one value in [lo, hi], so the 10-s means the
guard reads spread over the whole range (the coordinator's samples)."""
state = {"n": 0, "v": None}
def pace(rng):
if state["n"] % 10 == 0:
state["v"] = rng.uniform(lo, hi)
state["n"] += 1
return state["v"]
return pace
def realtime(rng):
return min(1.0, 1.0 + rng.uniform(-0.004, 0.002))
def case(seed, before, after, checks=180, degrade_at=None, events=None):
fly = Fly(seed)
baseline = [fly.sample(before) for _ in range(60)]
fly.restart() # start's own flysim restart
rows = []
for n in range(checks):
pace = after if degrade_at is not None and n >= degrade_at else before
status = "running"
if events and n in events:
kind = events[n]
if kind == "restart":
fly.restart()
elif kind == "paused":
status = "paused"
elif kind == "hiccup":
fly.lag += 1.3 # one pacing shortfall of 1.3 s, nothing more
rows.append(fly.sample(pace, status))
fly.run(50, pace)
return baseline, rows
CASES = {
# The release CT before the rebalance: a flat 0.66, 3 hours, with a restart and a pause.
"ct-flat-0.66": (case(1, flat(0.66), None, events={40: "restart", 90: "paused", 91: "paused"}), "pass"),
# After the rebalance: 0.77-0.99 noisy, 3 hours, a restart.
"ct-noisy-0.77-0.99": (case(2, noisy(0.77, 0.99), None, events={120: "restart"}), "pass"),
"ct-noisy-0.77-0.99-seed3": (case(3, noisy(0.77, 0.99), None), "pass"),
# The same spread at the level of the 10-s samples themselves, the harder case.
"ct-samples-0.77-0.99": (case(8, noisy_windows(0.77, 0.99), None, events={60: "restart"}), "pass"),
"ct-samples-0.77-0.99-seed9": (case(9, noisy_windows(0.77, 0.99), None), "pass"),
"ct-samples-0.77-0.99-seed10": (case(10, noisy_windows(0.77, 0.99), None), "pass"),
# At real time, with single pacing hiccups: never a trip.
"realtime-hiccups": (case(4, realtime, None, events={30: "hiccup", 100: "hiccup", 150: "hiccup"}), "pass"),
# A shadow that costs the fly real time.
"ct-flat-0.66-then-0.55": (case(5, flat(0.66), flat(0.55), checks=40, degrade_at=15), "trip"),
"ct-noisy-then-0.60-0.75": (case(6, noisy(0.77, 0.99), noisy(0.60, 0.75), checks=40, degrade_at=15), "trip"),
"realtime-then-0.90": (case(7, realtime, flat(0.90), checks=40, degrade_at=15), "trip"),
"ct-samples-then-0.55-0.75": (
case(11, noisy_windows(0.77, 0.99), noisy_windows(0.55, 0.75), checks=40, degrade_at=15),
"trip",
),
}
def main():
out = sys.argv[1]
for name, ((baseline, checks), expect) in CASES.items():
d = os.path.join(out, name)
os.makedirs(d, exist_ok=True)
for fname, rows in (("baseline.jsonl", baseline), ("checks.jsonl", checks)):
with open(os.path.join(d, fname), "w") as f:
for r in rows:
f.write(json.dumps(r) + "\n")
print(name, expect)
if __name__ == "__main__":
main()

View file

@ -2,14 +2,20 @@ import importlib.machinery
import importlib.util import importlib.util
import json import json
from pathlib import Path from pathlib import Path
import re
import tempfile import tempfile
import unittest import unittest
from unittest.mock import patch from unittest.mock import patch
script = Path(__file__).resolve().parents[1] / "bin/fly-loop-recover" repo = Path(__file__).resolve().parents[2]
script = repo / "infra/bin/fly-loop-recover"
spec = importlib.util.spec_from_loader("recover", importlib.machinery.SourceFileLoader("recover", str(script))) spec = importlib.util.spec_from_loader("recover", importlib.machinery.SourceFileLoader("recover", str(script)))
recover = importlib.util.module_from_spec(spec) recover = importlib.util.module_from_spec(spec)
spec.loader.exec_module(recover) spec.loader.exec_module(recover)
RESTORABLE_RUNGS = recover.restorable_rungs
WRAPPER = repo / "infra/bin/fly-loop-reset"
T0 = 1_790_000_000
class RecoveryTests(unittest.TestCase): class RecoveryTests(unittest.TestCase):
@ -17,74 +23,615 @@ class RecoveryTests(unittest.TestCase):
self.temp = tempfile.TemporaryDirectory() self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup) self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name) root = Path(self.temp.name)
recover.REPORT = root / "loop.json" self.root = root
recover.STATE = root / "recovery.json" for name, value in (("REPORT", "loop.json"), ("STATE", "var/state.json"),
self.report = {"suspected": 1, "at": 1000, "action": "none", "reason": "unrewarded"} ("HISTORY", "var/history.jsonl"), ("NOTICE", "run/notice.json")):
self.save() patcher = patch.object(recover, name, root / value)
patcher.start()
self.addCleanup(patcher.stop)
milestones = root / "state"
milestones.mkdir()
for rung in (1, 9, 10, 11, 12):
(milestones / f"milestone-{rung}.checkpoint").write_text("x")
patcher = patch.object(recover, "MILESTONES", milestones)
patcher.start()
self.addCleanup(patcher.stop)
self.env = patch.dict("os.environ", {}, clear=False)
self.env.start()
self.addCleanup(self.env.stop)
for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"):
recover.os.environ.pop(key, None)
self.acts = []
self.unrestorable = set()
restorable = patch.object(recover, "restorable_rungs", side_effect=lambda: {1, 9, 10, 11, 12} - self.unrestorable)
restorable.start()
self.addCleanup(restorable.stop)
self.act = patch.object(recover, "act", side_effect=lambda action, target: self.acts.append((action, target)) or True)
self.act.start()
self.addCleanup(self.act.stop)
self.report(suspected=1, at=T0)
def save(self): def report(self, **fields):
recover.REPORT.write_text(json.dumps(self.report)) base = {"suspected": 1, "action": "none", "reason": "unrewarded", "sequence": ["GO WARP"],
"milestone": {"rank": 12, "label": "MT. MOON"}, "map": 61}
base.update(fields)
if "rank" in fields:
base["milestone"] = {"rank": base.pop("rank"), "label": "X"}
recover.REPORT.write_text(json.dumps(base))
def test_two_probes_and_cooldown(self): def tick(self, at, **fields):
with patch.object(recover, "verdict", return_value=True), patch.object(recover.subprocess, "run") as restart: """One watchdog probe at `at` and the timer running right after it."""
self.assertIn("second probe", recover.run(1001)) self.report(at=at, **fields)
self.assertIn("next probe", recover.run(1002)) return recover.run(at + 5, sleep=lambda seconds: None)
self.report["at"] = 1300
self.save()
self.assertIn("restarted", recover.run(1301))
restart.assert_called_once_with(["sudo", "-n", "systemctl", "restart", "flysim.service"], check=True)
self.assertIn("cooldown", recover.run(1302))
def test_stale_and_clear_never_restart(self): def confirm(self, start, **fields):
with patch.object(recover.subprocess, "run") as restart: """Two probes ~5 min apart after `start`; returns the second decision."""
self.assertIn("not a fresh", recover.run(1700)) self.assertIn("second probe", self.tick(start, **fields))
self.report.update(at=1700, suspected=0) return self.tick(start + 300, **fields)
self.save()
self.assertIn("not a fresh", recover.run(1700))
restart.assert_not_called()
def test_router_failure_does_not_act(self): def test_ladder_restart_then_current_rung_then_rung_below(self):
recover.run(1000) self.assertIn("flysim restarted", self.confirm(T0))
self.report["at"] = 1300 self.assertEqual(self.acts, [("restart", None)])
self.save() self.assertIn("settling", self.tick(T0 + 600))
with patch.object(recover, "verdict", side_effect=ValueError("bad response")), patch.object(recover.subprocess, "run") as restart: self.assertIn("reset to rung 12", self.confirm(T0 + 300 + recover.SETTLE + 10))
self.assertEqual(recover.run(1300), "router unavailable") start = T0 + 2 * (300 + recover.SETTLE + 10)
restart.assert_not_called() self.assertIn("reset to rung 11", self.confirm(start, rank=12))
self.assertEqual([a for a in self.acts], [("restart", None), ("reset", 12), ("reset", 11)])
def test_cleared_probe_preserves_cooldown(self): def test_spent_reset_budget_holds_to_restarts_three_hours_apart(self):
with patch.object(recover, "verdict", return_value=True), patch.object(recover.subprocess, "run") as restart: at = T0
recover.run(1000) for _ in range(3):
self.report["at"] = 1300 self.confirm(at)
self.save() at += 300 + recover.SETTLE + 10
recover.run(1300) self.assertEqual(len(self.acts), 3)
self.report.update(at=1600, suspected=0) self.assertIn("holding", self.confirm(at))
self.save() # the trap never cleared while holding, so the first probe after the hold acts
recover.run(1600) self.assertIn("flysim restarted", self.tick(at + recover.HOLD))
self.report.update(at=1900, suspected=1) self.assertEqual(self.acts[-1], ("restart", None))
self.save()
recover.run(1900)
self.report["at"] = 2200
self.save()
self.assertIn("cooldown", recover.run(2200))
restart.assert_called_once()
def test_router_rejection_does_not_restart(self): def test_deeper_resets_never_go_below_the_rung_under_the_best(self):
recover.run(1000) state = {"level": 5, "bestRank": 12, "resets": [], "actedAt": 0}
self.report["at"] = 1300 recover.write_json(recover.STATE, state)
self.save() self.confirm(T0, rank=11)
with patch.object(recover, "verdict", return_value=False), patch.object(recover.subprocess, "run") as restart: self.assertEqual(self.acts, [("reset", 11)])
self.assertIn("did not confirm", recover.run(1300))
restart.assert_not_called()
def test_partial_router_configuration_cannot_bypass_veto(self): def test_an_unrestorable_rung_below_the_best_means_a_restart_never_a_lower_rung(self):
with patch.dict("os.environ", {"FLY_LOOP_ROUTER_URL": "http://router/v1"}, clear=True): self.unrestorable = {11}
self.assertFalse(recover.verdict(self.report)) recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
with patch.dict("os.environ", {"FLY_LOOP_MODEL": "free"}, clear=True): self.confirm(T0)
self.assertFalse(recover.verdict(self.report)) self.assertEqual(self.acts, [("restart", None)])
def test_unconfigured_router_uses_deterministic_confirmation(self): def test_a_fly_already_below_the_rung_under_its_best_is_restarted_not_reset(self):
with patch.dict("os.environ", {}, clear=True): recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.assertTrue(recover.verdict(self.report)) self.confirm(T0, rank=10)
self.assertEqual(self.acts, [("restart", None)])
def test_no_restorable_archive_means_a_restart(self):
self.unrestorable = {1, 9, 10, 11, 12}
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
def test_new_best_rung_starts_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.confirm(T0, rank=13)
self.assertEqual(self.acts, [("restart", None)])
# Row 70: the rung-11 reset replayed the run exactly (1,138 of 1,138 events), caught the Zubat
# again and walked into the same trap; the next step reset to rung 11 again and erased the catch.
def test_progress_after_the_last_step_starts_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 4, "bestRank": 12, "resets": [], "actedAt": T0 - 7200})
# an area and a species inside the windows of probes well after the step
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 2, "species": 0}})
self.assertIn("flysim restarted", self.confirm(T0))
self.assertEqual(self.acts, [("restart", None)])
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("progress since the last step", [event.get("why") for event in history])
def test_progress_while_a_step_settles_does_not_start_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 1500})
self.tick(T0 - 1400, suspected=0, window={"progress": {"lasting": 3, "species": 0}})
self.confirm(T0)
self.assertEqual(self.acts, [("reset", 11)])
def test_a_species_owned_recently_is_never_reset_away(self):
owned = T0 - 1200
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [],
"actedAt": T0 - recover.HOLD - 300, "speciesAt": owned})
self.assertIn("flysim restarted", self.confirm(T0))
self.assertEqual(self.acts, [("restart", None)])
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("protect", [event.get("event") for event in history])
# the hold still spaces the restarts, and says why
self.assertIn("protection window", self.confirm(T0 + 300 + recover.SETTLE + 10))
# the protection lasts PROTECT from the species; then the ladder resets as before
self.assertIn("reset to rung 11", self.tick(owned + recover.PROTECT + 60))
def test_a_probe_that_owns_a_species_starts_the_protection(self):
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
self.assertEqual(recover.load(recover.STATE, {}).get("speciesAt"), T0)
self.assertEqual(recover.load(recover.STATE, {}).get("progressAt"), T0)
def test_the_last_resets_archive_is_not_restored_again(self):
acted = T0 - recover.HOLD - 100
recover.write_json(recover.STATE, {"level": 3, "bestRank": 12, "resets": [acted],
"actedAt": acted, "lastReset": 11, "lastResetAt": acted})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
def test_a_protected_reset_does_not_climb_but_the_archive_just_used_does(self):
# protected: the restart keeps the level's slot, so the reset comes at the same rung later
owned = T0 - 600
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": 0,
"speciesAt": owned})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 1)
# the archive just restored: a restart that climbs, and the marker is forgotten after AGAIN
self.acts.clear()
reset_at = T0 - recover.HOLD - 100
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [reset_at], "actedAt": reset_at,
"lastReset": 12, "lastResetAt": reset_at})
self.confirm(T0 + 1000)
self.assertEqual(self.acts, [("restart", None)])
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
self.acts.clear()
self.tick(reset_at + recover.AGAIN + 60)
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
def test_a_reset_records_its_archive_and_a_new_best_rung_forgets_it(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.confirm(T0)
self.assertEqual(recover.load(recover.STATE, {}).get("lastReset"), 11)
self.tick(T0 + 300 + recover.SETTLE + 10, suspected=0, rank=13)
self.assertNotIn("lastReset", recover.load(recover.STATE, {}))
# Row 70 review r3: a reset restores the reward ledger, so its replay pays the archive's rewards
# again. Progress is a reward name the ladder has not seen before, not a count.
def test_a_replay_that_re_earns_seen_rewards_does_not_start_the_ladder_over(self):
seen = ["area:AREA 59", "pokedex:OWNED #8", "trainer:BEAT ROUTE 3 TRAINER 0", "milestone:Reached MT. MOON"]
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": seen})
replay = {"progress": {"lasting": 4, "species": 1, "keys": seen}}
self.tick(T0 - 3000, suspected=0, window=replay)
state = recover.load(recover.STATE, {})
self.assertNotIn("progressAt", state)
self.assertNotIn("speciesAt", state) # the replayed catch was protected before the reset
self.assertEqual(state["progressSeen"], seen)
self.confirm(T0)
self.assertEqual(self.acts, [("reset", 11)])
def test_a_reward_not_seen_before_starts_the_ladder_over_and_a_new_species_is_protected(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": ["area:AREA 59"]})
self.tick(T0 - 3000, suspected=0,
window={"progress": {"lasting": 2, "species": 1, "keys": ["area:AREA 59", "pokedex:OWNED #41"]}})
state = recover.load(recover.STATE, {})
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
self.assertEqual(state["progressSeen"], ["area:AREA 59", "pokedex:OWNED #41"])
self.assertIn("flysim restarted", self.confirm(T0))
history = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertIn("progress since the last step", [event.get("why") for event in history])
def test_a_catch_while_the_fly_stays_flagged_does_not_start_the_ladder_over(self):
acted = T0 - recover.HOLD - 600
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": acted,
"clearAt": acted + 60})
catch = {"progress": {"lasting": 1, "species": 1, "keys": ["pokedex:OWNED #41"]}}
self.assertIn("flysim restarted", self.confirm(T0, window=catch))
self.assertEqual(self.acts, [("restart", None)]) # the rung-11 reset, held for the new species
self.assertEqual(recover.load(recover.STATE, {}).get("level"), 2)
def test_without_reward_names_the_counts_still_count(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": T0 - 7200,
"progressSeen": ["pokedex:OWNED #8"]})
self.tick(T0 - 3000, suspected=0, window={"progress": {"lasting": 1, "species": 1}})
state = recover.load(recover.STATE, {})
self.assertEqual((state["progressAt"], state["speciesAt"]), (T0 - 3000, T0 - 3000))
def test_the_names_remembered_are_bounded(self):
recover.write_json(recover.STATE, {"progressSeen": [f"area:AREA {n}" for n in range(recover.SEEN)]})
self.tick(T0, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA X"]}})
seen = recover.load(recover.STATE, {})["progressSeen"]
self.assertEqual((len(seen), seen[0], seen[-1]), (recover.SEEN, "area:AREA 1", "area:AREA X"))
# a malformed list is ignored item by item
self.tick(T0 + 300, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": [{}, ["x"], 3]}})
self.assertEqual(recover.load(recover.STATE, {})["progressSeen"][-1], "area:AREA X")
def test_restarts_stay_a_hold_apart_after_the_ladder_starts_over(self):
recover.write_json(recover.STATE, {"level": 1, "bestRank": 12, "resets": [], "actedAt": T0 - 3600,
"lastAction": "restart"})
self.tick(T0 - 2000, suspected=0, window={"progress": {"lasting": 1, "species": 0, "keys": ["area:AREA 60"]}})
self.assertIn("last restart was under three hours ago", self.confirm(T0))
self.assertEqual(self.acts, [])
self.assertIn("flysim restarted", self.tick(T0 - 3600 + recover.HOLD))
def test_a_failed_reset_does_not_block_its_archive(self):
recover.act.side_effect = lambda action, target: self.acts.append((action, target)) or False
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "resets": [], "actedAt": 0})
self.assertIn("reset FAILED", self.confirm(T0))
state = recover.load(recover.STATE, {})
self.assertNotIn("lastReset", state)
self.assertEqual((state["level"], len(state["resets"])), (3, 1)) # it still climbed and spent the reset
def test_quiet_hours_start_the_ladder_over(self):
recover.write_json(recover.STATE, {"level": 2, "bestRank": 12, "actedAt": 0,
"lastSuspectedAt": T0 - recover.QUIET - 1})
self.confirm(T0)
self.assertEqual(self.acts, [("restart", None)])
def test_stale_clear_or_acted_reports_never_act(self):
self.report(at=T0 - 700)
self.assertIn("not a fresh", recover.run(T0))
self.report(suspected=0, at=T0)
self.assertIn("not a fresh", recover.run(T0 + 1))
self.report(at=T0, action="restart")
self.assertIn("not a fresh", recover.run(T0 + 2))
self.assertEqual(self.acts, [])
def test_a_clear_probe_breaks_the_streak(self):
self.tick(T0)
self.tick(T0 + 300, suspected=0)
self.assertIn("second probe", self.tick(T0 + 600))
self.assertEqual(self.acts, [])
def test_state_survives_a_reboot_and_ignores_a_missing_or_corrupt_file(self):
self.confirm(T0)
self.assertTrue(recover.STATE.exists())
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
recover.STATE.write_text("{nope")
self.assertIn("second probe", self.tick(T0 + 5000))
def test_model_vetoes_delay_a_step_but_never_deny_it(self):
with patch.object(recover, "verdict", return_value=(False, "m")):
self.tick(T0)
for n in range(1, recover.VETO_LIMIT + 1):
self.assertIn(f"({n}/{recover.VETO_LIMIT})", self.tick(T0 + 300 * n))
self.assertIn("veto limit reached", self.tick(T0 + 300 * (recover.VETO_LIMIT + 1)))
self.assertEqual(self.acts, [("restart", None)])
def test_no_model_answer_falls_back_to_the_watchdog(self):
with patch.object(recover, "verdict", return_value=(None, None)):
self.assertIn("watchdog alone", self.confirm(T0))
def test_models_are_tried_in_order_until_one_answers(self):
recover.os.environ.update(FLY_LOOP_ROUTER_URL="http://router/v1", FLY_LOOP_MODELS="a, b ,c")
replies = iter([OSError("429"), {"choices": [{"message": {"content": "thinking...\n```json\n{\"stuck\": true}\n```"}}]}])
asked = []
class Reply:
def __init__(self, body):
self.body = body
def __enter__(self):
return self
def __exit__(self, *exc):
return False
def read(self):
return json.dumps(self.body).encode()
def fake(request, timeout):
asked.append(json.loads(request.data)["model"])
reply = next(replies)
if isinstance(reply, Exception):
raise reply
return Reply(reply)
with patch.object(recover, "urlopen", side_effect=fake):
self.assertEqual(recover.verdict({"reason": "unrewarded"}), (True, "b"))
self.assertEqual(asked, ["a", "b"])
def test_parse_stuck_tolerates_prose_and_rejects_non_booleans(self):
self.assertIs(recover.parse_stuck('{"stuck":false}'), False)
self.assertIs(recover.parse_stuck('Answer: {"stuck": true} done'), True)
self.assertIsNone(recover.parse_stuck('{"stuck": "yes"}'))
self.assertIsNone(recover.parse_stuck(""))
self.assertIsNone(recover.parse_stuck(None))
def test_notice_goes_countdown_acting_done_for_the_splash(self):
phases = []
real = recover.notice
with patch.object(recover, "notice", side_effect=lambda base, phase, now: phases.append(phase) or real(base, phase, now)):
self.confirm(T0 + 300 + recover.SETTLE)
recover.write_json(recover.STATE, dict(json.loads(recover.STATE.read_text()), actedAt=0))
self.confirm(T0 + 2 * (300 + recover.SETTLE))
notice = json.loads(recover.NOTICE.read_text())
self.assertEqual(phases, ["countdown", "acting", "done"] * 2)
self.assertEqual((notice["v"], notice["action"], notice["toRung"], notice["toLabel"], notice["fromRung"]),
(1, "reset", 12, "MT. MOON", 12))
self.assertEqual(notice["executeAt"] - notice["announcedAt"], recover.COUNTDOWN)
def test_failed_action_is_reported_and_still_climbs(self):
self.act.stop()
with patch.object(recover, "act", return_value=False):
self.assertIn("FAILED", self.confirm(T0))
self.act.start()
self.assertEqual(json.loads(recover.NOTICE.read_text())["phase"], "failed")
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
def test_a_step_that_raises_or_times_out_is_a_failed_step_with_state_saved(self):
self.act.stop()
with patch.object(recover.subprocess, "run", side_effect=recover.subprocess.TimeoutExpired("sudo", 1)):
self.assertIn("FAILED", self.confirm(T0))
self.act.start()
self.assertEqual(json.loads(recover.NOTICE.read_text())["phase"], "failed")
self.assertEqual(json.loads(recover.STATE.read_text())["level"], 1)
def test_state_is_saved_before_the_step_runs(self):
seen = []
self.act.stop()
with patch.object(recover, "act", side_effect=lambda a, t: seen.append(json.loads(recover.STATE.read_text())) or True):
self.confirm(T0)
self.act.start()
self.assertEqual(seen[0]["level"], 1)
self.assertNotIn("observedAt", seen[0])
def test_restorable_rungs_parses_the_list_and_is_empty_on_any_failure(self):
ok = recover.subprocess.CompletedProcess([], 0, stdout="11\n12\n", stderr="")
with patch.object(recover.subprocess, "run", return_value=ok):
self.assertEqual(RESTORABLE_RUNGS(), {11, 12})
with patch.object(recover.subprocess, "run", side_effect=OSError("no sudo")):
self.assertEqual(RESTORABLE_RUNGS(), set())
with patch.object(recover.subprocess, "run", return_value=recover.subprocess.CompletedProcess([], 1, "12", "")):
self.assertEqual(RESTORABLE_RUNGS(), set())
def test_stuck_time_counts_from_the_last_progress_across_restarts(self):
self.report(at=T0 - 7200, suspected=0, places={"uniqueLocations": 10, "delta": 4})
recover.run(T0 - 7195)
recover.write_json(recover.STATE, dict(json.loads(recover.STATE.read_text()), vetoes=0))
self.confirm(T0)
self.assertEqual(json.loads(recover.NOTICE.read_text())["stuckSeconds"], 7505)
self.assertEqual(json.loads(recover.STATE.read_text())["lastProgressAt"], T0 - 7200)
def test_stuck_time_falls_back_to_the_streak_without_a_progress_mark(self):
self.confirm(T0)
self.assertEqual(json.loads(recover.NOTICE.read_text())["stuckSeconds"], 305 + 600)
def test_history_records_every_step(self):
self.confirm(T0)
lines = [json.loads(line) for line in recover.HISTORY.read_text().splitlines()]
self.assertEqual(lines[-1]["event"], "restart")
self.assertTrue(lines[-1]["ok"])
def test_ladder_labels_match_the_rust_table(self):
source = (repo / "services/flysim/crates/flybrain-gb/src/pokemon_red/mod.rs").read_text()
table = re.search(r"RANK_LADDER: \[&str; \d+\] = \[(.*?)\];", source, re.S).group(1)
self.assertEqual(recover.LADDER, re.findall(r'"([^"]*)"', table))
BUILD = "lif-1ms-f64-v2/pokered-unique8-v7/abc/fly-kc-mbon-rstdp-v2"
@unittest.skipIf(recover.os.geteuid() == 0, "the wrapper ignores test overrides as root")
class ClosedLoopTests(unittest.TestCase):
"""Row 70 review L1: a trap no restart clears, every reset replaying it exactly (closed loop)."""
M = 60
R11 = dict(events=[(20, "pokedex"), (21, "trainer"), (35, "trainer"), (44, "area"), (46, "milestone"),
(52, "pokedex")], trap=58, rank_after=[(46, 12)], start_rank=11)
R12 = dict(events=[(7, "pokedex")], trap=12, rank_after=[], start_rank=12)
R10 = dict(events=[(30, "area"), (60, "milestone"), (90, "milestone"), (100, "pokedex")], trap=110,
rank_after=[(60, 11), (90, 12)], start_rank=10)
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
for name, value in (("REPORT", "loop.json"), ("STATE", "s.json"), ("HISTORY", "h.jsonl"),
("NOTICE", "n.json")):
patcher = patch.object(recover, name, root / value)
patcher.start()
self.addCleanup(patcher.stop)
for name, value in (("restorable_rungs", lambda: {9, 10, 11, 12}), ("verdict", lambda report: (None, None))):
patcher = patch.object(recover, name, value)
patcher.start()
self.addCleanup(patcher.stop)
self.env = patch.dict("os.environ", {}, clear=False)
self.env.start()
self.addCleanup(self.env.stop)
for key in ("FLY_LOOP_ROUTER_URL", "FLY_LOOP_MODELS", "FLY_LOOP_MODEL", "FLY_LOOP_ROUTER_KEY"):
recover.os.environ.pop(key, None)
def simulate(self, archives, hours, species_before=None, names=True):
"""The fly is trapped from T0; returns [(hours, action, target)]. A reset replays its archive.
Every lasting reward has a name (window.progress.keys): the fly earned each archive's rewards
once before the trap, in clear probes the ladder saw, and a replay pays the same names again.
"""
M = self.M
sim = dict(events=[(T0 - species_before * M, "pokedex", "pokedex:pre")] if species_before else [],
rank=12, rank_changes=[], trap_from=T0, now=T0, acts=[])
history = [f"{k}:{rung}/{o}" for rung, a in sorted(archives.items()) for o, k in a["events"]]
for i in range(0, len(history), 3) if names else ():
recover.REPORT.write_text(json.dumps({
"at": T0 - 86400 + i * 300, "suspected": 0, "action": "none", "milestone": {"rank": 12},
"window": {"progress": {"lasting": 3, "species": 0, "keys": history[i:i + 3]}}}))
recover.run(now=T0 - 86400 + i * 300 + 5, sleep=lambda s: None)
seen = recover.load(recover.STATE, {}).get("progressSeen")
def act(action, target):
sim["acts"].append((sim["now"], action, target))
if action == "reset":
a = archives[target]
sim["rank"] = a["start_rank"]
sim["events"] = [(sim["now"] + o * M, k, f"{k}:{target}/{o}") for o, k in a["events"]]
sim["rank_changes"] = [(sim["now"] + o * M, r) for o, r in a["rank_after"]]
sim["trap_from"] = None if a["trap"] is None else sim["now"] + a["trap"] * M
return True
recover.write_json(recover.STATE, dict({"bestRank": 12, "rank": 12, "level": 0},
**({"progressSeen": seen} if seen else {})))
recover.HISTORY.write_text("")
with patch.object(recover, "act", side_effect=act):
t = T0
while t < T0 + hours * 3600:
for change in list(sim["rank_changes"]):
if change[0] <= t:
sim["rank"] = change[1]
sim["rank_changes"].remove(change)
win = [(k, name) for at, k, name in sim["events"] if t - 600 <= at <= t]
trapped = sim["trap_from"] is not None and t - sim["trap_from"] >= 600
recover.REPORT.write_text(json.dumps({
"at": t, "suspected": 1 if trapped else 0, "action": "none", "reason": "dominant",
"sequence": ["NEXT"], "milestone": {"rank": sim["rank"], "label": "X"}, "map": 59,
"window": {"progress": dict({
"lasting": sum(k in ("pokedex", "area", "trainer", "badge", "milestone") for k, _ in win),
"species": sum(k == "pokedex" for k, _ in win)},
**({"keys": [name for _, name in win]} if names else {}))}}))
sim["now"] = t + 5
recover.run(now=t + 5, sleep=lambda s: None)
t += 300
return [((at - T0) / 3600, action, target) for at, action, target in sim["acts"]]
def test_a_restart_proof_trap_is_reset_in_bounded_time_and_again(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 72, species_before=6)
resets = [a for a in acts if a[1] == "reset"]
# v0.7.0 resets again at 24.75 h; the ladder is no worse, and keeps resetting
self.assertTrue(resets and resets[0][0] <= 25, acts)
self.assertTrue(len([a for a in resets if a[0] <= 25]) >= 1, acts)
self.assertTrue(len(resets) >= 3, acts)
gaps = [b[0] - a[0] for a, b in zip(resets, resets[1:])]
self.assertTrue(all(g <= 25 for g in gaps), acts)
# the first step is a restart; the catch stays protected for 2 h
self.assertEqual(acts[0][1], "restart")
self.assertTrue(all(a[0] >= 2 - 0.2 for a in resets[:1]), acts)
def test_the_held_reset_is_the_rung_12_one_not_a_deeper_rung(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24, species_before=6)
self.assertEqual([a[2] for a in acts if a[1] == "reset"][:1], [12], acts)
def test_a_trap_the_rung_12_archive_escapes_ends_there(self):
clean = dict(self.R12, trap=None)
acts = self.simulate({11: self.R11, 12: clean, 10: self.R10, 9: self.R10}, 24, species_before=6)
self.assertEqual([a[1:] for a in acts if a[1] == "reset"], [("reset", 12)], acts)
self.assertEqual(len(acts), 2, acts)
def test_without_a_catch_the_ladder_resets_early(self):
acts = self.simulate({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10}, 24)
self.assertLessEqual(next(a[0] for a in acts if a[1] == "reset"), 1, acts)
def test_a_trap_only_the_rung_below_escapes_is_reached_promptly(self):
# review r2 N1: the rung-12 replay re-earns progress, then traps; only rung 11 escapes.
# v0.7.0 reset to 11 at 2.08 h; holding the level on the archive just used took 24.75 h, and
# counting the replay's area and species as progress took 5.58 h (6.83 h after a catch).
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
archives = {11: dict(self.R11, trap=None), 12: late12, 10: self.R10, 9: self.R10}
for species_before, bound in ((None, 2.1), (6, 2.1 + 2)): # a catch 6 min before the trap: +2 h at most
with self.subTest(species_before=species_before):
self.setUp()
acts = self.simulate(archives, 96, species_before=species_before)
resets = [a for a in acts if a[1] == "reset"]
self.assertEqual([a[2] for a in resets], [12, 11], acts)
self.assertLessEqual(resets[-1][0], bound, acts)
def test_restarts_are_a_hold_apart_in_every_closed_loop(self):
late12 = dict(events=[(30, "area"), (40, "pokedex")], trap=60, rank_after=[], start_rank=12)
for archives in ({11: self.R11, 12: self.R12, 10: self.R10, 9: self.R10},
{11: self.R11, 12: late12, 10: self.R10, 9: self.R10}):
for species_before in (None, 6):
self.setUp()
acts = self.simulate(archives, 72, species_before=species_before)
restarts = [a[0] for a in acts if a[1] == "restart"]
self.assertTrue(all(b - a >= 3 - 1e-6 for a, b in zip(restarts, restarts[1:])), acts)
resets = [a[0] for a in acts if a[1] == "reset"]
self.assertTrue(all(sum(1 for y in resets if x <= y < x + 24) <= 2 for x in resets), acts)
class WrapperTests(unittest.TestCase):
"""infra/bin/fly-loop-reset against a fake flysim, systemctl, reset tool and archives."""
def setUp(self):
self.temp = tempfile.TemporaryDirectory()
self.addCleanup(self.temp.cleanup)
root = Path(self.temp.name)
self.root = root
self.calls = root / "calls.log"
(root / "state").mkdir()
(root / "bin").mkdir()
# The watchdog probe is mid-run ("activating") for the first two looks.
self.script(root / "bin/systemctl", f'''echo "systemctl $*" >> {self.calls}
if [ "$1" = show ]; then
n=$(grep -c "^systemctl show" {self.calls})
if [ "$n" -le 2 ]; then echo activating; else echo inactive; fi
fi''')
self.script(root / "flysim", f'[ "$1" = --print-compatibility ] && echo "{BUILD}"')
self.script(root / "reset", f'echo "reset $* FLY_BIN=$FLY_BIN" >> {self.calls}')
self.env_file = root / "fly.env"
self.env_file.write_text('FLY_MACRO_MODE=macros\nGAME_TITLE=Pokemon (Red) $(touch pwned)\n')
self.archive(12, BUILD)
self.archive(11, BUILD.replace("-v7", "-v6"))
self.archive(1, BUILD.replace("-v7", "-v5"))
def script(self, path, body):
path.write_text("#!/bin/sh\n" + body + "\n")
path.chmod(0o755)
def archive(self, rung, compat):
(self.root / f"state/milestone-{rung}.checkpoint").write_bytes(
b"FLYSIM01" + json.dumps({"generation": 1, "compatibility": compat}).encode() + b"\x00" * 64)
def run_wrapper(self, *args):
env = {"PATH": f"{self.root}/bin:/usr/bin:/bin", "FLY_LOOP_RESET_TEST_STATE_DIR": str(self.root / "state"),
"FLY_LOOP_RESET_TEST_ENV_FILE": str(self.env_file), "FLY_LOOP_RESET_TEST_FLYSIM": str(self.root / "flysim"),
"FLY_LOOP_RESET_TEST_RESET_BIN": str(self.root / "reset")}
env.update(getattr(self, "extra_env", {}))
return recover.subprocess.run([str(WRAPPER), *args], env=env, capture_output=True, text=True, timeout=60)
def log(self):
return self.calls.read_text() if self.calls.exists() else ""
def test_list_names_only_rungs_this_build_restores(self):
self.assertEqual(self.run_wrapper("--list").stdout.split(), ["12"])
self.env_file.write_text("FLY_ACCEPT_ADAPTERS=pokered-unique8-v6\n")
self.assertEqual(self.run_wrapper("--list").stdout.split(), ["11", "12"])
self.assertFalse((self.root / "pwned").exists())
def test_reset_pauses_the_watchdog_and_always_starts_flysim_again(self):
done = self.run_wrapper("12")
self.assertEqual(done.returncode, 0, done.stderr)
self.assertEqual([line.split()[:3] for line in self.log().splitlines() if not line.startswith("systemctl is-active")], [
["systemctl", "stop", "fly-watchdog.timer"],
["systemctl", "show", "-p"], ["systemctl", "show", "-p"], ["systemctl", "show", "-p"], ["systemctl", "show", "-p"],
["systemctl", "stop", "flysim.service"],
["reset", "12", f"FLY_BIN={self.root}/flysim"],
["systemctl", "start", "flysim.service"], ["systemctl", "start", "fly-watchdog.timer"]])
def test_a_failed_reset_still_starts_flysim_and_the_watchdog(self):
self.script(self.root / "reset", f'echo "reset $*" >> {self.calls}; exit 7')
self.assertEqual(self.run_wrapper("12").returncode, 7)
self.assertIn("systemctl start flysim.service", self.log())
self.assertIn("systemctl start fly-watchdog.timer", self.log())
def test_an_unrestorable_or_missing_rung_touches_nothing(self):
for rung in ("11", "5"):
self.assertEqual(self.run_wrapper(rung).returncode, 3)
self.assertEqual(self.log(), "")
def test_no_build_compatibility_means_nothing_is_restorable(self):
(self.root / "flysim").unlink()
self.assertEqual(self.run_wrapper("--list").stdout, "")
self.assertEqual(self.run_wrapper("12").returncode, 3)
self.assertEqual(self.log(), "")
def test_a_root_copy_that_is_not_the_running_build_restores_nothing(self):
other = self.root / "live-flysim"
self.script(other, "echo other build")
self.extra_env = {"FLY_LOOP_RESET_TEST_LIVE_FLYSIM": str(other)}
self.assertEqual(self.run_wrapper("--list").stdout, "")
self.assertEqual(self.run_wrapper("12").returncode, 3)
def test_a_watchdog_probe_that_never_finishes_blocks_the_reset(self):
self.script(self.root / "bin/systemctl", f'echo "systemctl $*" >> {self.calls}; [ "$1" != show ] || echo activating')
self.script(self.root / "bin/sleep", "exit 0")
self.assertEqual(self.run_wrapper("12").returncode, 4)
self.assertNotIn("systemctl stop flysim.service", self.log())
self.assertIn("systemctl start fly-watchdog.timer", self.log())
def test_bad_arguments_are_refused(self):
for args in ((), ("--check", "12"), ("12", "13"), ("../12",), ("123",), ("-1",)):
self.assertEqual(self.run_wrapper(*args).returncode, 2, args)
self.assertEqual(self.log(), "")
if __name__ == "__main__": if __name__ == "__main__":

View file

@ -1,8 +1,13 @@
[Unit] [Unit]
Description=Check confirmed macro loops for minimal flysim recovery Description=Recover confirmed macro loops: flysim restart, then milestone resets
[Service] [Service]
Type=oneshot Type=oneshot
User=fly User=fly
EnvironmentFile=-/etc/fly/loop-recovery.env EnvironmentFile=-/etc/fly/loop-recovery.env
# The ladder's state and history outlive a reboot (/run does not).
StateDirectory=fly-loop-recover
# A step: the rung list (<=2 min), up to 90 s of model calls, a 60 s on-stream countdown,
# the reset (<=8 min) and 4 min to verify. systemd must never kill the wrapper mid-reset.
TimeoutStartSec=25min
ExecStart=/opt/fly/bin/fly-loop-recover ExecStart=/opt/fly/bin/fly-loop-recover

View file

@ -2,9 +2,12 @@
Description=Check for repeated macro loops after watchdog probes Description=Check for repeated macro loops after watchdog probes
[Timer] [Timer]
OnBootSec=7min # Every minute: a run only reads /run/fly/wd/loop.json unless a step is due, and the ladder's
OnUnitActiveSec=5min # state ignores a probe it has already seen. On a 5-minute cadence the timer's phase can sit just
AccuracySec=10s # before each loop probe (live, 2026-09-28: one second), costing ~5 minutes per confirmation.
OnBootSec=2min
OnUnitActiveSec=1min
AccuracySec=5s
Unit=fly-loop-recover.service Unit=fly-loop-recover.service
[Install] [Install]

View file

@ -13,3 +13,7 @@ ExecStart=/opt/fly/bin/fly-recap
Nice=19 Nice=19
IOSchedulingClass=idle IOSchedulingClass=idle
CPUWeight=20 CPUWeight=20
# Batch work never competes with anything: idle policy (Nice and CPUWeight are moot under it). The
# sim's CPUs are out of its reach anyway (fly-cpu-confine); this keeps it off the page's and the
# encoder's too. SCHED_IDLE measured harmless beside the pinned sweep workers.
CPUSchedulingPolicy=idle

Some files were not shown because too many files have changed in this diff Show more