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).
This commit is contained in:
acamilo 2026-09-29 18:03:59 +00:00
parent 817318f014
commit 7c8d5a33dc
12 changed files with 3015 additions and 0 deletions

View file

@ -435,6 +435,20 @@ dependencies = [
"tracing-subscriber", "tracing-subscriber",
] ]
[[package]]
name = "fly-legacy-session"
version = "0.1.1"
dependencies = [
"fly-session",
"flybrain-core",
"flybrain-gb",
"flybus",
"flysim",
"serde_json",
"tempfile",
"tokio",
]
[[package]] [[package]]
name = "fly-session" name = "fly-session"
version = "0.1.1" version = "0.1.1"

View file

@ -2,6 +2,7 @@
resolver = "3" resolver = "3"
members = [ members = [
"crates/fly-edge", "crates/fly-edge",
"crates/fly-legacy-session",
"crates/fly-session", "crates/fly-session",
"crates/fly-session-types", "crates/fly-session-types",
"crates/flybrain-core", "crates/flybrain-core",

View file

@ -0,0 +1,28 @@
[package]
name = "fly-legacy-session"
version.workspace = true
edition = "2024"
rust-version.workspace = true
license.workspace = true
publish = false
description = "The live fly's composition on the session framework: the pokered-macros-v1 task and executor, the FLYSIM01 import, and the parity harness against the legacy loop's FLY_TRACE."
[lib]
name = "fly_legacy_session"
path = "src/lib.rs"
[dependencies]
# The session framework and its legacy workers (AGENT-01, ENV-01).
fly-session = { path = "../fly-session" }
flybus = { path = "../flybus" }
# The unchanged legacy engine the task and executor run: flysim's macro layer, flybrain-gb's
# palette, macro executor, PokeState, reward adapter and ratchet, read through MEM-01's image.
# flysim is a library dependency only; nothing here changes the service it builds.
flysim = { path = "../flysim" }
flybrain-gb = { path = "../flybrain-gb" }
flybrain-core = { path = "../flybrain-core" }
serde_json = { workspace = true }
tokio = { version = "1", features = ["rt", "rt-multi-thread", "sync", "time", "macros"] }
[dev-dependencies]
tempfile = "3"

View file

@ -0,0 +1,112 @@
//! Sugar, admitted by the legacy rules onto the coordinator's admission queue, and the operator
//! reward pulse, refused (`legacy-gameboy-v1` section 15 and its amendment of 2026-09-29).
//!
//! The rules are flysim's own, unchanged: `flysim::ratelimit::RateLimiter` (the per-minute limit
//! and "no overlap with an active pulse") and the duration clamp to `[1, sugar_max_ms]`. What
//! changed is the pulse they read: the agent's `stimulusRemainingMs` from the **last completed
//! commit** ([`AdmissionQueue::stimulus_remaining_ms`]), which the operator accepted as one commit
//! stale. Until the first commit of an epoch it is unknown, and a request is refused with a retry.
//!
//! The operator's `POST /reward` pulse is refused. The legacy loop refuses it too unless an
//! operator turns `control.allow_reward` on (it is off in every shipped configuration); the new
//! runtime has no counterpart to turn on, and says so rather than approximating one -- a
//! reinforcement outside `Agent.Commit` is not a session-framework operation.
use flysim::ratelimit::{RateLimiter, Refusal};
use fly_session::coordinator::{Admission, AdmissionQueue};
use fly_session::fly_session_types::gameboy::STIMULUS_REWARD_PULSE;
use fly_session::types::*;
/// Why `POST /reward` is refused (`legacy-gameboy-v1` section 15, amendment of 2026-09-29).
pub const OPERATOR_REWARD_REFUSED: &str = "the operator reward pulse is not available on the session runtime (legacy-gameboy-v1 section 15)";
/// Retry advice while the pulse is unknown: one frame, rounded up.
pub const UNKNOWN_PULSE_RETRY_MS: u64 = 17;
/// The edge-side admission of the legacy composition.
pub struct LegacyAdmission {
queue: AdmissionQueue,
agent_id: Id,
limiter: RateLimiter,
default_ms: f64,
max_ms: f64,
serial: u64,
}
impl LegacyAdmission {
/// flysim's defaults: 6 per minute, 400 ms by default, at most 1000 ms.
pub fn new(queue: AdmissionQueue, agent_id: Id) -> LegacyAdmission {
let control = flysim::config::Config::default().control;
LegacyAdmission::with_limits(
queue,
agent_id,
control.sugar_per_minute,
control.sugar_default_ms,
control.sugar_max_ms,
)
}
pub fn with_limits(
queue: AdmissionQueue,
agent_id: Id,
per_minute: usize,
default_ms: f64,
max_ms: f64,
) -> LegacyAdmission {
LegacyAdmission {
queue,
agent_id,
limiter: RateLimiter::new(per_minute),
default_ms,
max_ms,
serial: 0,
}
}
fn next_id(&mut self, kind: &str) -> Id {
self.serial += 1;
id(&format!("{kind}-{}", self.serial))
}
/// `POST /stimulate`: the legacy rule over the last commit's pulse. On admission the sugar is
/// queued for the next Prepare; the result is its interaction id and the clamped duration.
pub fn sugar(&mut self, now_ms: u64, duration_ms: Option<f64>) -> Result<(Id, f64), Refusal> {
let Some(remaining) = self.queue.stimulus_remaining_ms(&self.agent_id) else {
return Err(Refusal::PulseActive {
retry_after_ms: UNKNOWN_PULSE_RETRY_MS,
});
};
self.limiter.admit(now_ms, remaining)?;
let duration = duration_ms
.unwrap_or(self.default_ms)
.clamp(1.0, self.max_ms)
.min(self.max_ms);
let interaction_id = self.next_id("sugar");
self.queue.admit(Admission::Stimulus {
agent_id: self.agent_id.clone(),
interaction_id: interaction_id.clone(),
kind_id: id(STIMULUS_REWARD_PULSE),
duration_ms: duration,
});
Ok((interaction_id, duration))
}
/// `POST /reward`: refused, always (the legacy default, `control.allow_reward = false`).
pub fn reward(&mut self, _value: f64) -> Result<Id, &'static str> {
Err(OPERATOR_REWARD_REFUSED)
}
/// Admits exactly this sugar, bypassing the rules: a parity run replays the legacy loop's
/// admitted inputs, it does not re-decide them.
pub fn replay_sugar(&mut self, duration_ms: f64) -> Id {
let interaction_id = self.next_id("sugar");
self.queue.admit(Admission::Stimulus {
agent_id: self.agent_id.clone(),
interaction_id: interaction_id.clone(),
kind_id: id(STIMULUS_REWARD_PULSE),
duration_ms,
});
interaction_id
}
}

View file

@ -0,0 +1,340 @@
//! The legacy Game Boy composition on the session framework: one legacy agent (AGENT-01), the
//! legacy environment (ENV-01), and the `pokered-macros-v1` task and executor (this crate) in the
//! coordinator, over one router, in any of the launcher's execution modes.
//!
//! This is the whole new runtime of the live fly short of its edge (EDGE-01) and its FLYSIM01
//! export (STATE-02): what CUT-01's shadow runs beside the legacy service.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf};
use flybus::{Grants, Pattern, Policy, RouterConfig};
use fly_session::coordinator::{AgentSlot, Coordinator, StepDetails, StepReport};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy;
use fly_session::launcher::{
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
ThreadBudget, Via,
};
use fly_session::legacy_agent::{LegacyProfileKind, SPIKES_ATTACHMENT};
use fly_session::legacy_env::BackendConfig;
use fly_session::task::ActionExecutor;
use fly_session::types::*;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flysim::snapshot::MacroMode;
use crate::task::{PokeredConfig, PokeredTask, TaskRecord};
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
let mut g = Grants::default();
f(&mut g);
g
}
const COORDINATOR_CLIENT: &str = "coordinator";
const ENV_CLIENT: &str = "legacy-world";
const ENV_SERVICE: &str = "env.world";
const ENV_WORKER: &str = "world";
const AGENT_CLIENT: &str = "legacy-fly";
/// How one legacy session is composed.
#[derive(Clone, Debug)]
pub struct LegacyConfig {
pub mode: ExecutionMode,
pub rom_path: PathBuf,
pub dataset_dir: PathBuf,
pub profile: LegacyProfileKind,
pub macro_mode: MacroMode,
pub agent_id: Id,
pub agent_threads: usize,
/// Record the step details and the task records (a parity run).
pub record: bool,
}
/// The macro channels and the macro group's hold for a mode: the decoder preset flysim builds.
pub fn channels_and_hold(mode: MacroMode) -> (Vec<String>, f64) {
let channels: Vec<&str> = if mode.dealt() {
flybrain_gb::macro_channels(crate::task::GAME)
} else {
Vec::new()
};
let preset = gameboy_decoder_config_with_macros(&channels);
let hold_ms = preset
.macros
.as_ref()
.or(preset.exclusive.as_ref())
.map_or(0.0, |group| group.hold_ms);
(channels.iter().map(|c| (*c).to_owned()).collect(), hold_ms)
}
/// A running legacy session: its launcher, its coordinator and the task object.
pub struct LegacySession {
pub coordinator: Coordinator,
pub task: PokeredTask,
pub launcher: Launcher,
pub rom: Vec<u8>,
pub config: LegacyConfig,
session_id: Id,
backend: BackendConfig,
/// Which generation of the world is running: 1 is the one the session started.
world_generation: u32,
}
/// One transition as a parity run sees it.
pub struct Step {
pub report: StepReport,
pub details: Option<StepDetails>,
pub records: Vec<TaskRecord>,
}
impl LegacySession {
/// Builds the router, launches the world and the fly, and builds the coordinator with the task
/// object's two faces. Nothing has been initialized yet.
pub async fn start(root: &Path, config: LegacyConfig) -> Result<LegacySession, String> {
let rom = std::fs::read(&config.rom_path)
.map_err(|e| format!("the cartridge {}: {e}", config.rom_path.display()))?;
let rom_digest = sha256_hex(&rom);
let session_id = id("legacy");
let epoch = id("e1");
let store_root = root.join("store");
let sockets = root.join("sockets");
std::fs::create_dir_all(&sockets).map_err(|e| format!("sockets: {e}"))?;
let agent_service = format!("agent.{}", config.agent_id);
let policy = Policy::closed()
.client(
COORDINATOR_CLIENT,
grants(|g| {
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
g.publish = vec![Pattern::prefix("session.")];
g.manage_topics = vec![Pattern::prefix("session.")];
g.register = vec![Pattern::prefix("session.")];
}),
)
// The launcher's supervisor: health checks and shutdown, never a registration.
.client(
SUPERVISOR_CLIENT,
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
)
.client(
ENV_CLIENT,
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
)
.client(
&format!("{ENV_CLIENT}-r2"),
grants(|g| g.register = vec![Pattern::exact(ENV_SERVICE)]),
)
.client(
AGENT_CLIENT,
grants(|g| g.register = vec![Pattern::exact(&agent_service)]),
);
let mut router_config = RouterConfig::new(&store_root);
router_config.policy = policy;
let router = flybus::Router::new(router_config).map_err(|e| format!("router: {e}"))?;
let budget = ThreadBudget::new(2 + config.agent_threads, 1).map_err(|e| e.message)?;
let mut launcher = Launcher::start(
router,
config.mode,
Via::Unix,
&store_root,
&sockets,
budget,
)
.await
.map_err(|e| format!("launcher: {}", e.message))?;
let mut backend = BackendConfig::legacy(&rom_digest);
backend.slots = vec![id(crate::task::SLOT)];
launcher
.launch_legacy_environment(LegacyEnvironmentLaunch {
session_id: session_id.clone(),
worker_id: id(ENV_WORKER),
incarnation_id: id("world-inc-1"),
worker_threads: 1,
rom_path: config.rom_path.clone(),
backend: backend.clone(),
client_id: ENV_CLIENT.to_owned(),
service: ENV_SERVICE.to_owned(),
})
.await
.map_err(|e| format!("the world: {}", e.message))?;
let environment = launcher
.worker(&id(ENV_WORKER))
.expect("launched")
.worker_ref();
let (macro_channels, hold_ms) = channels_and_hold(config.macro_mode);
let identity = launcher
.launch_legacy_agent(LegacyAgentLaunch {
session_id: session_id.clone(),
agent_id: config.agent_id.clone(),
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
incarnation_id: parse_id(&format!("{}-inc-1", config.agent_id))?,
worker_threads: config.agent_threads,
dataset_dir: config.dataset_dir.clone(),
profile: config.profile,
macro_channels: macro_channels.clone(),
client_id: AGENT_CLIENT.to_owned(),
service: agent_service,
})
.await
.map_err(|e| format!("the fly: {}", e.message))?;
let agent_ref = launcher
.worker(&config.agent_id)
.expect("launched")
.worker_ref();
let mut slot = AgentSlot::new(
agent_ref,
config.agent_id.clone(),
id(fly_session::legacy_env::DEFAULT_PORT),
config.profile.profile().asset,
fly_session::legacy_parity::LEGACY_SEED,
);
slot.worker_threads = identity.worker_threads as u64;
slot.model_version = gameboy::KERNEL_VERSION.to_owned();
slot.plasticity_version = gameboy::PLASTICITY_VERSION.to_owned();
let task = PokeredTask::new(
PokeredConfig {
agent_id: config.agent_id.clone(),
port_id: id(fly_session::legacy_env::DEFAULT_PORT),
mode: config.macro_mode,
macro_channels,
hold_ms,
record: config.record,
},
&rom,
&rom_digest,
&epoch,
)?;
let client = launcher
.connect(COORDINATOR_CLIENT)
.await
.map_err(|e| format!("connect: {}", e.message))?;
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
BTreeMap::from([(config.agent_id.clone(), task.executor())]);
let mut coordinator = Coordinator::new(
client,
session_id.clone(),
epoch,
id("ep1"),
environment,
vec![slot],
task.task(),
executors,
);
coordinator.set_environment_config(
backend.asset_ref(),
fly_session::environment::synthetic_asset("pokered-task", gameboy::EXECUTOR_ID),
);
coordinator.set_media(
&[gameboy::VIEW_ID],
&[fly_session::legacy_env::AUDIO_STREAM_ID],
);
coordinator.set_state_format(fly_session::legacy_env::STATE_FORMAT_ID);
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
coordinator
.declare_rollback_policy(ROLLBACK_POLICY)
.map_err(|e| e.message)?;
// The legacy loop runs as fast as its brain allows when measured, and the service paces
// itself; a parity run is a measurement.
if config.record {
coordinator.request_commit_attachments(&[SPIKES_ATTACHMENT]);
}
Ok(LegacySession {
coordinator,
task,
launcher,
rom,
config,
session_id,
backend,
world_generation: 1,
})
}
/// Hello, `Environment.Initialize` (the one-frame scaffold), the task's bootstrap on O[0],
/// `Agent.Initialize` (the warm-up): `Ready(0)`.
pub async fn bootstrap(&mut self) -> Result<(), String> {
self.coordinator
.bootstrap()
.await
.map_err(|e| format!("bootstrap ({}): {}", e.detail, e.error.message))?;
if self.config.record {
self.coordinator.disable_pacing();
}
Ok(())
}
/// Installs a FLYSIM01 checkpoint as this session's start (after [`LegacySession::bootstrap`],
/// before any transition): the world is replaced by a fresh one (the environment stages a
/// restore only on a replacement, as every group restore does), then [`crate::import`] runs
/// the group install and the session resumes at the checkpoint's boundary.
pub async fn import_flysim01(
&mut self,
bytes: &[u8],
checkpoint_id: &Id,
epoch: &Id,
) -> Result<crate::import::Imported, String> {
if self.world_generation != 1 {
return Err("this session has already replaced its world".to_owned());
}
self.launcher.reap(&id(ENV_WORKER), &id("import")).await;
self.world_generation = 2;
self.launcher
.launch_legacy_environment(LegacyEnvironmentLaunch {
session_id: self.session_id.clone(),
worker_id: id(ENV_WORKER),
incarnation_id: id("world-inc-2"),
worker_threads: 1,
rom_path: self.config.rom_path.clone(),
backend: self.backend.clone(),
client_id: format!("{ENV_CLIENT}-r2"),
service: ENV_SERVICE.to_owned(),
})
.await
.map_err(|e| format!("the replacement world: {}", e.message))?;
let world = self
.launcher
.worker(&id(ENV_WORKER))
.expect("launched")
.worker_ref();
self.coordinator
.replace_participant(&id(ENV_WORKER), world)
.map_err(|e| format!("replacing the world: {}", e.error.message))?;
let rom = self.rom.clone();
let imported = crate::import::import_flysim01(
&mut self.coordinator,
&self.task,
bytes,
&rom,
&self.config.agent_id,
checkpoint_id,
self.backend.audio_sample_rate,
epoch,
)
.await?;
if self.config.record {
self.coordinator.disable_pacing();
}
Ok(imported)
}
/// One transition, with its details when recorded.
pub async fn step(&mut self) -> Result<Step, String> {
let report = self
.coordinator
.step()
.await
.map_err(|e| format!("step ({} at {}): {}", e.detail, e.phase, e.error.message))?;
Ok(Step {
report,
details: self.coordinator.take_details(),
records: self.task.take_records(),
})
}
pub async fn stop(mut self) {
self.launcher.reap_all(&id("done")).await;
}
}

