Compare commits
20
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89101d1b20
|
||
|
|
2516fae4fc | ||
|
|
e0c08c8b00
|
||
|
|
5b106af0f3 | ||
|
|
6ef376763c
|
||
|
|
f50a3f127f
|
||
|
|
f0f3f972ce
|
||
|
|
b2d2533acb
|
||
|
|
4b499288e2
|
||
|
|
aa3b31deb5 | ||
|
|
f784ccd774
|
||
|
|
7cced0709b
|
||
|
|
e2a5a67621
|
||
|
|
fbe4d0cac0
|
||
|
|
4c0f1cb9ad
|
||
|
|
94ffd241bd
|
||
|
|
a415c172c7
|
||
|
|
c89116b6f8
|
||
|
|
dc279fe72b
|
||
|
|
01221769cd
|
Generated
+11
@@ -1674,6 +1674,17 @@ dependencies = [
|
|||||||
"winit",
|
"winit",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
[[package]]
|
||||||
|
name = "prometeu-host-headless"
|
||||||
|
version = "0.1.0"
|
||||||
|
dependencies = [
|
||||||
|
"prometeu-bytecode",
|
||||||
|
"prometeu-drivers",
|
||||||
|
"prometeu-firmware",
|
||||||
|
"prometeu-hal",
|
||||||
|
"prometeu-system",
|
||||||
|
]
|
||||||
|
|
||||||
[[package]]
|
[[package]]
|
||||||
name = "prometeu-layer-tests"
|
name = "prometeu-layer-tests"
|
||||||
version = "0.1.0"
|
version = "0.1.0"
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ members = [
|
|||||||
"crates/console/prometeu-system",
|
"crates/console/prometeu-system",
|
||||||
"crates/console/prometeu-vm",
|
"crates/console/prometeu-vm",
|
||||||
"crates/host/prometeu-host-desktop-winit",
|
"crates/host/prometeu-host-desktop-winit",
|
||||||
|
"crates/host/prometeu-host-headless",
|
||||||
"crates/tools/prometeu-cli",
|
"crates/tools/prometeu-cli",
|
||||||
"crates/tools/pbxgen-dummy-boy",
|
"crates/tools/pbxgen-dummy-boy",
|
||||||
"crates/tools/pbxgen-stress",
|
"crates/tools/pbxgen-stress",
|
||||||
|
|||||||
@@ -135,6 +135,7 @@ Current canonical domains:
|
|||||||
- `asset/bank`
|
- `asset/bank`
|
||||||
- `firmware`
|
- `firmware`
|
||||||
- `host-dependent`
|
- `host-dependent`
|
||||||
|
- `host/headless`
|
||||||
|
|
||||||
Global coverage artifacts:
|
Global coverage artifacts:
|
||||||
|
|
||||||
@@ -157,6 +158,7 @@ Domain-oriented evidence helpers:
|
|||||||
make coverage-domain-list
|
make coverage-domain-list
|
||||||
make coverage-domain-evidence DOMAIN=firmware
|
make coverage-domain-evidence DOMAIN=firmware
|
||||||
make coverage-domain-evidence DOMAIN=host-dependent
|
make coverage-domain-evidence DOMAIN=host-dependent
|
||||||
|
make coverage-domain-evidence DOMAIN=host/headless
|
||||||
```
|
```
|
||||||
|
|
||||||
Per-domain baselines currently start around `60`.
|
Per-domain baselines currently start around `60`.
|
||||||
|
|||||||
@@ -11,14 +11,14 @@ mod program_image;
|
|||||||
mod value;
|
mod value;
|
||||||
|
|
||||||
pub use abi::{
|
pub use abi::{
|
||||||
TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT, TRAP_ILLEGAL_INSTRUCTION,
|
SourceSpan, TrapInfo, TRAP_BAD_RET_SLOTS, TRAP_DIV_ZERO, TRAP_EXPLICIT,
|
||||||
TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL, TRAP_INVALID_SYSCALL, TRAP_OOB,
|
TRAP_ILLEGAL_INSTRUCTION, TRAP_INVALID_FUNC, TRAP_INVALID_INTRINSIC, TRAP_INVALID_LOCAL,
|
||||||
TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
TRAP_INVALID_SYSCALL, TRAP_OOB, TRAP_STACK_UNDERFLOW, TRAP_TYPE,
|
||||||
};
|
};
|
||||||
pub use assembler::{assemble, AsmError};
|
pub use assembler::{assemble, AsmError};
|
||||||
pub use decoder::{decode_next, DecodeError};
|
pub use decoder::{decode_next, DecodeError};
|
||||||
pub use disassembler::disassemble;
|
pub use disassembler::disassemble;
|
||||||
pub use layout::{compute_function_layouts, FunctionLayout};
|
pub use layout::{compute_function_layouts, FunctionLayout};
|
||||||
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl};
|
pub use model::{BytecodeLoader, FunctionMeta, LoadError, SyscallDecl, PBX_MAGIC};
|
||||||
pub use program_image::ProgramImage;
|
pub use program_image::ProgramImage;
|
||||||
pub use value::{string_materialization_count, HeapRef, Value};
|
pub use value::{string_materialization_count, HeapRef, Value};
|
||||||
|
|||||||
@@ -80,9 +80,11 @@ const SECTION_KIND_DEBUG: u32 = 3;
|
|||||||
const SECTION_KIND_EXPORTS: u32 = 4;
|
const SECTION_KIND_EXPORTS: u32 = 4;
|
||||||
const SECTION_KIND_SYSCALLS: u32 = 5;
|
const SECTION_KIND_SYSCALLS: u32 = 5;
|
||||||
|
|
||||||
/// Represents the final serialized format of a PBS v0 module.
|
pub const PBX_MAGIC: [u8; 4] = *b"PBX\0";
|
||||||
|
|
||||||
|
/// Represents the final serialized format of a PBX v0 module.
|
||||||
///
|
///
|
||||||
/// This structure is a pure data container for the PBS format. It does NOT
|
/// This structure is a pure data container for the PBX format. It does NOT
|
||||||
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
/// contain any linker-like logic (symbol resolution, patching, etc.).
|
||||||
/// All multi-module programs must be flattened and linked by the compiler
|
/// All multi-module programs must be flattened and linked by the compiler
|
||||||
/// before being serialized into this format.
|
/// before being serialized into this format.
|
||||||
@@ -126,8 +128,8 @@ impl BytecodeModule {
|
|||||||
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
||||||
|
|
||||||
let mut out = Vec::new();
|
let mut out = Vec::new();
|
||||||
// Magic "PBS\0"
|
// Magic "PBX\0"
|
||||||
out.extend_from_slice(b"PBS\0");
|
out.extend_from_slice(&PBX_MAGIC);
|
||||||
// Version 0
|
// Version 0
|
||||||
out.extend_from_slice(&0u16.to_le_bytes());
|
out.extend_from_slice(&0u16.to_le_bytes());
|
||||||
// Endianness 0 (Little Endian), Reserved
|
// Endianness 0 (Little Endian), Reserved
|
||||||
@@ -272,8 +274,8 @@ impl BytecodeLoader {
|
|||||||
return Err(LoadError::UnexpectedEof);
|
return Err(LoadError::UnexpectedEof);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Magic "PBS\0"
|
// Magic "PBX\0"
|
||||||
if &bytes[0..4] != b"PBS\0" {
|
if bytes[0..4] != PBX_MAGIC[..] {
|
||||||
return Err(LoadError::InvalidMagic);
|
return Err(LoadError::InvalidMagic);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -708,7 +710,7 @@ mod tests {
|
|||||||
|
|
||||||
fn create_header(section_count: u32) -> Vec<u8> {
|
fn create_header(section_count: u32) -> Vec<u8> {
|
||||||
let mut h = vec![0u8; 32];
|
let mut h = vec![0u8; 32];
|
||||||
h[0..4].copy_from_slice(b"PBS\0");
|
h[0..4].copy_from_slice(&PBX_MAGIC);
|
||||||
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
h[4..6].copy_from_slice(&0u16.to_le_bytes()); // version
|
||||||
h[6] = 0; // endianness
|
h[6] = 0; // endianness
|
||||||
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
h[8..12].copy_from_slice(§ion_count.to_le_bytes());
|
||||||
@@ -727,7 +729,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_pbs_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
fn build_pbx_with_sections(sections: Vec<(u32, Vec<u8>)>) -> Vec<u8> {
|
||||||
let mut data = create_header(sections.len() as u32);
|
let mut data = create_header(sections.len() as u32);
|
||||||
let mut offset = 32 + (sections.len() as u32 * 12);
|
let mut offset = 32 + (sections.len() as u32 * 12);
|
||||||
|
|
||||||
@@ -748,7 +750,7 @@ mod tests {
|
|||||||
#[test]
|
#[test]
|
||||||
fn test_invalid_magic() {
|
fn test_invalid_magic() {
|
||||||
let mut data = create_header(0);
|
let mut data = create_header(0);
|
||||||
data[0] = b'X';
|
data[0..4].copy_from_slice(b"PBS\0");
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidMagic));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -897,7 +899,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_malformed_sysc_section_is_rejected() {
|
fn test_malformed_sysc_section_is_rejected() {
|
||||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, vec![1, 0, 0])]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::MalformedSection));
|
||||||
}
|
}
|
||||||
@@ -914,7 +916,7 @@ mod tests {
|
|||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
sysc.extend_from_slice(&0u16.to_le_bytes());
|
sysc.extend_from_slice(&0u16.to_le_bytes());
|
||||||
|
|
||||||
let data = build_pbs_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
let data = build_pbx_with_sections(vec![(SECTION_KIND_SYSCALLS, sysc)]);
|
||||||
|
|
||||||
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
assert_eq!(BytecodeLoader::load(&data), Err(LoadError::InvalidUtf8));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ use crate::value::Value;
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Represents a fully linked, executable PBS program image.
|
/// Represents a fully linked, executable PBX program image.
|
||||||
///
|
///
|
||||||
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
/// Under the Prometeu architecture, the ProgramImage is a "closed-world" artifact
|
||||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||||
|
|||||||
@@ -191,10 +191,10 @@ impl GlyphAssetSlotIndex {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
|
const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||||
const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
const GLYPH_BANK_PALETTE_BYTES_V1: usize =
|
const GLYPH_BANK_PALETTE_BYTES_PER_PALETTE: usize =
|
||||||
GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * size_of::<u32>();
|
GLYPH_BANK_COLORS_PER_PALETTE * size_of::<u32>();
|
||||||
|
|
||||||
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
|
/// Resident metadata for a decoded/materialized asset inside a BankPolicy.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -599,7 +599,7 @@ impl AssetBridge for AssetManager {
|
|||||||
impl AssetManager {
|
impl AssetManager {
|
||||||
fn decode_glyph_bank_layout(
|
fn decode_glyph_bank_layout(
|
||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
) -> Result<(TileSize, usize, usize, usize), String> {
|
) -> Result<(TileSize, usize, usize, usize, usize, usize), String> {
|
||||||
let meta = entry.metadata_as_glyph_bank()?;
|
let meta = entry.metadata_as_glyph_bank()?;
|
||||||
|
|
||||||
let tile_size = match meta.tile_size {
|
let tile_size = match meta.tile_size {
|
||||||
@@ -609,7 +609,8 @@ impl AssetManager {
|
|||||||
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
|
_ => return Err(format!("Invalid tile_size: {}", meta.tile_size)),
|
||||||
};
|
};
|
||||||
|
|
||||||
if meta.palette_count as usize != GLYPH_BANK_PALETTE_COUNT_V1 {
|
let palette_count = meta.palette_count as usize;
|
||||||
|
if !(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count) {
|
||||||
return Err(format!("Invalid palette_count: {}", meta.palette_count));
|
return Err(format!("Invalid palette_count: {}", meta.palette_count));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -618,12 +619,14 @@ impl AssetManager {
|
|||||||
|
|
||||||
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
|
let logical_pixels = width.checked_mul(height).ok_or("GlyphBank dimensions overflow")?;
|
||||||
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
|
let serialized_pixel_bytes = logical_pixels.div_ceil(2);
|
||||||
|
let palette_bytes = palette_count
|
||||||
|
.checked_mul(GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
|
.ok_or("GlyphBank palette size overflow")?;
|
||||||
let serialized_size = serialized_pixel_bytes
|
let serialized_size = serialized_pixel_bytes
|
||||||
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
|
.checked_add(palette_bytes)
|
||||||
.ok_or("GlyphBank serialized size overflow")?;
|
.ok_or("GlyphBank serialized size overflow")?;
|
||||||
let decoded_size = logical_pixels
|
let decoded_size =
|
||||||
.checked_add(GLYPH_BANK_PALETTE_BYTES_V1)
|
logical_pixels.checked_add(palette_bytes).ok_or("GlyphBank decoded size overflow")?;
|
||||||
.ok_or("GlyphBank decoded size overflow")?;
|
|
||||||
|
|
||||||
if entry.size != serialized_size as u64 {
|
if entry.size != serialized_size as u64 {
|
||||||
return Err(format!(
|
return Err(format!(
|
||||||
@@ -639,7 +642,7 @@ impl AssetManager {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok((tile_size, width, height, serialized_pixel_bytes))
|
Ok((tile_size, width, height, serialized_pixel_bytes, palette_count, palette_bytes))
|
||||||
}
|
}
|
||||||
|
|
||||||
fn unpack_glyph_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
|
fn unpack_glyph_bank_pixels(packed_pixels: &[u8], logical_pixels: usize) -> Vec<u8> {
|
||||||
@@ -1200,19 +1203,18 @@ impl AssetManager {
|
|||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
buffer: &[u8],
|
buffer: &[u8],
|
||||||
) -> Result<GlyphBank, String> {
|
) -> Result<GlyphBank, String> {
|
||||||
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
|
let (tile_size, width, height, packed_pixel_bytes, palette_count, palette_bytes) =
|
||||||
if buffer.len() < packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1 {
|
Self::decode_glyph_bank_layout(entry)?;
|
||||||
|
if buffer.len() < packed_pixel_bytes + palette_bytes {
|
||||||
return Err("Buffer too small for GLYPHBANK".to_string());
|
return Err("Buffer too small for GLYPHBANK".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
let logical_pixels = width * height;
|
let logical_pixels = width * height;
|
||||||
let packed_pixels = &buffer[0..packed_pixel_bytes];
|
let packed_pixels = &buffer[0..packed_pixel_bytes];
|
||||||
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
|
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
|
||||||
let palette_data =
|
let palette_data = &buffer[packed_pixel_bytes..packed_pixel_bytes + palette_bytes];
|
||||||
&buffer[packed_pixel_bytes..packed_pixel_bytes + GLYPH_BANK_PALETTE_BYTES_V1];
|
|
||||||
|
|
||||||
let mut palettes =
|
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||||
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
|
|
||||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||||
for (c, slot) in pal.iter_mut().enumerate() {
|
for (c, slot) in pal.iter_mut().enumerate() {
|
||||||
let offset = (p * 16 + c) * 4;
|
let offset = (p * 16 + c) * 4;
|
||||||
@@ -1232,7 +1234,8 @@ impl AssetManager {
|
|||||||
entry: &AssetEntry,
|
entry: &AssetEntry,
|
||||||
reader: &mut impl Read,
|
reader: &mut impl Read,
|
||||||
) -> Result<GlyphBank, String> {
|
) -> Result<GlyphBank, String> {
|
||||||
let (tile_size, width, height, packed_pixel_bytes) = Self::decode_glyph_bank_layout(entry)?;
|
let (tile_size, width, height, packed_pixel_bytes, palette_count, palette_bytes) =
|
||||||
|
Self::decode_glyph_bank_layout(entry)?;
|
||||||
let logical_pixels = width * height;
|
let logical_pixels = width * height;
|
||||||
let mut packed_pixels = vec![0_u8; packed_pixel_bytes];
|
let mut packed_pixels = vec![0_u8; packed_pixel_bytes];
|
||||||
reader
|
reader
|
||||||
@@ -1241,13 +1244,12 @@ impl AssetManager {
|
|||||||
|
|
||||||
let pixel_indices = Self::unpack_glyph_bank_pixels(&packed_pixels, logical_pixels);
|
let pixel_indices = Self::unpack_glyph_bank_pixels(&packed_pixels, logical_pixels);
|
||||||
|
|
||||||
let mut palette_data = [0_u8; GLYPH_BANK_PALETTE_BYTES_V1];
|
let mut palette_data = vec![0_u8; palette_bytes];
|
||||||
reader
|
reader
|
||||||
.read_exact(&mut palette_data)
|
.read_exact(&mut palette_data)
|
||||||
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
|
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
|
||||||
|
|
||||||
let mut palettes =
|
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||||
[[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1];
|
|
||||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||||
for (c, slot) in pal.iter_mut().enumerate() {
|
for (c, slot) in pal.iter_mut().enumerate() {
|
||||||
let offset = (p * 16 + c) * 4;
|
let offset = (p * 16 + c) * 4;
|
||||||
@@ -1883,35 +1885,53 @@ mod tests {
|
|||||||
use prometeu_hal::tile::Tile;
|
use prometeu_hal::tile::Tile;
|
||||||
use prometeu_hal::tilemap::TileMap;
|
use prometeu_hal::tilemap::TileMap;
|
||||||
|
|
||||||
fn expected_glyph_payload_size(width: usize, height: usize) -> usize {
|
fn expected_glyph_payload_size(width: usize, height: usize, palette_count: usize) -> usize {
|
||||||
(width * height).div_ceil(2) + GLYPH_BANK_PALETTE_BYTES_V1
|
(width * height).div_ceil(2) + (palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn expected_glyph_decoded_size(width: usize, height: usize) -> usize {
|
fn expected_glyph_decoded_size(width: usize, height: usize, palette_count: usize) -> usize {
|
||||||
width * height + GLYPH_BANK_PALETTE_BYTES_V1
|
width * height + (palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_data() -> Vec<u8> {
|
fn test_glyph_asset_data() -> Vec<u8> {
|
||||||
|
test_glyph_asset_data_with_palette_count(GLYPH_BANK_MAX_PALETTE_COUNT_V1)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_glyph_asset_data_with_palette_count(palette_count: usize) -> Vec<u8> {
|
||||||
let mut data = vec![0x11u8; 128];
|
let mut data = vec![0x11u8; 128];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
|
data.extend_from_slice(&vec![0u8; palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE]);
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
|
fn test_glyph_asset_entry(asset_name: &str, width: usize, height: usize) -> AssetEntry {
|
||||||
|
test_glyph_asset_entry_with_palette_count(
|
||||||
|
asset_name,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn test_glyph_asset_entry_with_palette_count(
|
||||||
|
asset_name: &str,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
palette_count: usize,
|
||||||
|
) -> AssetEntry {
|
||||||
AssetEntry {
|
AssetEntry {
|
||||||
asset_id: 0,
|
asset_id: 0,
|
||||||
asset_name: asset_name.to_string(),
|
asset_name: asset_name.to_string(),
|
||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
size: expected_glyph_payload_size(width, height) as u64,
|
size: expected_glyph_payload_size(width, height, palette_count) as u64,
|
||||||
decoded_size: expected_glyph_decoded_size(width, height) as u64,
|
decoded_size: expected_glyph_decoded_size(width, height, palette_count) as u64,
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: serde_json::json!({
|
metadata: serde_json::json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": width,
|
"width": width,
|
||||||
"height": height,
|
"height": height,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": palette_count,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": palette_count
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -2034,22 +2054,67 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_unpacks_packed_pixels_and_reads_palette_colors() {
|
fn test_decode_glyph_bank_unpacks_packed_pixels_and_reads_palette_colors() {
|
||||||
let entry = test_glyph_asset_entry("glyphs", 2, 2);
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 2, 2, 1);
|
||||||
let mut data = vec![0x10, 0x23];
|
let mut data = vec![0x10, 0x23];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_V1]);
|
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_BYTES_PER_PALETTE]);
|
||||||
data[2..6].copy_from_slice(&[0x12, 0x34, 0x56, 0x78]);
|
data[2..6].copy_from_slice(&[0x12, 0x34, 0x56, 0x78]);
|
||||||
|
|
||||||
let bank =
|
let bank =
|
||||||
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
assert_eq!(bank.pixel_indices, vec![1, 0, 2, 3]);
|
assert_eq!(bank.pixel_indices, vec![1, 0, 2, 3]);
|
||||||
|
assert_eq!(bank.palette_count(), 1);
|
||||||
assert_eq!(bank.palettes[0][0], Color::from_raw(0x12345678));
|
assert_eq!(bank.palettes[0][0], Color::from_raw(0x12345678));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_accepts_intermediate_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 7);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(7);
|
||||||
|
|
||||||
|
let bank =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), 7);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_accepts_max_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count(
|
||||||
|
"glyphs",
|
||||||
|
16,
|
||||||
|
16,
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
|
);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
|
||||||
|
let bank =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("glyph decode");
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_reader_matches_buffer_for_variable_palette_count() {
|
||||||
|
let entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
let data = test_glyph_asset_data_with_palette_count(3);
|
||||||
|
|
||||||
|
let from_buffer =
|
||||||
|
AssetManager::decode_glyph_bank_from_buffer(&entry, &data).expect("buffer decode");
|
||||||
|
let mut reader = std::io::Cursor::new(data);
|
||||||
|
let from_reader = AssetManager::decode_glyph_bank_from_reader(&entry, &mut reader)
|
||||||
|
.expect("reader decode");
|
||||||
|
|
||||||
|
assert_eq!(from_buffer.palette_count(), from_reader.palette_count());
|
||||||
|
assert_eq!(from_buffer.pixel_indices, from_reader.pixel_indices);
|
||||||
|
assert_eq!(from_buffer.palettes, from_reader.palettes);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
|
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
|
||||||
let entry = test_glyph_asset_entry("glyphs", 16, 16);
|
let entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
let data = vec![0u8; expected_glyph_payload_size(16, 16) - 1];
|
let data =
|
||||||
|
vec![0u8; expected_glyph_payload_size(16, 16, GLYPH_BANK_MAX_PALETTE_COUNT_V1) - 1];
|
||||||
|
|
||||||
let err = match AssetManager::decode_glyph_bank_from_buffer(&entry, &data) {
|
let err = match AssetManager::decode_glyph_bank_from_buffer(&entry, &data) {
|
||||||
Ok(_) => panic!("glyph decode should reject short buffer"),
|
Ok(_) => panic!("glyph decode should reject short buffer"),
|
||||||
@@ -2060,9 +2125,9 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_decode_glyph_bank_requires_palette_count_64() {
|
fn test_decode_glyph_bank_rejects_palette_count_zero() {
|
||||||
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
entry.metadata["palette_count"] = serde_json::json!(32);
|
entry.metadata["palette_count"] = serde_json::json!(0);
|
||||||
|
|
||||||
let err =
|
let err =
|
||||||
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
||||||
@@ -2070,7 +2135,67 @@ mod tests {
|
|||||||
Err(err) => err,
|
Err(err) => err,
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(err, "Invalid palette_count: 32");
|
assert_eq!(err, "Invalid palette_count: 0");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_palette_count_above_v1_max() {
|
||||||
|
let mut entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||||
|
entry.metadata["palette_count"] = serde_json::json!(65);
|
||||||
|
|
||||||
|
let err =
|
||||||
|
match AssetManager::decode_glyph_bank_from_buffer(&entry, &test_glyph_asset_data()) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid palette_count"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(err, "Invalid palette_count: 65");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_mismatched_variable_decoded_size() {
|
||||||
|
let mut entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
entry.decoded_size += 1;
|
||||||
|
|
||||||
|
let err = match AssetManager::decode_glyph_bank_from_buffer(
|
||||||
|
&entry,
|
||||||
|
&test_glyph_asset_data_with_palette_count(3),
|
||||||
|
) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid decoded_size"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
err,
|
||||||
|
format!(
|
||||||
|
"Invalid GLYPHBANK decoded_size: expected {}, got {}",
|
||||||
|
expected_glyph_decoded_size(16, 16, 3),
|
||||||
|
expected_glyph_decoded_size(16, 16, 3) + 1
|
||||||
|
)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn test_decode_glyph_bank_rejects_mismatched_variable_serialized_size() {
|
||||||
|
let mut entry = test_glyph_asset_entry_with_palette_count("glyphs", 16, 16, 3);
|
||||||
|
entry.size += 1;
|
||||||
|
|
||||||
|
let err = match AssetManager::decode_glyph_bank_from_buffer(
|
||||||
|
&entry,
|
||||||
|
&test_glyph_asset_data_with_palette_count(3),
|
||||||
|
) {
|
||||||
|
Ok(_) => panic!("glyph decode should reject invalid serialized size"),
|
||||||
|
Err(err) => err,
|
||||||
|
};
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
err,
|
||||||
|
format!(
|
||||||
|
"Invalid GLYPHBANK serialized size: expected {}, got {}",
|
||||||
|
expected_glyph_payload_size(16, 16, 3),
|
||||||
|
expected_glyph_payload_size(16, 16, 3) + 1
|
||||||
|
)
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
|
|||||||
@@ -557,8 +557,9 @@ mod tests {
|
|||||||
|
|
||||||
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
fn make_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
||||||
let size = tile_size as usize;
|
let size = tile_size as usize;
|
||||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
let mut bank =
|
||||||
bank.palettes[palette_id as usize][1] = color;
|
GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
|
||||||
|
bank.palette_mut(palette_id).unwrap()[1] = color;
|
||||||
for pixel in &mut bank.pixel_indices {
|
for pixel in &mut bank.pixel_indices {
|
||||||
*pixel = 1;
|
*pixel = 1;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -812,7 +812,14 @@ impl Gfx {
|
|||||||
let fetch_x = if tile.entry.flip_x() { size - 1 - local_x } else { local_x };
|
let fetch_x = if tile.entry.flip_x() { size - 1 - local_x } else { local_x };
|
||||||
let fetch_y = if tile.entry.flip_y() { size - 1 - local_y } else { local_y };
|
let fetch_y = if tile.entry.flip_y() { size - 1 - local_y } else { local_y };
|
||||||
let px_index = tile.bank.get_pixel_index(tile.entry.glyph_id, fetch_x, fetch_y);
|
let px_index = tile.bank.get_pixel_index(tile.entry.glyph_id, fetch_x, fetch_y);
|
||||||
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index);
|
let color = tile.bank.resolve_color(tile.entry.palette_id, px_index).unwrap_or_else(
|
||||||
|
|| {
|
||||||
|
panic!(
|
||||||
|
"SCENE composition fatal: palette_id {} is not resident for glyph asset {}",
|
||||||
|
tile.entry.palette_id, tile.entry.glyph_asset_id
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
if color.alpha() == 0 {
|
if color.alpha() == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -862,7 +869,14 @@ impl Gfx {
|
|||||||
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
|
let fetch_y = if sprite.flip_y { size - 1 - local_y } else { local_y };
|
||||||
|
|
||||||
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
|
let px_index = bank.get_pixel_index(sprite.glyph.glyph_id, fetch_x, fetch_y);
|
||||||
let color = bank.resolve_color(sprite.glyph.palette_id, px_index);
|
let color = bank.resolve_color(sprite.glyph.palette_id, px_index).unwrap_or_else(
|
||||||
|
|| {
|
||||||
|
panic!(
|
||||||
|
"SPRITE composition fatal: palette_id {} is not resident for glyph bank {}",
|
||||||
|
sprite.glyph.palette_id, sprite.bank_id
|
||||||
|
)
|
||||||
|
},
|
||||||
|
);
|
||||||
if color.alpha() == 0 {
|
if color.alpha() == 0 {
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -1010,9 +1024,14 @@ mod tests {
|
|||||||
|
|
||||||
fn make_glyph_bank(tile_size: TileSize, palette_colors: &[(u8, u8, Color)]) -> GlyphBank {
|
fn make_glyph_bank(tile_size: TileSize, palette_colors: &[(u8, u8, Color)]) -> GlyphBank {
|
||||||
let size = tile_size as usize;
|
let size = tile_size as usize;
|
||||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
let palette_count = palette_colors
|
||||||
|
.iter()
|
||||||
|
.map(|(palette_id, _, _)| *palette_id as usize + 1)
|
||||||
|
.max()
|
||||||
|
.unwrap_or(1);
|
||||||
|
let mut bank = GlyphBank::with_palette_count(tile_size, size, size, palette_count);
|
||||||
for (palette_id, color_index, color) in palette_colors {
|
for (palette_id, color_index, color) in palette_colors {
|
||||||
bank.palettes[*palette_id as usize][*color_index as usize] = *color;
|
bank.palette_mut(*palette_id).unwrap()[*color_index as usize] = *color;
|
||||||
}
|
}
|
||||||
bank
|
bank
|
||||||
}
|
}
|
||||||
@@ -1152,6 +1171,26 @@ mod tests {
|
|||||||
assert_eq!(back[0], Color::RED.raw());
|
assert_eq!(back[0], Color::RED.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "SPRITE composition fatal: palette_id 1 is not resident")]
|
||||||
|
fn sprite_draw_panics_for_invalid_palette_reference() {
|
||||||
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
|
let mut back = vec![Color::BLACK.raw(); 8 * 8];
|
||||||
|
let sprite = Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer: 0,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
bank_id: 0,
|
||||||
|
active: true,
|
||||||
|
priority: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
Gfx::draw_sprite_pixel_by_pixel(&mut back, 8, 8, &sprite, &bank);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cached_tile_draws_opaque_color_index_zero() {
|
fn test_cached_tile_draws_opaque_color_index_zero() {
|
||||||
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
@@ -1194,6 +1233,26 @@ mod tests {
|
|||||||
assert_eq!(target.back[0], Color::RED.raw());
|
assert_eq!(target.back[0], Color::RED.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "SCENE composition fatal: palette_id 1 is not resident")]
|
||||||
|
fn cached_tile_draw_panics_for_invalid_palette_reference() {
|
||||||
|
let bank = make_filled_glyph_bank(TileSize::Size8, 0, &[(0, 0, Color::GREEN)]);
|
||||||
|
let mut back = vec![Color::BLACK.raw(); 8 * 8];
|
||||||
|
let mut target = RenderTarget { back: &mut back, screen_w: 8, screen_h: 8 };
|
||||||
|
let entry = CachedTileEntry {
|
||||||
|
active: true,
|
||||||
|
glyph_id: 0,
|
||||||
|
palette_id: 1,
|
||||||
|
flags: 0,
|
||||||
|
glyph_asset_id: 0,
|
||||||
|
};
|
||||||
|
|
||||||
|
Gfx::draw_cached_tile_pixels(
|
||||||
|
&mut target,
|
||||||
|
CachedTileDraw { x: 0, y: 0, entry, bank: &bank, tile_size: TileSize::Size8 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_draw_rect() {
|
fn test_draw_rect() {
|
||||||
let banks = Arc::new(MemoryBanks::new());
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
|||||||
@@ -118,7 +118,11 @@ impl Game2DFrameComposer for Hardware {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
fn emit_sprite(&mut self, sprite: Sprite) -> prometeu_hal::ComposerOpStatus {
|
||||||
if self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize).is_none() {
|
let Some(bank) = self.gfx.glyph_banks.glyph_bank_slot(sprite.bank_id as usize) else {
|
||||||
|
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||||
|
};
|
||||||
|
|
||||||
|
if !bank.contains_palette(sprite.glyph.palette_id) {
|
||||||
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
return prometeu_hal::ComposerOpStatus::BankInvalid;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -261,7 +265,7 @@ mod tests {
|
|||||||
|
|
||||||
fn make_glyph_bank() -> GlyphBank {
|
fn make_glyph_bank() -> GlyphBank {
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
bank.palettes[0][1] = Color::RED;
|
bank.palette_mut(0).unwrap()[1] = Color::RED;
|
||||||
for pixel in &mut bank.pixel_indices {
|
for pixel in &mut bank.pixel_indices {
|
||||||
*pixel = 1;
|
*pixel = 1;
|
||||||
}
|
}
|
||||||
@@ -433,4 +437,28 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
assert_eq!(hardware.gfx.front_buffer()[0], Color::RED.raw());
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn emit_sprite_rejects_palette_id_outside_loaded_glyph_bank() {
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(make_glyph_bank()));
|
||||||
|
let mut hardware = Hardware::new_with_memory_banks(banks);
|
||||||
|
|
||||||
|
let status = Game2DFrameComposer::emit_sprite(
|
||||||
|
&mut hardware,
|
||||||
|
Sprite {
|
||||||
|
glyph: Glyph { glyph_id: 0, palette_id: 1 },
|
||||||
|
x: 0,
|
||||||
|
y: 0,
|
||||||
|
layer: 0,
|
||||||
|
bank_id: 0,
|
||||||
|
active: false,
|
||||||
|
flip_x: false,
|
||||||
|
flip_y: false,
|
||||||
|
priority: 0,
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
assert_eq!(status, prometeu_hal::ComposerOpStatus::BankInvalid);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -196,7 +196,7 @@ mod tests {
|
|||||||
|
|
||||||
fn make_glyph_bank() -> GlyphBank {
|
fn make_glyph_bank() -> GlyphBank {
|
||||||
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
bank.palettes[0][1] = Color::WHITE;
|
bank.palette_mut(0).unwrap()[1] = Color::WHITE;
|
||||||
bank
|
bank
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -579,6 +579,8 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(firmware.os.sessions().vm_session_count(), 0);
|
assert_eq!(firmware.os.sessions().vm_session_count(), 0);
|
||||||
assert_eq!(firmware.os.vm().current_cartridge_title(), "");
|
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]
|
#[test]
|
||||||
|
|||||||
@@ -9,6 +9,10 @@ pub struct ResetStep;
|
|||||||
impl ResetStep {
|
impl ResetStep {
|
||||||
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
pub fn on_enter(&mut self, ctx: &mut PrometeuContext) {
|
||||||
ctx.os.log(LogLevel::Info, LogSource::Pos, 0, "Firmware Reset".to_string());
|
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.sessions().clear_vm_sessions();
|
||||||
ctx.os.vm().reset_global_runtime_state();
|
ctx.os.vm().reset_global_runtime_state();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -203,7 +203,7 @@ mod tests {
|
|||||||
use super::*;
|
use super::*;
|
||||||
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
use crate::asset::{AssetCodec, AssetEntry, BankType, PreloadEntry};
|
||||||
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
use crate::cartridge::{ASSETS_PA_MAGIC, ASSETS_PA_SCHEMA_VERSION, AssetsPackPrelude};
|
||||||
use crate::glyph_bank::GLYPH_BANK_PALETTE_COUNT_V1;
|
use crate::glyph_bank::GLYPH_BANK_MAX_PALETTE_COUNT_V1;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::path::{Path, PathBuf};
|
use std::path::{Path, PathBuf};
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
@@ -369,14 +369,14 @@ mod tests {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset,
|
offset,
|
||||||
size,
|
size,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -452,14 +452,14 @@ mod tests {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 4,
|
offset: 4,
|
||||||
size: 4,
|
size: 4,
|
||||||
decoded_size: 16 * 16 + (GLYPH_BANK_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
decoded_size: 16 * 16 + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 as u64 * 16 * 4),
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: json!({
|
metadata: json!({
|
||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
@@ -519,8 +519,8 @@ mod tests {
|
|||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
"preload": []
|
"preload": []
|
||||||
@@ -561,8 +561,8 @@ mod tests {
|
|||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}
|
}
|
||||||
}],
|
}],
|
||||||
"preload": []
|
"preload": []
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use crate::color::Color;
|
use crate::color::Color;
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
pub const GLYPH_BANK_PALETTE_COUNT_V1: usize = 64;
|
pub const GLYPH_BANK_MAX_PALETTE_COUNT_V1: usize = 64;
|
||||||
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
pub const GLYPH_BANK_COLORS_PER_PALETTE: usize = 16;
|
||||||
|
|
||||||
/// Standard sizes for square tiles.
|
/// Standard sizes for square tiles.
|
||||||
@@ -35,22 +35,59 @@ pub struct GlyphBank {
|
|||||||
/// Palette indices are ordinary indices; transparency is resolved through
|
/// Palette indices are ordinary indices; transparency is resolved through
|
||||||
/// the RGBA alpha channel of the palette entry.
|
/// the RGBA alpha channel of the palette entry.
|
||||||
pub pixel_indices: Vec<u8>,
|
pub pixel_indices: Vec<u8>,
|
||||||
/// Runtime-facing v1 palette table: 64 palettes of 16 RGBA8888 colors each.
|
/// Runtime-facing v1 palette table.
|
||||||
pub palettes: [[Color; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
///
|
||||||
|
/// Palette identity is the direct index in this vector. A resident glyph
|
||||||
|
/// bank carries exactly the palettes materialized from its payload.
|
||||||
|
pub palettes: Vec<[Color; GLYPH_BANK_COLORS_PER_PALETTE]>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl GlyphBank {
|
impl GlyphBank {
|
||||||
/// Creates an empty glyph bank with the specified dimensions.
|
/// Creates an empty glyph bank with one palette.
|
||||||
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
pub fn new(tile_size: TileSize, width: usize, height: usize) -> Self {
|
||||||
|
Self::with_palette_count(tile_size, width, height, 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates an empty glyph bank with the specified resident palette count.
|
||||||
|
pub fn with_palette_count(
|
||||||
|
tile_size: TileSize,
|
||||||
|
width: usize,
|
||||||
|
height: usize,
|
||||||
|
palette_count: usize,
|
||||||
|
) -> Self {
|
||||||
|
assert!(
|
||||||
|
(1..=GLYPH_BANK_MAX_PALETTE_COUNT_V1).contains(&palette_count),
|
||||||
|
"glyph bank palette_count must be in 1..={}",
|
||||||
|
GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
|
);
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
tile_size,
|
tile_size,
|
||||||
width,
|
width,
|
||||||
height,
|
height,
|
||||||
pixel_indices: vec![0; width * height],
|
pixel_indices: vec![0; width * height],
|
||||||
palettes: [[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; GLYPH_BANK_PALETTE_COUNT_V1],
|
palettes: vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns the number of resident palettes.
|
||||||
|
pub fn palette_count(&self) -> usize {
|
||||||
|
self.palettes.len()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns true when the palette id is valid for this resident bank.
|
||||||
|
pub fn contains_palette(&self, palette_id: u8) -> bool {
|
||||||
|
(palette_id as usize) < self.palette_count()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Returns a mutable palette slot when the palette exists.
|
||||||
|
pub fn palette_mut(
|
||||||
|
&mut self,
|
||||||
|
palette_id: u8,
|
||||||
|
) -> Option<&mut [Color; GLYPH_BANK_COLORS_PER_PALETTE]> {
|
||||||
|
self.palettes.get_mut(palette_id as usize)
|
||||||
|
}
|
||||||
|
|
||||||
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
/// Resolves a global tile ID and local pixel coordinates to a palette index.
|
||||||
/// tile_id: the tile index in the bank
|
/// tile_id: the tile index in the bank
|
||||||
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
/// local_x, local_y: the pixel position inside the tile (0 to tile_size-1)
|
||||||
@@ -71,11 +108,48 @@ impl GlyphBank {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Maps a 4-bit index to a real RGBA8888 Color using the specified palette.
|
/// Maps a 4-bit index to a real RGBA8888 Color using the specified palette.
|
||||||
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Color {
|
pub fn resolve_color(&self, palette_id: u8, pixel_index: u8) -> Option<Color> {
|
||||||
self.palettes
|
self.palettes
|
||||||
.get(palette_id as usize)
|
.get(palette_id as usize)
|
||||||
.and_then(|palette| palette.get(pixel_index as usize))
|
.and_then(|palette| palette.get(pixel_index as usize))
|
||||||
.copied()
|
.copied()
|
||||||
.unwrap_or(Color::TRANSPARENT)
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn new_glyph_bank_uses_single_resident_palette() {
|
||||||
|
let bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), 1);
|
||||||
|
assert!(bank.contains_palette(0));
|
||||||
|
assert!(!bank.contains_palette(1));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn glyph_bank_can_materialize_v1_max_palette_count() {
|
||||||
|
let bank =
|
||||||
|
GlyphBank::with_palette_count(TileSize::Size8, 8, 8, GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
|
||||||
|
assert_eq!(bank.palette_count(), GLYPH_BANK_MAX_PALETTE_COUNT_V1);
|
||||||
|
assert!(bank.contains_palette((GLYPH_BANK_MAX_PALETTE_COUNT_V1 - 1) as u8));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn invalid_palette_lookup_is_distinct_from_transparent_color() {
|
||||||
|
let mut bank = GlyphBank::new(TileSize::Size8, 8, 8);
|
||||||
|
bank.palette_mut(0).unwrap()[1] = Color::TRANSPARENT;
|
||||||
|
|
||||||
|
assert_eq!(bank.resolve_color(0, 1), Some(Color::TRANSPARENT));
|
||||||
|
assert_eq!(bank.resolve_color(1, 1), None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
#[should_panic(expected = "glyph bank palette_count must be in 1..=64")]
|
||||||
|
fn glyph_bank_rejects_zero_resident_palettes() {
|
||||||
|
let _ = GlyphBank::with_palette_count(TileSize::Size8, 8, 8, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -159,6 +159,15 @@ impl<'a> VmFacade<'a> {
|
|||||||
self.os.vm_runtime.debug_step_request = true;
|
self.os.vm_runtime.debug_step_request = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub fn clear_debug_step_request(&mut self) {
|
||||||
|
if let Some(session) = self.active_session_mut() {
|
||||||
|
session.runtime.debug_step_request = false;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
self.os.vm_runtime.debug_step_request = false;
|
||||||
|
}
|
||||||
|
|
||||||
pub fn debug_step_requested(&self) -> bool {
|
pub fn debug_step_requested(&self) -> bool {
|
||||||
self.active_session()
|
self.active_session()
|
||||||
.map(|session| session.runtime.debug_step_request)
|
.map(|session| session.runtime.debug_step_request)
|
||||||
|
|||||||
@@ -65,7 +65,7 @@ pub struct VirtualMachineRuntime {
|
|||||||
|
|
||||||
impl VirtualMachineRuntime {
|
impl VirtualMachineRuntime {
|
||||||
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 1_500_000;
|
pub const CYCLES_PER_LOGICAL_FRAME: u64 = 1_500_000;
|
||||||
pub const SLICE_PER_TICK: u64 = 1_500_000;
|
pub const SLICE_PER_TICK: u64 = 250_000;
|
||||||
pub const MAX_LOG_LEN: usize = 256;
|
pub const MAX_LOG_LEN: usize = 256;
|
||||||
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
pub const MAX_LOGS_PER_FRAME: u32 = 10;
|
||||||
|
|
||||||
|
|||||||
@@ -15,7 +15,7 @@ use prometeu_hal::asset::{
|
|||||||
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
use prometeu_hal::cartridge::{AssetsPayloadSource, Cartridge};
|
||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::glyph::Glyph;
|
use prometeu_hal::glyph::Glyph;
|
||||||
use prometeu_hal::glyph_bank::{GLYPH_BANK_PALETTE_COUNT_V1, GlyphBank, TileSize};
|
use prometeu_hal::glyph_bank::{GLYPH_BANK_MAX_PALETTE_COUNT_V1, GlyphBank, TileSize};
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
use prometeu_hal::scene_bank::SceneBank;
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
use prometeu_hal::syscalls::caps;
|
use prometeu_hal::syscalls::caps;
|
||||||
@@ -113,11 +113,12 @@ fn serialized_single_function_module_with_consts(
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
|
fn test_glyph_payload_size(width: usize, height: usize) -> usize {
|
||||||
(width * height).div_ceil(2) + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
(width * height).div_ceil(2)
|
||||||
|
+ (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
|
fn test_glyph_decoded_size(width: usize, height: usize) -> usize {
|
||||||
width * height + (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
width * height + (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * std::mem::size_of::<u32>())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
||||||
@@ -133,23 +134,23 @@ fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
|||||||
"tile_size": 16,
|
"tile_size": 16,
|
||||||
"width": 16,
|
"width": 16,
|
||||||
"height": 16,
|
"height": 16,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn test_glyph_asset_data() -> Vec<u8> {
|
fn test_glyph_asset_data() -> Vec<u8> {
|
||||||
let mut data =
|
let mut data =
|
||||||
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4)];
|
vec![0x11u8; test_glyph_payload_size(16, 16) - (GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4)];
|
||||||
data.extend_from_slice(&[0u8; GLYPH_BANK_PALETTE_COUNT_V1 * 16 * 4]);
|
data.extend_from_slice(&[0u8; GLYPH_BANK_MAX_PALETTE_COUNT_V1 * 16 * 4]);
|
||||||
data
|
data
|
||||||
}
|
}
|
||||||
|
|
||||||
fn runtime_test_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
fn runtime_test_glyph_bank(tile_size: TileSize, palette_id: u8, color: Color) -> GlyphBank {
|
||||||
let size = tile_size as usize;
|
let size = tile_size as usize;
|
||||||
let mut bank = GlyphBank::new(tile_size, size, size);
|
let mut bank = GlyphBank::with_palette_count(tile_size, size, size, palette_id as usize + 1);
|
||||||
bank.palettes[palette_id as usize][1] = color;
|
bank.palette_mut(palette_id).unwrap()[1] = color;
|
||||||
for pixel in &mut bank.pixel_indices {
|
for pixel in &mut bank.pixel_indices {
|
||||||
*pixel = 1;
|
*pixel = 1;
|
||||||
}
|
}
|
||||||
@@ -1275,6 +1276,53 @@ fn tick_composer_emit_sprite_operational_error_returns_status_not_crash() {
|
|||||||
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn tick_composer_emit_sprite_invalid_palette_returns_bank_invalid() {
|
||||||
|
let mut runtime = VirtualMachineRuntime::new(None);
|
||||||
|
let mut log_service = LogService::new(4096);
|
||||||
|
let mut fs = VirtualFS::new();
|
||||||
|
let mut fs_state = FsState::Unmounted;
|
||||||
|
let mut memcard = MemcardService::new();
|
||||||
|
let mut open_files: HashMap<u32, String> = HashMap::new();
|
||||||
|
let mut next_handle = 1;
|
||||||
|
let mut vm = VirtualMachine::default();
|
||||||
|
let banks = Arc::new(MemoryBanks::new());
|
||||||
|
banks.install_glyph_bank(0, Arc::new(runtime_test_glyph_bank(TileSize::Size8, 0, Color::BLUE)));
|
||||||
|
let mut platform = TestPlatform::new_with_memory_banks(banks);
|
||||||
|
let signals = InputSignals::default();
|
||||||
|
let code = assemble(
|
||||||
|
"PUSH_I32 0\nPUSH_I32 1\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_I32 0\nPUSH_BOOL 0\nPUSH_BOOL 0\nPUSH_I32 0\nHOSTCALL 0\nHALT",
|
||||||
|
)
|
||||||
|
.expect("assemble");
|
||||||
|
let program = serialized_single_function_module(
|
||||||
|
code,
|
||||||
|
vec![SyscallDecl {
|
||||||
|
module: "composer".into(),
|
||||||
|
name: "emit_sprite".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 9,
|
||||||
|
ret_slots: 1,
|
||||||
|
}],
|
||||||
|
);
|
||||||
|
let cartridge = cartridge_with_program(program, caps::GFX);
|
||||||
|
|
||||||
|
runtime.initialize_vm(&mut log_service, &mut vm, &cartridge).expect("runtime must initialize");
|
||||||
|
let report = runtime.tick(
|
||||||
|
&mut log_service,
|
||||||
|
&mut fs,
|
||||||
|
&mut fs_state,
|
||||||
|
&mut memcard,
|
||||||
|
&mut open_files,
|
||||||
|
&mut next_handle,
|
||||||
|
&mut vm,
|
||||||
|
&signals,
|
||||||
|
&mut platform,
|
||||||
|
);
|
||||||
|
assert!(report.is_none(), "invalid palette must not crash VM execution");
|
||||||
|
assert!(vm.is_halted());
|
||||||
|
assert_eq!(vm.operand_stack_top(1), vec![Value::Int64(ComposerOpStatus::BankInvalid as i64)]);
|
||||||
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
|
fn tick_composer_emit_sprite_invalid_layer_returns_status_not_crash() {
|
||||||
let mut runtime = VirtualMachineRuntime::new(None);
|
let mut runtime = VirtualMachineRuntime::new(None);
|
||||||
|
|||||||
@@ -76,6 +76,9 @@ impl VirtualMachineRuntime {
|
|||||||
vm: &mut VirtualMachine,
|
vm: &mut VirtualMachine,
|
||||||
platform: &mut dyn RuntimePlatform,
|
platform: &mut dyn RuntimePlatform,
|
||||||
) -> Option<CrashReport> {
|
) -> Option<CrashReport> {
|
||||||
|
if vm.call_stack_is_empty() {
|
||||||
|
vm.prepare_boot_call();
|
||||||
|
}
|
||||||
let step_result = {
|
let step_result = {
|
||||||
let mut ctx = HostContext::new_platform(Some(platform));
|
let mut ctx = HostContext::new_platform(Some(platform));
|
||||||
let mut fs = VirtualFS::new();
|
let mut fs = VirtualFS::new();
|
||||||
@@ -96,18 +99,28 @@ impl VirtualMachineRuntime {
|
|||||||
};
|
};
|
||||||
|
|
||||||
match step_result {
|
match step_result {
|
||||||
Ok(_) => None,
|
Ok(())
|
||||||
Err(e) => {
|
| Err(
|
||||||
let report = match e {
|
LogicalFrameEndingReason::FrameSync
|
||||||
LogicalFrameEndingReason::Trap(trap) => CrashReport::VmTrap { trap },
|
| LogicalFrameEndingReason::BudgetExhausted
|
||||||
LogicalFrameEndingReason::Panic(message) => {
|
| LogicalFrameEndingReason::Halted
|
||||||
CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) }
|
| LogicalFrameEndingReason::EndOfRom
|
||||||
|
| LogicalFrameEndingReason::Breakpoint,
|
||||||
|
) => None,
|
||||||
|
Err(LogicalFrameEndingReason::Trap(trap)) => {
|
||||||
|
let report = CrashReport::VmTrap { trap };
|
||||||
|
self.log(
|
||||||
|
log_service,
|
||||||
|
LogLevel::Error,
|
||||||
|
LogSource::Vm,
|
||||||
|
report.log_tag(),
|
||||||
|
format!("PVM Fault during Step: {}", report),
|
||||||
|
);
|
||||||
|
self.last_crash_report = Some(report.clone());
|
||||||
|
Some(report)
|
||||||
}
|
}
|
||||||
other => CrashReport::VmPanic {
|
Err(LogicalFrameEndingReason::Panic(message)) => {
|
||||||
message: format!("Unexpected fault during step: {:?}", other),
|
let report = CrashReport::VmPanic { message, pc: Some(vm.pc() as u32) };
|
||||||
pc: Some(vm.pc() as u32),
|
|
||||||
},
|
|
||||||
};
|
|
||||||
self.log(
|
self.log(
|
||||||
log_service,
|
log_service,
|
||||||
LogLevel::Error,
|
LogLevel::Error,
|
||||||
|
|||||||
@@ -2627,7 +2627,7 @@ mod tests {
|
|||||||
fn test_loader_hardening_unsupported_version() {
|
fn test_loader_hardening_unsupported_version() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
|
header[4..6].copy_from_slice(&1u16.to_le_bytes()); // version 1 (unsupported)
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
@@ -2635,16 +2635,16 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_loader_hardening_malformed_pbs_v0() {
|
fn test_loader_hardening_malformed_pbx_v0() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
|
header[8..12].copy_from_slice(&1u32.to_le_bytes()); // 1 section claimed but none provided
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
match res {
|
match res {
|
||||||
Err(VmInitError::ImageLoadFailed(prometeu_bytecode::LoadError::UnexpectedEof)) => {}
|
Err(VmInitError::ImageLoadFailed(prometeu_bytecode::LoadError::UnexpectedEof)) => {}
|
||||||
_ => panic!("Expected PbsV0LoadFailed(UnexpectedEof), got {:?}", res),
|
_ => panic!("Expected PBX v0 load failure UnexpectedEof, got {:?}", res),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -2695,6 +2695,13 @@ mod tests {
|
|||||||
assert_eq!(vm.pc, 0);
|
assert_eq!(vm.pc, 0);
|
||||||
assert_eq!(vm.program.rom.len(), 2);
|
assert_eq!(vm.program.rom.len(), 2);
|
||||||
assert_eq!(vm.cycles, 0);
|
assert_eq!(vm.cycles, 0);
|
||||||
|
|
||||||
|
vm.prepare_boot_call();
|
||||||
|
let mut native = MockNative;
|
||||||
|
let mut ctx = HostContext::new(None);
|
||||||
|
let report = vm.run_budget(100, &mut native, &mut ctx).expect("run loaded PBX");
|
||||||
|
assert_eq!(report.reason, LogicalFrameEndingReason::Halted);
|
||||||
|
assert!(vm.is_halted());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@@ -3084,7 +3091,7 @@ mod tests {
|
|||||||
fn test_loader_hardening_missing_sysc_section() {
|
fn test_loader_hardening_missing_sysc_section() {
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let mut header = vec![0u8; 32];
|
let mut header = vec![0u8; 32];
|
||||||
header[0..4].copy_from_slice(b"PBS\0");
|
header[0..4].copy_from_slice(&prometeu_bytecode::PBX_MAGIC);
|
||||||
|
|
||||||
let res = vm.initialize(header);
|
let res = vm.initialize(header);
|
||||||
|
|
||||||
|
|||||||
@@ -83,8 +83,7 @@ impl VirtualMachine {
|
|||||||
self.scheduler = Scheduler::new();
|
self.scheduler = Scheduler::new();
|
||||||
self.current_coro = None;
|
self.current_coro = None;
|
||||||
|
|
||||||
let program = if program_bytes.starts_with(b"PBS\0") {
|
let program = match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
||||||
match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
|
||||||
Ok(mut module) => {
|
Ok(mut module) => {
|
||||||
patch_module_hostcalls(&mut module, self.capabilities)
|
patch_module_hostcalls(&mut module, self.capabilities)
|
||||||
.map_err(VmInitError::LoaderPatchFailed)?;
|
.map_err(VmInitError::LoaderPatchFailed)?;
|
||||||
@@ -103,10 +102,13 @@ impl VirtualMachine {
|
|||||||
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
||||||
return Err(VmInitError::UnsupportedFormat);
|
return Err(VmInitError::UnsupportedFormat);
|
||||||
}
|
}
|
||||||
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
|
Err(prometeu_bytecode::LoadError::InvalidMagic) => {
|
||||||
}
|
|
||||||
} else {
|
|
||||||
return Err(VmInitError::InvalidFormat);
|
return Err(VmInitError::InvalidFormat);
|
||||||
|
}
|
||||||
|
Err(prometeu_bytecode::LoadError::UnexpectedEof) if program_bytes.len() < 32 => {
|
||||||
|
return Err(VmInitError::InvalidFormat);
|
||||||
|
}
|
||||||
|
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
|
||||||
};
|
};
|
||||||
|
|
||||||
let pc = program
|
let pc = program
|
||||||
|
|||||||
@@ -2,8 +2,8 @@ use prometeu_vm::{VirtualMachine, VmInitError};
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn invalid_image_format_is_rejected_before_execution() {
|
fn invalid_image_format_is_rejected_before_execution() {
|
||||||
// Provide bytes that are not a valid PBS image. The VM must reject it with InvalidFormat.
|
// Provide bytes that are not a valid PBX image. The VM must reject it with InvalidFormat.
|
||||||
let program_bytes = b"NOT_PBS_IMAGE".to_vec();
|
let program_bytes = b"NOT_PBX_IMAGE".to_vec();
|
||||||
let mut vm = VirtualMachine::default();
|
let mut vm = VirtualMachine::default();
|
||||||
let result = vm.initialize(program_bytes);
|
let result = vm.initialize(program_bytes);
|
||||||
assert!(matches!(result, Err(VmInitError::InvalidFormat)));
|
assert!(matches!(result, Err(VmInitError::InvalidFormat)));
|
||||||
|
|||||||
@@ -0,0 +1,74 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::path::{Path, PathBuf};
|
||||||
|
|
||||||
|
const TARGET_MANIFESTS: &[&str] =
|
||||||
|
&["crates/console/prometeu-bytecode/Cargo.toml", "crates/console/prometeu-vm/Cargo.toml"];
|
||||||
|
|
||||||
|
const FORBIDDEN_DEPENDENCY_FRAGMENTS: &[&str] = &["compiler", "frontend"];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn pbx_and_pvm_crates_must_not_depend_on_compiler_or_frontend_crates() {
|
||||||
|
let workspace_root = find_workspace_root().expect("runtime workspace root");
|
||||||
|
let mut violations = Vec::new();
|
||||||
|
|
||||||
|
for relative_path in TARGET_MANIFESTS {
|
||||||
|
let manifest_path = workspace_root.join(relative_path);
|
||||||
|
let manifest = fs::read_to_string(&manifest_path)
|
||||||
|
.unwrap_or_else(|error| panic!("failed to read {}: {error}", manifest_path.display()));
|
||||||
|
|
||||||
|
for dependency in dependency_names(&manifest) {
|
||||||
|
let normalized = dependency.to_ascii_lowercase();
|
||||||
|
if FORBIDDEN_DEPENDENCY_FRAGMENTS.iter().any(|fragment| normalized.contains(fragment)) {
|
||||||
|
violations.push(format!("{relative_path}: forbidden dependency `{dependency}`"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
assert!(
|
||||||
|
violations.is_empty(),
|
||||||
|
"PBX/PVM crates must remain independent of compiler and frontend crates:\n{}",
|
||||||
|
violations.join("\n")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
fn dependency_names(manifest: &str) -> Vec<&str> {
|
||||||
|
let mut names = Vec::new();
|
||||||
|
let mut in_dependency_section = false;
|
||||||
|
|
||||||
|
for raw_line in manifest.lines() {
|
||||||
|
let line = raw_line.trim();
|
||||||
|
if line.starts_with('[') && line.ends_with(']') {
|
||||||
|
let section = &line[1..line.len() - 1];
|
||||||
|
in_dependency_section = section == "dependencies"
|
||||||
|
|| section == "dev-dependencies"
|
||||||
|
|| section == "build-dependencies"
|
||||||
|
|| section.ends_with(".dependencies")
|
||||||
|
|| section.ends_with(".dev-dependencies")
|
||||||
|
|| section.ends_with(".build-dependencies");
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if !in_dependency_section || line.is_empty() || line.starts_with('#') {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if let Some((name, _)) = line.split_once('=') {
|
||||||
|
names.push(name.trim().trim_matches('"'));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
names
|
||||||
|
}
|
||||||
|
|
||||||
|
fn find_workspace_root() -> Option<PathBuf> {
|
||||||
|
let mut cursor = Path::new(env!("CARGO_MANIFEST_DIR")).to_path_buf();
|
||||||
|
loop {
|
||||||
|
let manifest = cursor.join("Cargo.toml");
|
||||||
|
if fs::read_to_string(&manifest).is_ok_and(|contents| contents.contains("[workspace]")) {
|
||||||
|
return Some(cursor);
|
||||||
|
}
|
||||||
|
if !cursor.pop() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -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,425 @@
|
|||||||
|
use std::fmt;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
use prometeu_bytecode::Value;
|
||||||
|
use prometeu_drivers::MemoryBanks;
|
||||||
|
use prometeu_drivers::hardware::Hardware;
|
||||||
|
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,
|
||||||
|
RuntimePlatform, TelemetryPlatform,
|
||||||
|
};
|
||||||
|
use prometeu_system::{CrashReport, LatestRenderFrameStore};
|
||||||
|
|
||||||
|
const BOOT_TICK_LIMIT: usize = 64;
|
||||||
|
const LOGICAL_FRAME_TICK_LIMIT: usize = 100_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 tick_index: u64,
|
||||||
|
pub app_id: u32,
|
||||||
|
pub status: HostExecutionStatus,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||||
|
pub enum HostExecutionStatus {
|
||||||
|
Running,
|
||||||
|
Paused,
|
||||||
|
Terminated,
|
||||||
|
Faulted,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum AdvanceFrameOutcome {
|
||||||
|
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
|
||||||
|
Faulted(CrashReport),
|
||||||
|
Terminated,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum AdvanceFramesStop {
|
||||||
|
Completed,
|
||||||
|
Faulted(CrashReport),
|
||||||
|
Terminated,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub struct AdvanceFramesOutcome {
|
||||||
|
pub requested: u64,
|
||||||
|
pub completed: u64,
|
||||||
|
pub stop: AdvanceFramesStop,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
|
pub enum HostError {
|
||||||
|
AlreadyBooted,
|
||||||
|
BootFailed { reason: String, report: Option<CrashReport> },
|
||||||
|
InvalidState { operation: &'static str, status: HostExecutionStatus },
|
||||||
|
LogicalFrameDidNotClose,
|
||||||
|
FrameNotPublished { previous: Option<FrameId> },
|
||||||
|
NoFrameAvailable,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl fmt::Display for HostError {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
match self {
|
||||||
|
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
|
||||||
|
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
|
||||||
|
Self::InvalidState { operation, status } => {
|
||||||
|
write!(f, "{operation} is invalid while execution is {status:?}")
|
||||||
|
}
|
||||||
|
Self::LogicalFrameDidNotClose => {
|
||||||
|
write!(f, "logical frame did not reach FrameSync, end of ROM, or a fault")
|
||||||
|
}
|
||||||
|
Self::FrameNotPublished { .. } => {
|
||||||
|
write!(f, "logical frame closed without its canonical published frame")
|
||||||
|
}
|
||||||
|
Self::NoFrameAvailable => write!(f, "no completed frame is available for capture"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,
|
||||||
|
boot_attempted: bool,
|
||||||
|
last_completed_frame: Option<CompletedFrame>,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
struct CompletedFrame {
|
||||||
|
logical_frame_index: u64,
|
||||||
|
frame_id: 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(),
|
||||||
|
boot_attempted: false,
|
||||||
|
last_completed_frame: 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> {
|
||||||
|
if self.boot_attempted {
|
||||||
|
return Err(HostError::AlreadyBooted);
|
||||||
|
}
|
||||||
|
self.boot_attempted = true;
|
||||||
|
let path = path.into();
|
||||||
|
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
|
||||||
|
|
||||||
|
for _ in 0..BOOT_TICK_LIMIT {
|
||||||
|
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||||
|
return Ok(());
|
||||||
|
}
|
||||||
|
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
|
||||||
|
let report = self.get_fault();
|
||||||
|
let reason = report
|
||||||
|
.as_ref()
|
||||||
|
.map(CrashReport::summary)
|
||||||
|
.unwrap_or_else(|| "cartridge crashed during boot".to_string());
|
||||||
|
return Err(HostError::BootFailed { reason, report });
|
||||||
|
}
|
||||||
|
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
|
||||||
|
return Err(HostError::BootFailed {
|
||||||
|
reason: "cartridge did not load".to_string(),
|
||||||
|
report: None,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
self.tick_once();
|
||||||
|
}
|
||||||
|
|
||||||
|
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(HostError::BootFailed {
|
||||||
|
reason: "boot did not reach the game".to_string(),
|
||||||
|
report: self.get_fault(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn reset(&mut self) {
|
||||||
|
self.signals = InputSignals::default();
|
||||||
|
self.firmware.change_state(
|
||||||
|
FirmwareState::Reset(ResetStep),
|
||||||
|
&self.signals,
|
||||||
|
&mut self.platform,
|
||||||
|
);
|
||||||
|
self.platform.store = LatestRenderFrameStore::default();
|
||||||
|
self.boot_attempted = false;
|
||||||
|
self.last_completed_frame = None;
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn pause(&mut self) -> Result<(), HostError> {
|
||||||
|
self.require_active("pause")?;
|
||||||
|
self.firmware.os.vm().set_paused(true);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn resume(&mut self) -> Result<(), HostError> {
|
||||||
|
self.require_active("resume")?;
|
||||||
|
self.firmware.os.vm().set_paused(false);
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Execute one VM instruction. This does not close a logical frame.
|
||||||
|
pub fn step(&mut self) -> Result<Option<CrashReport>, HostError> {
|
||||||
|
self.require_active("step")?;
|
||||||
|
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();
|
||||||
|
Ok(report)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn advance_frame(&mut self) -> Result<AdvanceFrameOutcome, HostError> {
|
||||||
|
if let Some(report) = self.get_fault() {
|
||||||
|
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||||
|
}
|
||||||
|
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||||
|
return Ok(AdvanceFrameOutcome::Terminated);
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = self.firmware.os.vm().logical_frame_index();
|
||||||
|
let 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 let Some(report) = self.get_fault() {
|
||||||
|
self.finish_frame_step();
|
||||||
|
return Ok(AdvanceFrameOutcome::Faulted(report));
|
||||||
|
}
|
||||||
|
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||||
|
return Ok(AdvanceFrameOutcome::Terminated);
|
||||||
|
}
|
||||||
|
|
||||||
|
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
|
||||||
|
if logical_frame_index > start {
|
||||||
|
self.finish_frame_step();
|
||||||
|
let frame = self
|
||||||
|
.platform
|
||||||
|
.store
|
||||||
|
.latest_frame()
|
||||||
|
.ok_or(HostError::FrameNotPublished { previous: previous_frame_id })?;
|
||||||
|
if Some(frame.frame_id) == previous_frame_id {
|
||||||
|
return Err(HostError::FrameNotPublished { previous: previous_frame_id });
|
||||||
|
}
|
||||||
|
self.last_completed_frame =
|
||||||
|
Some(CompletedFrame { logical_frame_index, frame_id: frame.frame_id });
|
||||||
|
return Ok(AdvanceFrameOutcome::FrameCompleted {
|
||||||
|
logical_frame_index,
|
||||||
|
frame_id: frame.frame_id,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self.finish_frame_step();
|
||||||
|
Err(HostError::LogicalFrameDidNotClose)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn advance_frames(&mut self, count: u64) -> Result<AdvanceFramesOutcome, HostError> {
|
||||||
|
let mut completed = 0;
|
||||||
|
for _ in 0..count {
|
||||||
|
match self.advance_frame()? {
|
||||||
|
AdvanceFrameOutcome::FrameCompleted { .. } => completed += 1,
|
||||||
|
AdvanceFrameOutcome::Faulted(report) => {
|
||||||
|
return Ok(AdvanceFramesOutcome {
|
||||||
|
requested: count,
|
||||||
|
completed,
|
||||||
|
stop: AdvanceFramesStop::Faulted(report),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
AdvanceFrameOutcome::Terminated => {
|
||||||
|
return Ok(AdvanceFramesOutcome {
|
||||||
|
requested: count,
|
||||||
|
completed,
|
||||||
|
stop: AdvanceFramesStop::Terminated,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
|
||||||
|
}
|
||||||
|
|
||||||
|
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(&self) -> Result<CapturedFrame, HostError> {
|
||||||
|
let completed = self.last_completed_frame.ok_or(HostError::NoFrameAvailable)?;
|
||||||
|
let frame = self.platform.store.latest_frame().ok_or(HostError::NoFrameAvailable)?;
|
||||||
|
if frame.frame_id != completed.frame_id {
|
||||||
|
return Err(HostError::FrameNotPublished { previous: Some(completed.frame_id) });
|
||||||
|
}
|
||||||
|
Ok(CapturedFrame { logical_frame_index: completed.logical_frame_index, frame })
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_state(&mut self) -> HostState {
|
||||||
|
let status = self.execution_status();
|
||||||
|
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(),
|
||||||
|
tick_index: self.firmware.os.vm().tick_index(),
|
||||||
|
app_id: self.firmware.os.vm().current_app_id(),
|
||||||
|
status,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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 execution_status(&mut self) -> HostExecutionStatus {
|
||||||
|
if self.fault_is_visible() {
|
||||||
|
HostExecutionStatus::Faulted
|
||||||
|
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
|
||||||
|
HostExecutionStatus::Terminated
|
||||||
|
} else if self.firmware.os.vm().paused() {
|
||||||
|
HostExecutionStatus::Paused
|
||||||
|
} else {
|
||||||
|
HostExecutionStatus::Running
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn fault_is_visible(&mut self) -> bool {
|
||||||
|
self.firmware.os.vm().last_crash_report().is_some()
|
||||||
|
|| matches!(self.firmware.state, FirmwareState::AppCrashes(_))
|
||||||
|
}
|
||||||
|
|
||||||
|
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
|
||||||
|
let status = self.execution_status();
|
||||||
|
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
|
||||||
|
Ok(())
|
||||||
|
} else {
|
||||||
|
Err(HostError::InvalidState { operation, status })
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn finish_frame_step(&mut self) {
|
||||||
|
self.firmware.os.vm().set_paused(true);
|
||||||
|
self.firmware.os.vm().clear_debug_step_request();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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,14 @@
|
|||||||
|
//! 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::{
|
||||||
|
AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost,
|
||||||
|
HostError, HostExecutionStatus, HostState,
|
||||||
|
};
|
||||||
@@ -0,0 +1,639 @@
|
|||||||
|
use std::fs;
|
||||||
|
use std::path::Path;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
|
use prometeu_bytecode::SourceSpan;
|
||||||
|
use prometeu_bytecode::assembler::assemble;
|
||||||
|
use prometeu_bytecode::model::{BytecodeModule, DebugInfo, Export, FunctionMeta, SyscallDecl};
|
||||||
|
use prometeu_hal::InputSignals;
|
||||||
|
use prometeu_hal::app_mode::AppMode;
|
||||||
|
use prometeu_hal::color::Color;
|
||||||
|
use prometeu_host_headless::{
|
||||||
|
AdvanceFrameOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost, HostError,
|
||||||
|
HostExecutionStatus, HostState,
|
||||||
|
};
|
||||||
|
use prometeu_system::CrashReport;
|
||||||
|
|
||||||
|
const RED: u32 = Color::RED.raw();
|
||||||
|
const BLUE: u32 = Color::BLUE.raw();
|
||||||
|
const GREEN: u32 = Color::GREEN.raw();
|
||||||
|
const BLACK: u32 = Color::BLACK.raw();
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn headless_source_has_no_timing_wait_or_interactive_backend_dependency() {
|
||||||
|
let source = include_str!("../src/host.rs");
|
||||||
|
let manifest = include_str!("../Cargo.toml");
|
||||||
|
|
||||||
|
for forbidden in
|
||||||
|
["FRAME_PUBLISH_SPINS", "spin_loop", "thread::sleep", "ensure_worker", "RenderWorkerConfig"]
|
||||||
|
{
|
||||||
|
assert!(!source.contains(forbidden), "headless source contains {forbidden}");
|
||||||
|
}
|
||||||
|
for forbidden in ["winit", "pixels", "cpal"] {
|
||||||
|
assert!(!manifest.contains(forbidden), "headless manifest contains {forbidden}");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn lifecycle_state_and_preconditions_are_structural() {
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||||
|
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||||
|
assert_eq!(
|
||||||
|
host.pause(),
|
||||||
|
Err(HostError::InvalidState {
|
||||||
|
operation: "pause",
|
||||||
|
status: HostExecutionStatus::Terminated,
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
|
let cartridge = color_cartridge();
|
||||||
|
host.boot(&cartridge).expect("boot");
|
||||||
|
let booted = host.get_state();
|
||||||
|
assert_eq!(booted.status, HostExecutionStatus::Running);
|
||||||
|
assert_eq!(booted.pc, 0, "boot must not execute the first game instruction");
|
||||||
|
assert_eq!(host.boot(&cartridge), Err(HostError::AlreadyBooted));
|
||||||
|
|
||||||
|
host.pause().expect("pause");
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||||
|
host.resume().expect("resume");
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Running);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn step_does_not_complete_a_logical_frame() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
let before = host.get_state();
|
||||||
|
assert_eq!(host.step().expect("step"), None);
|
||||||
|
let after = host.get_state();
|
||||||
|
assert_eq!(after.frame_index, before.frame_index);
|
||||||
|
assert_ne!(after.pc, before.pc);
|
||||||
|
assert_eq!(after.status, HostExecutionStatus::Paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame() {
|
||||||
|
let dir = temp_cart("step-frame-sync");
|
||||||
|
write_cartridge(&dir, 51, "Step Frame Sync", &module(asm("FRAME_SYNC\nRET\n"), vec![]), &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot frame-sync cartridge");
|
||||||
|
let before = host.get_state().frame_index;
|
||||||
|
|
||||||
|
assert_eq!(host.step().expect("step frame sync"), None);
|
||||||
|
assert_eq!(host.get_state().frame_index, before);
|
||||||
|
assert!(host.get_fault().is_none());
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_logical_frame_may_span_multiple_internal_ticks() {
|
||||||
|
let dir = temp_cart("multi-tick");
|
||||||
|
write_cartridge(&dir, 47, "Multi Tick", &multi_tick_program(), &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot multi-tick cartridge");
|
||||||
|
let before = host.get_state();
|
||||||
|
|
||||||
|
completed(host.advance_frame().expect("multi-tick frame"));
|
||||||
|
|
||||||
|
let after = host.get_state();
|
||||||
|
assert_eq!(after.frame_index, before.frame_index + 1);
|
||||||
|
assert!(after.tick_index >= before.tick_index + 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn outer_frame_limit_is_a_host_error_and_finishes_paused() {
|
||||||
|
let dir = temp_cart("frame-limit");
|
||||||
|
write_cartridge(&dir, 50, "Frame Limit", &module(asm("JMP 0\n"), vec![]), &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot non-closing cartridge");
|
||||||
|
|
||||||
|
assert_eq!(host.advance_frame(), Err(HostError::LogicalFrameDidNotClose));
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||||
|
assert!(host.get_fault().is_none());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn one_frame_returns_and_captures_the_exact_published_frame() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
let before = host.get_state().frame_index;
|
||||||
|
let (logical_frame_index, frame_id) = completed(host.advance_frame().expect("frame"));
|
||||||
|
let captured = host.capture_frame().expect("capture");
|
||||||
|
|
||||||
|
assert_eq!(logical_frame_index, before + 1);
|
||||||
|
assert_eq!(captured.logical_frame_index, logical_frame_index);
|
||||||
|
assert_eq!(captured.frame.frame_id, frame_id);
|
||||||
|
assert_eq!(captured.frame.ownership.app_mode, AppMode::Game);
|
||||||
|
assert_eq!(captured.frame.ownership.app_id, 41);
|
||||||
|
assert_eq!(captured.frame.stride_pixels, captured.frame.width);
|
||||||
|
assert_eq!(captured.frame.pixels.len(), 480 * 270);
|
||||||
|
assert_eq!(host.capture_frame().expect("repeat capture"), captured);
|
||||||
|
|
||||||
|
let mut mutated_clone = captured.clone();
|
||||||
|
mutated_clone.frame.pixels[0] = GREEN;
|
||||||
|
assert_ne!(host.capture_frame().expect("owned capture").frame.pixels[0], GREEN);
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn zero_frames_is_an_explicit_noop() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
let before = host.get_state();
|
||||||
|
let outcome = host.advance_frames(0).expect("zero frames");
|
||||||
|
|
||||||
|
assert_eq!(outcome.requested, 0);
|
||||||
|
assert_eq!(outcome.completed, 0);
|
||||||
|
assert_eq!(outcome.stop, AdvanceFramesStop::Completed);
|
||||||
|
let after = host.get_state();
|
||||||
|
assert_eq!(after.frame_index, before.frame_index);
|
||||||
|
assert_eq!(after.tick_index, before.tick_index);
|
||||||
|
assert_eq!(after.status, before.status);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn clear_input_drops_right() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
host.set_right(true);
|
||||||
|
host.clear_input();
|
||||||
|
completed(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);
|
||||||
|
assert_completed(host.advance_frames(60).expect("hold"), 60);
|
||||||
|
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);
|
||||||
|
assert_completed(host.advance_frames(1).expect("release"), 1);
|
||||||
|
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 normalized_button_press_hold_release_and_clear_are_observable() {
|
||||||
|
let mut host = boot_input_edges();
|
||||||
|
|
||||||
|
let mut signals = InputSignals { right_signal: true, ..InputSignals::default() };
|
||||||
|
host.set_input(signals);
|
||||||
|
completed(host.advance_frame().expect("press"));
|
||||||
|
assert_color(&host.capture_frame().expect("pressed"), RED);
|
||||||
|
|
||||||
|
completed(host.advance_frame().expect("hold"));
|
||||||
|
assert_color(&host.capture_frame().expect("held"), BLUE);
|
||||||
|
|
||||||
|
signals.right_signal = false;
|
||||||
|
host.set_input(signals);
|
||||||
|
completed(host.advance_frame().expect("release"));
|
||||||
|
assert_color(&host.capture_frame().expect("released"), GREEN);
|
||||||
|
|
||||||
|
host.set_input(InputSignals {
|
||||||
|
right_signal: true,
|
||||||
|
f_signal: true,
|
||||||
|
x_pos: 123,
|
||||||
|
y_pos: 45,
|
||||||
|
..InputSignals::default()
|
||||||
|
});
|
||||||
|
host.clear_input();
|
||||||
|
completed(host.advance_frame().expect("clear"));
|
||||||
|
assert_color(&host.capture_frame().expect("cleared"), BLACK);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn normalized_touch_edges_and_coordinates_use_the_same_input_surface() {
|
||||||
|
let mut host = boot_touch_edges();
|
||||||
|
let mut signals =
|
||||||
|
InputSignals { f_signal: true, x_pos: 123, y_pos: 45, ..InputSignals::default() };
|
||||||
|
|
||||||
|
host.set_input(signals);
|
||||||
|
completed(host.advance_frame().expect("touch press"));
|
||||||
|
assert_color(&host.capture_frame().expect("touch pressed"), RED);
|
||||||
|
|
||||||
|
completed(host.advance_frame().expect("touch hold"));
|
||||||
|
assert_color(&host.capture_frame().expect("touch held"), BLUE);
|
||||||
|
|
||||||
|
signals.f_signal = false;
|
||||||
|
host.set_input(signals);
|
||||||
|
completed(host.advance_frame().expect("touch release"));
|
||||||
|
assert_color(&host.capture_frame().expect("touch released"), GREEN);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[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();
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
|
||||||
|
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
|
||||||
|
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");
|
||||||
|
let outcome = host.advance_frame().expect("faulting frame");
|
||||||
|
|
||||||
|
match outcome {
|
||||||
|
AdvanceFrameOutcome::Faulted(CrashReport::VmTrap { trap }) => {
|
||||||
|
assert_eq!(trap.code, prometeu_bytecode::TRAP_EXPLICIT);
|
||||||
|
assert_eq!(trap.opcode, prometeu_bytecode::isa::core::CoreOpCode::Trap as u16);
|
||||||
|
assert_eq!(trap.pc, 0);
|
||||||
|
assert_eq!(trap.span, Some(SourceSpan { file_id: 7, start: 11, end: 15 }));
|
||||||
|
assert!(trap.message.contains("main"));
|
||||||
|
}
|
||||||
|
other => panic!("expected VmTrap outcome, got {other:?}"),
|
||||||
|
}
|
||||||
|
assert!(matches!(host.get_fault(), Some(CrashReport::VmTrap { .. })));
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn instruction_step_fault_remains_structured() {
|
||||||
|
let dir = temp_cart("step-fault");
|
||||||
|
write_cartridge(&dir, 48, "Step Fault", &fault_program(), &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot fault cartridge");
|
||||||
|
|
||||||
|
let report = host.step().expect("step result").expect("structured step fault");
|
||||||
|
assert!(matches!(report, CrashReport::VmTrap { .. }));
|
||||||
|
assert_eq!(host.get_fault(), Some(report));
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn batch_stops_early_on_fault_and_reports_partial_progress() {
|
||||||
|
let dir = temp_cart("fault-batch");
|
||||||
|
write_cartridge(&dir, 43, "Fault Batch", &delayed_fault_program(), &gfx_syscalls());
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot fault cartridge");
|
||||||
|
|
||||||
|
let outcome = host.advance_frames(5).expect("batch outcome");
|
||||||
|
assert_eq!(outcome.requested, 5);
|
||||||
|
assert_eq!(outcome.completed, 2);
|
||||||
|
assert!(matches!(outcome.stop, AdvanceFramesStop::Faulted(CrashReport::VmTrap { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn advance_after_reset_reports_termination_without_ticking() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
host.reset();
|
||||||
|
let before = host.get_state().tick_index;
|
||||||
|
|
||||||
|
assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated);
|
||||||
|
assert_eq!(host.get_state().tick_index, before);
|
||||||
|
let batch = host.advance_frames(3).expect("terminated batch");
|
||||||
|
assert_eq!(batch.completed, 0);
|
||||||
|
assert_eq!(batch.stop, AdvanceFramesStop::Terminated);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn vm_init_failure_is_returned_as_structured_boot_failure() {
|
||||||
|
let dir = temp_cart("bad-pbx");
|
||||||
|
write_cartridge(&dir, 44, "Bad PBX", b"not a pbx", &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
|
||||||
|
let error = host.boot(&dir).expect_err("invalid PBX must fail boot");
|
||||||
|
assert!(matches!(
|
||||||
|
error,
|
||||||
|
HostError::BootFailed { report: Some(CrashReport::VmInit { .. }), .. }
|
||||||
|
));
|
||||||
|
assert_eq!(host.get_state().status, HostExecutionStatus::Faulted);
|
||||||
|
assert!(matches!(host.get_fault(), Some(CrashReport::VmInit { .. })));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn end_of_rom_completes_a_logical_frame() {
|
||||||
|
let dir = temp_cart("end-of-rom");
|
||||||
|
write_cartridge(&dir, 45, "End Of Rom", &module(asm("RET\n"), vec![]), &[]);
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot end-of-rom cartridge");
|
||||||
|
|
||||||
|
let first = completed(host.advance_frame().expect("first frame"));
|
||||||
|
let second = completed(host.advance_frame().expect("second frame"));
|
||||||
|
assert_eq!(second.0, first.0 + 1);
|
||||||
|
assert_ne!(second.1, first.1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn three_hundred_frames_finish_without_refresh_sleep() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
let started = Instant::now();
|
||||||
|
assert_completed(host.advance_frames(300).expect("fast frames"), 300);
|
||||||
|
assert!(started.elapsed() < Duration::from_secs(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn audio_play_does_not_need_a_device() {
|
||||||
|
let mut host = boot_color();
|
||||||
|
completed(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 boot_input_edges() -> HeadlessHost {
|
||||||
|
let dir = temp_cart("input-edges");
|
||||||
|
write_cartridge(&dir, 46, "Input Edges", &input_edge_program(), &gfx_syscalls());
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot input cartridge");
|
||||||
|
host
|
||||||
|
}
|
||||||
|
|
||||||
|
fn boot_touch_edges() -> HeadlessHost {
|
||||||
|
let dir = temp_cart("touch-edges");
|
||||||
|
write_cartridge(&dir, 49, "Touch Edges", &touch_edge_program(), &gfx_syscalls());
|
||||||
|
let mut host = HeadlessHost::new();
|
||||||
|
host.boot(&dir).expect("boot touch 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);
|
||||||
|
assert_completed(host.advance_frames(60).expect("hold"), 60);
|
||||||
|
let held = host.capture_frame().expect("held");
|
||||||
|
host.set_right(false);
|
||||||
|
assert_completed(host.advance_frames(1).expect("release"), 1);
|
||||||
|
let released = host.capture_frame().expect("released");
|
||||||
|
let state = host.get_state();
|
||||||
|
let fault = host.get_fault();
|
||||||
|
ColorOracle { held, released, state, fault }
|
||||||
|
}
|
||||||
|
|
||||||
|
fn completed(outcome: AdvanceFrameOutcome) -> (u64, prometeu_hal::FrameId) {
|
||||||
|
match outcome {
|
||||||
|
AdvanceFrameOutcome::FrameCompleted { logical_frame_index, frame_id } => {
|
||||||
|
(logical_frame_index, frame_id)
|
||||||
|
}
|
||||||
|
other => panic!("expected completed frame, got {other:?}"),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn assert_completed(outcome: prometeu_host_headless::AdvanceFramesOutcome, expected: u64) {
|
||||||
|
assert_eq!(outcome.requested, expected);
|
||||||
|
assert_eq!(outcome.completed, expected);
|
||||||
|
assert_eq!(outcome.stop, AdvanceFramesStop::Completed);
|
||||||
|
}
|
||||||
|
|
||||||
|
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.tick_index, right.tick_index);
|
||||||
|
assert_eq!(left.app_id, right.app_id);
|
||||||
|
assert_eq!(left.status, right.status);
|
||||||
|
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 input_edge_program() -> Vec<u8> {
|
||||||
|
let mut rom = Vec::new();
|
||||||
|
let pressed_jump = emit_right_predicate(&mut rom, 0x2030);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let released_at = rom.len() as u32;
|
||||||
|
rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes());
|
||||||
|
|
||||||
|
let released_jump = emit_right_predicate(&mut rom, 0x2031);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let down_at = rom.len() as u32;
|
||||||
|
rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes());
|
||||||
|
|
||||||
|
let down_jump = emit_right_predicate(&mut rom, 0x2032);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let idle_at = rom.len() as u32;
|
||||||
|
rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes());
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
|
||||||
|
module(rom, gfx_syscalls())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_right_predicate(rom: &mut Vec<u8>, predicate: u32) -> usize {
|
||||||
|
rom.extend(asm(&format!("INTRINSIC 0x2000\nINTRINSIC 0x2013\nINTRINSIC {predicate:#x}\n")));
|
||||||
|
let target = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP_IF_FALSE 0\n"));
|
||||||
|
target
|
||||||
|
}
|
||||||
|
|
||||||
|
fn touch_edge_program() -> Vec<u8> {
|
||||||
|
let mut rom = Vec::new();
|
||||||
|
let pressed_jump = emit_touch_predicate(&mut rom, 0x2030);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {RED}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let released_at = rom.len() as u32;
|
||||||
|
rom[pressed_jump..pressed_jump + 4].copy_from_slice(&released_at.to_le_bytes());
|
||||||
|
|
||||||
|
let released_jump = emit_touch_predicate(&mut rom, 0x2031);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {GREEN}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let down_at = rom.len() as u32;
|
||||||
|
rom[released_jump..released_jump + 4].copy_from_slice(&down_at.to_le_bytes());
|
||||||
|
|
||||||
|
let down_jump = emit_touch_predicate(&mut rom, 0x2032);
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {BLUE}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
let idle_at = rom.len() as u32;
|
||||||
|
rom[down_jump..down_jump + 4].copy_from_slice(&idle_at.to_le_bytes());
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
|
||||||
|
module(rom, gfx_syscalls())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn emit_touch_predicate(rom: &mut Vec<u8>, predicate: u32) -> usize {
|
||||||
|
rom.extend(asm(&format!(
|
||||||
|
"INTRINSIC 0x2001\nINTRINSIC 0x2020\nINTRINSIC {predicate:#x}\n\
|
||||||
|
INTRINSIC 0x2001\nINTRINSIC 0x2021\nPUSH_I64 123\nEQ\nAND\n\
|
||||||
|
INTRINSIC 0x2001\nINTRINSIC 0x2022\nPUSH_I64 45\nEQ\nAND\n"
|
||||||
|
)));
|
||||||
|
let target = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP_IF_FALSE 0\n"));
|
||||||
|
target
|
||||||
|
}
|
||||||
|
|
||||||
|
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 delayed_fault_program() -> Vec<u8> {
|
||||||
|
let mut rom =
|
||||||
|
asm("GET_GLOBAL 0\nPUSH_I32 1\nADD\nSET_GLOBAL 0\nGET_GLOBAL 0\nPUSH_I32 3\nEQ\n");
|
||||||
|
let continue_jump = rom.len() + 2;
|
||||||
|
rom.extend(asm("JMP_IF_FALSE 0\nTRAP\n"));
|
||||||
|
let continue_at = rom.len() as u32;
|
||||||
|
rom[continue_jump..continue_jump + 4].copy_from_slice(&continue_at.to_le_bytes());
|
||||||
|
rom.extend(asm(&format!("PUSH_I64 {BLACK}\nHOSTCALL 0\nFRAME_SYNC\nRET\n")));
|
||||||
|
module(rom, gfx_syscalls())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn multi_tick_program() -> Vec<u8> {
|
||||||
|
let mut rom = asm("PUSH_I32 30000\nSET_LOCAL 0\n");
|
||||||
|
let loop_at = rom.len() as u32;
|
||||||
|
rom.extend(asm("GET_LOCAL 0\nPUSH_I32 1\nSUB\nSET_LOCAL 0\nGET_LOCAL 0\nPUSH_I32 0\nGT\n"));
|
||||||
|
rom.extend(asm(&format!("JMP_IF_TRUE {loop_at}\nFRAME_SYNC\nRET\n")));
|
||||||
|
module_with_locals(rom, vec![], 1)
|
||||||
|
}
|
||||||
|
|
||||||
|
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 gfx_syscalls() -> Vec<SyscallDecl> {
|
||||||
|
vec![SyscallDecl {
|
||||||
|
module: "gfx2d".into(),
|
||||||
|
name: "clear".into(),
|
||||||
|
version: 1,
|
||||||
|
arg_slots: 1,
|
||||||
|
ret_slots: 0,
|
||||||
|
}]
|
||||||
|
}
|
||||||
|
|
||||||
|
fn module(code: Vec<u8>, syscalls: Vec<SyscallDecl>) -> Vec<u8> {
|
||||||
|
module_with_locals(code, syscalls, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn module_with_locals(code: Vec<u8>, syscalls: Vec<SyscallDecl>, local_slots: u16) -> 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,
|
||||||
|
return_slots: 0,
|
||||||
|
max_stack_slots: 8,
|
||||||
|
}],
|
||||||
|
code,
|
||||||
|
debug_info: Some(DebugInfo {
|
||||||
|
pc_to_span: vec![(0, SourceSpan { file_id: 7, start: 11, end: 15 })],
|
||||||
|
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")
|
||||||
|
}
|
||||||
@@ -130,7 +130,7 @@ mod tests {
|
|||||||
fn generated_program_is_pbx_module_with_expected_syscalls() {
|
fn generated_program_is_pbx_module_with_expected_syscalls() {
|
||||||
let bytes = build_program();
|
let bytes = build_program();
|
||||||
|
|
||||||
assert!(bytes.starts_with(b"PBS\0"));
|
assert!(bytes.starts_with(&prometeu_bytecode::PBX_MAGIC));
|
||||||
assert!(bytes.len() > 64);
|
assert!(bytes.len() > 64);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -14,7 +14,7 @@ use prometeu_hal::cartridge::{
|
|||||||
use prometeu_hal::color::Color;
|
use prometeu_hal::color::Color;
|
||||||
use prometeu_hal::glyph::Glyph;
|
use prometeu_hal::glyph::Glyph;
|
||||||
use prometeu_hal::glyph_bank::{
|
use prometeu_hal::glyph_bank::{
|
||||||
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_PALETTE_COUNT_V1,
|
TileSize, GLYPH_BANK_COLORS_PER_PALETTE, GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
};
|
};
|
||||||
use prometeu_hal::scene_bank::SceneBank;
|
use prometeu_hal::scene_bank::SceneBank;
|
||||||
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
use prometeu_hal::scene_layer::{ParallaxFactor, SceneLayer};
|
||||||
@@ -275,15 +275,15 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
|
|||||||
bank_type: BankType::GLYPH,
|
bank_type: BankType::GLYPH,
|
||||||
offset: 0,
|
offset: 0,
|
||||||
size: payload.len() as u64,
|
size: payload.len() as u64,
|
||||||
decoded_size: (8 * 8 + GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
|
decoded_size: (8 * 8 + GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4)
|
||||||
as u64,
|
as u64,
|
||||||
codec: AssetCodec::None,
|
codec: AssetCodec::None,
|
||||||
metadata: serde_json::json!({
|
metadata: serde_json::json!({
|
||||||
"tile_size": 8,
|
"tile_size": 8,
|
||||||
"width": 8,
|
"width": 8,
|
||||||
"height": 8,
|
"height": 8,
|
||||||
"palette_count": GLYPH_BANK_PALETTE_COUNT_V1,
|
"palette_count": GLYPH_BANK_MAX_PALETTE_COUNT_V1,
|
||||||
"palette_authored": GLYPH_BANK_PALETTE_COUNT_V1
|
"palette_authored": GLYPH_BANK_MAX_PALETTE_COUNT_V1
|
||||||
}),
|
}),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -292,8 +292,8 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
|
|||||||
|
|
||||||
fn build_palette_bytes() -> Vec<u8> {
|
fn build_palette_bytes() -> Vec<u8> {
|
||||||
let mut bytes =
|
let mut bytes =
|
||||||
Vec::with_capacity(GLYPH_BANK_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
|
Vec::with_capacity(GLYPH_BANK_MAX_PALETTE_COUNT_V1 * GLYPH_BANK_COLORS_PER_PALETTE * 4);
|
||||||
for palette_id in 0..GLYPH_BANK_PALETTE_COUNT_V1 {
|
for palette_id in 0..GLYPH_BANK_MAX_PALETTE_COUNT_V1 {
|
||||||
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
|
for color_index in 0..GLYPH_BANK_COLORS_PER_PALETTE {
|
||||||
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
|
let color = if color_index == 1 { stress_color(palette_id) } else { Color::BLACK };
|
||||||
bytes.extend_from_slice(&color.raw().to_be_bytes());
|
bytes.extend_from_slice(&color.raw().to_be_bytes());
|
||||||
|
|||||||
+10
-4
@@ -1,4 +1,6 @@
|
|||||||
{"type":"meta","next_id":{"DSC":45,"AGD":48,"DEC":41,"PLN":167,"LSN":55,"CLSN":1}}
|
{"type":"meta","next_id":{"DSC":51,"AGD":54,"DEC":45,"PLN":176,"LSN":59,"CLSN":1}}
|
||||||
|
{"type":"discussion","id":"DSC-0050","status":"done","ticket":"headless-automation-host-hardening","title":"AGD-0052 Hardening — Headless Automation Host and Deterministic Runtime Control","created_at":"2026-09-22","updated_at":"2026-09-23","tags":["runtime","host","headless","automation","deterministic","concurrency","testing"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0058","file":"discussion/lessons/DSC-0050-headless-automation-host-hardening/LSN-0058-deterministic-observation-must-follow-the-active-producer.md","status":"done","created_at":"2026-09-23","updated_at":"2026-09-23"}]}
|
||||||
|
{"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-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-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."}
|
{"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,11 +16,12 @@
|
|||||||
{"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-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-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-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-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-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-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-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-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"}]}
|
{"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"}]}
|
||||||
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-07-01","tags":["perf","asset","fs","async","scheduler","runtime"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0009-perf-async-background-work-lanes-for-assets-and-fs/LSN-0050-serial-async-lanes-bound-backlog-complexity.md","status":"done","created_at":"2026-07-01","updated_at":"2026-07-01"}]}
|
{"type":"discussion","id":"DSC-0009","status":"done","ticket":"perf-async-background-work-lanes-for-assets-and-fs","title":"Agenda - [PERF] Async Background Work Lanes for Assets and FS","created_at":"2026-03-27","updated_at":"2026-07-01","tags":["perf","asset","fs","async","scheduler","runtime"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0050","file":"discussion/lessons/DSC-0009-perf-async-background-work-lanes-for-assets-and-fs/LSN-0050-serial-async-lanes-bound-backlog-complexity.md","status":"done","created_at":"2026-07-01","updated_at":"2026-07-01"}]}
|
||||||
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"perf-host-desktop-frame-pacing-and-presentation","title":"Agenda - [PERF] Host Desktop Frame Pacing and Presentation","created_at":"2026-03-27","updated_at":"2026-04-20","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0010-perf-host-desktop-frame-pacing-and-presentation/LSN-0036-frame-publication-and-host-invalidation-must-be-separate.md","status":"done","created_at":"2026-04-20","updated_at":"2026-04-20"}]}
|
{"type":"discussion","id":"DSC-0010","status":"done","ticket":"perf-host-desktop-frame-pacing-and-presentation","title":"Agenda - [PERF] Host Desktop Frame Pacing and Presentation","created_at":"2026-03-27","updated_at":"2026-04-20","tags":[],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0036","file":"discussion/lessons/DSC-0010-perf-host-desktop-frame-pacing-and-presentation/LSN-0036-frame-publication-and-host-invalidation-must-be-separate.md","status":"done","created_at":"2026-04-20","updated_at":"2026-04-20"}]}
|
||||||
@@ -43,3 +46,6 @@
|
|||||||
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
{"type":"discussion","id":"DSC-0033","status":"done","ticket":"system-os-service-ownership-and-module-layout","title":"Agenda - SystemOS Service Ownership and Module Layout","created_at":"2026-05-14","updated_at":"2026-05-15","tags":["runtime","os","services","module-layout","vm","window-manager","logging"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0042","file":"discussion/lessons/DSC-0033-system-os-service-ownership-and-module-layout/LSN-0042-systemos-service-ownership-boundary.md","status":"done","created_at":"2026-05-15","updated_at":"2026-05-15"}]}
|
||||||
{"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-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-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-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"}]}
|
||||||
|
|||||||
+97
@@ -0,0 +1,97 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0055
|
||||||
|
ticket: runtime-owned-variable-glyph-bank-palette-protocol
|
||||||
|
title: Runtime-Owned Asset Protocols Must Align Payload, Residency, and Lookup
|
||||||
|
created: 2026-07-14
|
||||||
|
tags: [runtime, assets, glyph-bank, palette-serialization, protocol]
|
||||||
|
decision: DEC-0041
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The runtime changed the `GLYPH/indexed_v1` glyph-bank palette contract from a
|
||||||
|
fixed 64-palette payload and resident table to variable palette serialization
|
||||||
|
and variable resident palette storage.
|
||||||
|
|
||||||
|
The initiating pressure came from packer/studio: fixed RGBA8888 palette padding
|
||||||
|
made small glyph banks pay for `64 * 16 * 4` palette bytes even when they used
|
||||||
|
far fewer palettes. The important architectural point was that the runtime, not
|
||||||
|
the packer, had to decide the protocol. The packer can only emit payloads that
|
||||||
|
conform to the runtime contract once the runtime spec is published.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### Variable Glyph Bank Palette Protocol
|
||||||
|
|
||||||
|
**What:**
|
||||||
|
`palette_count` became the number of serialized palettes and the number of
|
||||||
|
resident palettes in the loaded `GlyphBank`. The valid range is `1..=64`.
|
||||||
|
`palette_id` remains a direct palette identity and is valid only when
|
||||||
|
`palette_id < palette_count` for the referenced resident bank.
|
||||||
|
|
||||||
|
**Why:**
|
||||||
|
Keeping serialized count variable while retaining a fixed 64-slot resident
|
||||||
|
table would preserve two meanings for palette capacity. The runtime would save
|
||||||
|
payload bytes but still carry a split contract between payload shape, resident
|
||||||
|
shape, and lookup validity. Making all three agree gives the runtime one
|
||||||
|
source of truth.
|
||||||
|
|
||||||
|
**Trade-offs:**
|
||||||
|
Palette validity is now bank-dependent. Scene and sprite composition must check
|
||||||
|
the referenced loaded bank instead of relying on a global `0..63` rule. This
|
||||||
|
adds validation work, but it prevents invalid references from silently becoming
|
||||||
|
transparent or default colors.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Let the runtime own runtime-facing asset protocols. Tooling can discover pain,
|
||||||
|
but the runtime spec must define effective metadata, payload shape, resident
|
||||||
|
shape, and failure semantics.
|
||||||
|
|
||||||
|
Make count fields material. A count such as `palette_count` should not describe
|
||||||
|
only what the producer authored or only what the payload happens to include. If
|
||||||
|
runtime lookup depends on it, the count must also define resident state and
|
||||||
|
validation boundaries.
|
||||||
|
|
||||||
|
Keep identity direct unless a real remapping problem exists. Sparse-to-dense
|
||||||
|
palette remapping was rejected because it would add a second identity layer
|
||||||
|
across scenes, sprites, packer output, and runtime lookup. V1 keeps palette id
|
||||||
|
`N` as palette slot `N` in the resident bank.
|
||||||
|
|
||||||
|
Separate transparent color from invalid lookup. RGBA alpha is valid color data.
|
||||||
|
An invalid palette reference must be observable as invalid; it must not be
|
||||||
|
collapsed into `Color::TRANSPARENT`.
|
||||||
|
|
||||||
|
Use residue scans after protocol migrations. Search for fixed byte formulas,
|
||||||
|
old constants, fixture helpers, and spec phrases. Legitimate hits should be
|
||||||
|
renamed as maximum-bound concepts, not left as accidental active contracts.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Partially variable specs are worse than fixed specs. The asset spec already had
|
||||||
|
variable size formulas in some places but still required `palette_count = 64`
|
||||||
|
elsewhere. That contradiction made it unclear which rule was canonical.
|
||||||
|
|
||||||
|
Resident data structures can preserve obsolete protocol assumptions after the
|
||||||
|
payload changes. A fixed array in `GlyphBank` would have kept the old model
|
||||||
|
alive even if decode accepted variable payloads.
|
||||||
|
|
||||||
|
Fallback rendering hides contract errors. Returning transparent for an invalid
|
||||||
|
palette id makes bad assets and bad scene references look like intentional
|
||||||
|
alpha, which is exactly the wrong failure mode for a runtime protocol.
|
||||||
|
|
||||||
|
Fixture generators are part of the contract surface. Stress cartridges and
|
||||||
|
test payload builders must express whether they are using a variable count or
|
||||||
|
the v1 maximum; otherwise they reintroduce fixed-padding assumptions.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Runtime-facing asset protocols should align payload size, resident memory,
|
||||||
|
and lookup validity.
|
||||||
|
- `palette_count` is effective runtime metadata, not producer commentary.
|
||||||
|
- Direct identity is simpler than remapping until a concrete remapping need
|
||||||
|
exists.
|
||||||
|
- Invalid palette references should fail explicitly; transparent remains a
|
||||||
|
valid RGBA color, not an error substitute.
|
||||||
|
- Protocol migrations need spec edits, code changes, fixture updates, and
|
||||||
|
residue scans in the same workflow.
|
||||||
+61
@@ -0,0 +1,61 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0056
|
||||||
|
ticket: corrigir-identificacao-formato-pbx
|
||||||
|
title: Runtime Artifact Identity Must Not Borrow Frontend Names
|
||||||
|
created: 2026-07-15
|
||||||
|
tags: [runtime, bytecode, pbx, frontend, format-boundary]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Prometeu accepts bytecode produced by multiple frontends. PBS is the base
|
||||||
|
frontend language, while PBX is the executable bytecode artifact consumed by the
|
||||||
|
runtime.
|
||||||
|
|
||||||
|
The runtime had inherited PBS terminology in the executable bytecode path,
|
||||||
|
including the serialized magic number, comments, tests, and VM loader checks.
|
||||||
|
That made one frontend appear to own the runtime executable format.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### PBX Executable Format Identity
|
||||||
|
|
||||||
|
**What:** PBX is the runtime executable bytecode format, and `PBX\0` is its only
|
||||||
|
valid magic number.
|
||||||
|
|
||||||
|
**Why:** Runtime artifact identity must be independent from any frontend that can
|
||||||
|
produce the artifact. Naming the executable format after PBS would make the
|
||||||
|
runtime boundary look language-specific.
|
||||||
|
|
||||||
|
**Trade-offs:** The correction intentionally rejects old PBS-prefixed executable
|
||||||
|
artifacts instead of carrying a compatibility alias. This keeps the format
|
||||||
|
contract singular, but requires stale generated fixtures to be regenerated or
|
||||||
|
updated.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
Put file-format identity in the module that serializes and deserializes the
|
||||||
|
format. Loaders and higher-level runtime code should call that boundary instead
|
||||||
|
of duplicating magic-number checks.
|
||||||
|
|
||||||
|
When renaming an artifact identity, update all fixture construction and generator
|
||||||
|
assertions in the same pass as production serialization. Mixed fixture identity
|
||||||
|
usually means tests are asserting historical spelling rather than current
|
||||||
|
contract.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
Do not globally erase frontend names. PBS remains correct when the subject is
|
||||||
|
the PBS language, stdlib, or frontend-facing API. It is wrong only when it names
|
||||||
|
the executable bytecode artifact.
|
||||||
|
|
||||||
|
Do not preserve old magic values just to make a rename feel less disruptive. If
|
||||||
|
there is no compatibility requirement for old artifacts, aliases keep the
|
||||||
|
incorrect model alive.
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Runtime artifact names should describe the runtime contract, not the compiler
|
||||||
|
or frontend that produced the artifact.
|
||||||
|
- Magic numbers are normative format identity, not cosmetic labels.
|
||||||
|
- Loader code should delegate file-format validation to the format owner.
|
||||||
+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.
|
||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
---
|
||||||
|
id: LSN-0058
|
||||||
|
ticket: headless-automation-host-hardening
|
||||||
|
title: Deterministic Observation Must Follow the Active Producer
|
||||||
|
created: 2026-09-23
|
||||||
|
tags: [runtime, host, headless, deterministic, rendering, testing, debugger]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
The first headless automation host appeared to synchronize frame capture with a
|
||||||
|
render worker: it started a worker, remembered the latest published frame id,
|
||||||
|
and spun for a bounded number of iterations after logical execution. Source
|
||||||
|
revalidation showed that this story did not match the running system. A Game
|
||||||
|
cartridge executes inside an active `VmSession`, and that session selected the
|
||||||
|
existing `LocalSynchronous` render consumer. The worker started on the global
|
||||||
|
fallback runtime never consumed the active session's submissions.
|
||||||
|
|
||||||
|
The visible frame was already published synchronously through the normal
|
||||||
|
platform sink. The spin was therefore redundant in successful runs and would
|
||||||
|
still have been incorrect for a future asynchronous path because it waited for
|
||||||
|
"any different frame" rather than the specific frame requested by automation.
|
||||||
|
|
||||||
|
## Key Decisions
|
||||||
|
|
||||||
|
### The Observation Contract Follows the Active Execution Owner
|
||||||
|
|
||||||
|
**What:** The headless host intentionally uses the active session's local
|
||||||
|
synchronous consumer and removes the unused global worker and bounded spin.
|
||||||
|
|
||||||
|
**Why:** Synchronization must be defined against the component that actually
|
||||||
|
produces the observed value. Waiting on an unrelated worker creates accidental
|
||||||
|
success and makes the architecture harder to reason about.
|
||||||
|
|
||||||
|
**Trade-offs:** The deterministic headless host does not exercise worker
|
||||||
|
concurrency on every cartridge run. Worker equivalence remains a separate
|
||||||
|
runtime conformance concern rather than part of each game's oracle.
|
||||||
|
|
||||||
|
### Completion Carries Exact Identity
|
||||||
|
|
||||||
|
**What:** Successful frame advancement retains the explicit
|
||||||
|
`{logical_frame_index, FrameId}` pair and capture validates that exact published
|
||||||
|
frame before cloning its `OwnedRgba8888Frame`.
|
||||||
|
|
||||||
|
**Why:** A generation change only proves that something was published. It does
|
||||||
|
not prove which logical operation produced it. Exact identity makes stale or
|
||||||
|
mis-associated observations detectable.
|
||||||
|
|
||||||
|
**Trade-offs:** Logical frame numbers and render frame ids remain separate
|
||||||
|
domains. Callers compare the explicit pair rather than assuming equality or a
|
||||||
|
fixed offset.
|
||||||
|
|
||||||
|
### A Tick Slice Must Be Smaller Than the Logical Budget
|
||||||
|
|
||||||
|
**What:** The runtime's per-firmware-tick execution slice is smaller than the
|
||||||
|
total logical-frame cycle budget. Headless advancement loops across slices
|
||||||
|
until the frame closes or a terminal outcome occurs.
|
||||||
|
|
||||||
|
**Why:** When both limits were equal, `BudgetExhausted` left zero remaining
|
||||||
|
logical budget, so another tick could not make progress. The documented
|
||||||
|
multi-tick contract existed only nominally. Separating the limits makes a tick
|
||||||
|
an implementation slice and keeps a logical frame as the automation unit.
|
||||||
|
|
||||||
|
**Trade-offs:** A computation-heavy logical frame can span several firmware
|
||||||
|
ticks. This is observable through deterministic tick counters but does not
|
||||||
|
change guest frame semantics.
|
||||||
|
|
||||||
|
### Debug Instruction Step Must Prime the Entry Call
|
||||||
|
|
||||||
|
**What:** The shared debugger instruction-step primitive prepares the VM entry
|
||||||
|
call when the call stack is empty before executing one instruction.
|
||||||
|
|
||||||
|
**Why:** Direct boot intentionally stops before the first game instruction. A
|
||||||
|
debug step at that point previously encountered the coroutine safepoint and
|
||||||
|
reported `FrameSync` as an unexpected panic instead of executing the first
|
||||||
|
instruction.
|
||||||
|
|
||||||
|
**Trade-offs:** Entry preparation remains shared runtime behavior. No
|
||||||
|
headless-specific VM branch is introduced.
|
||||||
|
|
||||||
|
## Patterns and Algorithms
|
||||||
|
|
||||||
|
### Deterministic Frame Advance
|
||||||
|
|
||||||
|
1. Record the current logical-frame index and latest canonical frame id.
|
||||||
|
2. Release pause and request the same one-frame stop used by debugger control.
|
||||||
|
3. Tick firmware while feeding the retained normalized `InputSignals`.
|
||||||
|
4. Continue through internal cycle-slice exhaustion.
|
||||||
|
5. Stop on exactly one logical-frame increment, structured fault, lifecycle
|
||||||
|
termination, or a typed host safety-limit error.
|
||||||
|
6. Clear the frame-step request and finish paused.
|
||||||
|
7. On success, require a new canonical frame and retain its exact identity with
|
||||||
|
the completed logical index.
|
||||||
|
|
||||||
|
### Deterministic Oracle Boundary
|
||||||
|
|
||||||
|
Include observations that describe simulated execution: logical frame and
|
||||||
|
frame identity, canonical pixels and layout, guest-visible state, structured
|
||||||
|
status/faults, and deterministic machine counters.
|
||||||
|
|
||||||
|
Exclude observations of the host running the simulation: wall time, CPU time,
|
||||||
|
thread scheduling, presentation cadence, worker timing, and host-only
|
||||||
|
identities.
|
||||||
|
|
||||||
|
## Pitfalls
|
||||||
|
|
||||||
|
- A worker created by a host may not own the active session being automated.
|
||||||
|
- Bounded spinning is neither an acknowledgement nor an identity check.
|
||||||
|
- "Latest changed" is weaker than "the requested frame was published."
|
||||||
|
- Equal slice and logical budgets can make multi-tick continuation impossible
|
||||||
|
even when the control loop appears to support it.
|
||||||
|
- A debug step from a pristine boot boundary must establish the same entry-call
|
||||||
|
precondition as normal execution.
|
||||||
|
- Human-readable fault summaries are useful diagnostics but are not a stable
|
||||||
|
automation interface; retain structured `CrashReport` values.
|
||||||
|
|
||||||
|
## References
|
||||||
|
|
||||||
|
- Decision: `DEC-0044` (Deterministic Headless Automation Host Contract)
|
||||||
|
- Prior lesson: `LSN-0057` (Deterministic Host Control Follows Logical Runtime Boundaries)
|
||||||
|
- Render worker lesson: `LSN-0049` (Render Workers Publish Frames, Hosts Present Them)
|
||||||
|
- Graphics contract: `docs/specs/runtime/04-gfx-peripheral.md`
|
||||||
|
- Debug contract: `docs/specs/runtime/10-debug-inspection-and-profiling.md`
|
||||||
|
- Portability and headless contract: `docs/specs/runtime/11-portability-and-cross-platform-execution.md`
|
||||||
|
|
||||||
|
## Takeaways
|
||||||
|
|
||||||
|
- Revalidate ownership and data flow from source before hardening a wait.
|
||||||
|
- Deterministic observation requires exact completion identity, not timing luck.
|
||||||
|
- Keep logical-frame control above internal execution slices.
|
||||||
|
- Use one production runtime path for interactive debugging and headless
|
||||||
|
automation; vary host transport and pacing, not machine semantics.
|
||||||
|
- Test infrastructure boundaries with counters and structured outcomes instead
|
||||||
|
of sleeps or log parsing.
|
||||||
@@ -83,4 +83,36 @@ Pode virar PR quando houver definição escrita de:
|
|||||||
- arquivos obrigatórios;
|
- arquivos obrigatórios;
|
||||||
- erros canônicos;
|
- erros canônicos;
|
||||||
- invariantes de segurança;
|
- 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
|
## 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;
|
- a superfície gerada é só `system.has_cart` (`Syscall::SystemHasCart`), com 1 retorno e capability `SYSTEM`;
|
||||||
- `SystemRunCart` ainda nao tem efeito real;
|
- o dispatch devolve `true` fixo, sem consultar cartucho e sem `status`;
|
||||||
- a agenda `009` resolve semantica funcional, mas nao fecha por si so a politica de fault do dominio.
|
- `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
|
## Dor
|
||||||
|
|
||||||
- sem uma agenda propria, `system` pode herdar fault semantics por acidente;
|
- `has_cart` pode permanecer um bool fixo e mascarar ausência, cartucho inválido ou consulta fora de autoridade;
|
||||||
- `run_cart` pode acabar consolidando `Panic` ou `Trap` onde deveria existir retorno operacional;
|
- uma futura operação de `system` pode herdar `Trap` ou `Panic` onde o contrato transversal pede `status`;
|
||||||
- a fronteira entre falha do app, falha do firmware e falha do runtime fica opaca.
|
- 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
|
## Hotspots Atuais
|
||||||
|
|
||||||
- [dispatch.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system/src/virtual_machine_runtime/dispatch.rs#L114)
|
- `crates/console/prometeu-hal/src/syscalls/domains/system.rs`
|
||||||
- [system.rs](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-hal/src/syscalls/domains/system.rs#L4)
|
- `crates/console/prometeu-system/src/services/vm_runtime/dispatch.rs` (`SystemHasCart` retorna `true`)
|
||||||
- [009-system-run-cart.md](/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/docs/runtime/agendas/009-system-run-cart.md)
|
- `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
|
## 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
|
## O Que Precisa Ser Definido
|
||||||
|
|
||||||
1. Queries simples.
|
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`.
|
2. Operações que não voltam para a userland.
|
||||||
Decidir como falhas operacionais de transicao devem ser expostas:
|
`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.
|
||||||
- `status`;
|
|
||||||
- `Trap`;
|
|
||||||
- `Panic`.
|
|
||||||
|
|
||||||
3. Relacao com firmware.
|
3. Relação com firmware e com o host.
|
||||||
Delimitar quando a falha pertence ao app, ao firmware ou ao runtime.
|
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
|
## Dependencias
|
||||||
|
|
||||||
- `../specs/16a-syscall-policies.md`
|
- `docs/specs/runtime/16a-syscall-policies.md`
|
||||||
- `009-system-run-cart.md`
|
- `LSN-0051` / `DSC-0004`
|
||||||
|
- `AGD-0052` / `DSC-0049`, apenas como consumidor da observação estruturada
|
||||||
|
|
||||||
## Critério de Saida Desta Agenda
|
## 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`;
|
- matriz de `status` / `Trap` / `Panic` para as operações userland que o domínio `system` mantém, começando por `has_cart`;
|
||||||
- politica de retorno/falha de `run_cart`;
|
- confirmação de que launch de cartucho permanece fora da ABI de convidado;
|
||||||
- relacao com firmware e crash surface.
|
- 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
|
## 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?
|
2. `next` retorna apenas `int` ou precisamos variantes (`u32`, `float`) no mesmo ciclo?
|
||||||
3. precisamos de clone/split de gerador no MVP?
|
3. precisamos de clone/split de gerador no MVP?
|
||||||
4. destruicao explicita deve ser obrigatoria para certificacao/custo ou opcional?
|
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
|
## Dependencias
|
||||||
|
|
||||||
- `../decisions/006-vm-owned-stateful-core-contract.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`
|
||||||
- `../virtual-machine/ISA_CORE.md`
|
- `docs/vm-arch/ISA_CORE.md`
|
||||||
- `../specs/16-host-abi-and-syscalls.md`
|
- `docs/specs/runtime/16-host-abi-and-syscalls.md`
|
||||||
- `../specs/16a-syscall-policies.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
|
## Fora de Escopo
|
||||||
|
|
||||||
- entropy nao deterministica como contrato base;
|
- entropia não determinística como contrato base;
|
||||||
- PRNGs multiplos no mesmo ciclo de fechamento;
|
- PRNGs múltiplos no mesmo ciclo de fechamento;
|
||||||
- APIs de colecoes stateful;
|
- APIs de coleções stateful;
|
||||||
- window/app model.
|
- 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
|
## 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;
|
- surface mínima de random VM-owned;
|
||||||
- contrato de determinismo/replay;
|
- contrato de determinismo: seed explícita, ausência de entropia implícita de host, reprodução da sequência;
|
||||||
- fault/status de random;
|
- 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.
|
||||||
|
|||||||
@@ -0,0 +1,208 @@
|
|||||||
|
---
|
||||||
|
id: AGD-0048
|
||||||
|
ticket: background-service-audio-execution
|
||||||
|
title: Agenda - Background Service and Audio Execution
|
||||||
|
status: open
|
||||||
|
created: 2026-07-05
|
||||||
|
resolved:
|
||||||
|
decision:
|
||||||
|
tags: [runtime, os, lifecycle, service, audio, background, architecture]
|
||||||
|
---
|
||||||
|
|
||||||
|
# Agenda - Background Service and Audio Execution
|
||||||
|
|
||||||
|
## Contexto
|
||||||
|
|
||||||
|
O runtime ja tem sinais claros de preparacao para multitarefa controlada:
|
||||||
|
|
||||||
|
- `TaskState::Background` existe como estado de tarefa;
|
||||||
|
- `VmSession` separa estado mutavel de VM por tarefa/processo;
|
||||||
|
- `SystemOS` e dono de lifecycle, task/process, VM sessions, filesystem,
|
||||||
|
memcard, windows e logging;
|
||||||
|
- a spec de eventos separa foreground ownership de execution eligibility;
|
||||||
|
- o contrato atual declara que execucao real em background fica fora do v1, mas
|
||||||
|
o modelo foi desenhado para permitir servicos ou processos de midia no futuro.
|
||||||
|
|
||||||
|
O caso motivador e:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Game foreground -> Home -> music player -> escolher musica -> voltar ao Game
|
||||||
|
```
|
||||||
|
|
||||||
|
Depois disso, o Game deve voltar ao foreground enquanto o player continua
|
||||||
|
executando e produzindo audio junto com audio do Game.
|
||||||
|
|
||||||
|
## Problema
|
||||||
|
|
||||||
|
Hoje o runtime preserva sessoes, mas nao tem contrato para uma sessao continuar
|
||||||
|
executando quando nao e foreground.
|
||||||
|
|
||||||
|
Os pontos atuais que bloqueiam o caso:
|
||||||
|
|
||||||
|
- `TaskKind` so distingue `Game` e `Shell`;
|
||||||
|
- `ProcessKind` so distingue `VmGame`, `VmShell` e `NativeShell`;
|
||||||
|
- `ProcessState` nao possui estado normativo de background-running;
|
||||||
|
- `GameRunningStep` ticka apenas o Game foreground;
|
||||||
|
- `ShellRunningStep` ticka apenas o Shell foreground;
|
||||||
|
- `HubHomeStep` nao ticka sessoes VM em background;
|
||||||
|
- `Audio` e `AudioMixer` usam vozes globais sem namespace por tarefa/sessao;
|
||||||
|
- cada logical frame chama `platform.audio_mut().clear_commands()`, o que torna
|
||||||
|
perigoso tickar dois produtores de audio no mesmo frame;
|
||||||
|
- pausa de lifecycle hoje emite `MasterPause`, afetando o mixer inteiro.
|
||||||
|
|
||||||
|
Sem uma decisao, background service pode virar apenas "tickar mais uma VM", mas
|
||||||
|
isso quebraria isolamento, audio, debugger, lifecycle e previsibilidade.
|
||||||
|
|
||||||
|
## Pontos Criticos
|
||||||
|
|
||||||
|
1. **Execution eligibility nao e foreground.**
|
||||||
|
O contrato atual ja separa os conceitos, mas a implementacao ainda so ticka o
|
||||||
|
owner foreground. Precisamos introduzir uma politica explicita de quem pode
|
||||||
|
executar em background.
|
||||||
|
|
||||||
|
2. **Servico nao e Shell escondido.**
|
||||||
|
Um music player pode ter UI de Shell para escolher musica, mas a reproducao
|
||||||
|
continua como servico quando a UI deixa o foreground. Fechar isso como
|
||||||
|
`Shell` em background confundiria janela, tarefa, sessao e servico.
|
||||||
|
|
||||||
|
3. **Audio precisa de origem.**
|
||||||
|
Hoje `voice_id` e global no mixer. Se Game e player usam `voice_id = 0`, um
|
||||||
|
sobrescreve o outro. Precisamos decidir se o mixer tera namespaces por
|
||||||
|
`AudioOwner`, se servicos terao pool dedicado, ou se o player nao usara a
|
||||||
|
mesma superficie `audio.*`.
|
||||||
|
|
||||||
|
4. **Pausa de Game nao pode pausar servico de midia.**
|
||||||
|
`MasterPause` global serve para o contrato atual de pausa/debug, mas nao
|
||||||
|
expressa "pausar Game audio e manter music player". Pausa precisa virar
|
||||||
|
escopo por origem ou politica de mixer.
|
||||||
|
|
||||||
|
5. **Servico precisa de lifecycle proprio.**
|
||||||
|
Deve existir contrato para start, foreground UI, background-running, stop,
|
||||||
|
crash, terminate, recurso negado, e talvez wake/resume de UI.
|
||||||
|
|
||||||
|
6. **Budget e determinismo precisam ser fechados.**
|
||||||
|
Se servicos rodam junto com Game, precisamos decidir cota por frame, ordem de
|
||||||
|
ticks, starvation, crash isolation, e se background service participa do
|
||||||
|
mesmo tempo deterministico da maquina.
|
||||||
|
|
||||||
|
7. **Sistema de apps precisa descobrir e lancar o player.**
|
||||||
|
Hoje Home lista Game cartridges e tem Shells nativos fixos. O caso de music
|
||||||
|
player exige decidir se ele e cartridge `System`, app instalado, Shell nativo,
|
||||||
|
ou novo perfil `Service`.
|
||||||
|
|
||||||
|
## Opcoes
|
||||||
|
|
||||||
|
### Opcao A - Background Service como novo tipo de processo/sessao
|
||||||
|
|
||||||
|
Criar contrato explicito para `Service`:
|
||||||
|
|
||||||
|
- `TaskKind::Service` ou entidade equivalente;
|
||||||
|
- `ProcessKind::VmService` / `NativeService`;
|
||||||
|
- execution eligibility independente de foreground;
|
||||||
|
- UI de controle opcional via Shell task associada ao servico;
|
||||||
|
- audio com origem por service/session;
|
||||||
|
- lifecycle proprio: start, background, foreground-control, stop, crash.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- modela diretamente music player e futuros servicos;
|
||||||
|
- preserva a separacao entre UI foreground e execucao;
|
||||||
|
- evita transformar Shell em "processo que tambem e daemon";
|
||||||
|
- facilita quotas, permissao e observabilidade.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- maior mudanca arquitetural;
|
||||||
|
- exige novo contrato em specs, SystemOS, firmware, audio e testes;
|
||||||
|
- precisa fechar politica de recursos antes de implementar.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- melhor base para crescer com qualidade, desde que o MVP seja pequeno.
|
||||||
|
|
||||||
|
### Opcao B - Shell em background com audio permitido
|
||||||
|
|
||||||
|
Permitir que uma VM Shell continue tickando quando sai do foreground e use audio
|
||||||
|
normalmente.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- reaproveita Shell, WindowManager e VM session existentes;
|
||||||
|
- menor numero de novos tipos no curto prazo.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- mistura UI e servico;
|
||||||
|
- torna `TaskState::Background` semantico antes de definir `ProcessState`;
|
||||||
|
- abre precedente para qualquer Shell continuar executando;
|
||||||
|
- nao resolve sozinho namespace de audio, pause por origem, quotas e debugging.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- atraente como atalho, mas tende a espalhar excecoes pela firmware state
|
||||||
|
machine.
|
||||||
|
|
||||||
|
### Opcao C - Audio player como servico nativo OS-owned, sem VM background
|
||||||
|
|
||||||
|
Implementar music player como servico nativo de SystemOS, controlado por uma
|
||||||
|
Shell UI. A reproducao continua no host/OS sem tickar VM em background.
|
||||||
|
|
||||||
|
**Pros:**
|
||||||
|
- entrega o caso de musica com menor risco para scheduler VM;
|
||||||
|
- evita abrir execucao arbitraria de background agora;
|
||||||
|
- audio service pode ser projetado como recurso OS-owned e depois exposto.
|
||||||
|
|
||||||
|
**Contras:**
|
||||||
|
- nao resolve background VM services em geral;
|
||||||
|
- player deixa de ser app userland completo no primeiro ciclo;
|
||||||
|
- precisa ainda fechar origem/mixagem de audio e relacao com UI.
|
||||||
|
|
||||||
|
**Manutencao:**
|
||||||
|
- bom MVP se o objetivo imediato for media playback, mas deve ser declarado como
|
||||||
|
`media service` nativo, nao como contrato geral de background VM.
|
||||||
|
|
||||||
|
## Sugestao / Recomendacao
|
||||||
|
|
||||||
|
Recomendo fechar em duas camadas:
|
||||||
|
|
||||||
|
1. **Decisao de arquitetura:** introduzir o conceito de service/background
|
||||||
|
execution como contrato de SystemOS, separado de foreground Shell e Game.
|
||||||
|
Essa decisao deve definir execution eligibility, lifecycle, quotas, crash
|
||||||
|
policy, controle de UI e relacao com VM sessions.
|
||||||
|
|
||||||
|
2. **MVP de media:** implementar primeiro um `media/audio service` com escopo
|
||||||
|
reduzido, preferencialmente OS-owned ou `Service` bem delimitado, antes de
|
||||||
|
permitir background VM arbitrario.
|
||||||
|
|
||||||
|
Para excelente qualidade, o primeiro plano nao deve tentar "qualquer app em
|
||||||
|
background". O alvo deve ser: um unico servico de audio/midia, com origem de
|
||||||
|
audio propria, controle por Hub/Shell, execucao enquanto Game esta foreground,
|
||||||
|
e testes end-to-end de mistura e lifecycle.
|
||||||
|
|
||||||
|
## Perguntas em Aberto
|
||||||
|
|
||||||
|
- O music player deve ser um cartridge `System`, um novo `Service`, ou um
|
||||||
|
servico nativo do OS controlado por Shell?
|
||||||
|
- A UI do player e a reproducao pertencem a mesma tarefa ou a tarefas
|
||||||
|
separadas?
|
||||||
|
- Um servico pode ter janela foreground temporaria e continuar sem janela?
|
||||||
|
- Quantos servicos background podem existir no MVP: um media service ou N
|
||||||
|
servicos?
|
||||||
|
- O background service recebe ticks todo frame, tick rate reduzido, ou apenas
|
||||||
|
eventos?
|
||||||
|
- O audio mixer deve isolar vozes por `TaskId`, `ProcessId`, `VmSessionId`,
|
||||||
|
`AppId`, ou novo `AudioOwner`?
|
||||||
|
- Como pausar apenas o audio do Game durante Home/debug sem pausar musica?
|
||||||
|
- O debugger inspeciona foreground session apenas ou tambem sessoes background?
|
||||||
|
- Como crash de servico e exibido: toast/log, janela de crash, ou parada
|
||||||
|
silenciosa com diagnostico?
|
||||||
|
- Que capacidades sao necessarias para media service: `audio`, `fs`, `asset`,
|
||||||
|
talvez `background_audio`?
|
||||||
|
|
||||||
|
## Criterio para Encerrar
|
||||||
|
|
||||||
|
Esta agenda pode virar decisao quando houver resposta escrita para:
|
||||||
|
|
||||||
|
- modelo de entidade (`Service` novo vs Shell background vs native OS service);
|
||||||
|
- execution eligibility e ordem de ticks;
|
||||||
|
- lifecycle e estados de task/process;
|
||||||
|
- ownership/namespace de audio e politica de pausa por origem;
|
||||||
|
- relacao entre UI foreground do player e reproducao background;
|
||||||
|
- escopo do MVP e explicitamente o que fica fora;
|
||||||
|
- testes obrigatorios de lifecycle, audio mixing, crash isolation e regressao do
|
||||||
|
contrato Game/Home/Shell existente.
|
||||||
|
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
---
|
||||||
|
id: AGD-0050
|
||||||
|
ticket: portable-host-backend-strategy
|
||||||
|
title: Portable Host Backend Strategy
|
||||||
|
status: open
|
||||||
|
created: 2026-07-14
|
||||||
|
resolved:
|
||||||
|
decision:
|
||||||
|
tags: [host, desktop, portable, sdl, backend, rendering, input, audio, linux, android, handheld]
|
||||||
|
---
|
||||||
|
|
||||||
|
## Contexto
|
||||||
|
|
||||||
|
O runtime ja tem uma fronteira de host relativamente clara: o host desktop atual vive em `crates/host/prometeu-host-desktop-winit`, usando `winit`, `pixels` e `cpal` para janela, apresentacao de framebuffer, input e audio.
|
||||||
|
|
||||||
|
A direcao desejada nao e substituir esse host de forma disruptiva no primeiro corte. A proposta e estudar e construir um segundo host portatil para servir como runtime host em handhelds e consoles portateis, especialmente hardwares chineses que rodam Linux internamente e, em alguns casos, Android customizado. O mesmo host tambem deve servir como base para uma futura versao DIY do hardware, desde que ela rode sobre um Linux base compatível. SDL e a hipotese principal, mas a agenda tambem deve avaliar outras familias de host/backend antes de virar decisao normativa.
|
||||||
|
|
||||||
|
Esse novo host deve conviver com o host atual durante estabilizacao, mas nao e descartavel: ele e candidato a se tornar o host principal quando provar paridade e estabilidade.
|
||||||
|
|
||||||
|
A troca deve ficar isolada no dominio de host: contratos de runtime, firmware, frame, input semantico e audio semantico nao devem mudar por causa da escolha de backend. Essa separacao e justamente o objetivo arquitetural que permite que um host portatil evolua para principal sem arrastar o runtime.
|
||||||
|
|
||||||
|
## Problema
|
||||||
|
|
||||||
|
Hoje a existencia de um unico host desktop torna dificil separar problemas do runtime de problemas do adaptador de plataforma. Um novo host portatil pode ajudar em testes, portabilidade, comparacao operacional e reducao de dependencia de uma pilha unica de janela/render/audio. O alvo "mobile" desta agenda nao significa telefone/tablet como produto primario; significa hardware portatil dedicado, geralmente com controles fisicos, framebuffer/display integrado, Linux customizado e distribuicao fora do modelo desktop tradicional. O alvo tambem inclui um possivel handheld DIY futuro, em que o valor esperado e ja existir um host pronto se o dispositivo expuser um Linux base suficiente.
|
||||||
|
|
||||||
|
O risco e tratar uma tecnologia especifica como resposta antes de comparar os requisitos reais de Linux handheld e Android. A agenda precisa cravar o modelo de host paralelo em estabilizacao, com destino de host principal, e entao escolher a familia de backend que melhor atende esse objetivo.
|
||||||
|
|
||||||
|
## Pontos Criticos
|
||||||
|
|
||||||
|
- A troca de host deve ser simples e local ao host, sem exigir mudancas em runtime, firmware, asset protocol, render packet, VM ou syscalls.
|
||||||
|
- O novo host precisa consumir as mesmas saidas canonicas do runtime: frames RGBA8888, comandos semanticos de audio e eventos de input normalizados.
|
||||||
|
- A estrategia deve preservar o host `winit` enquanto o novo host ainda nao provar equivalencia operacional, mas o novo host e candidato a virar o host principal depois dessa prova.
|
||||||
|
- O alvo primario e portabilidade operacional para handhelds Linux e consoles portateis com controles fisicos; Android customizado e um alvo possivel que deve influenciar a escolha de API, packaging e input/audio.
|
||||||
|
- O host portatil deve ser viavel em um futuro hardware DIY rodando Linux base, sem exigir um runtime especial ou fork de contratos.
|
||||||
|
- Testes devem distinguir contrato comum de host de detalhes especificos de backend.
|
||||||
|
- SDL2 pode ter ecossistema Rust mais estabelecido; SDL3 pode estar mais alinhado com a direcao upstream. A escolha da versao e uma pergunta separada da decisao de criar um segundo host.
|
||||||
|
- A arquitetura deve evitar duplicar logica de runtime loop, pacing, debugger, stats e presentation policy quando essa logica for comum a qualquer host.
|
||||||
|
- Outras familias de host tambem devem ser avaliadas: evoluir `winit`, SDL2/SDL3, backend Android nativo, ou uma camada multiplataforma alternativa.
|
||||||
|
|
||||||
|
## Opcoes
|
||||||
|
|
||||||
|
### Opcao A - Manter apenas o host winit atual
|
||||||
|
|
||||||
|
- **Abordagem:** continuar evoluindo `prometeu-host-desktop-winit` como unico host desktop.
|
||||||
|
- **Pro:** menor custo imediato; evita nova dependencia nativa.
|
||||||
|
- **Con:** mantem a pilha de plataforma unica como ponto de acoplamento pratico.
|
||||||
|
- **Tradeoff:** bom para estabilidade curta, fraco para provar independencia real do host.
|
||||||
|
|
||||||
|
### Opcao B - Migrar diretamente do host winit para outro backend
|
||||||
|
|
||||||
|
- **Abordagem:** substituir o host desktop atual por um novo backend portatil assim que a escolha tecnologica for feita.
|
||||||
|
- **Pro:** reduz a manutencao para um unico host depois da migracao.
|
||||||
|
- **Con:** aumenta risco de regressao e mistura decisao de backend com mudanca operacional.
|
||||||
|
- **Tradeoff:** so faz sentido depois de prova local de superioridade e paridade, o que ainda nao existe.
|
||||||
|
|
||||||
|
### Opcao C - Criar um host SDL paralelo com destino de principal
|
||||||
|
|
||||||
|
- **Abordagem:** adicionar um novo crate/binario de host SDL que implemente os mesmos contratos externos do host atual, mantendo `winit` como referencia e rollback ate haver evidencia de equivalencia.
|
||||||
|
- **Pro:** permite teste A/B, reduz risco, valida se a fronteira de host esta realmente limpa, atende a meta de handheld Linux/Android customizado/DIY e preserva caminho para tornar SDL o host principal.
|
||||||
|
- **Con:** aumenta temporariamente manutencao e exige fatorar partes comuns se houver duplicacao.
|
||||||
|
- **Tradeoff:** melhor caminho para chegar a um host principal portatil sem reabrir runtime.
|
||||||
|
|
||||||
|
### Opcao D - Evoluir winit/pixels/cpal como host portatil
|
||||||
|
|
||||||
|
- **Abordagem:** manter a familia atual e investir em configuracao, input, fullscreen, packaging e compatibilidade de Linux handheld/Android/DIY dentro dela.
|
||||||
|
- **Pro:** reaproveita o host existente e reduz dependencias nativas novas.
|
||||||
|
- **Con:** pode nao resolver os problemas praticos de distribuicao, gamepad/device handling, fullscreen/scaling, Android customizado e ambientes handheld.
|
||||||
|
- **Tradeoff:** forte se a pilha atual suportar bem os alvos; fraco se o problema real for portabilidade operacional.
|
||||||
|
|
||||||
|
### Opcao E - Host Android nativo separado
|
||||||
|
|
||||||
|
- **Abordagem:** tratar Linux handheld e Android como hosts diferentes: SDL ou winit para Linux; Android com camada nativa/propria quando o alvo amadurecer.
|
||||||
|
- **Pro:** permite respeitar o ciclo de vida, packaging, input e audio do Android sem contaminar o host Linux.
|
||||||
|
- **Con:** duplica mais superficie e adia a promessa de um host portatil unico.
|
||||||
|
- **Tradeoff:** bom se Android tiver requisitos proprios demais; ruim se SDL conseguir cobrir Android bem o bastante.
|
||||||
|
|
||||||
|
### Opcao F - Camada multiplataforma alternativa
|
||||||
|
|
||||||
|
- **Abordagem:** avaliar alternativas como uma camada Rust-first ou game-framework-level para janela, input, audio e render.
|
||||||
|
- **Pro:** pode reduzir FFI nativa e integrar melhor com Cargo.
|
||||||
|
- **Con:** pode ser menos madura para Linux handheld/Android real, packaging e controles.
|
||||||
|
- **Tradeoff:** deve ser considerada, mas precisa provar vantagem concreta sobre SDL para justificar risco.
|
||||||
|
|
||||||
|
## Sugestao / Recomendacao
|
||||||
|
|
||||||
|
Recomendacao inicial: manter a **Opcao C** como favorita, mas ampliar a fase de agenda para comparar SDL com as demais familias de host antes da decisao. O resultado desejado continua sendo um segundo host portatil, inicialmente paralelo, com destino explicito de se tornar o host principal quando atingir paridade e estabilidade.
|
||||||
|
|
||||||
|
O caminho recomendado e:
|
||||||
|
|
||||||
|
1. Definir o contrato minimo de equivalencia entre hosts: janela, framebuffer RGBA8888, input, audio, pacing, debugger/logs e encerramento.
|
||||||
|
2. Identificar o que e comum ao host e o que e backend especifico.
|
||||||
|
3. Comparar as familias candidatas contra esse contrato: SDL2, SDL3, winit atual evoluido, Android nativo separado e alternativas Rust-first.
|
||||||
|
4. Implementar o candidato escolhido como novo crate/binario sem remover `prometeu-host-desktop-winit`.
|
||||||
|
5. Permitir troca simples por binario/comando/feature, mantendo o runtime cego para a escolha.
|
||||||
|
6. Tratar handheld Linux como alvo primario de produto para esse host; tratar Android customizado e DIY Linux como restricoes de desenho quando afetarem backend, packaging, input, audio ou boot/runtime integration.
|
||||||
|
7. Promover o novo host a principal apenas depois de evidencia de estabilidade e paridade.
|
||||||
|
|
||||||
|
## Perguntas em Aberto
|
||||||
|
|
||||||
|
- [ ] A primeira implementacao SDL deve usar SDL2 ou SDL3?
|
||||||
|
- [ ] SDL deve ser a familia escolhida, ou winit evoluido, Android nativo separado ou outra camada oferece melhor caminho?
|
||||||
|
- [ ] A selecao do host deve ser por binario separado, feature Cargo, parametro CLI, ou combinacao desses mecanismos?
|
||||||
|
- [ ] Qual e o menor conjunto de comportamento que define paridade aceitavel com o host winit?
|
||||||
|
- [ ] Quais partes do host atual devem virar modulo comum antes do SDL, e quais devem ser duplicadas primeiro para evitar abstracao prematura?
|
||||||
|
- [ ] O host SDL deve reutilizar `cpal` para audio inicialmente ou usar audio SDL desde o primeiro corte?
|
||||||
|
- [ ] Quais familias de hardware handheld Linux devem ser usadas como referencia inicial?
|
||||||
|
- [ ] 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? 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
|
||||||
|
|
||||||
|
A agenda pode virar decision quando estiver claro:
|
||||||
|
|
||||||
|
- se o novo host sera paralelo em estabilizacao, com destino de host principal;
|
||||||
|
- qual familia de backend sera alvo inicial;
|
||||||
|
- se SDL for escolhido, qual versao SDL sera alvo inicial;
|
||||||
|
- como a selecao/troca de host deve funcionar;
|
||||||
|
- quais contratos sao comuns e proibidos de mudar;
|
||||||
|
- quais requisitos minimos de handheld Linux e possivel Android customizado entram no primeiro plano;
|
||||||
|
- qual contrato minimo de Linux base mantem aberta a opcao de hardware DIY;
|
||||||
|
- qual evidencia minima prova paridade suficiente para iniciar planos de implementacao.
|
||||||
|
|
||||||
|
## Discussion
|
||||||
|
|
||||||
|
Ponto inicial aceito pelo usuario: a intencao e ter um segundo host para testes, com troca simples e facil, aproveitando o trabalho ja feito para isolar essa troca no host sem envolver runtime ou outros dominios.
|
||||||
|
|
||||||
|
Atualizacao de escopo: o novo host nao e descartavel. O objetivo e servir como runtime host para sistemas Linux rodando em consoles portateis e hardwares handheld chineses, e possivelmente Android customizado. Assim que estiver estavel, ele deve poder virar o host principal.
|
||||||
|
|
||||||
|
Atualizacao de escopo: outras familias de host/backend tambem devem viver nesta agenda. SDL segue como hipotese forte, mas a decisao deve comparar opcoes antes de cravar a tecnologia.
|
||||||
|
|
||||||
|
Clarificacao: "mobile" nesta agenda nao se refere primariamente a telefone/tablet. O foco sao dispositivos portateis dedicados com Linux interno ou Android customizado, geralmente com controles fisicos e ambiente de distribuicao proprio.
|
||||||
|
|
||||||
|
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
|
||||||
@@ -75,7 +75,9 @@ palette, host presentation, or compatibility contract.
|
|||||||
|
|
||||||
### Published owned frame
|
### Published owned frame
|
||||||
|
|
||||||
The canonical worker-published frame value is `OwnedRgba8888Frame`.
|
The canonical published frame value is `OwnedRgba8888Frame`. It is produced by
|
||||||
|
either the local synchronous consumer or the asynchronous render worker; the
|
||||||
|
consumer path does not change the frame contract.
|
||||||
|
|
||||||
`OwnedRgba8888Frame` contains:
|
`OwnedRgba8888Frame` contains:
|
||||||
|
|
||||||
@@ -184,6 +186,13 @@ producer path MUST remain non-blocking with respect to worker rasterization and
|
|||||||
host present. A slow worker can cause replacement/drop telemetry, but it MUST
|
host present. A slow worker can cause replacement/drop telemetry, but it MUST
|
||||||
NOT create an unbounded queue or stall VM logical frame production.
|
NOT create an unbounded queue or stall VM logical frame production.
|
||||||
|
|
||||||
|
A local synchronous consumer consumes the same immutable `RenderSubmission`
|
||||||
|
through the same render backend and publishes the same canonical
|
||||||
|
`OwnedRgba8888Frame` before returning. It does not use the asynchronous
|
||||||
|
single-slot handoff and therefore does not weaken or reinterpret the worker's
|
||||||
|
non-blocking producer contract. A host may select this path when an explicit
|
||||||
|
synchronous observation boundary is part of its host contract.
|
||||||
|
|
||||||
### 4.4 Frame pacing
|
### 4.4 Frame pacing
|
||||||
|
|
||||||
Game logical frames are paced by the runtime frame scheduler, not by render
|
Game logical frames are paced by the runtime frame scheduler, not by render
|
||||||
@@ -625,7 +634,8 @@ Each tilemap cell contains:
|
|||||||
|
|
||||||
Runtime-facing validity rule for v1:
|
Runtime-facing validity rule for v1:
|
||||||
|
|
||||||
- `palette_id` values are valid only in the range `0..63`
|
- `palette_id` values are valid only when `palette_id < palette_count` for the
|
||||||
|
resolved resident glyph bank
|
||||||
|
|
||||||
#### Sprite
|
#### Sprite
|
||||||
|
|
||||||
@@ -640,7 +650,8 @@ Each sprite draw contains:
|
|||||||
|
|
||||||
Runtime-facing validity rule for v1:
|
Runtime-facing validity rule for v1:
|
||||||
|
|
||||||
- `palette_id` values are valid only in the range `0..63`
|
- `palette_id` values are valid only when `palette_id < palette_count` for the
|
||||||
|
referenced resident glyph bank
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -649,7 +660,7 @@ Runtime-facing validity rule for v1:
|
|||||||
The pipeline works like this:
|
The pipeline works like this:
|
||||||
|
|
||||||
1. Read indexed pixel from tile (value 0..15)
|
1. Read indexed pixel from tile (value 0..15)
|
||||||
2. Resolve:
|
2. Validate and resolve:
|
||||||
- real_color = palette[palette_id][index]
|
- real_color = palette[palette_id][index]
|
||||||
3. Apply:
|
3. Apply:
|
||||||
- flip
|
- flip
|
||||||
@@ -667,6 +678,9 @@ else:
|
|||||||
draw_or_blend(color)
|
draw_or_blend(color)
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The `palette_id` lookup above is valid only after the runtime has established
|
||||||
|
that the referenced resident glyph bank contains that palette.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 19.7. Organization of Tile Banks
|
### 19.7. Organization of Tile Banks
|
||||||
@@ -766,6 +780,8 @@ Rules:
|
|||||||
- missing glyph dependencies referenced by a resident scene are not a passive `status:int` case;
|
- missing glyph dependencies referenced by a resident scene are not a passive `status:int` case;
|
||||||
- if scene activation discovers that a layer dependency cannot be resolved to a committed glyph asset, the machine MUST fail fatally and emit a clear log;
|
- if scene activation discovers that a layer dependency cannot be resolved to a committed glyph asset, the machine MUST fail fatally and emit a clear log;
|
||||||
- if scene composition later discovers that a layer dependency can no longer be resolved, the machine MUST fail fatally and emit a clear log;
|
- if scene composition later discovers that a layer dependency can no longer be resolved, the machine MUST fail fatally and emit a clear log;
|
||||||
|
- if scene activation or composition discovers that a tile references `palette_id >= palette_count` for its resolved glyph bank, the machine MUST fail fatally and emit a clear log;
|
||||||
|
- invalid scene palette references are scene dependency failures and MUST NOT be rendered through transparent, black, or default color substitution;
|
||||||
- runtime MUST NOT continue canonical scene composition after such a dependency failure.
|
- runtime MUST NOT continue canonical scene composition after such a dependency failure.
|
||||||
|
|
||||||
### 20.2 `composer.emit_sprite`
|
### 20.2 `composer.emit_sprite`
|
||||||
@@ -774,7 +790,7 @@ Rules:
|
|||||||
|
|
||||||
ABI:
|
ABI:
|
||||||
1. `glyph_id: int` — glyph index within the bank
|
1. `glyph_id: int` — glyph index within the bank
|
||||||
2. `palette_id: int` — palette index
|
2. `palette_id: int` — palette index within the referenced bank; valid only when `palette_id < palette_count` for that resident glyph bank
|
||||||
3. `x: int` — x coordinate
|
3. `x: int` — x coordinate
|
||||||
4. `y: int` — y coordinate
|
4. `y: int` — y coordinate
|
||||||
5. `layer: int` — composition layer reference
|
5. `layer: int` — composition layer reference
|
||||||
@@ -797,4 +813,6 @@ Operational notes:
|
|||||||
- the canonical public sprite contract is frame-emission based;
|
- the canonical public sprite contract is frame-emission based;
|
||||||
- no caller-provided sprite index exists in the v1 canonical ABI;
|
- no caller-provided sprite index exists in the v1 canonical ABI;
|
||||||
- no `active` flag exists in the v1 canonical ABI;
|
- no `active` flag exists in the v1 canonical ABI;
|
||||||
|
- `palette_id >= palette_count` for the referenced glyph bank MUST return `BANK_INVALID`;
|
||||||
|
- invalid sprite palette references MUST NOT be rendered through transparent, black, or default color substitution;
|
||||||
- overflow remains non-fatal and must not escalate to trap in v1.
|
- overflow remains non-fatal and must not escalate to trap in v1.
|
||||||
|
|||||||
@@ -81,6 +81,25 @@ When the host activates instruction-level inspection, it may observe:
|
|||||||
- operand stack
|
- operand stack
|
||||||
- call stack
|
- call stack
|
||||||
|
|
||||||
|
### 3.3 Debugger and Headless Semantic Alignment
|
||||||
|
|
||||||
|
Interactive debugging and deterministic headless automation share runtime
|
||||||
|
meanings even though their transports and pacing differ:
|
||||||
|
|
||||||
|
| Runtime meaning | Debugger command/observation | Headless operation |
|
||||||
|
| --- | --- | --- |
|
||||||
|
| Pause active VM execution | `pause` | `pause()` |
|
||||||
|
| Resume active VM execution | `resume` | `resume()` |
|
||||||
|
| Execute one VM instruction and remain paused | `step` | `step()` |
|
||||||
|
| Complete one logical frame and remain paused | `stepFrame` | `advance_frame()` |
|
||||||
|
| Read overlapping execution state | `getState` | `get_state()` |
|
||||||
|
| Observe structured current fault | event/current state | `get_fault()` |
|
||||||
|
| Inject normalized input | not defined by the debugger protocol | `set_input()` |
|
||||||
|
| Reset the machine execution | not defined by the debugger protocol | `reset()` |
|
||||||
|
| Capture the canonical published frame | not defined by the debugger protocol | `capture_frame()` |
|
||||||
|
|
||||||
|
The headless API does not define or extend an external automation protocol.
|
||||||
|
|
||||||
## 4 State Inspection Boundary
|
## 4 State Inspection Boundary
|
||||||
|
|
||||||
Detailed state inspection is a host-owned concern. The runtime may expose deterministic machine state to host tooling, but this chapter does not define a general guest ABI for introspection convenience.
|
Detailed state inspection is a host-owned concern. The runtime may expose deterministic machine state to host tooling, but this chapter does not define a general guest ABI for introspection convenience.
|
||||||
|
|||||||
@@ -118,8 +118,8 @@ Hardware differences:
|
|||||||
The graphics system:
|
The graphics system:
|
||||||
|
|
||||||
- produces typed logical render submissions that render to RGBA8888 output
|
- produces typed logical render submissions that render to RGBA8888 output
|
||||||
- may consume Game submissions through a render worker that publishes owned
|
- consumes Game submissions through either a local synchronous consumer or a
|
||||||
`OwnedRgba8888Frame` values
|
render worker, both of which publish owned `OwnedRgba8888Frame` values
|
||||||
- uses an indexed palette
|
- uses an indexed palette
|
||||||
- does not depend on a specific GPU
|
- does not depend on a specific GPU
|
||||||
|
|
||||||
@@ -128,8 +128,8 @@ The platform layer:
|
|||||||
- exposes typed service facades for render submission, render backend
|
- exposes typed service facades for render submission, render backend
|
||||||
execution, Game 2D composition, input, audio, assets, and telemetry
|
execution, Game 2D composition, input, audio, assets, and telemetry
|
||||||
- consumes closed render submissions through a render-surface implementation
|
- consumes closed render submissions through a render-surface implementation
|
||||||
- transports published RGBA8888 output or worker-published
|
- transports published `OwnedRgba8888Frame` pixels into a host presentation
|
||||||
`OwnedRgba8888Frame` pixels into a host presentation surface without
|
surface without
|
||||||
injecting host-owned debug overlay pixels
|
injecting host-owned debug overlay pixels
|
||||||
- is the runtime-facing portability boundary; runtime and firmware code must not
|
- is the runtime-facing portability boundary; runtime and firmware code must not
|
||||||
depend on a monolithic hardware bridge or on a concrete hardware aggregate
|
depend on a monolithic hardware bridge or on a concrete hardware aggregate
|
||||||
@@ -216,3 +216,72 @@ PROMETEU promises:
|
|||||||
|
|
||||||
- **identical logical behavior**
|
- **identical logical behavior**
|
||||||
- **reproducible technical decisions**
|
- **reproducible technical decisions**
|
||||||
|
|
||||||
|
## 13 Deterministic Headless Control
|
||||||
|
|
||||||
|
The headless host is a separate, generic Prometeu host for in-process
|
||||||
|
automation. It runs the same directory cartridge, firmware, active VM session,
|
||||||
|
capability checks, normalized input, render submissions, and fault model as an
|
||||||
|
interactive host. A cartridge cannot detect or request headless execution, and
|
||||||
|
headless execution grants no additional guest capability.
|
||||||
|
|
||||||
|
The headless host requires no native window, display server, physical input,
|
||||||
|
physical audio device, or realtime frame pacing. It uses the explicit local
|
||||||
|
synchronous Game render consumer. A successful logical-frame advance returns
|
||||||
|
only after the exact canonical `OwnedRgba8888Frame` for that advance has been
|
||||||
|
published. It does not start or wait for an asynchronous render worker, and
|
||||||
|
publication correctness does not use spinning, yielding, sleeping, or a
|
||||||
|
wall-clock timeout.
|
||||||
|
|
||||||
|
### 13.1 Control contract
|
||||||
|
|
||||||
|
- `boot(path)` loads a normal directory cartridge and stops on entry to
|
||||||
|
`GameRunning`, before the first game instruction. A second boot attempt
|
||||||
|
requires `reset()` and otherwise returns `AlreadyBooted`.
|
||||||
|
- `reset()` enters the normal firmware reset boundary and clears input, active
|
||||||
|
sessions, structured faults, and headless frame correlation. Capture is
|
||||||
|
unavailable until the new run completes a frame.
|
||||||
|
- `pause()` and `resume()` control the active VM session. `step()` executes one
|
||||||
|
VM instruction and finishes paused without reporting a completed logical
|
||||||
|
frame.
|
||||||
|
- `set_input()` retains one complete `InputSignals` snapshot, including the
|
||||||
|
digital pad and touch signal/coordinates. `clear_input()` restores its
|
||||||
|
default. The normal begin-frame input sampling defined by the input
|
||||||
|
peripheral derives `pressed`, `released`, `down`, and `hold` state.
|
||||||
|
- `advance_frame()` advances internal firmware ticks until exactly one logical
|
||||||
|
frame closes through `FrameSync` or `EndOfRom`, or until a structured fault or
|
||||||
|
lifecycle termination prevents completion. Internal cycle-slice exhaustion
|
||||||
|
continues the same frame; it is not itself a frame boundary.
|
||||||
|
- `advance_frames(n)` is repeated `advance_frame()`. It reports the requested
|
||||||
|
and completed counts plus completed-all, fault, or termination. Zero is a
|
||||||
|
no-op; fault or termination preserves partial completed progress.
|
||||||
|
- A frame advance finishes paused. Guest faults are outcomes represented by
|
||||||
|
`CrashReport`; host precondition, publication, and safety-limit failures are
|
||||||
|
host errors.
|
||||||
|
- `capture_frame()` returns an owned clone of the canonical frame paired with
|
||||||
|
the latest successful advance. The explicit `{logical_frame_index, FrameId}`
|
||||||
|
pair is authoritative; no numeric equality or fixed offset is implied.
|
||||||
|
- `get_state()` classifies execution as running, paused, terminated, or faulted
|
||||||
|
and exposes the overlapping debugger state. `get_fault()` returns structured
|
||||||
|
`CrashReport` data rather than requiring log or summary parsing.
|
||||||
|
- Valid audio commands pass through normal runtime semantics. The headless host
|
||||||
|
drains them into a null/discard sink; it does not synthesize PCM or require an
|
||||||
|
output device.
|
||||||
|
|
||||||
|
### 13.2 Deterministic oracle
|
||||||
|
|
||||||
|
Deterministic comparison includes the logical-frame index and paired `FrameId`,
|
||||||
|
canonical framebuffer pixels (or a stable pixel hash) and dimensions/stride,
|
||||||
|
guest-visible PC/stack/app state, structured execution status and fault data,
|
||||||
|
and deterministic counters describing simulated execution.
|
||||||
|
|
||||||
|
The oracle excludes wall-clock or boot-time timestamps, real elapsed duration,
|
||||||
|
host CPU time, thread-scheduling measurements, presentation cadence,
|
||||||
|
render-worker timing telemetry, and host-owned identities without simulated
|
||||||
|
machine meaning. The same cartridge, initial machine state, and per-frame input
|
||||||
|
timeline must produce the same included observations on independent runs and
|
||||||
|
after reset.
|
||||||
|
|
||||||
|
AI tooling may consume this generic host API from outside the machine. It does
|
||||||
|
not create an AI mode, testing mode, replay protocol, gameplay introspection
|
||||||
|
surface, or guest capability.
|
||||||
|
|||||||
@@ -115,7 +115,7 @@ For `BankType::GLYPH`, the v1 runtime-facing contract is:
|
|||||||
- `codec = NONE`
|
- `codec = NONE`
|
||||||
- serialized pixels use packed `u4` palette indices
|
- serialized pixels use packed `u4` palette indices
|
||||||
- serialized palettes use `RGBA8888` with canonical RGBA channel order
|
- serialized palettes use `RGBA8888` with canonical RGBA channel order
|
||||||
- `palette_count = 64`
|
- `palette_count` is the number of serialized and resident palettes and must be in `1..=64`
|
||||||
- runtime materialization may expand pixel indices to one `u8` per pixel
|
- runtime materialization may expand pixel indices to one `u8` per pixel
|
||||||
|
|
||||||
For `GLYPH`, `NONE` means there is no additional generic codec layer beyond the bank contract itself.
|
For `GLYPH`, `NONE` means there is no additional generic codec layer beyond the bank contract itself.
|
||||||
@@ -136,7 +136,7 @@ Required effective metadata fields for `GLYPH` at the root level:
|
|||||||
- `tile_size`: tile edge in pixels; valid values are `8`, `16`, or `32`
|
- `tile_size`: tile edge in pixels; valid values are `8`, `16`, or `32`
|
||||||
- `width`: total sheet width in pixels
|
- `width`: total sheet width in pixels
|
||||||
- `height`: total sheet height in pixels
|
- `height`: total sheet height in pixels
|
||||||
- `palette_count`: number of serialized palettes for the bank
|
- `palette_count`: number of serialized palettes and resident runtime palettes for the bank
|
||||||
|
|
||||||
Optional informative subtrees:
|
Optional informative subtrees:
|
||||||
|
|
||||||
@@ -145,7 +145,7 @@ Optional informative subtrees:
|
|||||||
|
|
||||||
Validation rules for `GLYPH` v1:
|
Validation rules for `GLYPH` v1:
|
||||||
|
|
||||||
- `palette_count` must be `64`
|
- `palette_count` must be in the inclusive range `1..=64`
|
||||||
- `width * height` defines the number of logical indexed pixels in the decoded sheet
|
- `width * height` defines the number of logical indexed pixels in the decoded sheet
|
||||||
- extra metadata may exist, but the runtime contract must not depend on it to reconstruct the in-memory bank unless that data is defined at the root as an effective field.
|
- extra metadata may exist, but the runtime contract must not depend on it to reconstruct the in-memory bank unless that data is defined at the root as an effective field.
|
||||||
|
|
||||||
@@ -158,7 +158,16 @@ The tile-bank payload therefore separates serialized storage form from runtime m
|
|||||||
|
|
||||||
- serialized pixel plane: packed `4bpp`
|
- serialized pixel plane: packed `4bpp`
|
||||||
- decoded pixel plane: expanded `u8` indices, one entry per pixel
|
- decoded pixel plane: expanded `u8` indices, one entry per pixel
|
||||||
- palette table: `64 * 16` colors in RGBA8888 channel order
|
- palette table: `palette_count * 16` colors in RGBA8888 channel order
|
||||||
|
|
||||||
|
For `GLYPH` v1:
|
||||||
|
|
||||||
|
```text
|
||||||
|
serialized_pixel_bytes = ceil(width * height / 2)
|
||||||
|
palette_bytes = palette_count * 16 * 4
|
||||||
|
size = serialized_pixel_bytes + palette_bytes
|
||||||
|
decoded_size = (width * height) + palette_bytes
|
||||||
|
```
|
||||||
|
|
||||||
For `GLYPH` v1:
|
For `GLYPH` v1:
|
||||||
|
|
||||||
@@ -172,6 +181,11 @@ before they are loaded by the runtime.
|
|||||||
Palette indices are ordinary indices. Transparency is represented by the alpha
|
Palette indices are ordinary indices. Transparency is represented by the alpha
|
||||||
channel of the resolved RGBA8888 palette entry, not by reserving index `0`.
|
channel of the resolved RGBA8888 palette entry, not by reserving index `0`.
|
||||||
|
|
||||||
|
`palette_id` is valid only when it is lower than the referenced resident glyph
|
||||||
|
bank's `palette_count`. Canonical runtime composition MUST NOT substitute
|
||||||
|
transparent, black, or any other default color for `palette_id >=
|
||||||
|
palette_count`.
|
||||||
|
|
||||||
### 4.2 `SCENE` asset contract in v1
|
### 4.2 `SCENE` asset contract in v1
|
||||||
|
|
||||||
For `BankType::SCENE`, the v1 runtime-facing contract is:
|
For `BankType::SCENE`, the v1 runtime-facing contract is:
|
||||||
|
|||||||
@@ -65,6 +65,12 @@ dedicated `System` profile ABI and stdlib/framework.
|
|||||||
|
|
||||||
## 3 Syscall Resolution
|
## 3 Syscall Resolution
|
||||||
|
|
||||||
|
PBX, Prometeu Bytecode Executable, is the runtime executable bytecode format.
|
||||||
|
Its canonical file magic is `PBX\0`. The former PBS-prefixed magic is not valid
|
||||||
|
for PBX artifacts: PBS names a frontend language, while PBX names the executable
|
||||||
|
artifact accepted by the runtime. This distinction is required because Prometeu
|
||||||
|
bytecode can be produced by multiple frontends.
|
||||||
|
|
||||||
The host maintains a registry:
|
The host maintains a registry:
|
||||||
|
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -50,6 +50,12 @@
|
|||||||
"paths": [
|
"paths": [
|
||||||
"crates/host/prometeu-host-desktop-winit/src/"
|
"crates/host/prometeu-host-desktop-winit/src/"
|
||||||
]
|
]
|
||||||
|
},
|
||||||
|
"host/headless": {
|
||||||
|
"baseline_percent": 80,
|
||||||
|
"paths": [
|
||||||
|
"crates/host/prometeu-host-headless/src/"
|
||||||
|
]
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user