Merge pull request 'add headless automation' (#39) from dev/headless-automation-host-and-deterministic-runtime-control into master
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good
Reviewed-on: #39
This commit was merged in pull request #39.
This commit is contained in:
Generated
+11
@@ -1674,6 +1674,17 @@ dependencies = [
|
||||
"winit",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prometeu-host-headless"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"prometeu-bytecode",
|
||||
"prometeu-drivers",
|
||||
"prometeu-firmware",
|
||||
"prometeu-hal",
|
||||
"prometeu-system",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "prometeu-layer-tests"
|
||||
version = "0.1.0"
|
||||
|
||||
@@ -7,6 +7,7 @@ members = [
|
||||
"crates/console/prometeu-system",
|
||||
"crates/console/prometeu-vm",
|
||||
"crates/host/prometeu-host-desktop-winit",
|
||||
"crates/host/prometeu-host-headless",
|
||||
"crates/tools/prometeu-cli",
|
||||
"crates/tools/pbxgen-dummy-boy",
|
||||
"crates/tools/pbxgen-stress",
|
||||
|
||||
@@ -579,6 +579,8 @@ mod tests {
|
||||
|
||||
assert_eq!(firmware.os.sessions().vm_session_count(), 0);
|
||||
assert_eq!(firmware.os.vm().current_cartridge_title(), "");
|
||||
assert_eq!(firmware.os.lifecycle().resident_game(), None);
|
||||
assert_eq!(firmware.os.lifecycle().foreground_owner(), ForegroundOwner::Hub);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -9,6 +9,10 @@ pub struct ResetStep;
|
||||
impl ResetStep {
|
||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
||||
// Reset is a cold-boot boundary. Clearing only the VM session leaves
|
||||
// the lifecycle registry pointing at the old resident game, which
|
||||
// rejects the next cartridge as a second resident game.
|
||||
let _ = ctx.os.lifecycle().terminate_resident_game();
|
||||
ctx.os.sessions().clear_vm_sessions();
|
||||
ctx.os.vm().reset_global_runtime_state();
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "prometeu-host-headless"
|
||||
version = "0.1.0"
|
||||
edition = "2024"
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
description = "In-process Prometeu host that boots and steps cartridges without a window, display, or audio device."
|
||||
|
||||
[dependencies]
|
||||
prometeu-bytecode = { path = "../../console/prometeu-bytecode" }
|
||||
prometeu-drivers = { path = "../../console/prometeu-drivers" }
|
||||
prometeu-firmware = { path = "../../console/prometeu-firmware" }
|
||||
prometeu-hal = { path = "../../console/prometeu-hal" }
|
||||
prometeu-system = { path = "../../console/prometeu-system" }
|
||||
@@ -0,0 +1,333 @@
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
use prometeu_bytecode::Value;
|
||||
use prometeu_drivers::hardware::Hardware;
|
||||
use prometeu_drivers::{LocalFramebufferRenderBackend, MemoryBanks};
|
||||
use prometeu_firmware::firmware_state::{AppCrashesStep, ResetStep};
|
||||
use prometeu_firmware::{BootTarget, Firmware, FirmwareState};
|
||||
use prometeu_hal::{
|
||||
AssetBridge, AudioBridge, FrameId, Game2DFrameComposer, InputPlatform, InputSignals,
|
||||
OwnedRgba8888Frame, RenderBackend, RenderSubmission, RenderSubmissionSink, RenderSubmitError,
|
||||
RenderWorkerError, RuntimePlatform, TelemetryPlatform,
|
||||
};
|
||||
use prometeu_system::{CrashReport, LatestRenderFrameStore, RenderWorkerConfig};
|
||||
|
||||
const BOOT_TICK_LIMIT: usize = 64;
|
||||
const LOGICAL_FRAME_TICK_LIMIT: usize = 100_000;
|
||||
const FRAME_PUBLISH_SPINS: usize = 10_000;
|
||||
|
||||
/// One published logical frame plus the automation counter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct CapturedFrame {
|
||||
pub logical_frame_index: u64,
|
||||
pub frame: OwnedRgba8888Frame,
|
||||
}
|
||||
|
||||
/// Debugger-shaped execution snapshot.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct HostState {
|
||||
pub pc: usize,
|
||||
pub stack_top: Vec<Value>,
|
||||
pub frame_index: u64,
|
||||
pub app_id: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum HostError {
|
||||
BootFailed(String),
|
||||
LogicalFrameDidNotClose,
|
||||
FrameNotPublished,
|
||||
RenderWorker(RenderWorkerError),
|
||||
}
|
||||
|
||||
impl fmt::Display for HostError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
match self {
|
||||
Self::BootFailed(reason) => write!(f, "boot failed: {reason}"),
|
||||
Self::LogicalFrameDidNotClose => {
|
||||
write!(f, "logical frame did not reach FrameSync, end of ROM, or a fault")
|
||||
}
|
||||
Self::FrameNotPublished => write!(f, "logical frame closed without a published frame"),
|
||||
Self::RenderWorker(error) => write!(f, "render worker failed: {error:?}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for HostError {}
|
||||
|
||||
/// In-process host. The desktop winit runner is a separate crate and is not linked here.
|
||||
pub struct HeadlessHost {
|
||||
firmware: Firmware,
|
||||
platform: HeadlessPlatform,
|
||||
signals: InputSignals,
|
||||
/// Frame id observed before the logical frame that `capture_frame` should return.
|
||||
previous_frame_id: Option<FrameId>,
|
||||
}
|
||||
|
||||
struct HeadlessPlatform {
|
||||
hardware: Hardware,
|
||||
store: LatestRenderFrameStore,
|
||||
}
|
||||
|
||||
impl HeadlessHost {
|
||||
pub fn new() -> Self {
|
||||
let memory_banks = Arc::new(MemoryBanks::new());
|
||||
let hardware = Hardware::new_with_memory_banks(Arc::clone(&memory_banks));
|
||||
let store = LatestRenderFrameStore::default();
|
||||
Self {
|
||||
firmware: Firmware::new(None),
|
||||
platform: HeadlessPlatform { hardware, store },
|
||||
signals: InputSignals::default(),
|
||||
previous_frame_id: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Load `path` and tick until the firmware is in `GameRunning`.
|
||||
///
|
||||
/// The transition into `GameRunning` is the last tick. The first game
|
||||
/// logical frame stays available for [`Self::advance_frame`].
|
||||
pub fn boot(&mut self, path: impl Into<String>) -> Result<(), HostError> {
|
||||
let path = path.into();
|
||||
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||
self.ensure_worker()?;
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
for _ in 0..BOOT_TICK_LIMIT {
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||
let detail = self
|
||||
.get_fault()
|
||||
.map(|report| report.summary())
|
||||
.unwrap_or_else(|| "cartridge crashed during boot".to_string());
|
||||
return Err(HostError::BootFailed(detail));
|
||||
}
|
||||
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||
return Err(HostError::BootFailed("cartridge did not load".to_string()));
|
||||
}
|
||||
self.tick_once();
|
||||
}
|
||||
|
||||
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(HostError::BootFailed("boot did not reach the game".to_string()))
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reset(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
self.firmware.change_state(
|
||||
FirmwareState::Reset(ResetStep),
|
||||
&self.signals,
|
||||
&mut self.platform,
|
||||
);
|
||||
self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
}
|
||||
|
||||
pub fn resume(&mut self) {
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
}
|
||||
|
||||
/// Execute one VM instruction. This does not close a logical frame.
|
||||
pub fn step(&mut self) -> Option<CrashReport> {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
let report = self.firmware.os.vm().debug_step_active_session(&mut self.platform);
|
||||
self.platform.hardware.audio.clear_commands();
|
||||
report
|
||||
}
|
||||
|
||||
pub fn advance_frame(&mut self) -> Result<(), HostError> {
|
||||
let start = self.firmware.os.vm().logical_frame_index();
|
||||
self.previous_frame_id = self.platform.store.latest_frame().map(|frame| frame.frame_id);
|
||||
self.firmware.os.vm().set_paused(false);
|
||||
self.firmware.os.vm().request_debug_step();
|
||||
|
||||
for _ in 0..LOGICAL_FRAME_TICK_LIMIT {
|
||||
self.tick_once();
|
||||
if self.fault_is_visible() {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
return Ok(());
|
||||
}
|
||||
if self.firmware.os.vm().logical_frame_index() > start {
|
||||
self.firmware.os.vm().set_paused(true);
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
|
||||
Err(HostError::LogicalFrameDidNotClose)
|
||||
}
|
||||
|
||||
pub fn advance_frames(&mut self, count: u64) -> Result<(), HostError> {
|
||||
for _ in 0..count {
|
||||
self.advance_frame()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_input(&mut self, signals: InputSignals) {
|
||||
self.signals = signals;
|
||||
}
|
||||
|
||||
pub fn clear_input(&mut self) {
|
||||
self.signals = InputSignals::default();
|
||||
}
|
||||
|
||||
pub fn set_right(&mut self, down: bool) {
|
||||
self.signals.right_signal = down;
|
||||
}
|
||||
|
||||
pub fn capture_frame(&mut self) -> Result<CapturedFrame, HostError> {
|
||||
let frame = self.wait_for_published_frame(self.previous_frame_id)?;
|
||||
Ok(CapturedFrame {
|
||||
logical_frame_index: self.firmware.os.vm().logical_frame_index(),
|
||||
frame,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn get_state(&mut self) -> HostState {
|
||||
HostState {
|
||||
pc: self.firmware.os.vm().active_pc().unwrap_or(0),
|
||||
stack_top: self.firmware.os.vm().active_operand_stack_top(10),
|
||||
frame_index: self.firmware.os.vm().logical_frame_index(),
|
||||
app_id: self.firmware.os.vm().current_app_id(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn get_fault(&mut self) -> Option<CrashReport> {
|
||||
if let Some(report) = self.firmware.os.vm().last_crash_report() {
|
||||
return Some(report.clone());
|
||||
}
|
||||
match &self.firmware.state {
|
||||
FirmwareState::AppCrashes(AppCrashesStep { report }) => Some(report.clone()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn tick_once(&mut self) {
|
||||
self.firmware.tick(&self.signals, &mut self.platform);
|
||||
self.platform.hardware.audio.clear_commands();
|
||||
}
|
||||
|
||||
fn fault_is_visible(&mut self) -> bool {
|
||||
self.firmware.os.vm().last_crash_report().is_some()
|
||||
|| matches!(self.firmware.state, FirmwareState::AppCrashes(_))
|
||||
}
|
||||
|
||||
fn ensure_worker(&mut self) -> Result<(), HostError> {
|
||||
if self.firmware.os.vm().render_worker_controller().is_some() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let backend = LocalFramebufferRenderBackend::new_with_memory_banks(
|
||||
Hardware::W,
|
||||
Hardware::H,
|
||||
Arc::clone(&self.platform.hardware.memory_banks),
|
||||
self.platform.hardware.assets.glyph_asset_slot_index(),
|
||||
);
|
||||
let store = self.platform.store.clone();
|
||||
self.firmware.os.vm().start_render_worker(RenderWorkerConfig::default(), backend, store);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn wait_for_published_frame(
|
||||
&mut self,
|
||||
previous: Option<FrameId>,
|
||||
) -> Result<OwnedRgba8888Frame, HostError> {
|
||||
for _ in 0..FRAME_PUBLISH_SPINS {
|
||||
if let Some(error) = self
|
||||
.firmware
|
||||
.os
|
||||
.vm()
|
||||
.render_worker_controller()
|
||||
.and_then(|worker| worker.last_error())
|
||||
{
|
||||
return Err(HostError::RenderWorker(error));
|
||||
}
|
||||
if let Some(frame) = self.platform.store.latest_frame()
|
||||
&& Some(frame.frame_id) != previous
|
||||
{
|
||||
return Ok(frame);
|
||||
}
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
Err(HostError::FrameNotPublished)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for HeadlessHost {
|
||||
fn default() -> Self {
|
||||
Self::new()
|
||||
}
|
||||
}
|
||||
|
||||
impl RenderSubmissionSink for HeadlessPlatform {
|
||||
fn submit_render_submission(
|
||||
&mut self,
|
||||
submission: RenderSubmission,
|
||||
) -> Result<(), RenderSubmitError> {
|
||||
let frame_id = submission.frame_id;
|
||||
let ownership = submission.ownership;
|
||||
self.hardware.submit_render_submission(submission)?;
|
||||
let (width, height) = self.hardware.gfx.size();
|
||||
let pixels = self.hardware.gfx.front_buffer().to_vec();
|
||||
let frame = OwnedRgba8888Frame::packed(frame_id, ownership, width, height, pixels)
|
||||
.map_err(|_| RenderSubmitError::SubmissionRejected)?;
|
||||
self.store.publish_frame(frame);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl RuntimePlatform for HeadlessPlatform {
|
||||
fn display_size(&self) -> (usize, usize) {
|
||||
(Hardware::W, Hardware::H)
|
||||
}
|
||||
|
||||
fn render_submission_sink(&mut self) -> &mut dyn RenderSubmissionSink {
|
||||
self
|
||||
}
|
||||
|
||||
fn render_backend(&mut self) -> &mut dyn RenderBackend {
|
||||
&mut self.hardware
|
||||
}
|
||||
|
||||
fn game2d_frame_composer(&mut self) -> &mut dyn Game2DFrameComposer {
|
||||
&mut self.hardware
|
||||
}
|
||||
|
||||
fn audio(&self) -> &dyn AudioBridge {
|
||||
self.hardware.audio()
|
||||
}
|
||||
|
||||
fn audio_mut(&mut self) -> &mut dyn AudioBridge {
|
||||
self.hardware.audio_mut()
|
||||
}
|
||||
|
||||
fn input(&self) -> &dyn InputPlatform {
|
||||
self.hardware.input()
|
||||
}
|
||||
|
||||
fn input_mut(&mut self) -> &mut dyn InputPlatform {
|
||||
self.hardware.input_mut()
|
||||
}
|
||||
|
||||
fn assets(&self) -> &dyn AssetBridge {
|
||||
self.hardware.assets()
|
||||
}
|
||||
|
||||
fn assets_mut(&mut self) -> &mut dyn AssetBridge {
|
||||
self.hardware.assets_mut()
|
||||
}
|
||||
|
||||
fn telemetry(&self) -> &dyn TelemetryPlatform {
|
||||
self.hardware.telemetry()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
//! Headless Prometeu host.
|
||||
//!
|
||||
//! This crate boots a directory cartridge and steps logical frames in process.
|
||||
//! It does not open a window, a display surface, or an audio device.
|
||||
//!
|
||||
//! The desktop host's `stepFrame` command still advances on the 60 Hz winit loop.
|
||||
//! That pacing stays in `prometeu-host-desktop-winit` until a later protocol agenda.
|
||||
|
||||
mod host;
|
||||
|
||||
pub use host::{CapturedFrame, HeadlessHost, HostError, HostState};
|
||||
@@ -0,0 +1,260 @@
|
||||
use std::fs;
|
||||
use std::path::Path;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use prometeu_bytecode::assembler::assemble;
|
||||
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
|
||||
use prometeu_hal::color::Color;
|
||||
use prometeu_host_headless::{CapturedFrame, HeadlessHost, HostState};
|
||||
use prometeu_system::CrashReport;
|
||||
|
||||
const RED: u32 = Color::RED.raw();
|
||||
const BLUE: u32 = Color::BLUE.raw();
|
||||
|
||||
#[test]
|
||||
fn step_does_not_complete_a_logical_frame() {
|
||||
let mut host = boot_color();
|
||||
let before = host.get_state().frame_index;
|
||||
host.step();
|
||||
assert_eq!(host.get_state().frame_index, before);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn clear_input_drops_right() {
|
||||
let mut host = boot_color();
|
||||
host.set_right(true);
|
||||
host.clear_input();
|
||||
host.advance_frame().expect("frame");
|
||||
assert_color(&host.capture_frame().expect("frame"), BLUE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn right_hold_then_release_changes_pixels() {
|
||||
let mut host = boot_color();
|
||||
let before = host.get_state().frame_index;
|
||||
|
||||
host.set_right(true);
|
||||
host.advance_frames(60).expect("hold");
|
||||
let held = host.capture_frame().expect("held frame");
|
||||
assert_eq!(host.get_state().frame_index, before + 60);
|
||||
assert_color(&held, RED);
|
||||
assert!(host.get_fault().is_none());
|
||||
|
||||
host.set_right(false);
|
||||
host.advance_frames(1).expect("release");
|
||||
let released = host.capture_frame().expect("released frame");
|
||||
assert_eq!(released.logical_frame_index, before + 61);
|
||||
assert_color(&released, BLUE);
|
||||
assert!(host.get_fault().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_runs_match_oracle() {
|
||||
let first = run_color_sequence();
|
||||
let second = run_color_sequence();
|
||||
assert_eq!(first.held.logical_frame_index, second.held.logical_frame_index);
|
||||
assert_eq!(first.held.frame.pixels, second.held.frame.pixels);
|
||||
assert_eq!(first.held.frame.frame_id, second.held.frame.frame_id);
|
||||
assert_eq!(first.released.frame.pixels, second.released.frame.pixels);
|
||||
assert_eq!(first.released.frame.frame_id, second.released.frame.frame_id);
|
||||
assert_eq!(first.released.logical_frame_index, second.released.logical_frame_index);
|
||||
assert_same_state(&first.state, &second.state);
|
||||
assert_eq!(first.fault, second.fault);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_matches_fresh_host() {
|
||||
let mut host = boot_color();
|
||||
let _ = run_on(&mut host);
|
||||
host.reset();
|
||||
host.boot(color_cartridge()).expect("reboot");
|
||||
let after_reset = run_on(&mut host);
|
||||
let fresh = run_color_sequence();
|
||||
|
||||
assert_eq!(after_reset.held.frame.pixels, fresh.held.frame.pixels);
|
||||
assert_eq!(after_reset.released.frame.pixels, fresh.released.frame.pixels);
|
||||
assert_eq!(after_reset.held.frame.frame_id, fresh.held.frame.frame_id);
|
||||
assert_eq!(after_reset.released.frame.frame_id, fresh.released.frame.frame_id);
|
||||
assert_eq!(after_reset.released.logical_frame_index, fresh.released.logical_frame_index);
|
||||
assert_same_state(&after_reset.state, &fresh.state);
|
||||
assert_eq!(after_reset.fault, fresh.fault);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn trap_is_structured() {
|
||||
let dir = temp_cart("fault");
|
||||
write_cartridge(&dir, 42, "Fault", &fault_program(), &[]);
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(&dir).expect("boot fault cartridge");
|
||||
host.advance_frame().expect("faulting frame");
|
||||
|
||||
match host.get_fault() {
|
||||
Some(report @ CrashReport::VmTrap { .. }) => {
|
||||
assert!(report.pc().is_some());
|
||||
}
|
||||
other => panic!("expected VmTrap, got {other:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn three_hundred_frames_finish_without_refresh_sleep() {
|
||||
let mut host = boot_color();
|
||||
let started = Instant::now();
|
||||
host.advance_frames(300).expect("fast frames");
|
||||
assert!(started.elapsed() < Duration::from_secs(2));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn audio_play_does_not_need_a_device() {
|
||||
let mut host = boot_color();
|
||||
host.advance_frame().expect("frame with audio.play");
|
||||
assert!(host.get_fault().is_none());
|
||||
assert_color(&host.capture_frame().expect("frame"), BLUE);
|
||||
}
|
||||
|
||||
struct ColorOracle {
|
||||
held: CapturedFrame,
|
||||
released: CapturedFrame,
|
||||
state: HostState,
|
||||
fault: Option<CrashReport>,
|
||||
}
|
||||
|
||||
fn boot_color() -> HeadlessHost {
|
||||
let mut host = HeadlessHost::new();
|
||||
host.boot(color_cartridge()).expect("boot color cartridge");
|
||||
host
|
||||
}
|
||||
|
||||
fn color_cartridge() -> String {
|
||||
let dir = temp_cart("color");
|
||||
write_cartridge(&dir, 41, "Right Pixel", &color_program(), &color_syscalls());
|
||||
dir
|
||||
}
|
||||
|
||||
fn run_color_sequence() -> ColorOracle {
|
||||
let mut host = boot_color();
|
||||
run_on(&mut host)
|
||||
}
|
||||
|
||||
fn run_on(host: &mut HeadlessHost) -> ColorOracle {
|
||||
host.set_right(true);
|
||||
host.advance_frames(60).expect("hold");
|
||||
let held = host.capture_frame().expect("held");
|
||||
host.set_right(false);
|
||||
host.advance_frames(1).expect("release");
|
||||
let released = host.capture_frame().expect("released");
|
||||
let state = host.get_state();
|
||||
let fault = host.get_fault();
|
||||
ColorOracle { held, released, state, fault }
|
||||
}
|
||||
|
||||
fn assert_color(captured: &CapturedFrame, color: u32) {
|
||||
assert_eq!(captured.frame.width, 480);
|
||||
assert_eq!(captured.frame.height, 270);
|
||||
assert!(captured.frame.pixels.iter().all(|pixel| *pixel == color));
|
||||
}
|
||||
|
||||
fn assert_same_state(left: &HostState, right: &HostState) {
|
||||
assert_eq!(left.pc, right.pc);
|
||||
assert_eq!(left.frame_index, right.frame_index);
|
||||
assert_eq!(left.app_id, right.app_id);
|
||||
assert_eq!(format!("{:?}", left.stack_top), format!("{:?}", right.stack_top));
|
||||
}
|
||||
|
||||
fn temp_cart(name: &str) -> String {
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"prometeu-headless-{name}-{}-{}",
|
||||
std::process::id(),
|
||||
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
|
||||
));
|
||||
fs::create_dir_all(&dir).expect("temp cartridge dir");
|
||||
dir.to_string_lossy().into_owned()
|
||||
}
|
||||
|
||||
fn write_cartridge(dir: &str, app_id: u32, title: &str, program: &[u8], syscalls: &[SyscallDecl]) {
|
||||
let path = Path::new(dir);
|
||||
fs::write(path.join("program.pbx"), program).expect("program");
|
||||
fs::write(
|
||||
path.join("manifest.json"),
|
||||
format!(
|
||||
"{{\n \"magic\": \"PMTU\",\n \"cartridge_version\": 1,\n \"app_id\": {app_id},\n \"title\": \"{title}\",\n \"app_version\": \"0.1.0\",\n \"app_mode\": \"Game\",\n \"capabilities\": [\"gfx2d\", \"audio\"]\n}}\n"
|
||||
),
|
||||
)
|
||||
.expect("manifest");
|
||||
let _ = syscalls;
|
||||
}
|
||||
|
||||
fn color_program() -> Vec<u8> {
|
||||
let mut rom = Vec::new();
|
||||
rom.extend(asm("PUSH_I32 0\n\
|
||||
PUSH_I32 0\n\
|
||||
PUSH_I32 0\n\
|
||||
PUSH_I32 255\n\
|
||||
PUSH_I32 128\n\
|
||||
PUSH_I32 1\n\
|
||||
PUSH_I32 0\n\
|
||||
HOSTCALL 1\n\
|
||||
POP_N 1\n\
|
||||
INTRINSIC 0x2000\n\
|
||||
INTRINSIC 0x2013\n\
|
||||
INTRINSIC 0x2032\n"));
|
||||
let jump_to_blue = rom.len() + 2;
|
||||
rom.extend(asm("JMP_IF_FALSE 0"));
|
||||
rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
let blue_at = rom.len() as u32;
|
||||
rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||
rom[jump_to_blue..jump_to_blue + 4].copy_from_slice(&blue_at.to_le_bytes());
|
||||
module(rom, color_syscalls())
|
||||
}
|
||||
|
||||
fn fault_program() -> Vec<u8> {
|
||||
// `INTRINSIC 0xDEADBEEF` is rejected by the loader as `VerificationFailed`.
|
||||
// `TRAP` is a legal instruction that becomes `CrashReport::VmTrap` at runtime.
|
||||
module(asm("TRAP\nFRAME_SYNC\nRET\n"), vec![])
|
||||
}
|
||||
|
||||
fn color_syscalls() -> Vec<SyscallDecl> {
|
||||
vec![
|
||||
SyscallDecl {
|
||||
module: "gfx2d".into(),
|
||||
name: "clear".into(),
|
||||
version: 1,
|
||||
arg_slots: 1,
|
||||
ret_slots: 0,
|
||||
},
|
||||
SyscallDecl {
|
||||
module: "audio".into(),
|
||||
name: "play".into(),
|
||||
version: 1,
|
||||
arg_slots: 7,
|
||||
ret_slots: 1,
|
||||
},
|
||||
]
|
||||
}
|
||||
|
||||
fn module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
||||
BytecodeModule {
|
||||
version: 0,
|
||||
const_pool: vec![],
|
||||
functions: vec![FunctionMeta {
|
||||
code_offset: 0,
|
||||
code_len: code.len() as u32,
|
||||
param_slots: 0,
|
||||
local_slots: 0,
|
||||
return_slots: 0,
|
||||
max_stack_slots: 8,
|
||||
}],
|
||||
code,
|
||||
debug_info: Some(DebugInfo {
|
||||
pc_to_span: vec![],
|
||||
function_names: vec![(0, "main".into())],
|
||||
}),
|
||||
exports: vec![Export { symbol: "main".into(), func_idx: 0 }],
|
||||
syscalls,
|
||||
}
|
||||
.serialize()
|
||||
}
|
||||
|
||||
fn asm(source: &str) -> Vec<u8> {
|
||||
assemble(source).expect("assemble")
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
{"type":"meta","next_id":{"DSC":49,"AGD":52,"DEC":43,"PLN":174,"LSN":57,"CLSN":1}}
|
||||
{"type":"meta","next_id":{"DSC":50,"AGD":53,"DEC":44,"PLN":175,"LSN":58,"CLSN":1}}
|
||||
{"type":"discussion","id":"DSC-0049","status":"done","ticket":"headless-automation-host-and-deterministic-runtime-control","title":"Headless Automation Host and Deterministic Runtime Control","created_at":"2026-09-22","updated_at":"2026-09-22","tags":["runtime","host","headless","automation","testing","ai","deterministic","input","framebuffer","debugger"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0057","file":"discussion/lessons/DSC-0049-headless-automation-host-and-deterministic-runtime-control/LSN-0057-deterministic-host-control-follows-logical-runtime-boundaries.md","status":"done","created_at":"2026-09-22","updated_at":"2026-09-22"}]}
|
||||
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"hub-suspended-game-kill-affordance","title":"Hub Suspended Game Kill Affordance","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["hub","lifecycle","game","ui"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0044-hub-suspended-game-kill-affordance/LSN-0054-manual-hub-kill-must-share-game-termination-cleanup.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0043-system-os-cartridge-switch-orchestrator/LSN-0053-game-switching-is-lifecycle-replacement-not-loader-work.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||
{"type":"discussion","id":"DSC-0039","status":"abandoned","ticket":"render-pipeline-family-and-future-3d","title":"Render Pipeline Family and Future 3D","created_at":"2026-06-04","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","architecture","pipeline"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-render-pipeline-family-and-future-3d.md","status":"abandoned","created_at":"2026-06-04","updated_at":"2026-06-04","_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}
|
||||
@@ -14,10 +15,10 @@
|
||||
{"type":"discussion","id":"DSC-0022","status":"done","ticket":"tile-bank-vs-glyph-bank-domain-naming","title":"Glyph Bank Domain Naming Contract","created_at":"2026-04-09","updated_at":"2026-04-10","tags":["gfx","runtime","naming","domain-model"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0025","file":"discussion/lessons/DSC-0022-glyph-bank-domain-naming/LSN-0025-rename-artifact-by-meaning-not-by-token.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
|
||||
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"legacy-runtime-learn-import","title":"Import legacy runtime learn into discussion lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["migration","tech-debt"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0001-prometeu-learn-index.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0002-historical-asset-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0003-historical-audio-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0004-historical-cartridge-boot-protocol-and-manifest-authority.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0005-historical-game-memcard-slots-surface-and-semantics.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0006-historical-gfx-status-first-fault-and-return-contract.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0007-historical-retired-fault-and-input-decisions.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0008-historical-vm-core-and-assets.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0009","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0009-mental-model-asset-management.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0010-mental-model-audio.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0011-mental-model-gfx.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0012-mental-model-input.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0013-mental-model-observability-and-debugging.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0014-mental-model-portability-and-cross-platform.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0015-mental-model-save-memory-and-memcard.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0016-mental-model-status-first-and-fault-thinking.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0017-mental-model-time-and-cycles.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0018","file":"discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0018-mental-model-touch.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
|
||||
{"type":"discussion","id":"DSC-0002","status":"done","ticket":"runtime-edge-test-plan","title":"Agenda - Runtime Edge Test Plan","created_at":"2026-03-27","updated_at":"2026-04-21","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0037","file":"discussion/lessons/DSC-0002-runtime-edge-test-plan/LSN-0037-domain-gates-must-be-owned-by-the-repository.md","status":"done","created_at":"2026-04-21","updated_at":"2026-04-21"}]}
|
||||
{"type":"discussion","id":"DSC-0003","status":"open","ticket":"packed-cartridge-loader-pmc","title":"Agenda - Packed Cartridge Loader PMC","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0002","file":"AGD-0002-packed-cartridge-loader-pmc.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0003","status":"open","ticket":"packed-cartridge-loader-pmc","title":"Agenda - Packed Cartridge Loader PMC","created_at":"2026-03-27","updated_at":"2026-09-22","tags":[],"agendas":[{"id":"AGD-0002","file":"AGD-0002-packed-cartridge-loader-pmc.md","status":"open","created_at":"2026-03-27","updated_at":"2026-09-22"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0004","status":"done","ticket":"system-run-cart","title":"Agenda - System Run Cart","created_at":"2026-03-27","updated_at":"2026-07-03","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0051","file":"discussion/lessons/DSC-0004-system-run-cart/LSN-0051-launch-authority-belongs-to-systemos.md","status":"done","created_at":"2026-07-03","updated_at":"2026-07-03"}]}
|
||||
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"system-fault-semantics-and-control-surface","title":"Agenda - System Fault Semantics and Control Surface","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0004","file":"AGD-0004-system-fault-semantics-and-control-surface.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"vm-owned-random-service","title":"Agenda - VM-Owned Random Service","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0005","file":"AGD-0005-vm-owned-random-service.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"system-fault-semantics-and-control-surface","title":"Agenda - System Fault Semantics and Control Surface","created_at":"2026-03-27","updated_at":"2026-09-22","tags":[],"agendas":[{"id":"AGD-0004","file":"AGD-0004-system-fault-semantics-and-control-surface.md","status":"open","created_at":"2026-03-27","updated_at":"2026-09-22"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"vm-owned-random-service","title":"Agenda - VM-Owned Random Service","created_at":"2026-03-27","updated_at":"2026-09-22","tags":[],"agendas":[{"id":"AGD-0005","file":"AGD-0005-vm-owned-random-service.md","status":"open","created_at":"2026-03-27","updated_at":"2026-09-22"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0007","status":"open","ticket":"app-home-filesystem-surface-and-semantics","title":"Agenda - App Home Filesystem Surface and Semantics","created_at":"2026-03-27","updated_at":"2026-03-27","tags":[],"agendas":[{"id":"AGD-0006","file":"AGD-0006-app-home-filesystem-surface-and-semantics.md","status":"open","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0045","status":"open","ticket":"background-service-audio-execution","title":"Background Service and Audio Execution","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","service","audio","background","architecture"],"agendas":[{"id":"AGD-0048","file":"AGD-0048-background-service-audio-execution.md","status":"open","created_at":"2026-07-05","updated_at":"2026-07-05"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"perf-runtime-telemetry-hot-path","title":"Agenda - [PERF] Runtime Telemetry Hot Path","created_at":"2026-03-27","updated_at":"2026-06-04","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0026","file":"discussion/lessons/DSC-0008-perf-runtime-telemetry-hot-path/LSN-0026-push-based-telemetry-model.md","status":"done","created_at":"2026-04-10","updated_at":"2026-04-10"}]}
|
||||
@@ -45,5 +46,5 @@
|
||||
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"prometeu-hub-ui-direction","title":"Agenda - Prometeu Hub UI Direction","created_at":"2026-05-15","updated_at":"2026-05-22","tags":["hub","ui","shell","system-apps","lifecycle","design-system"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0036-prometeu-hub-ui-direction/LSN-0045-hub-ui-slices-should-prove-os-boundaries.md","status":"done","created_at":"2026-05-22","updated_at":"2026-05-22"}]}
|
||||
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"rgba8888-framebuffer-and-pixel-format-direction","title":"Agenda - RGBA8888 Framebuffer and Pixel Format Direction","created_at":"2026-05-22","updated_at":"2026-05-23","tags":["gfx","framebuffer","rgb565","rgba8888","renderer","assets","host","backend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0037-rgba8888-framebuffer-and-pixel-format-direction/LSN-0046-pixel-format-contracts-must-move-as-one-surface.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23"}]}
|
||||
{"type":"discussion","id":"DSC-0046","status":"done","ticket":"runtime-owned-variable-glyph-bank-palette-protocol","title":"Runtime-Owned Variable Glyph Bank Palette Protocol","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["runtime","gfx","assets","glyph-bank","palette-serialization","protocol"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0046-runtime-owned-variable-glyph-bank-palette-protocol/LSN-0055-runtime-owned-asset-protocols-must-align-payload-residency-and-lookup.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
|
||||
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"portable-host-backend-strategy","title":"Portable Host Backend Strategy","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["host","desktop","portable","sdl","backend","rendering","input","audio","linux","android","handheld"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-portable-host-backend-strategy.md","status":"open","created_at":"2026-07-14","updated_at":"2026-07-14"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"portable-host-backend-strategy","title":"Portable Host Backend Strategy","created_at":"2026-07-14","updated_at":"2026-09-22","tags":["host","desktop","portable","sdl","backend","rendering","input","audio","linux","android","handheld"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-portable-host-backend-strategy.md","status":"open","created_at":"2026-07-14","updated_at":"2026-09-22"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-0048","status":"done","ticket":"corrigir-identificacao-formato-pbx","title":"Corrigir Identificacao do Formato PBX","created_at":"2026-07-15","updated_at":"2026-07-15","tags":["runtime","bytecode","pbx","loader","format","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0056","file":"discussion/lessons/DSC-0048-corrigir-identificacao-formato-pbx/LSN-0056-runtime-artifact-identity-must-not-borrow-frontend-names.md","status":"done","created_at":"2026-07-15","updated_at":"2026-07-15"}]}
|
||||
|
||||
+125
@@ -0,0 +1,125 @@
|
||||
---
|
||||
id: LSN-0057
|
||||
ticket: headless-automation-host-and-deterministic-runtime-control
|
||||
title: Deterministic Host Control Follows Logical Runtime Boundaries
|
||||
created: 2026-09-22
|
||||
tags: [runtime, host, headless, deterministic, testing, input, framebuffer, lifecycle]
|
||||
---
|
||||
|
||||
## Context
|
||||
|
||||
Prometeu needed an automation host that could boot and control a real cartridge
|
||||
without a window, display surface, audio device, or refresh-rate delay. The
|
||||
runtime already had the necessary domain boundaries: normalized
|
||||
`InputSignals`, logical-frame execution, structured `CrashReport` values, and
|
||||
worker-published `OwnedRgba8888Frame` values. The missing piece was a host that
|
||||
composed those boundaries without inheriting desktop presentation concerns.
|
||||
|
||||
The implementation introduced the in-process `prometeu-host-headless` library
|
||||
under `DEC-0043`. It proved deterministic input, frame advancement, pixel
|
||||
capture, faults, audio discard, and reset behavior with directory cartridges
|
||||
assembled directly in Rust tests.
|
||||
|
||||
## Key Decisions
|
||||
|
||||
### Logical Frames, Not Host Ticks, Are the Automation Unit
|
||||
|
||||
**What:** `advance_frame` repeatedly ticks firmware until the VM closes one
|
||||
logical frame or reports a fault. It temporarily releases VM pause through the
|
||||
existing debug-step request and leaves the VM paused afterward.
|
||||
|
||||
**Why:** A firmware tick is an execution budget slice, not necessarily a guest
|
||||
frame. Exposing ticks would make automation sensitive to budget configuration
|
||||
and host speed. Waiting for `FrameSync`, end-of-ROM, or a fault gives callers a
|
||||
guest-visible boundary.
|
||||
|
||||
**Trade-offs:** One automation operation may execute multiple firmware ticks.
|
||||
The host must therefore drain audio after every tick and must distinguish
|
||||
instruction stepping from logical-frame advancement.
|
||||
|
||||
### Published Worker Frames Are the Pixel Oracle
|
||||
|
||||
**What:** Frame capture reads the `LatestRenderFrameStore` populated by the
|
||||
existing render worker and waits for a frame id newer than the one observed
|
||||
before advancement.
|
||||
|
||||
**Why:** Reading mutable hardware buffers would create a second observation
|
||||
path and could expose partially applied work. The published
|
||||
`OwnedRgba8888Frame` is already the runtime's canonical completed-frame
|
||||
boundary, as described by `LSN-0049`.
|
||||
|
||||
**Trade-offs:** Logical execution and frame publication finish on different
|
||||
threads, so capture must synchronize with publication. That wait is worker
|
||||
completion, not refresh pacing.
|
||||
|
||||
### Cold Reset Must Clear Lifecycle Ownership as Well as VM State
|
||||
|
||||
**What:** Entering `FirmwareState::Reset` terminates the resident game before
|
||||
clearing VM sessions and global runtime cartridge state.
|
||||
|
||||
**Why:** Clearing only the VM session registry leaves the foreground lifecycle
|
||||
stack pointing at the old resident task. The next boot then looks like a second
|
||||
resident game and fails with `ResidentGameAlreadyExists`. A cold boot boundary
|
||||
must clear both execution state and the ownership records that authorize it.
|
||||
|
||||
**Trade-offs:** Reset is destructive lifecycle replacement. It intentionally
|
||||
does not preserve the previous game as resumable state; Home suspend/resume is
|
||||
the separate contract for preservation.
|
||||
|
||||
## Patterns and Algorithms
|
||||
|
||||
### Deterministic Frame Advancement
|
||||
|
||||
1. Record the current logical-frame index and latest published frame id.
|
||||
2. Unpause the active VM session and request one debug frame step.
|
||||
3. Tick firmware with the retained `InputSignals`.
|
||||
4. Clear pending audio commands after every tick.
|
||||
5. Continue until the logical-frame index advances or a structured fault is
|
||||
visible.
|
||||
6. Pause the VM again.
|
||||
7. Read the publication store until the worker publishes a different frame id.
|
||||
|
||||
This keeps the oracle independent of wall-clock refresh timing while exercising
|
||||
the same firmware, VM, render worker, input, and audio paths as a real host.
|
||||
|
||||
### Repeatability Oracle
|
||||
|
||||
Compare only stable runtime outputs:
|
||||
|
||||
- logical-frame index;
|
||||
- published RGBA8888 pixels and frame identity progression;
|
||||
- debugger-shaped state (`pc`, stack top, frame index, and app id);
|
||||
- structured fault data.
|
||||
|
||||
Do not compare host CPU time, `Instant` timestamps, or certification budgets.
|
||||
Those values characterize execution conditions, not deterministic guest state.
|
||||
|
||||
## Pitfalls
|
||||
|
||||
- One firmware tick is not guaranteed to complete one guest frame.
|
||||
- Instruction `step` and logical-frame advancement have different contracts.
|
||||
- Capturing the hardware front buffer bypasses the canonical worker publication
|
||||
boundary.
|
||||
- Sleeping for a display period makes a headless host inherit presentation
|
||||
pacing and turns 300-frame tests into multi-second runs.
|
||||
- Clearing VM sessions without clearing resident-game lifecycle ownership does
|
||||
not produce a cold reset.
|
||||
- Opening or emulating an audio device is unnecessary when the required sink
|
||||
semantics are simply to consume and discard queued commands.
|
||||
|
||||
## References
|
||||
|
||||
- Decision: `DEC-0043` (Headless Host and Deterministic Frame Control)
|
||||
- Related lesson: `LSN-0049` (Render Workers Publish Frames, Hosts Present Them)
|
||||
- Related lesson: `LSN-0053` (Game Switching Is Lifecycle Replacement, Not Loader Work)
|
||||
- Audio contract: `docs/specs/runtime/05-audio-peripheral.md`
|
||||
|
||||
## Takeaways
|
||||
|
||||
- Automation should advance guest-defined logical boundaries, not host loop
|
||||
iterations.
|
||||
- Deterministic input is a retained normalized value supplied to every tick.
|
||||
- The render worker's publication store is the single trustworthy pixel oracle.
|
||||
- Headless execution can reuse production runtime paths without linking native
|
||||
presentation or audio-device libraries.
|
||||
- A cold reset must clear lifecycle ownership and execution state together.
|
||||
@@ -83,4 +83,36 @@ Pode virar PR quando houver definição escrita de:
|
||||
- arquivos obrigatórios;
|
||||
- erros canônicos;
|
||||
- invariantes de segurança;
|
||||
- estratégia de testes de compatibilidade entre diretório e pacote.
|
||||
- estratégia de testes de compatibilidade entre diretório e pacote;
|
||||
- equivalência observável entre diretório e `.pmc` para qualquer host que use `CartridgeLoader`, incluindo o host desktop e o host headless de `AGD-0052`.
|
||||
|
||||
## Revalidação — 2026-09-22
|
||||
|
||||
Revalidada contra o código atual e contra `AGD-0052` / `DSC-0049` (Headless Automation Host and Deterministic Runtime Control). A agenda permanece aberta.
|
||||
|
||||
### O que permanece
|
||||
|
||||
`PackedCartridgeLoader::load` ainda retorna `CartridgeError::InvalidFormat` sem ler o arquivo. O dispatcher continua aceitando a extensão `.pmc` e delegando para esse stub. O loader de diretório é o caminho real: `manifest.json`, `program.pbx` e `assets.pa` quando a capability de asset exige. Boot direto (`BootTarget::Cartridge`) e o host desktop usam esse mesmo `CartridgeLoader`.
|
||||
|
||||
O problema original segue válido: a plataforma anuncia dois formatos e só o diretório funciona.
|
||||
|
||||
### Efeito da direção headless
|
||||
|
||||
`AGD-0052` coloca o host headless como consumidor novo do loader, e deixa o formato `.pmc` fora do primeiro ciclo. O primeiro boot automatizado usa cartucho de diretório, o mesmo artefato que o host desktop já carrega.
|
||||
|
||||
Consequências para esta agenda:
|
||||
|
||||
- headless, CI e agente não definem o container;
|
||||
- quando `.pmc` existir, diretório e pacote precisam materializar o mesmo cartucho lógico, para o determinismo não depender da origem dos bytes;
|
||||
- a ordem física do container continua impedida de alterar o resultado, como o item de segurança e determinismo já pedia;
|
||||
- esta agenda não absorve captura de framebuffer, replay ou protocolo de automação.
|
||||
|
||||
### O que não mudou no critério
|
||||
|
||||
Formato, arquivos obrigatórios, erros canônicos, invariantes de segurança e testes de equivalência continuam sendo o fechamento. O critério de saída ganhou só a exigência de que essa equivalência valha para todo host do `CartridgeLoader`.
|
||||
|
||||
### Perguntas que continuam abertas
|
||||
|
||||
- [ ] O `.pmc` é zip, tar, formato próprio ou envelope com header e blobs?
|
||||
- [ ] Quais entradas são obrigatórias além das que o loader de diretório já exige?
|
||||
- [ ] Qual matriz de erro determinística substitui o `InvalidFormat` genérico do stub?
|
||||
|
||||
+45
-26
@@ -13,53 +13,72 @@ tags: []
|
||||
|
||||
## Problema
|
||||
|
||||
O dominio `system` e pequeno, mas mistura consulta simples com superficie de controle de fluxo.
|
||||
O domínio `system` exposto à userland ficou pequeno, e a política de retorno dele ainda não está escrita.
|
||||
|
||||
Hoje:
|
||||
Estado em 2026-09-22:
|
||||
|
||||
- `SystemHasCart` responde diretamente;
|
||||
- `SystemRunCart` ainda nao tem efeito real;
|
||||
- a agenda `009` resolve semantica funcional, mas nao fecha por si so a politica de fault do dominio.
|
||||
- a superfície gerada é só `system.has_cart` (`Syscall::SystemHasCart`), com 1 retorno e capability `SYSTEM`;
|
||||
- o dispatch devolve `true` fixo, sem consultar cartucho e sem `status`;
|
||||
- `system.run_cart` saiu da ABI de userland. Launch de cartucho é ação de SystemOS/firmware/host (`LSN-0051`, `DSC-0004`);
|
||||
- fault de execução da VM já tem forma estruturada em `CrashReport` (`VmTrap`, `VmPanic`, `VmInit`), observada pelo host e pelo debugger.
|
||||
|
||||
O texto de 2026-03-27 tratava `SystemRunCart` como operação ainda sem efeito e apontava a agenda `009` e `virtual_machine_runtime/dispatch.rs`. Esses dois pontos ficaram obsoletos. A política de fault do que permanece no domínio `system` continua aberta.
|
||||
|
||||
## Dor
|
||||
|
||||
- sem uma agenda propria, `system` pode herdar fault semantics por acidente;
|
||||
- `run_cart` pode acabar consolidando `Panic` ou `Trap` onde deveria existir retorno operacional;
|
||||
- a fronteira entre falha do app, falha do firmware e falha do runtime fica opaca.
|
||||
- `has_cart` pode permanecer um bool fixo e mascarar ausência, cartucho inválido ou consulta fora de autoridade;
|
||||
- uma futura operação de `system` pode herdar `Trap` ou `Panic` onde o contrato transversal pede `status`;
|
||||
- automação headless (`AGD-0052`) precisa observar fault estruturado sem que esta agenda redesenhe `CrashReport` nem invente syscall de controle para CI ou agente.
|
||||
|
||||
## Hotspots Atuais
|
||||
|
||||
- [dispatch.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system/src/virtual_machine_runtime/dispatch.rs#L114)
|
||||
- [system.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-hal/src/syscalls/domains/system.rs#L4)
|
||||
- [009-system-run-cart.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/runtime/agendas/009-system-run-cart.md)
|
||||
- `crates/console/prometeu-hal/src/syscalls/domains/system.rs`
|
||||
- `crates/console/prometeu-system/src/services/vm_runtime/dispatch.rs` (`SystemHasCart` retorna `true`)
|
||||
- `crates/console/prometeu-system/src/crash_report.rs`
|
||||
- `docs/specs/runtime/16a-syscall-policies.md`
|
||||
- `discussion/lessons/DSC-0004-system-run-cart/LSN-0051-launch-authority-belongs-to-systemos.md`
|
||||
|
||||
## Alvo da Discussao
|
||||
|
||||
Fechar a politica de fault e retorno do dominio `system`.
|
||||
Fechar a política de fault e retorno do domínio `system` que ainda é visível à userland, e separar essa política da observação de fault de VM feita pelo host.
|
||||
|
||||
## O Que Precisa Ser Definido
|
||||
|
||||
1. Queries simples.
|
||||
Decidir a politica de fault para consultas como `has_cart`.
|
||||
Decidir a política de `has_cart`: bool atual, `status` mais payload, ou outra forma compatível com `16a`. Incluir o que a consulta realmente observa.
|
||||
|
||||
2. `run_cart`.
|
||||
Decidir como falhas operacionais de transicao devem ser expostas:
|
||||
- `status`;
|
||||
- `Trap`;
|
||||
- `Panic`.
|
||||
2. Operações que não voltam para a userland.
|
||||
`run_cart` permanece fora da ABI de convidado. Falha de boot direto continua no caminho de host/firmware (`CartridgeError`, `CrashReport::VmInit`, transição de firmware), não como syscall de app.
|
||||
|
||||
3. Relacao com firmware.
|
||||
Delimitar quando a falha pertence ao app, ao firmware ou ao runtime.
|
||||
3. Relação com firmware e com o host.
|
||||
Delimitar falha de app, falha de firmware e falha de runtime. `CrashReport` é a observação estruturada de Trap/Panic/init. `summary()` e log são apresentação, não o contrato.
|
||||
|
||||
## Dependencias
|
||||
|
||||
- `../specs/16a-syscall-policies.md`
|
||||
- `009-system-run-cart.md`
|
||||
- `docs/specs/runtime/16a-syscall-policies.md`
|
||||
- `LSN-0051` / `DSC-0004`
|
||||
- `AGD-0052` / `DSC-0049`, apenas como consumidor da observação estruturada
|
||||
|
||||
## Critério de Saida Desta Agenda
|
||||
|
||||
Pode virar PR quando houver decisao escrita sobre:
|
||||
Pode virar decision quando houver definição escrita sobre:
|
||||
|
||||
- matriz de `status`/`Trap`/`Panic` para `system`;
|
||||
- politica de retorno/falha de `run_cart`;
|
||||
- relacao com firmware e crash surface.
|
||||
- matriz de `status` / `Trap` / `Panic` para as operações userland que o domínio `system` mantém, começando por `has_cart`;
|
||||
- confirmação de que launch de cartucho permanece fora da ABI de convidado;
|
||||
- fronteira entre retorno operacional de syscall, erro de loader/boot e `CrashReport`.
|
||||
|
||||
## Revalidação — 2026-09-22
|
||||
|
||||
Revalidada contra o código atual e contra `AGD-0052`. A agenda permanece aberta. O alvo encolheu: ela não reabre `run_cart`.
|
||||
|
||||
### O que a direção headless muda
|
||||
|
||||
`AGD-0052` exige que automação distinga execução em curso, pause, término, `Trap` e `Panic` lendo dados estruturados. Esse requisito observa `CrashReport` e o estado da VM. Ele não altera a semântica normativa de fault de outros domínios e não cria syscall `system` para controle headless.
|
||||
|
||||
Esta agenda continua dona da matriz de retorno de `system`. A agenda headless continua dona de como o host expõe o fault que já existe.
|
||||
|
||||
### Perguntas que continuam abertas
|
||||
|
||||
- [ ] `has_cart` passa a ter `status` e um significado real de presença de cartucho, ou o bool atual é o contrato e o stub `true` é o bug a corrigir em outra discussão?
|
||||
- [ ] Alguma falha de boot direto precisa ser visível ao convidado, ou toda falha de launch permanece em host, firmware e `CrashReport`?
|
||||
- [ ] Quais campos de `CrashReport` são o contrato observável (`kind`, `pc`, `trap.code`) e quais são só texto de log?
|
||||
|
||||
@@ -50,30 +50,50 @@ Fechar o perfil minimo de random VM-owned em cima do core definido na decisao `0
|
||||
|
||||
## Open Questions de Arquitetura
|
||||
|
||||
1. v1 aceita apenas modo deterministico por seed ou tambem entropy host?
|
||||
1. O caminho determinístico aceita só seed explícita. Entropia de host, se um dia existir, é modo separado e fica fora da timeline automatizada?
|
||||
2. `next` retorna apenas `int` ou precisamos variantes (`u32`, `float`) no mesmo ciclo?
|
||||
3. precisamos de clone/split de gerador no MVP?
|
||||
4. destruicao explicita deve ser obrigatoria para certificacao/custo ou opcional?
|
||||
5. O primeiro oráculo de `AGD-0052` pode provar determinismo com cartucho que não chama random, e qualquer cartucho que chame random espera o fechamento desta agenda?
|
||||
|
||||
## Dependencias
|
||||
|
||||
- `../decisions/006-vm-owned-stateful-core-contract.md`
|
||||
- `../virtual-machine/ISA_CORE.md`
|
||||
- `../specs/16-host-abi-and-syscalls.md`
|
||||
- `../specs/16a-syscall-policies.md`
|
||||
- contexto histórico, já aposentado como decisão viva: `discussion/lessons/DSC-0001-runtime-learn-legacy-import/LSN-0008-historical-vm-core-and-assets.md` cita `006-vm-owned-stateful-core-contract.md`
|
||||
- `docs/vm-arch/ISA_CORE.md`
|
||||
- `docs/specs/runtime/16-host-abi-and-syscalls.md`
|
||||
- `docs/specs/runtime/16a-syscall-policies.md`
|
||||
- `AGD-0052` / `DSC-0049`, como consumidor do contrato determinístico
|
||||
|
||||
Não há arquivo vivo em `discussion/workflow/decisions/` para a decisão `006`. Esta agenda não trata esse texto como contrato atual.
|
||||
|
||||
## Fora de Escopo
|
||||
|
||||
- entropy nao deterministica como contrato base;
|
||||
- PRNGs multiplos no mesmo ciclo de fechamento;
|
||||
- APIs de colecoes stateful;
|
||||
- window/app model.
|
||||
- entropia não determinística como contrato base;
|
||||
- PRNGs múltiplos no mesmo ciclo de fechamento;
|
||||
- APIs de coleções stateful;
|
||||
- window/app model;
|
||||
- formato persistente de replay. Esta agenda define reprodução em memória: seed explícita mais sequência de `next`. Arquivo, versão e timeline de input ficam para a agenda de replay citada por `AGD-0052`.
|
||||
|
||||
## Criterio de Saida Desta Agenda
|
||||
|
||||
Pode virar PR quando houver decisao escrita sobre:
|
||||
Pode virar decision quando houver definição escrita sobre:
|
||||
|
||||
- surface minima de random VM-owned;
|
||||
- contrato de determinismo/replay;
|
||||
- surface mínima de random VM-owned;
|
||||
- contrato de determinismo: seed explícita, ausência de entropia implícita de host, reprodução da sequência;
|
||||
- fault/status de random;
|
||||
- IDs/versionamento e validacoes de verifier para as operacoes do dominio.
|
||||
- IDs/versionamento e validações de verifier para as operações do domínio;
|
||||
- o que um host automatizado precisa fixar (seeds iniciais) para que duas execuções coincidam.
|
||||
|
||||
## Revalidação — 2026-09-22
|
||||
|
||||
Revalidada contra o código atual e contra `AGD-0052`. A agenda permanece aberta. Não existe serviço de random na VM. O scheduler declara ausência de randomness. `prometeu-test-support` oferece `StdRng` semeado para testes Rust; isso não é random de convidado.
|
||||
|
||||
### Efeito da direção headless
|
||||
|
||||
`AGD-0052` diz que random VM-owned usado em execução automatizada obedece ao contrato desta agenda, e que entropia implícita do host não entra no caminho determinístico. Isso reforça a pergunta 1 na direção de seed explícita como único modo determinístico.
|
||||
|
||||
O primeiro teste end-to-end headless pode usar um cartucho que não chama random. Esse teste prova input, frame e fault. Ele não prova random. Cartucho cujo resultado depende de random só serve como oráculo depois que esta agenda fechar seeds, sequência e faults.
|
||||
|
||||
Relógio de parede em telemetria (`host_cpu_time_us`, timestamp de certificação) não é fonte de random e não entra neste contrato.
|
||||
|
||||
Replay em arquivo continua fora daqui e fora do primeiro ciclo headless. O que esta agenda precisa deixar pronto é a reprodução em memória da sequência a partir das seeds.
|
||||
|
||||
@@ -107,7 +107,7 @@ O caminho recomendado e:
|
||||
- [ ] Handheld Linux exige controles/gamepad, fullscreen, scaling, latency, sleep/resume, framebuffer/display mode ou packaging especificos desde o primeiro corte?
|
||||
- [ ] Qual e o "Linux base" minimo que um futuro hardware DIY precisaria expor para rodar o host portatil sem fork?
|
||||
- [ ] Android customizado deve ser criterio de escolha entre SDL2 e SDL3 agora, ou deve ficar como compatibilidade futura?
|
||||
- [ ] Como validar input e pacing de forma automatizada sem depender de janela real em CI?
|
||||
- [ ] Como validar input e pacing de forma automatizada sem depender de janela real em CI? Encaminhada para `AGD-0052` / `DSC-0049`: o host headless é o lugar dessa prova. Esta agenda continua dona da escolha de backend portátil, não do controle determinístico.
|
||||
- [ ] O nome do crate deve ser `prometeu-host-desktop-sdl`, `prometeu-host-desktop-sdl2`, ou algo neutro a versao?
|
||||
|
||||
## Criterio para Encerrar
|
||||
@@ -135,4 +135,6 @@ Clarificacao: "mobile" nesta agenda nao se refere primariamente a telefone/table
|
||||
|
||||
Clarificacao: a agenda tambem deve preservar a opcao de um futuro hardware DIY. A premissa desejada e que, se esse hardware expuser um Linux base suficiente, o runtime ja tenha um host portatil pronto para rodar nele.
|
||||
|
||||
Atualizacao 2026-09-22: `AGD-0052` abre um terceiro host, headless, para teste, CI e controle determinístico em memória. Esse host não substitui o candidato portátil desta agenda e não escolhe SDL. A pergunta de validar input e pacing sem janela em CI passa a ser respondida lá. Extração de loop comum entre winit, SDL e headless continua esperando duplicação real.
|
||||
|
||||
## Resolution
|
||||
|
||||
@@ -48,7 +48,8 @@
|
||||
"host-dependent": {
|
||||
"baseline_percent": 35,
|
||||
"paths": [
|
||||
"crates/host/prometeu-host-desktop-winit/src/"
|
||||
"crates/host/prometeu-host-desktop-winit/src/",
|
||||
"crates/host/prometeu-host-headless/src/"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user