View file

@ -0,0 +1,79 @@
//! A stub readout for parity runs that must earn real rewards: the rotation driver of flysim's ROM
//! tests (`tests/rom_catch.rs`, `tests/rom_macros_mode.rs`) -- a decoder of its own, fed rates
//! that lean on one macro population at a time, rotating every [`BURST_FRAMES`] frames.
//!
//! The brain still ticks and decodes exactly as it would; the driver only replaces the decision
//! the executor is handed, at the one point the legacy loop lets a harness do that
//! (`flysim::frame::FrameObserver::readout`). A session run hands the same driver the same
//! `(ms, bound)` in its executor ([`crate::task::PokeredTask::set_driver`]), so both arms press the
//! same macros and the rewards those macros earn reach `Agent.Commit`. Not a service path.
use flybrain_core::decoder::PopulationDecoder;
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_core::ordered::NumberMap;
/// Frames the stub leans on one channel before the rotation moves on (`rom_catch.rs`).
pub const BURST_FRAMES: u32 = 24;
/// The hot population's rate, and every other one's (`rom_catch.rs`).
const HOT: f64 = 16.0;
const REST: f64 = 10.0;
/// Replaces a decision, given the brain clock and the scene's bound channels.
pub trait DecisionDriver: Send {
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>);
}
/// The rotation: one macro population hot at a time, in channel order.
pub struct RotationDriver {
decoder: PopulationDecoder,
channels: Vec<&'static str>,
frame: u32,
}
impl Default for RotationDriver {
fn default() -> Self {
Self::new()
}
}
impl RotationDriver {
pub fn new() -> RotationDriver {
let channels = flybrain_gb::macro_channels(crate::task::GAME);
let mut decoder = PopulationDecoder::new(gameboy_decoder_config_with_macros(&channels))
.expect("the preset is well formed");
decoder.calibrate(&rates(&channels, None));
RotationDriver {
decoder,
channels,
frame: 0,
}
}
}
fn rates(channels: &[&str], hot: Option<&str>) -> NumberMap {
let mut rates = NumberMap::new();
for channel in channels {
rates.set(channel, REST);
}
for bucket in 0..8 {
rates.set(&format!("command_{bucket}"), REST);
}
if let Some(channel) = hot {
rates.set(channel, HOT);
}
rates
}
impl DecisionDriver for RotationDriver {
fn readout(&mut self, ms: f64, bound: &[String], active: &mut Vec<String>) {
let hot = self.channels[(self.frame / BURST_FRAMES) as usize % self.channels.len()];
self.frame += 1;
*active = self.decoder.decode_bound(
&rates(&self.channels, Some(hot)),
ms,
false,
None,
Some(bound),
);
}
}

View file

@ -0,0 +1,169 @@
//! A FLYSIM01 checkpoint as a session's start: the legacy fly's own save, installed into the new
//! runtime through the ordinary group restore (`Coordinator::import`).
//!
//! Each participant gets its half of the file in its own capture format and validates it as one of
//! its own captures:
//!
//! - **the world**: `WorldState::from_flysim01` (ENV-01) at `k = emulatorFrame - 1`, the ratchet's
//! snapshot as the slot `best`, as a `FLYENV01` payload;
//! - **the agent**: the checkpoint's agent state in the worker's own `FLYAGT01` capture, the way
//! AGENT-01's parity harness seeds a worker (`legacy_parity::legacy_state_payload`), with
//! `learning.updates` started at `plasticity.updates` (legacy-gameboy-v1 section 13 amendment of
//! 2026-09-29) and the checkpoint's identity and boundary written in;
//! - **the task**: the adapter state and the ratchet state (FLYSIM01's `reward` and `ratchet`).
//!
//! The rest is `restore: legacy-transient-reset` (section 14): the executor starts fresh and
//! observes the restored boundary, the agent's readout transient starts as a fresh process has it.
//! The decision context the agent is given is computed here from the restored world -- the task's
//! own boot, bound channels and location on the checkpoint's memory image -- and the coordinator
//! holds the task to it after the install.
use std::collections::BTreeMap;
use serde_json::json;
use fly_session::coordinator::{Coordinator, ImportSpec, ImportedAgent};
use fly_session::legacy_env::{PayloadHeader, WorldState};
use fly_session::legacy_parity::legacy_state_payload;
use fly_session::types::*;
use flybrain_gb::{DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator, MemoryImage};
use crate::task::PokeredTask;
/// What an import installed.
#[derive(Clone, Debug)]
pub struct Imported {
pub boundary: u64,
pub epoch: Id,
pub brain_ticks: u64,
}
/// The checkpoint's memory image at its boundary, read the way the environment reads it after an
/// import: the emulator state imported into a stopped emulator, then one bulk read.
pub fn image_of(rom: &[u8], emulator_state: &[u8]) -> Result<MemoryImage, String> {
let mut emulator = Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES)
.map_err(|e| format!("the cartridge: {e}"))?;
emulator
.import_state(emulator_state)
.map_err(|e| format!("the emulator state: {e}"))?;
let mut image = MemoryImage::zeroed();
emulator.read_memory_image_into(&mut image);
Ok(image)
}
/// Installs a FLYSIM01 checkpoint as the start of a bootstrapped session that has taken no
/// transition. `task` is the composition's task object (the coordinator holds its two faces).
#[allow(clippy::too_many_arguments)]
pub async fn import_flysim01(
coordinator: &mut Coordinator,
task: &PokeredTask,
bytes: &[u8],
rom: &[u8],
agent_id: &Id,
checkpoint_id: &Id,
audio_sample_rate: u64,
new_epoch: &Id,
) -> Result<Imported, String> {
let checkpoint = flysim::store::decode(bytes).map_err(|e| format!("FLYSIM01: {e}"))?;
let descriptor = coordinator
.descriptor()
.cloned()
.ok_or("the session never bootstrapped")?;
let environment_id = coordinator.environment_ref().worker_id.clone();
let world = WorldState::from_flysim01(
bytes,
coordinator.episode_id(),
&id(crate::task::SLOT),
audio_sample_rate,
)?;
let boundary = world.boundary;
let scope = coordinator.import_scope(boundary);
let world_payload = world.encode(&PayloadHeader {
worker_id: environment_id,
checkpoint_id: checkpoint_id.clone(),
source_scope: scope.clone(),
configuration_digest: descriptor.configuration_digest.clone(),
});
// The task's ledger, and from it and the restored image the context the agent resumes with.
let ledger = PokeredTask::ledger_from_flysim01(
&checkpoint.runtime.reward,
&checkpoint.runtime.ratchet,
!checkpoint.runtime.ratchet_game.is_empty(),
);
let brain_ms = checkpoint.agent.network.ms;
let context = task.preview_context(
&ledger,
&image_of(rom, &checkpoint.runtime.emulator)?,
brain_ms,
)?;
// The agent: its own capture as the template, the legacy state written into it.
let template = coordinator
.capture_participant(agent_id)
.await
.map_err(|e| format!("the agent template: {}", e.error.message))?;
let payload = legacy_state_payload(&template, &checkpoint.agent, &context)?;
let payload = restamp_agent_payload(&payload, checkpoint_id, &scope, boundary)?;
let remainder =
fly_session::legacy_agent::legacy_remainder_to_rational(checkpoint.agent.remainder)
.map_err(|e| format!("the remainder: {e}"))?;
let audio_positions: BTreeMap<String, u64> = descriptor
.audio
.iter()
.map(|stream| (stream.stream_id.clone(), world.audio_next_sample))
.collect();
let spec = ImportSpec {
checkpoint_id: checkpoint_id.clone(),
boundary,
world_payload,
agents: vec![ImportedAgent {
agent_id: agent_id.clone(),
payload,
brain_ticks: brain_ms as u64,
remainder,
context,
}],
task_ledger: ledger,
audio_positions,
};
coordinator
.import(spec, new_epoch)
.await
.map_err(|e| format!("the import ({}): {}", e.detail, e.error.message))?;
coordinator
.resume()
.map_err(|e| format!("resuming the import: {}", e.error.message))?;
Ok(Imported {
boundary,
epoch: new_epoch.clone(),
brain_ticks: brain_ms as u64,
})
}
/// Writes the checkpoint's identity and boundary into an agent payload's session member: the
/// template was captured at boundary 0 under another checkpoint id.
fn restamp_agent_payload(
payload: &[u8],
checkpoint_id: &Id,
scope: &Scope,
boundary: u64,
) -> Result<Vec<u8>, String> {
let magic = fly_session::legacy_agent::PAYLOAD_MAGIC;
let parts =
flybrain_core::envelope::decode_envelope(payload, magic).map_err(|e| e.to_string())?;
let mut manifest = parts.manifest.clone();
let session = manifest.get("session").ok_or("no session member")?;
let mut session: serde_json::Value =
serde_json::from_str(&session.stringify()).map_err(|e| e.to_string())?;
session["checkpointId"] = json!(checkpoint_id.as_str());
session["sourceScope"] = scope.to_json();
session["committedStep"] = json!(boundary.to_string());
manifest.set(
"session",
flybrain_core::json::JsonValue::parse(&session.to_string()).map_err(|e| e.to_string())?,
);
flybrain_core::envelope::encode_envelope(magic, &manifest, &parts.chunks)
.map_err(|e| e.to_string())
}

View file

@ -0,0 +1,19 @@
//! The live fly on the session framework (TASK-01).
//!
//! - [`task`]: `pokered-macros-v1`, the Pokémon Red task and its action executor as one object,
//! running the legacy macro engine and reward adapter unchanged over the boundary memory image.
//! - [`composition`]: the legacy agent, the legacy environment and the task under one coordinator.
//! - [`import`]: a FLYSIM01 checkpoint as the session's start.
//! - [`admission`]: sugar by the legacy rules; the operator reward pulse refused.
//! - [`trace`]: the session's `FLY_TRACE`, in the legacy loop's format, and the comparison.
//! - [`driver`]: a stub readout for parity runs that must earn rewards.
//!
//! `docs/design/session-framework/legacy-gameboy-v1.md` is the contract, `implementation.md`
//! TASK-01 the record.
pub mod admission;
pub mod composition;
pub mod driver;
pub mod import;
pub mod task;
pub mod trace;

View file

@ -0,0 +1,916 @@
//! `pokered-macros-v1`: the Pokémon Red task and its action executor, one object
//! (`legacy-gameboy-v1` section 10, `workers-v1` section 4 amendment of 2026-09-23).
//!
//! Nothing here is a port of a rule. The reward adapter (`PokemonRedReward`), the ratchet, and the
//! macro layer (`flysim::macros::MacroLayer` over `flybrain-gb`'s palette, executor and `PokeState`)
//! are the very types the legacy loop runs, called in `flysim::frame::LegacyFrame`'s order. What
//! changed is what they read: a boundary's 64 KiB memory image and the cartridge, through
//! `flybrain_gb::ImageReader` (MEM-01), instead of a live emulator.
//!
//! | legacy frame | here |
//! | --- | --- |
//! | `execute`: `MacroLayer::decide` over the emulator | Phase B, [`ActionExecutor::apply`] over `ImageReader(O[k])` |
//! | `evaluate`: `adapter.sample`, `MacroLayer::observe`, location, progress | Phase C, [`Task::evaluate_transition`] over `ImageReader(O[k+1])` |
//! | `boundary`: the ratchet's capture and decision | Phase C too: a slot save and a rollback request, applied by the coordinator at `Ready(k+1)` |
//! | `rollback`: `recover_game`'s `clear_transient`, `cancel`, `observe` | [`Task::rollback`] over `ImageReader(O'[k+1])` |
//!
//! The ratchet keeps its ledger here; its *slot* lives in the environment (`gameboy-slots-v1`).
//! The ratchet only needs to know a slot exists (its budget test is `snapshot.is_none()`), so it
//! holds a marker [`Snapshot`] in place of the bytes.
//!
//! `restore: legacy-transient-reset` (section 14): a restore installs the adapter and the ratchet,
//! and the executor starts as a fresh process has it -- a new macro layer with empty ledgers and
//! nothing running, which observes the restored boundary before it decides anything.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex, MutexGuard};
use serde_json::{Value, json};
use fly_session::fly_session_types::gameboy::{
self, ChannelsDecision, Location, MemoryInspection, ReadoutContext, RollbackRequest,
};
use fly_session::task::{
ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task,
};
use fly_session::types::*;
use flybrain_core::decoder::gameboy::to_button_mask;
use flybrain_gb::adapter::GameAdapter;
use flybrain_gb::emulator::FRAMEBUFFER_LEN;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::{Ratchet, RatchetState, Snapshot};
use flybrain_gb::{AdapterLedger, Cartridge, ImageReader, MemoryImage};
use flysim::config::Config;
use flysim::macros::{MacroEvent, MacroLayer, macro_layer};
use flysim::snapshot::MacroMode;
/// The attachment the image travels under (ENV-01's `legacy_env::MEMORY_ATTACHMENT`).
pub const MEMORY_ATTACHMENT: &str = fly_session::legacy_env::MEMORY_ATTACHMENT;
/// The composition's one slot, which is the ratchet's.
pub const SLOT: &str = fly_session::legacy_env::DEFAULT_SLOT;
/// The game id the adapter and the palette are chosen by.
pub const GAME: &str = "pokemon-red";
/// The palette seed. `flybrain_gb::palette_for` carries it for a macro with a random component
/// and no macro has one (`MacroMachine`'s generator is never read; `macros/tests.rs` proves two
/// seeds press the same buttons), so the legacy loop's `rng_state()` seed is not needed here.
pub const PALETTE_SEED: u32 = 0;
fn schema(name: &str) -> SchemaRef {
let digest = digest_of_bytes(format!("fly-legacy-session-schema-v1\n{name}\n1\n").as_bytes());
SchemaRef::new(name, 1, &digest).expect("a task-local schema reference is valid")
}
/// The task ledger's schema: the adapter state and the ratchet's (FLYSIM01's `reward` and
/// `ratchet`).
pub fn ledger_schema() -> SchemaRef {
schema("pokered.ledger.v1")
}
/// The executor's capture: a marker only, because its state is transient (section 10, "Capture").
pub fn executor_schema() -> SchemaRef {
schema("pokered.executor.v1")
}
pub fn progress_schema() -> SchemaRef {
schema("pokered.progress.v1")
}
pub fn event_schema() -> SchemaRef {
schema("pokered.event.v1")
}
fn state_error(message: impl std::fmt::Display) -> DomainError {
DomainError::before(ErrorCode::IncompatibleState, message)
}
/// The ratchet's stand-in for a slot it knows the environment holds.
fn slot_marker() -> Snapshot {
Snapshot {
game: format!("slot:{SLOT}").into_bytes(),
frame: vec![0; FRAMEBUFFER_LEN],
}
}
/// The legacy trace's JSON of one macro event (`flysim::trace::macro_json`).
pub fn macro_json(phase: &str, event: &MacroEvent) -> Value {
json!({
"phase": phase,
"slot": event.slot,
"name": event.name,
"outcome": event.outcome.map(|outcome| outcome.as_str()),
})
}
/// What the object did in one transition, for the trace and the ledger comparison: the fields of
/// `flysim-legacy-frame-trace-v1` that are the task's and the executor's.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct TaskRecord {
/// The boundary the transition started from.
pub boundary: u64,
/// The decision as the executor was given it, as the legacy active set (buttons, then the
/// macro channel).
pub decision: Vec<String>,
/// The bound channels the decision was masked to (the context of this transition's Prepare).
pub bound: Vec<String>,
pub mask: u32,
/// `macroEvents`, phases `execute`, `evaluate` and `rollback`, in order.
pub macro_events: Vec<Value>,
/// SHA-256 of work RAM, `$C000-$DFFF`, of O[k+1].
pub wram_digest: String,
/// `rewards`: `{kind, value, stimulationMs}` in adapter order.
pub rewards: Vec<Value>,
pub rank: u32,
/// The ratchet asked for a slot save at `Ready(k+1)`.
pub saved: bool,
/// The ratchet asked for a rollback at `Ready(k+1)`, and it ran.
pub rolled_back: bool,
/// The ledgers after the boundary: adapter, ratchet and executor, as one canonical string.
pub ledgers: String,
}
/// The ledgers as one canonical string: the adapter's export (its lifetime ledgers), the
/// ratchet's state and whether it holds a slot, and the executor's observable state -- scene,
/// bound channels, running macro, outcome counts, "nearer the objective". A legacy loop computes
/// the same string from its own parts, which is how a parity run compares ledgers frame by frame.
pub fn ledgers_of(
adapter: &PokemonRedReward,
ratchet: &Ratchet,
macros: Option<&MacroLayer>,
) -> String {
let executor = match macros {
Some(layer) => json!({
"scene": layer.scene_name(),
"bound": layer.bound_channels(),
"running": layer.running(),
"counts": format!("{:?}", layer.counts()),
"nearer": layer.nearer_the_objective(),
}),
None => Value::Null,
};
json!({
"adapter": adapter.export_state(),
"ratchet": serde_json::to_value(ratchet.state).expect("serializes"),
"slot": ratchet.snapshot.is_some(),
"executor": executor,
})
.to_string()
}
/// How the object is configured. Everything here is composition, not state.
#[derive(Clone, Debug)]
pub struct PokeredConfig {
pub agent_id: Id,
pub port_id: Id,
pub mode: MacroMode,
/// `executor.macroChannels`, composition order; empty in raw mode.
pub macro_channels: Vec<String>,
/// The macro group's `holdMs` from the decoder configuration.
pub hold_ms: f64,
/// Record a [`TaskRecord`] per transition (a parity run); off in service.
pub record: bool,
}
struct Inner {
config: PokeredConfig,
cartridge: Cartridge,
adapter: PokemonRedReward,
ratchet: Ratchet,
macros: Option<MacroLayer>,
epoch: Id,
/// O[k]: the image the executor reads in Phase B and the task reads as "old" in Phase C.
current: Option<(u64, MemoryImage)>,
/// The brain clock of the transition in flight (Phase B's clock), in ms.
ms: f64,
evaluations: u64,
issued: u64,
last_source_step: u64,
open: Option<TaskRecord>,
records: Vec<TaskRecord>,
/// A parity run's stub readout ([`crate::driver`]); never set in service.
driver: Option<Box<dyn crate::driver::DecisionDriver>>,
/// Addresses the engine read that the image does not capture ([`Watched`]).
uncaptured: std::collections::BTreeSet<u16>,
}
/// The one object. [`PokeredTask::task`] and [`PokeredTask::executor`] are its two faces; the
/// coordinator holds each where it expects a task and an executor, and both reach the same state.
#[derive(Clone)]
pub struct PokeredTask {
inner: Arc<Mutex<Inner>>,
}
impl PokeredTask {
/// A fresh object over the cartridge. `rom_digest` is the environment's `contentDigest`: a
/// cartridge that is not it is refused (`legacy-gameboy-v1` section 8).
pub fn new(
config: PokeredConfig,
rom: &[u8],
rom_digest: &str,
epoch: &Id,
) -> Result<Self, String> {
let cartridge = Cartridge::verified(rom, rom_digest).map_err(|e| e.to_string())?;
let adapter = PokemonRedReward::new();
let ratchet = Ratchet::with_policy(adapter.recovery_policy());
let macros = fresh_layer(&config);
Ok(Self {
inner: Arc::new(Mutex::new(Inner {
config,
cartridge,
adapter,
ratchet,
macros,
epoch: epoch.clone(),
current: None,
ms: 0.0,
evaluations: 0,
issued: 0,
last_source_step: 0,
open: None,
records: Vec::new(),
driver: None,
uncaptured: std::collections::BTreeSet::new(),
})),
})
}
fn lock(&self) -> MutexGuard<'_, Inner> {
self.inner
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// The task face.
pub fn task(&self) -> Box<dyn Task> {
Box::new(TaskFace(self.clone()))
}
/// The executor face.
pub fn executor(&self) -> Box<dyn ActionExecutor> {
Box::new(ExecutorFace(self.clone()))
}
/// Replace every decision the executor is handed by `driver`'s, as a legacy harness does
/// through `FrameObserver::readout`. A parity run's tool; the service never sets one.
pub fn set_driver(&self, driver: Box<dyn crate::driver::DecisionDriver>) {
self.lock().driver = Some(driver);
}
/// Every address the engine has read that the image does not capture. Empty is the contract
/// (`legacy-gameboy-v1` section 8): a register window reads `$FF` in the image.
pub fn uncaptured_reads(&self) -> Vec<u16> {
self.lock().uncaptured.iter().copied().collect()
}
/// The records since the last call.
pub fn take_records(&self) -> Vec<TaskRecord> {
std::mem::take(&mut self.lock().records)
}
/// The ledgers as one canonical string: the adapter's export, the ratchet's state, and the
/// executor's observable state (scene, bound channels, running macro, outcome counts).
pub fn ledgers(&self) -> String {
self.lock().ledgers()
}
/// The ledger a FLYSIM01 checkpoint carries for the task: its `reward` and `ratchet`, and
/// whether it holds a ratchet snapshot (which the environment's slot `best` now holds).
pub fn ledger_from_flysim01(
reward: &Value,
ratchet: &RatchetState,
has_slot: bool,
) -> TypedValue {
TypedValue::new(
ledger_schema(),
json!({
"adapter": reward,
"ratchet": serde_json::to_value(ratchet).expect("the ratchet state serializes"),
"slot": has_slot,
"evaluations": 0,
"issued": 0,
"lastSourceStep": 0,
}),
)
.expect("a ledger fits the contract")
}
/// The context a restore of `ledger` onto the boundary `image` shows at brain time `ms`: what
/// [`Task::restored`] will compute after the install, computed before it so the agent's
/// payload can carry it. Changes nothing.
pub fn preview_context(
&self,
ledger: &TypedValue,
image: &MemoryImage,
ms: f64,
) -> Result<TypedValue, String> {
let inner = self.lock();
let (adapter, _ratchet) = parse_ledger(&inner, ledger).map_err(|e| e.message)?;
let mut layer = fresh_layer(&inner.config);
if let Some(layer) = layer.as_mut() {
let mut reader = ImageReader::new(image, &inner.cartridge);
let _ = layer.observe(&mut reader, &AdapterLedger(&adapter), ms);
}
Ok(ReadoutContext {
boot: adapter.boot(),
bound: layer
.as_ref()
.map(MacroLayer::bound_channels)
.unwrap_or_default(),
location: adapter
.location()
.map(|(area, x, y)| Location { area, x, y }),
}
.to_typed())
}
/// The readout context the task would hand the decoder now.
pub fn context(&self) -> ReadoutContext {
self.lock().context()
}
}
/// `Sim::boot`'s layer: the configuration's palette at the macro group's hold.
fn fresh_layer(config: &PokeredConfig) -> Option<MacroLayer> {
let mut service = Config::default();
service.loop_.game = GAME.to_owned();
service.macros.mode = config.mode;
macro_layer(&service, config.hold_ms, PALETTE_SEED)
}
/// The image reader the engine is handed: `ImageReader`, plus a record of any address it was asked
/// for that the image does not capture (`legacy-gameboy-v1` section 8, MEM-01 amendment). Such a
/// read answers `$FF` where the live emulator would answer the register, so the engine and the
/// legacy loop could disagree; the record makes that visible rather than silent.
struct Watched<'a> {
reader: ImageReader<'a>,
uncaptured: &'a mut std::collections::BTreeSet<u16>,
}
impl flybrain_gb::adapter::MemoryReader for Watched<'_> {
fn read8(&mut self, address: u16) -> u8 {
if !flybrain_gb::captured(address) {
self.uncaptured.insert(address);
}
self.reader.read8(address)
}
fn read_rom(&mut self, bank: u8, address: u16) -> Option<u8> {
self.reader.read_rom(bank, address)
}
}
fn decision_active(decision: &ChannelsDecision) -> Vec<String> {
let mut active: Vec<String> = gameboy::GAMEBOY_BUTTONS
.iter()
.zip(decision.buttons)
.filter(|(_, down)| *down)
.map(|(name, _)| (*name).to_owned())
.collect();
if let Some(channel) = &decision.macro_channel {
active.push(channel.clone());
}
active
}
fn intent_of(mask: u32) -> ControllerIntent {
let control = fly_session::legacy_env::control_of("p1", mask as u8);
ControllerIntent {
buttons: control.buttons,
axes: control.axes,
}
}
impl Inner {
fn image_of(&self, inspection: &Inspection) -> DomainResult<MemoryImage> {
let typed = MemoryInspection::from_typed(&inspection.value)
.map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?;
if typed.rom_digest != self.cartridge.sha256_hex() {
return Err(DomainError::before(
ErrorCode::IdentityMismatch,
"the inspection's romDigest is not the executor's cartridge",
));
}
let bytes = inspection
.attachments
.get(MEMORY_ATTACHMENT)
.ok_or_else(|| {
DomainError::new(
ErrorCode::BufferInvalid,
format!(
"boundary {} has no {MEMORY_ATTACHMENT}",
inspection.boundary
),
MutationCertainty::Unknown,
)
})?;
MemoryImage::from_bytes(bytes).map_err(|e| {
DomainError::new(
ErrorCode::BufferInvalid,
e.to_string(),
MutationCertainty::Unknown,
)
})
}
fn context(&self) -> ReadoutContext {
ReadoutContext {
boot: self.adapter.boot(),
bound: self
.macros
.as_ref()
.map(MacroLayer::bound_channels)
.unwrap_or_default(),
location: self
.adapter
.location()
.map(|(area, x, y)| Location { area, x, y }),
}
}
fn contexts(&self) -> BTreeMap<Id, TypedValue> {
BTreeMap::from([(self.config.agent_id.clone(), self.context().to_typed())])
}
fn progress_value(&self) -> TypedValue {
let progress = self.adapter.progress();
TypedValue::new(
progress_schema(),
json!({
"rank": progress.rank,
"uniqueLocations": progress.unique_locations,
"rewardTotal": progress.reward_total,
"best": self.ratchet.state.best,
"recoveries": self.ratchet.state.recoveries,
}),
)
.expect("progress fits the contract")
}
fn ledgers(&self) -> String {
ledgers_of(&self.adapter, &self.ratchet, self.macros.as_ref())
}
fn observe(&mut self, image: &MemoryImage, ms: f64) -> Vec<MacroEvent> {
let cartridge = self.cartridge.clone();
let Inner {
macros,
adapter,
uncaptured,
..
} = self;
let mut reader = Watched {
reader: ImageReader::new(image, &cartridge),
uncaptured,
};
match macros.as_mut() {
Some(layer) => layer.observe(&mut reader, &AdapterLedger(&*adapter), ms),
None => Vec::new(),
}
}
fn event(
&mut self,
source_step: u64,
rule: &str,
ordinal: u32,
kind: &str,
payload: Value,
) -> TaskEvent {
self.issued += 1;
TaskEvent {
id: event_id(&self.epoch, source_step, rule, ordinal),
kind_id: id(kind),
source_step,
agent_id: Some(self.config.agent_id.clone()),
payload: TypedValue::new(event_schema(), payload).expect("an event payload fits"),
}
}
fn close(&mut self) {
if let Some(mut record) = self.open.take() {
record.ledgers = self.ledgers();
self.records.push(record);
}
}
}
struct TaskFace(PokeredTask);
struct ExecutorFace(PokeredTask);
impl Task for TaskFace {
fn schema(&self) -> SchemaRef {
progress_schema()
}
fn inspection_attachments(&self) -> Vec<String> {
vec![MEMORY_ATTACHMENT.to_owned()]
}
fn bootstrap(
&mut self,
initial: &Inspection,
bindings: &[PortBinding],
) -> DomainResult<Bootstrap> {
let mut inner = self.0.lock();
if bindings.len() != 1
|| bindings[0].agent_id != inner.config.agent_id
|| bindings[0].port_id != inner.config.port_id
{
return Err(DomainError::before(
ErrorCode::IdentityMismatch,
"pokered-macros-v1 serves exactly one agent on its one port",
));
}
let image = inner.image_of(initial)?;
// `Sim::boot` on a fresh start: the layer observes O[0] once, at the warm-up's end. The
// agent is initialized after this, but its warm-up is the profile's constant, so the
// brain time the legacy loop observes at is known: exactly `warmupMs`.
let ms = gameboy::WARMUP_MS as f64;
inner.ms = ms;
inner.observe(&image, ms);
inner.current = Some((initial.boundary, image));
Ok(Bootstrap {
contexts: inner.contexts(),
progress: inner.progress_value(),
events: Vec::new(),
})
}
fn evaluate_transition(
&mut self,
scope: &Scope,
old: &Inspection,
new: &Inspection,
_applied_controls: &[PortControl],
) -> DomainResult<Evaluation> {
let mut inner = self.0.lock();
match &inner.current {
Some((boundary, _)) if *boundary == old.boundary && old.boundary == scope.step => {}
_ => {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"the task evaluates the transition from the boundary it last observed",
));
}
}
let image = inner.image_of(new)?;
let ms = inner.ms;
let k1 = scope.step + 1;
inner.evaluations += 1;
inner.last_source_step = k1;
// `LegacyFrame::evaluate`: rewards from the frame just produced, then the scene, then the
// location (the agent's, from the context), then the rank.
let cartridge = inner.cartridge.clone();
let rewards = {
let Inner {
adapter,
uncaptured,
..
} = &mut *inner;
let mut reader = Watched {
reader: ImageReader::new(&image, &cartridge),
uncaptured,
};
adapter.sample(&mut reader, ms)
};
let abandoned = inner.observe(&image, ms);
let progress = inner.adapter.progress();
// `LegacyFrame::boundary`, the decision half: the ratchet captures on a safe frame above
// its best -- a slot save at `Ready(k+1)` -- and says whether to roll back.
let safe = inner.adapter.safe_for_snapshot();
let nearer = inner
.macros
.as_ref()
.is_some_and(MacroLayer::nearer_the_objective);
let game_over = inner.adapter.game_over();
let mut saved = false;
let recover = inner.ratchet.observe_with_progress(
safe,
u64::from(progress.rank),
progress.unique_locations as u64,
ms as u64,
game_over,
nearer,
|| {
saved = true;
slot_marker()
},
);
let mut outcome = AgentOutcome::default();
let mut events = Vec::new();
for (n, event) in rewards.iter().enumerate() {
let ordinal = n as u32;
let task_event = inner.event(
k1,
"reward",
ordinal,
"pokered.reward",
json!({"kind": event.kind, "label": event.label, "value": event.value}),
);
outcome.rewards.push(Reward {
event_id: task_event.id.clone(),
rule_id: id(event.kind),
value: event.value,
});
// `Stimulus.durationMs` is positive: an event that drives no pulse is a Reward alone,
// as the legacy `stimulate(0)` changes nothing.
if event.stimulation_ms > 0 {
outcome.stimulations.push(Stimulus {
id: task_event.id.clone(),
kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(),
duration_ms: f64::from(event.stimulation_ms),
});
}
events.push(task_event);
}
let episode = recover.then(|| EpisodeRequest {
kind: EpisodeRequestKind::Rollback,
reason: id(if game_over { "game-over" } else { "stall" }),
outcome: RollbackRequest {
slot_id: SLOT.to_owned(),
trigger: if game_over { "game-over" } else { "stall" }.to_owned(),
}
.to_typed(),
});
if let Some(record) = inner.open.as_mut() {
record
.macro_events
.extend(abandoned.iter().map(|e| macro_json("evaluate", e)));
record.wram_digest = sha256_hex(&image.as_bytes()[0xc000..=0xdfff]);
record.rewards = rewards
.iter()
.map(|e| json!({"kind": e.kind, "value": e.value, "stimulationMs": e.stimulation_ms}))
.collect();
record.rank = progress.rank;
record.saved = saved;
}
let next_contexts = inner.contexts();
let progress_value = inner.progress_value();
inner.current = Some((new.boundary, image));
if !recover {
inner.close();
}
Ok(Evaluation {
outcomes: BTreeMap::from([(inner.config.agent_id.clone(), outcome)]),
next_contexts,
progress: progress_value,
events,
episode,
slot_saves: if saved { vec![id(SLOT)] } else { Vec::new() },
})
}
fn rollback(
&mut self,
scope: &Scope,
restored: &Inspection,
) -> DomainResult<RollbackEvaluation> {
let mut inner = self.0.lock();
let image = inner.image_of(restored)?;
let ms = inner.ms;
inner.epoch = scope.epoch.clone();
// `recover_game`'s task half: the adapter's transient observations; then the executor
// cancels and observes the restored game (`LegacyFrame::rollback`).
inner.adapter.clear_transient();
let mut events = match inner.macros.as_mut() {
Some(layer) => layer.cancel(ms),
None => Vec::new(),
};
events.extend(inner.observe(&image, ms));
if let Some(record) = inner.open.as_mut() {
record.rolled_back = true;
record
.macro_events
.extend(events.iter().map(|e| macro_json("rollback", e)));
}
inner.current = Some((restored.boundary, image));
inner.close();
Ok(RollbackEvaluation {
next_contexts: inner.contexts(),
events: Vec::new(),
})
}
fn restored(
&mut self,
scope: &Scope,
restored: &Inspection,
clock: &RationalNs,
) -> DomainResult<Option<BTreeMap<Id, TypedValue>>> {
let mut inner = self.0.lock();
let image = inner.image_of(restored)?;
let ms = clock_ms(clock)?;
inner.epoch = scope.epoch.clone();
inner.ms = ms;
// `Sim::boot` after a restore: a fresh layer (installed by `install_restore`) observes the
// restored game once, at the restored brain time, before the first frame decides.
inner.observe(&image, ms);
inner.current = Some((restored.boundary, image));
Ok(Some(inner.contexts()))
}
fn progress(&self) -> TypedValue {
self.0.lock().progress_value()
}
fn evaluations(&self) -> u64 {
self.0.lock().evaluations
}
fn capture(&self) -> DomainResult<TypedValue> {
let inner = self.0.lock();
TypedValue::new(
ledger_schema(),
json!({
"adapter": inner.adapter.export_state(),
"ratchet": serde_json::to_value(inner.ratchet.state).expect("serializes"),
"slot": inner.ratchet.snapshot.is_some(),
"evaluations": inner.evaluations,
"issued": inner.issued,
"lastSourceStep": inner.last_source_step,
}),
)
.map_err(|e| DomainError::invalid(e.0))
}
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> {
let inner = self.0.lock();
let (adapter, ratchet) = parse_ledger(&inner, state)?;
drop((adapter, ratchet));
Ok(())
}
fn install_restore(&mut self, epoch: &Id, state: &TypedValue) -> DomainResult<()> {
let mut inner = self.0.lock();
let (adapter, ratchet) = parse_ledger(&inner, state)?;
let number = |key: &str| state.value.get(key).and_then(Value::as_u64).unwrap_or(0);
inner.adapter = adapter;
inner.ratchet = ratchet;
// `legacy-transient-reset`: a fresh executor, nothing running, empty ledgers.
inner.macros = fresh_layer(&inner.config);
inner.current = None;
inner.open = None;
inner.epoch = epoch.clone();
inner.evaluations = number("evaluations");
inner.issued = number("issued");
inner.last_source_step = number("lastSourceStep");
Ok(())
}
fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult<BTreeMap<Id, Id>> {
Err(DomainError::before(
ErrorCode::Unsupported,
"pokered-macros-v1 compares runs by FLY_TRACE, not by rebased event ids",
))
}
fn event_watermarks(&self) -> (u64, u64) {
let inner = self.0.lock();
(inner.last_source_step, inner.issued)
}
}
fn parse_ledger(inner: &Inner, state: &TypedValue) -> DomainResult<(PokemonRedReward, Ratchet)> {
if state.schema != ledger_schema() {
return Err(state_error(
"the captured ledger is not a pokered-macros-v1 ledger",
));
}
let mut adapter = PokemonRedReward::new();
let reward = state
.value
.get("adapter")
.ok_or_else(|| state_error("the ledger has no adapter"))?;
if !reward.is_null() {
adapter
.import_state(reward)
.map_err(|e| state_error(format!("adapter: {e}")))?;
}
let ratchet_state: RatchetState = serde_json::from_value(
state
.value
.get("ratchet")
.cloned()
.ok_or_else(|| state_error("the ledger has no ratchet"))?,
)
.map_err(|e| state_error(format!("ratchet: {e}")))?;
let slot = state
.value
.get("slot")
.and_then(Value::as_bool)
.ok_or_else(|| state_error("the ledger has no slot flag"))?;
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
ratchet
.import(
Some(ratchet_state),
slot.then(slot_marker),
adapter.rank_ladder().len(),
)
.map_err(|e| state_error(format!("ratchet: {e}")))?;
let _ = inner;
Ok((adapter, ratchet))
}
impl ActionExecutor for ExecutorFace {
fn apply(
&mut self,
scope: &Scope,
decision: &TypedValue,
current: &Inspection,
_progress: &TypedValue,
clock: &RationalNs,
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
let mut inner = self.0.lock();
let decision = ChannelsDecision::from_typed(decision)
.map_err(|e| DomainError::before(ErrorCode::IdentityMismatch, e.0))?;
let image = match &inner.current {
Some((boundary, image)) if *boundary == current.boundary && *boundary == scope.step => {
image.clone()
}
_ => {
return Err(DomainError::before(
ErrorCode::InvalidPhase,
"the executor reads the boundary the task last observed",
));
}
};
// The clock is the brain time after Prepare, whole milliseconds (the legacy
// `network.ms`), which is what the macro layer's windows read.
let ms = clock_ms(clock)?;
inner.ms = ms;
let mut active = decision_active(&decision);
let bound = inner
.macros
.as_ref()
.map(MacroLayer::bound_channels)
.unwrap_or_default();
if let Some(driver) = inner.driver.as_mut() {
driver.readout(ms, &bound, &mut active);
}
let raw = to_button_mask(&active);
let cartridge = inner.cartridge.clone();
let (mask, events) = {
let Inner {
macros,
adapter,
uncaptured,
..
} = &mut *inner;
match macros.as_mut() {
Some(layer) => {
let mut reader = Watched {
reader: ImageReader::new(&image, &cartridge),
uncaptured,
};
let decided =
layer.decide(&active, raw, ms, &mut reader, &AdapterLedger(&*adapter));
(decided.mask, decided.events)
}
None => (raw, Vec::new()),
}
};
if inner.config.record {
inner.open = Some(TaskRecord {
boundary: scope.step,
decision: active,
bound,
mask,
macro_events: events.iter().map(|e| macro_json("execute", e)).collect(),
..TaskRecord::default()
});
}
Ok((intent_of(mask), Vec::new()))
}
fn capture(&self) -> DomainResult<TypedValue> {
TypedValue::new(executor_schema(), json!({"executor": gameboy::EXECUTOR_ID}))
.map_err(|e| DomainError::invalid(e.0))
}
fn validate_restore(&self, state: &TypedValue) -> DomainResult<()> {
if state.schema != executor_schema()
|| state.value.get("executor").and_then(Value::as_str) != Some(gameboy::EXECUTOR_ID)
{
return Err(state_error(
"the captured executor is not pokered-macros-v1",
));
}
Ok(())
}
/// Nothing to install: the executor's state is transient (`legacy-transient-reset`), and
/// the task's install already gave it a fresh layer.
fn install_restore(&mut self, state: &TypedValue) -> DomainResult<()> {
self.validate_restore(state)
}
}
/// Brain time in ms from the executor's clock: exact whole nanoseconds of whole milliseconds.
pub fn clock_ms(clock: &RationalNs) -> DomainResult<f64> {
if clock.denominator != 1 || clock.numerator % 1_000_000 != 0 {
return Err(DomainError::invalid(
"the executor clock is not a whole number of milliseconds",
));
}
Ok((clock.numerator / 1_000_000) as f64)
}

View file

@ -0,0 +1,238 @@
//! The session's own `FLY_TRACE`: the legacy loop's trace format (`flysim-legacy-frame-trace-v1`,
//! FND-01) written from a session-framework run, and the comparison of two of them.
//!
//! FND-01's trace is what the running service does, frame by frame, as digests. A new-runtime
//! session driven from the same checkpoint with the same admissions must write the same lines. So
//! the session trace is assembled from exactly what crosses the session's boundaries --
//! `Agent.Prepare` (ticks, clock, remainder, decision), `Agent.Commit` (rates, spike bitset), the
//! executor's joypad batch, `Environment.Advance`'s view, the task's image-derived fields, and the
//! boundary actions -- and compared as JSON, with one declared exclusion: the decision is compared
//! as `gameboy-channels-v1` sees it ([`channels`]): the buttons down, and the first channel of the
//! context's bound set the decode holds. The decoder's list order is not in the decision schema,
//! and a macro channel the macro group still holds after its scene unbound it (the legacy `active`
//! can carry one) reaches nothing: the macro layer starts only a bound channel, and the joypad mask
//! is the buttons'. The mask, the macro events and every other field are compared as they are.
use std::collections::BTreeSet;
use serde_json::{Value, json};
use fly_session::coordinator::StepDetails;
use fly_session::fly_session_types::gameboy::GAMEBOY_BUTTONS;
use fly_session::legacy_parity::trace_rates_digest;
use fly_session::types::*;
use crate::task::TaskRecord;
pub const FORMAT: &str = "flysim-legacy-frame-trace-v1";
/// flysim's `remainder_ns`: the exact rational nanoseconds of the frame remainder.
fn remainder_json(remainder: &RationalNs) -> Value {
json!({"numerator": remainder.numerator.to_string(), "denominator": remainder.denominator.to_string()})
}
fn popcount(bytes: &[u8]) -> u64 {
bytes.iter().map(|b| u64::from(b.count_ones())).sum()
}
/// One transition line of the session's trace, built from the coordinator's details of the
/// transition and the task's record of it.
pub fn line(details: &StepDetails, record: &TaskRecord) -> Result<Value, String> {
let [(agent_id, prepared)] = details.prepared.as_slice() else {
return Err("the legacy composition has exactly one agent".to_owned());
};
let commit = details
.commits
.iter()
.find(|(id, _)| id == agent_id)
.map(|(_, result)| result)
.ok_or("no commit for the agent")?;
let spikes = details
.commit_attachments
.iter()
.find(|(id, name, _)| {
id == agent_id && name == fly_session::legacy_agent::SPIKES_ATTACHMENT
})
.map(|(_, _, bytes)| bytes)
.ok_or("the commit carried no spike bitset")?;
let step: u64 = details
.engine_frame
.as_deref()
.ok_or("O[k] has no engineFrame")?
.parse()
.map_err(|_| "engineFrame is not a U64")?;
let admissions: Vec<Value> = details
.admissions
.iter()
.map(|admission| match admission {
fly_session::coordinator::Admission::Stimulus { duration_ms, .. } => {
json!({"kind": "sugar", "durationMs": duration_ms})
}
})
.collect();
let framebuffer = details
.view_digests
.iter()
.find(|(view, _)| view == "lcd")
.map(|(_, digest)| digest.clone())
.ok_or("O[k+1] has no lcd view")?;
let boundary_actions: Vec<Value> = details
.boundary_actions
.iter()
.map(|action| {
json!({
"kind": action.kind.as_str(),
"slotId": action.slot_id,
"stateDigest": action.state_digest,
})
})
.collect();
Ok(json!({
"behaviour": {
"step": step.to_string(),
"admissions": admissions,
"ticksAdvanced": prepared.ticks_advanced.to_string(),
"brainTicks": prepared.brain_ticks.to_string(),
"remainder": remainder_json(&prepared.remainder),
"ratesDigest": trace_rates_digest(&commit.telemetry)?,
"spikesDigest": sha256_hex(spikes),
"spikeCount": popcount(spikes),
"decision": record.decision,
"mask": record.mask,
"macroEvents": record.macro_events,
"framebufferDigest": framebuffer,
"wramDigest": record.wram_digest,
"rewards": record.rewards,
"rank": record.rank,
"acknowledgedBoundary": (step + 1).to_string(),
"boundaryActions": boundary_actions,
}
}))
}
/// The decision as `gameboy-channels-v1` sees it, given the bound channels it was masked to: the
/// buttons down, and the first bound channel the active set holds (AGENT-01's rule).
pub fn channels(decision: &Value, bound: &[String]) -> (BTreeSet<String>, Option<String>) {
let active: Vec<&str> = decision
.as_array()
.into_iter()
.flatten()
.filter_map(Value::as_str)
.collect();
let buttons = active
.iter()
.filter(|name| GAMEBOY_BUTTONS.contains(name))
.map(|name| (*name).to_owned())
.collect();
let macro_channel = bound
.iter()
.find(|channel| active.contains(&channel.as_str()))
.cloned();
(buttons, macro_channel)
}
/// Reads a trace file's transition lines (`behaviour` only), skipping the header and the start
/// boundary line.
pub fn behaviours(text: &str) -> Result<Vec<Value>, String> {
let mut lines = text.lines().filter(|l| !l.trim().is_empty());
let header: Value = serde_json::from_str(lines.next().ok_or("an empty trace")?)
.map_err(|e| format!("header: {e}"))?;
if header["format"] != FORMAT {
return Err(format!("not {FORMAT}: {}", header["format"]));
}
let mut out = Vec::new();
for line in lines {
let value: Value = serde_json::from_str(line).map_err(|e| format!("line: {e}"))?;
if let Some(behaviour) = value.get("behaviour") {
out.push(behaviour.clone());
}
}
Ok(out)
}
/// What a comparison found, for the report.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Agreement {
pub transitions: u64,
pub sugar: u64,
pub reward_pulses: u64,
pub rewards: u64,
pub reward_kinds: Vec<String>,
pub macro_events: u64,
pub pressed: u64,
pub saves: u64,
pub rollbacks: u64,
pub spikes: u64,
}
/// Every transition identical, field by field; the decision as [`channels`] of the session's bound
/// set for that transition. The first difference is the error, with both values.
pub fn compare(
legacy: &[Value],
session: &[Value],
bounds: &[Vec<String>],
) -> Result<Agreement, String> {
if bounds.len() != session.len() {
return Err("one bound set per session transition".to_owned());
}
if legacy.len() != session.len() {
return Err(format!(
"the legacy trace has {} transitions, the session's {}",
legacy.len(),
session.len()
));
}
let mut agreement = Agreement::default();
for (n, (a, b)) in legacy.iter().zip(session).enumerate() {
let (Some(a_map), Some(b_map)) = (a.as_object(), b.as_object()) else {
return Err(format!("transition {n}: not an object"));
};
let keys: BTreeSet<&String> = a_map.keys().chain(b_map.keys()).collect();
for key in keys {
let (x, y) = (&a[key.as_str()], &b[key.as_str()]);
let same = if key == "decision" {
channels(x, &bounds[n]) == channels(y, &bounds[n])
} else {
x == y
};
if !same {
return Err(format!(
"transition {n} (step {}) {key}:\n legacy {x}\n session {y}",
a["step"]
));
}
}
agreement.transitions += 1;
for admission in a["admissions"].as_array().into_iter().flatten() {
match admission["kind"].as_str() {
Some("sugar") => agreement.sugar += 1,
Some("reward") => agreement.reward_pulses += 1,
_ => {}
}
}
for reward in a["rewards"].as_array().into_iter().flatten() {
agreement.rewards += 1;
if let Some(kind) = reward["kind"].as_str()
&& !agreement.reward_kinds.iter().any(|k| k == kind)
{
agreement.reward_kinds.push(kind.to_owned());
}
}
agreement.macro_events += a["macroEvents"].as_array().map_or(0, |v| v.len() as u64);
if a["mask"].as_u64().unwrap_or(0) != 0 {
agreement.pressed += 1;
}
for action in a["boundaryActions"].as_array().into_iter().flatten() {
match action["kind"].as_str() {
Some("save-slot") => agreement.saves += 1,
Some("rollback") => agreement.rollbacks += 1,
_ => {}
}
}
agreement.spikes += a["spikeCount"].as_u64().unwrap_or(0);
}
Ok(agreement)
}
/// `GAMEBOY_BUTTONS`, re-exported for the decision reconstruction's tests.
pub const BUTTONS: [&str; 8] = GAMEBOY_BUTTONS;

View file

@ -0,0 +1,510 @@
//! The coordinator's boundary actions on the legacy workers, without a ROM: ENV-01's toy
//! cartridge, AGENT-01's toy connectome, and a scripted task that asks for a slot save at
//! boundary 3, a reward at 4 and a rollback onto the slot at 6.
//!
//! What it holds, in-process and as processes:
//!
//! - the rollback runs `Ready(e, 6) -> RollingBack(6) -> Ready(e', 6)`, in the policy's order
//! (`RestoreSlot`, the task's part, `Agent.Rollback`), and the session steps on in `e'`;
//! - the restored boundary is the saved one: the task reads O'[6]'s memory image and it is O[3]'s;
//! - the step details record the save's state digest and the rollback, and the trace carries them
//! as boundary actions, saves first;
//! - admitted sugar is cut into the next Prepare and reported applied at the boundary it committed.
use std::collections::BTreeMap;
use std::sync::{Arc, Mutex};
use serde_json::json;
use flybus::{Grants, Pattern, Policy, RouterConfig};
use fly_session::coordinator::{Admission, AdmissionEnd, AgentSlot, Coordinator};
use fly_session::fly_session_types::extensions::ROLLBACK_POLICY;
use fly_session::fly_session_types::gameboy::{
self, ChannelsDecision, ReadoutContext, RollbackRequest,
};
use fly_session::fly_session_types::trace::BoundaryActionKind;
use fly_session::launcher::{
ExecutionMode, Launcher, LegacyAgentLaunch, LegacyEnvironmentLaunch, SUPERVISOR_CLIENT,
ThreadBudget, Via,
};
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_env::{BackendConfig, MEMORY_ATTACHMENT, STATE_FORMAT_ID};
use fly_session::legacy_env_parity::toy_cart;
use fly_session::task::{
ActionExecutor, Bootstrap, Evaluation, Inspection, RollbackEvaluation, Task,
};
use fly_session::types::*;
fn grants(f: impl FnOnce(&mut Grants)) -> Grants {
let mut g = Grants::default();
f(&mut g);
g
}
fn schema(name: &str) -> SchemaRef {
SchemaRef::new(name, 1, &digest_of_bytes(name.as_bytes())).unwrap()
}
/// What the scripted task saw.
#[derive(Default)]
struct Seen {
/// Boundary -> the image digest the task read for it (the last reading wins).
images: BTreeMap<u64, String>,
restored: Option<(u64, String)>,
}
struct Scripted {
agent: Id,
seen: Arc<Mutex<Seen>>,
evaluations: u64,
}
fn context() -> TypedValue {
ReadoutContext {
boot: false,
bound: Vec::new(),
location: None,
}
.to_typed()
}
fn image_digest(inspection: &Inspection) -> DomainResult<String> {
let bytes = inspection
.attachments
.get(MEMORY_ATTACHMENT)
.ok_or_else(|| DomainError::invalid("no image"))?;
assert_eq!(bytes.len(), 65_536);
Ok(digest_of_bytes(bytes))
}
impl Task for Scripted {
fn schema(&self) -> SchemaRef {
schema("scripted.progress")
}
fn inspection_attachments(&self) -> Vec<String> {
vec![MEMORY_ATTACHMENT.to_owned()]
}
fn bootstrap(
&mut self,
initial: &Inspection,
_bindings: &[PortBinding],
) -> DomainResult<Bootstrap> {
let digest = image_digest(initial)?;
self.seen
.lock()
.unwrap()
.images
.insert(initial.boundary, digest);
Ok(Bootstrap {
contexts: BTreeMap::from([(self.agent.clone(), context())]),
progress: self.progress(),
events: Vec::new(),
})
}
fn evaluate_transition(
&mut self,
scope: &Scope,
old: &Inspection,
new: &Inspection,
_controls: &[PortControl],
) -> DomainResult<Evaluation> {
assert_eq!(old.boundary, scope.step, "O[k] is the old inspection");
assert_eq!(new.boundary, scope.step + 1, "O[k+1] is the new one");
self.evaluations += 1;
let k1 = scope.step + 1;
self.seen
.lock()
.unwrap()
.images
.insert(k1, image_digest(new)?);
let mut outcome = AgentOutcome::default();
let mut events = Vec::new();
if k1 == 4 {
let event = TaskEvent {
id: event_id(&scope.epoch, k1, "scripted", 0),
kind_id: id("scripted.reward"),
source_step: k1,
agent_id: Some(self.agent.clone()),
payload: TypedValue::new(schema("scripted.event"), json!({})).unwrap(),
};
outcome.rewards.push(Reward {
event_id: event.id.clone(),
rule_id: id("scripted"),
value: 0.5,
});
outcome.stimulations.push(Stimulus {
id: event.id.clone(),
kind_id: gameboy::STIMULUS_REWARD_PULSE.to_owned(),
duration_ms: 100.0,
});
events.push(event);
}
Ok(Evaluation {
outcomes: BTreeMap::from([(self.agent.clone(), outcome)]),
next_contexts: BTreeMap::from([(self.agent.clone(), context())]),
progress: self.progress(),
events,
episode: (k1 == 6).then(|| EpisodeRequest {
kind: EpisodeRequestKind::Rollback,
reason: id("stall"),
outcome: RollbackRequest {
slot_id: "best".into(),
trigger: "stall".into(),
}
.to_typed(),
}),
slot_saves: if k1 == 3 {
vec![id("best")]
} else {
Vec::new()
},
})
}
fn rollback(
&mut self,
scope: &Scope,
restored: &Inspection,
) -> DomainResult<RollbackEvaluation> {
assert_eq!(restored.boundary, scope.step);
self.seen.lock().unwrap().restored = Some((restored.boundary, image_digest(restored)?));
Ok(RollbackEvaluation {
next_contexts: BTreeMap::from([(self.agent.clone(), context())]),
events: Vec::new(),
})
}
fn progress(&self) -> TypedValue {
TypedValue::new(
schema("scripted.progress"),
json!({"evaluations": self.evaluations}),
)
.unwrap()
}
fn evaluations(&self) -> u64 {
self.evaluations
}
fn capture(&self) -> DomainResult<TypedValue> {
Ok(self.progress())
}
fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> {
Ok(())
}
fn install_restore(&mut self, _epoch: &Id, _state: &TypedValue) -> DomainResult<()> {
Ok(())
}
fn rebase_ids(&self, _to_epoch: &Id) -> DomainResult<BTreeMap<Id, Id>> {
Ok(BTreeMap::new())
}
fn event_watermarks(&self) -> (u64, u64) {
(0, 0)
}
}
/// The joypad the decision's buttons ask for.
struct Buttons;
impl ActionExecutor for Buttons {
fn apply(
&mut self,
_scope: &Scope,
decision: &TypedValue,
_current: &Inspection,
_progress: &TypedValue,
_clock: &RationalNs,
) -> DomainResult<(ControllerIntent, Vec<TaskEvent>)> {
let decision =
ChannelsDecision::from_typed(decision).map_err(|e| DomainError::invalid(e.0))?;
let control = fly_session::legacy_env::control_of("p1", decision.mask());
Ok((
ControllerIntent {
buttons: control.buttons,
axes: control.axes,
},
Vec::new(),
))
}
fn capture(&self) -> DomainResult<TypedValue> {
Ok(TypedValue::new(schema("buttons"), json!({})).unwrap())
}
fn validate_restore(&self, _state: &TypedValue) -> DomainResult<()> {
Ok(())
}
fn install_restore(&mut self, _state: &TypedValue) -> DomainResult<()> {
Ok(())
}
}
async fn run(mode: ExecutionMode) {
let root = tempfile::tempdir().unwrap();
let rom = toy_cart::rom(0);
let rom_path = root.path().join("toy.gb");
std::fs::write(&rom_path, &rom).unwrap();
let store = root.path().join("store");
let sockets = root.path().join("sockets");
std::fs::create_dir_all(&sockets).unwrap();
let policy = Policy::closed()
.client(
"coordinator",
grants(|g| {
g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")];
g.publish = vec![Pattern::prefix("session.")];
g.manage_topics = vec![Pattern::prefix("session.")];
g.register = vec![Pattern::prefix("session.")];
}),
)
.client(
SUPERVISOR_CLIENT,
grants(|g| g.call = vec![Pattern::prefix("agent."), Pattern::prefix("env.")]),
)
.client(
"world",
grants(|g| g.register = vec![Pattern::exact("env.world")]),
)
.client(
"fly",
grants(|g| g.register = vec![Pattern::exact("agent.fly")]),
);
let mut config = RouterConfig::new(&store);
config.policy = policy;
let router = flybus::Router::new(config).unwrap();
let mut launcher = Launcher::start(
router,
mode,
Via::Unix,
&store,
&sockets,
ThreadBudget::new(3, 1).unwrap(),
)
.await
.unwrap();
let mut backend = BackendConfig::legacy(&digest_of_bytes(&rom));
backend.slots = vec![id("best")];
launcher
.launch_legacy_environment(LegacyEnvironmentLaunch {
session_id: id("s"),
worker_id: id("world"),
incarnation_id: id("world-1"),
worker_threads: 1,
rom_path,
backend: backend.clone(),
client_id: "world".into(),
service: "env.world".into(),
})
.await
.unwrap();
launcher
.launch_legacy_agent(LegacyAgentLaunch {
session_id: id("s"),
agent_id: id("fly"),
port_id: id("p1"),
incarnation_id: id("fly-1"),
worker_threads: 1,
dataset_dir: fly_session::legacy_parity::toy::dir(),
profile: LegacyProfileKind::Toy,
macro_channels: Vec::new(),
client_id: "fly".into(),
service: "agent.fly".into(),
})
.await
.unwrap();
let mut slot = AgentSlot::new(
launcher.worker(&id("fly")).unwrap().worker_ref(),
id("fly"),
id("p1"),
LegacyProfileKind::Toy.profile().asset,
fly_session::legacy_parity::LEGACY_SEED,
);
slot.model_version = gameboy::KERNEL_VERSION.into();
slot.plasticity_version = gameboy::PLASTICITY_VERSION.into();
let seen = Arc::new(Mutex::new(Seen::default()));
let task = Scripted {
agent: id("fly"),
seen: seen.clone(),
evaluations: 0,
};
let executors: BTreeMap<Id, Box<dyn ActionExecutor>> =
BTreeMap::from([(id("fly"), Box::new(Buttons) as Box<dyn ActionExecutor>)]);
let mut coordinator = Coordinator::new(
launcher.connect("coordinator").await.unwrap(),
id("s"),
id("e1"),
id("ep1"),
launcher.worker(&id("world")).unwrap().worker_ref(),
vec![slot],
Box::new(task),
executors,
);
coordinator.set_environment_config(
backend.asset_ref(),
fly_session::environment::synthetic_asset("scripted", "scripted-v1"),
);
coordinator.set_media(
&[gameboy::VIEW_ID],
&[fly_session::legacy_env::AUDIO_STREAM_ID],
);
coordinator.set_state_format(STATE_FORMAT_ID);
coordinator.set_decision_schema(gameboy::CHANNELS.schema_ref());
coordinator
.declare_rollback_policy(ROLLBACK_POLICY)
.unwrap();
coordinator.record_details(true);
coordinator
.bootstrap()
.await
.unwrap_or_else(|e| panic!("bootstrap: {}", e.error.message));
coordinator.disable_pacing();
let admissions = coordinator.admissions();
assert_eq!(
admissions.stimulus_remaining_ms(&id("fly")),
None,
"no commit yet"
);
let mut actions = Vec::new();
for k in 0..9u64 {
if k == 2 {
admissions.admit(Admission::Stimulus {
agent_id: id("fly"),
interaction_id: id("sugar-1"),
kind_id: id(gameboy::STIMULUS_REWARD_PULSE),
duration_ms: 300.0,
});
}
let report = coordinator.step().await.unwrap_or_else(|e| {
panic!(
"{} step {k}: {} ({})",
mode.label(),
e.error.message,
e.detail
)
});
assert_eq!(report.boundary, k + 1);
assert!(
!report.paused && !report.terminal,
"a rollback is not an episode end"
);
let details = coordinator.take_details().unwrap();
if k == 2 {
assert_eq!(
details.admissions.len(),
1,
"the sugar is cut into Prepare(2)"
);
}
for action in &details.boundary_actions {
actions.push((k + 1, action.kind, action.state_digest.clone()));
}
if k + 1 == 6 {
let rollback = details.rollback.as_ref().expect("the rollback's details");
assert_eq!(rollback.epoch, id("e1.rb1"));
assert_eq!(rollback.observation.boundary, 6);
assert!(
rollback.observation.audio.is_empty(),
"a restore plays no interval"
);
assert_eq!(rollback.agents.len(), 1);
}
}
assert_eq!(
coordinator.epoch(),
&id("e1.rb1"),
"the session steps on in the new epoch"
);
assert_eq!(actions.len(), 2);
assert_eq!(
(actions[0].0, actions[0].1),
(3, BoundaryActionKind::SaveSlot)
);
assert!(
actions[0].2.is_some(),
"a save records the saved state's digest"
);
assert_eq!(
(actions[1].0, actions[1].1, actions[1].2.clone()),
(6, BoundaryActionKind::Rollback, None)
);
let phases: Vec<String> = coordinator
.trace
.phases
.iter()
.map(|p| format!("{}->{}", p.from, p.to))
.collect();
assert!(
phases.contains(&"Ready(6)->RollingBack(6)".to_owned()),
"{phases:?}"
);
assert!(
phases.contains(&"RollingBack(6)->Ready(6)".to_owned()),
"{phases:?}"
);
let traced: Vec<(u64, usize)> = coordinator
.trace
.transitions
.iter()
.map(|t| {
(
t.behaviour.acknowledged_boundary,
t.behaviour.boundary_actions.len(),
)
})
.filter(|(_, n)| *n > 0)
.collect();
assert_eq!(
traced,
vec![(3, 1), (6, 1)],
"the trace carries the boundary actions"
);
let seen = seen.lock().unwrap();
let (boundary, restored) = seen.restored.clone().expect("the task rolled back");
assert_eq!(boundary, 6);
assert_eq!(
restored, seen.images[&3],
"O'[6] is the world saved at boundary 3"
);
assert_ne!(
restored, seen.images[&6],
"and not the one the rollback threw away"
);
let ended = admissions.take_ended();
assert_eq!(ended.len(), 1);
assert_eq!(ended[0].1, AdmissionEnd::Applied { boundary: 3 });
assert!(admissions.stimulus_remaining_ms(&id("fly")).is_some());
let audit = coordinator.audit.join(" ");
for needle in [
"save-slot:best@3",
"restore-slot:best@6",
"agent-rollback:fly@6",
"rolled-back:best@6",
] {
assert!(audit.contains(needle), "{needle} in {audit}");
}
launcher.reap_all(&id("done")).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_save_then_a_rollback_in_process() {
run(ExecutionMode::InProcess).await;
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn a_save_then_a_rollback_as_processes() {
if !fly_session::launcher::default_worker_program().is_file() {
eprintln!("process mode skipped: no worker program");
return;
}
run(ExecutionMode::Process).await;
}

View file

@ -0,0 +1,589 @@
//! TASK-01's pre-shadow proof: a whole new-runtime session -- the legacy agent worker (AGENT-01),
//! the legacy environment worker (ENV-01) and the `pokered-macros-v1` task and executor in the
//! coordinator -- reproduces the legacy loop's `FLY_TRACE` (FND-01) frame by frame: ticks, clock,
//! remainder, rates, spikes, decision, joypad mask, macro events, frame, work RAM, rewards, rank,
//! slot saves and rollbacks. Where the legacy side is a host run in this process, the ledgers
//! (adapter, ratchet, executor) are compared after every boundary too.
//!
//! Every run is an explicit ROM job (the operator's rom env script, never a download):
//!
//! - `toy_raw_from_power_on` (`FLY_ROM`): the committed toy connectome in raw mode from power-on,
//! with sugar admitted through the coordinator's admission queue.
//! - `fafb_service_trace_checkpoints` (`FLY_TASK01_FAFB=1`, `FLY_ENV01_TRACE_DIR`,
//! `FLY_DOOR_CHECKPOINT`): the checkpoints of the service's own traces (the FND-01 review's
//! `rollback`, `climb` and `r58`: a ratchet rollback, a slot save, two real rewards), for each
//! trace's length, against today's legacy loop; the session imported from the same FLYSIM01
//! files. `FLY_TASK01_TRACE_LIMIT` caps each.
//! - `fafb_reward_segments` (`FLY_TASK01_FAFB=1`): host runs of `LegacyFrame` from stream
//! checkpoints, with sugar, in two arms. The brain arm: the adapter ledger thinned so rewards
//! fire where the fly already is (new area, exits, new ground, wild wins). The driver arm: the
//! brain ticks and decodes as always but the executor is handed the ROM tests' rotation driver's
//! decision (`fly_legacy_session::driver`), which walks, talks, fights and picks up, so real
//! rewards reach `Agent.Commit`. `FLY_TASK01_SEGMENTS` picks the checkpoints (`name=path,...`),
//! `FLY_TASK01_FRAMES` the length.
//!
//! Execution modes: in-process, then process (the workspace's `fly-session` binary); a build
//! without it skips process mode and says so.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use serde_json::Value;
use fly_legacy_session::admission::LegacyAdmission;
use fly_legacy_session::composition::{LegacyConfig, LegacySession, channels_and_hold};
use fly_legacy_session::driver::{DecisionDriver, RotationDriver};
use fly_legacy_session::task::ledgers_of;
use fly_legacy_session::trace::{self, Agreement};
use fly_session::ExecutionMode;
use fly_session::legacy_agent::LegacyProfileKind;
use fly_session::legacy_parity;
use fly_session::types::id;
use flybrain_core::agent::{AgentConfig, NeuralAgent};
use flybrain_core::dataset::{BrainDataset, load_brain_dataset_from_dir};
use flybrain_core::decoder::gameboy::gameboy_decoder_config_with_macros;
use flybrain_gb::adapter::GameAdapter;
use flybrain_gb::pokemon_red::PokemonRedReward;
use flybrain_gb::ratchet::Ratchet;
use flybrain_gb::{AdapterLedger, DEFAULT_AUDIO_FRAMES, DEFAULT_AUDIO_FREQUENCY, Emulator};
use flysim::config::Config;
use flysim::frame::{LegacyFrame, Parts};
use flysim::macros::macro_layer;
use flysim::snapshot::MacroMode;
use flysim::trace::FrameTrace;
fn rom_path() -> Option<PathBuf> {
match std::env::var_os("FLY_ROM") {
Some(path) => Some(PathBuf::from(path)),
None => {
eprintln!("skipping: FLY_ROM is not set (source bin/rom-env.sh)");
None
}
}
}
fn fafb() -> Option<PathBuf> {
if std::env::var_os("FLY_TASK01_FAFB").is_none() {
eprintln!("skipping: FLY_TASK01_FAFB is not set");
return None;
}
let dir = legacy_parity::fafb_dir();
if dir.is_none() {
eprintln!("skipping: data/fafb-v783 is not present in this checkout");
}
dir
}
fn env_usize(name: &str, default: usize) -> usize {
std::env::var(name)
.ok()
.and_then(|v| v.parse().ok())
.unwrap_or(default)
}
fn modes() -> Vec<ExecutionMode> {
let mut modes = vec![ExecutionMode::InProcess];
let program = fly_session::launcher::default_worker_program();
if program.is_file() {
modes.push(ExecutionMode::Process);
} else {
eprintln!(
"process mode skipped: no worker program at {}",
program.display()
);
}
modes
}
/// What each frame admits at its top, in admission order, and whether the rotation driver hands
/// the executor its decisions.
#[derive(Clone, Debug, Default)]
struct Inputs {
/// `(frame index from 1, duration ms)`.
sugar: Vec<(usize, f64)>,
driver: bool,
}
/// The legacy loop's one look into a decision: the driver's, when the run has one.
struct Driven(Option<RotationDriver>);
impl flysim::frame::FrameObserver for Driven {
fn readout(&mut self, ms: f64, bound: Option<&[String]>, active: &mut Vec<String>) {
if let Some(driver) = self.0.as_mut() {
driver.readout(ms, bound.unwrap_or(&[]), active);
}
}
}
/// How a run starts.
#[derive(Clone)]
enum Start {
PowerOn,
/// A FLYSIM01 file.
Checkpoint(Vec<u8>),
}
/// The run's `FLY_TRACE` behaviours and, when it has them, the ledgers after every boundary.
struct Run {
behaviours: Vec<Value>,
ledgers: Vec<String>,
/// The bound set of each transition's decision (session runs only).
bounds: Vec<Vec<String>>,
}
fn decoder_hold(mode: MacroMode) -> (Vec<&'static str>, f64) {
let channels = if mode.dealt() {
flybrain_gb::macro_channels("pokemon-red")
} else {
Vec::new()
};
let (_, hold) = channels_and_hold(mode);
(channels, hold)
}
/// The legacy loop in this process: `LegacyFrame` with `FLY_TRACE` on, admitting the inputs at
/// the top of each frame as the service's command drain does, the ledgers read after each
/// boundary.
fn run_legacy(
rom: &[u8],
data: &Arc<BrainDataset>,
start: &Start,
mode: MacroMode,
frames: usize,
inputs: &Inputs,
trace_path: &Path,
) -> Run {
let mut emulator =
Emulator::new(rom, DEFAULT_AUDIO_FREQUENCY, DEFAULT_AUDIO_FRAMES).expect("binjgb");
let mut adapter = PokemonRedReward::new();
let mut ratchet = Ratchet::with_policy(adapter.recovery_policy());
let mut config = Config::default();
config.loop_.game = "pokemon-red".to_owned();
config.macros.mode = mode;
let (channels, hold_ms) = decoder_hold(mode);
let mut agent_config = AgentConfig::with_decoder(gameboy_decoder_config_with_macros(&channels));
agent_config.warmup_ms = config.loop_.warmup_ms;
let mut agent = NeuralAgent::new(Arc::clone(data), agent_config).expect("an agent");
let mut frame =
LegacyFrame::new().with_trace(Some(FrameTrace::create(trace_path).expect("a trace")));
match start {
Start::PowerOn => {
frame
.initialize(&mut emulator, &mut agent)
.expect("the first frame and the warm-up");
}
Start::Checkpoint(bytes) => {
let checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
frame
.restore(
&mut Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: None,
},
&checkpoint,
)
.expect("the checkpoint restores");
}
}
let mut macros = macro_layer(&config, hold_ms, agent.network.rng_state() as u32);
if let Some(layer) = macros.as_mut() {
let _ = layer.observe(&mut emulator, &AdapterLedger(&adapter), agent.network.ms);
}
let mut ledgers = Vec::new();
let mut observer = Driven(inputs.driver.then(RotationDriver::new));
for k in 1..=frames {
// The command drain: the sugar admitted for this frame, in admission order.
for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) {
agent.network.stimulate(*duration);
if let Some(trace) = frame.trace_mut() {
trace.sugar(*duration);
}
}
let mut parts = Parts {
agent: &mut agent,
emulator: &mut emulator,
adapter: &mut adapter,
ratchet: &mut ratchet,
macros: macros.as_mut(),
};
let transition = frame
.transition(&mut parts, &mut observer)
.expect("a frame");
frame
.boundary(&mut parts, &transition.evaluated.progress, transition.ms)
.expect("the boundary");
ledgers.push(ledgers_of(&adapter, &ratchet, macros.as_ref()));
}
frame.finish_trace();
drop(frame);
let text = std::fs::read_to_string(trace_path).expect("the trace reads back");
Run {
behaviours: trace::behaviours(&text).expect("a FLY_TRACE"),
ledgers,
bounds: Vec::new(),
}
}
/// The same run on the session framework.
#[allow(clippy::too_many_arguments)]
async fn run_session(
mode: ExecutionMode,
rom_path: &Path,
dataset_dir: &Path,
profile: LegacyProfileKind,
macro_mode: MacroMode,
start: &Start,
frames: usize,
inputs: &Inputs,
) -> Run {
let root = tempfile::tempdir().expect("tmp");
let config = LegacyConfig {
mode,
rom_path: rom_path.to_owned(),
dataset_dir: dataset_dir.to_owned(),
profile,
macro_mode,
agent_id: id("fly"),
agent_threads: 1,
record: true,
};
let mut session = LegacySession::start(root.path(), config)
.await
.unwrap_or_else(|e| panic!("the session starts: {e}"));
if inputs.driver {
session.task.set_driver(Box::new(RotationDriver::new()));
}
session
.bootstrap()
.await
.unwrap_or_else(|e| panic!("Ready(0): {e}"));
if let Start::Checkpoint(bytes) = start {
session
.import_flysim01(bytes, &id("flysim01"), &id("e2"))
.await
.unwrap_or_else(|e| panic!("the FLYSIM01 import: {e}"));
}
let mut admission = LegacyAdmission::new(session.coordinator.admissions(), id("fly"));
assert!(
admission.reward(1.0).is_err(),
"the operator reward pulse is refused"
);
let mut behaviours = Vec::new();
let mut ledgers = Vec::new();
let mut bounds = Vec::new();
for k in 1..=frames {
for (_, duration) in inputs.sugar.iter().filter(|(at, _)| *at == k) {
admission.replay_sugar(*duration);
}
let step = session
.step()
.await
.unwrap_or_else(|e| panic!("{} frame {k}: {e}", mode.label()));
let details = step.details.expect("details are recorded");
let [record] = step.records.as_slice() else {
panic!("frame {k}: {} task records", step.records.len());
};
behaviours.push(
trace::line(&details, record).unwrap_or_else(|e| panic!("frame {k}: {e}"))["behaviour"]
.clone(),
);
ledgers.push(record.ledgers.clone());
bounds.push(record.bound.clone());
}
let ended = session.coordinator.admissions().take_ended();
assert_eq!(
ended.len(),
inputs.sugar.iter().filter(|(k, _)| *k <= frames).count(),
"every admission ended"
);
assert!(
ended
.iter()
.all(|(_, end)| matches!(end, fly_session::coordinator::AdmissionEnd::Applied { .. })),
"and every one was applied"
);
let uncaptured = session.task.uncaptured_reads();
assert!(
uncaptured.is_empty(),
"the engine read addresses the image does not capture: {:04x?}",
uncaptured
);
session.stop().await;
Run {
behaviours,
ledgers,
bounds,
}
}
fn report(what: &str, agreement: &Agreement, elapsed: std::time::Duration) {
eprintln!(
"{what} ({elapsed:?}): {} transitions identical ({} sugar, {} rewards {:?}, \
{} macro events, {} pressed, {} slot saves, {} rollbacks, {} spikes)",
agreement.transitions,
agreement.sugar,
agreement.rewards,
agreement.reward_kinds,
agreement.macro_events,
agreement.pressed,
agreement.saves,
agreement.rollbacks,
agreement.spikes
);
}
fn compare_ledgers(legacy: &[String], session: &[String]) {
assert_eq!(legacy.len(), session.len());
for (k, (a, b)) in legacy.iter().zip(session).enumerate() {
assert_eq!(a, b, "the ledgers after frame {}", k + 1);
}
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn toy_raw_from_power_on() {
let Some(rom_path) = rom_path() else { return };
let rom = std::fs::read(&rom_path).expect("the cartridge");
let data = Arc::new(load_brain_dataset_from_dir(legacy_parity::toy::dir()).expect("the toy"));
let frames = env_usize("FLY_TASK01_TOY_FRAMES", 600);
let inputs = Inputs {
sugar: vec![(40, 300.0), (frames / 2, 500.0)],
driver: false,
};
let dir = tempfile::tempdir().expect("tmp");
let legacy = run_legacy(
&rom,
&data,
&Start::PowerOn,
MacroMode::Raw,
frames,
&inputs,
&dir.path().join("trace.jsonl"),
);
for mode in modes() {
let started = std::time::Instant::now();
let session = run_session(
mode,
&rom_path,
&legacy_parity::toy::dir(),
LegacyProfileKind::Toy,
MacroMode::Raw,
&Start::PowerOn,
frames,
&inputs,
)
.await;
let agreement = trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
.unwrap_or_else(|e| panic!("{}: {e}", mode.label()));
compare_ledgers(&legacy.ledgers, &session.ledgers);
assert_eq!(agreement.sugar, 2);
report(
&format!("toy raw, {}", mode.label()),
&agreement,
started.elapsed(),
);
}
}
/// The checkpoints of the service's own traces (the FND-01 review's `rollback` -- a ratchet
/// rollback on the first boundary, a real `talk` reward -- `climb` -- a ratchet slot save -- and
/// `r58` -- a real `talk` reward -- with their start checkpoints).
///
/// Those traces were recorded by the service as it stood on 2026-09-23. The macro engine has
/// changed since (loop-review rows 59 to 67), so from some frame on they are not what today's
/// engine does. The reference is therefore FND-01's harness at this tree -- `LegacyFrame` with
/// `FLY_TRACE` on, which FND-01 proved byte-identical to the service's loop -- run here from the
/// same checkpoint for the trace's length; the session must match it frame by frame, ledgers
/// included. How far the recorded service trace agrees with today's legacy loop is reported, not
/// asserted.
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fafb_service_trace_checkpoints() {
let Some(rom_path) = rom_path() else { return };
let Some(dataset) = fafb() else { return };
let Some(dir) = std::env::var_os("FLY_ENV01_TRACE_DIR").map(PathBuf::from) else {
eprintln!("skipping: FLY_ENV01_TRACE_DIR is not set");
return;
};
let rom = std::fs::read(&rom_path).expect("the cartridge");
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
let limit = env_usize("FLY_TASK01_TRACE_LIMIT", usize::MAX);
let names: Vec<String> = std::env::var("FLY_TASK01_TRACES")
.map(|v| v.split(',').map(str::to_owned).collect())
.unwrap_or_else(|_| vec!["rollback".into(), "climb".into(), "r58".into()]);
for name in names {
let checkpoint = if name == "r58" {
std::env::var_os("FLY_DOOR_CHECKPOINT").map(PathBuf::from)
} else {
Some(dir.join(format!("{name}.checkpoint")))
};
let Some(checkpoint) = checkpoint.filter(|c| c.is_file()) else {
eprintln!("skipping {name}: no checkpoint");
continue;
};
let text =
std::fs::read_to_string(dir.join(format!("{name}.trace.jsonl"))).expect("the trace");
let mut service = trace::behaviours(&text).expect("a FLY_TRACE");
service.truncate(limit);
let frames = service.len();
let bytes = std::fs::read(&checkpoint).expect("the checkpoint");
let start = Start::Checkpoint(bytes);
let tmp = tempfile::tempdir().expect("tmp");
let started = std::time::Instant::now();
let legacy = run_legacy(
&rom,
&data,
&start,
MacroMode::Macros,
frames,
&Inputs::default(),
&tmp.path().join("trace.jsonl"),
);
let agreed = legacy
.behaviours
.iter()
.zip(&service)
.take_while(|(today, recorded)| today == recorded)
.count();
eprintln!(
"legacy loop {name}: {frames} frames in {:?}; the recorded service trace agrees with \
today's loop for its first {agreed} transitions",
started.elapsed()
);
for mode in modes() {
let started = std::time::Instant::now();
let session = run_session(
mode,
&rom_path,
&dataset,
LegacyProfileKind::Production,
MacroMode::Macros,
&start,
frames,
&Inputs::default(),
)
.await;
let agreement =
trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
.unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label()));
compare_ledgers(&legacy.ledgers, &session.ledgers);
report(
&format!("service checkpoint {name}, {}", mode.label()),
&agreement,
started.elapsed(),
);
}
}
}
/// Thins a checkpoint's adapter ledger so the fly earns rewards: the current map is unvisited
/// (an `AREA` payout on the first sample), its exits unfound (`boundary`), its ground unwalked
/// (`exploration`), and no wild win is a replay (`battle`).
fn reward_bearing(bytes: &[u8]) -> Vec<u8> {
let mut checkpoint = flysim::store::decode(bytes).expect("FLYSIM01");
let reward = &mut checkpoint.runtime.reward;
let map = reward["location"]
.as_str()
.and_then(|l| l.split(':').next())
.unwrap_or("0")
.to_owned();
if let Some(seen) = reward["seen"].as_array_mut() {
seen.retain(|key| {
let key = key.as_str().unwrap_or("");
key != format!("map:{map}") && !key.starts_with(&format!("boundary:{map}:"))
});
}
if let Some(tiles) = reward["tiles"].as_array_mut() {
tiles.retain(|tile| !tile.as_str().unwrap_or("").starts_with(&format!("{map}:")));
}
if let Some(counts) = reward["tileCounts"].as_object_mut() {
counts.remove(&map);
}
reward["wildWins"] = serde_json::json!({});
reward["replayBlocked"] = serde_json::json!([]);
flysim::store::encode(&checkpoint.agent, &checkpoint.runtime).expect("encodes")
}
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
async fn fafb_reward_segments() {
let Some(rom_path) = rom_path() else { return };
let Some(dataset) = fafb() else { return };
let rom = std::fs::read(&rom_path).expect("the cartridge");
let segments: Vec<(String, PathBuf)> = match std::env::var("FLY_TASK01_SEGMENTS") {
Ok(list) => list
.split(',')
.filter_map(|item| {
item.split_once('=')
.map(|(n, p)| (n.to_owned(), PathBuf::from(p)))
})
.collect(),
Err(_) => [
"FLY_DOOR_CHECKPOINT",
"FLY_CATCH_CHECKPOINT",
"FLY_ENGAGE_CHECKPOINT",
]
.iter()
.filter_map(|var| std::env::var_os(var).map(|p| ((*var).to_owned(), PathBuf::from(p))))
.collect(),
};
let frames = env_usize("FLY_TASK01_FRAMES", 1200);
let data = Arc::new(load_brain_dataset_from_dir(&dataset).expect("the dataset"));
let arms: Vec<String> = std::env::var("FLY_TASK01_ARMS")
.map(|v| v.split(',').map(str::to_owned).collect())
.unwrap_or_else(|_| vec!["brain".into(), "driver".into()]);
for (segment, path) in segments {
for arm in &arms {
let name = format!("{segment} {arm}");
let original = std::fs::read(&path).expect("the checkpoint");
let bytes = if arm == "brain" {
reward_bearing(&original)
} else {
original
};
let inputs = Inputs {
sugar: vec![(10, 400.0), (frames / 2, 250.0)],
driver: arm == "driver",
};
let dir = tempfile::tempdir().expect("tmp");
let started = std::time::Instant::now();
let start = Start::Checkpoint(bytes);
let legacy = run_legacy(
&rom,
&data,
&start,
MacroMode::Macros,
frames,
&inputs,
&dir.path().join("trace.jsonl"),
);
eprintln!(
"legacy loop {name}: {frames} frames in {:?}",
started.elapsed()
);
for mode in modes() {
let started = std::time::Instant::now();
let session = run_session(
mode,
&rom_path,
&dataset,
LegacyProfileKind::Production,
MacroMode::Macros,
&start,
frames,
&inputs,
)
.await;
let agreement =
trace::compare(&legacy.behaviours, &session.behaviours, &session.bounds)
.unwrap_or_else(|e| panic!("{name}, {}: {e}", mode.label()));
compare_ledgers(&legacy.ledgers, &session.ledgers);
report(
&format!("segment {name}, {}", mode.label()),
&agreement,
started.elapsed(),
);
}
}
}
}