Compare commits
7
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6ef376763c
|
||
|
|
f50a3f127f
|
||
|
|
f0f3f972ce
|
||
|
|
b2d2533acb
|
||
|
|
4b499288e2
|
||
|
|
aa3b31deb5 | ||
|
|
f784ccd774
|
@@ -19,6 +19,6 @@ pub use assembler::{assemble, AsmError};
|
||||
pub use decoder::{decode_next, DecodeError};
|
||||
pub use disassembler::disassemble;
|
||||
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 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_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.).
|
||||
/// All multi-module programs must be flattened and linked by the compiler
|
||||
/// before being serialized into this format.
|
||||
@@ -126,8 +128,8 @@ impl BytecodeModule {
|
||||
final_sections.push((SECTION_KIND_SYSCALLS, syscall_data));
|
||||
|
||||
let mut out = Vec::new();
|
||||
// Magic "PBS\0"
|
||||
out.extend_from_slice(b"PBS\0");
|
||||
// Magic "PBX\0"
|
||||
out.extend_from_slice(&PBX_MAGIC);
|
||||
// Version 0
|
||||
out.extend_from_slice(&0u16.to_le_bytes());
|
||||
// Endianness 0 (Little Endian), Reserved
|
||||
@@ -272,8 +274,8 @@ impl BytecodeLoader {
|
||||
return Err(LoadError::UnexpectedEof);
|
||||
}
|
||||
|
||||
// Magic "PBS\0"
|
||||
if &bytes[0..4] != b"PBS\0" {
|
||||
// Magic "PBX\0"
|
||||
if bytes[0..4] != PBX_MAGIC[..] {
|
||||
return Err(LoadError::InvalidMagic);
|
||||
}
|
||||
|
||||
@@ -708,7 +710,7 @@ mod tests {
|
||||
|
||||
fn create_header(section_count: u32) -> Vec<u8> {
|
||||
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[6] = 0; // endianness
|
||||
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 offset = 32 + (sections.len() as u32 * 12);
|
||||
|
||||
@@ -748,7 +750,7 @@ mod tests {
|
||||
#[test]
|
||||
fn test_invalid_magic() {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -897,7 +899,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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));
|
||||
}
|
||||
@@ -914,7 +916,7 @@ mod tests {
|
||||
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));
|
||||
}
|
||||
|
||||
@@ -4,7 +4,7 @@ use crate::value::Value;
|
||||
use std::collections::HashMap;
|
||||
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
|
||||
/// produced by the compiler. All linking, relocation, and symbol resolution
|
||||
|
||||
@@ -625,9 +625,8 @@ impl AssetManager {
|
||||
let serialized_size = serialized_pixel_bytes
|
||||
.checked_add(palette_bytes)
|
||||
.ok_or("GlyphBank serialized size overflow")?;
|
||||
let decoded_size = logical_pixels
|
||||
.checked_add(palette_bytes)
|
||||
.ok_or("GlyphBank decoded size overflow")?;
|
||||
let decoded_size =
|
||||
logical_pixels.checked_add(palette_bytes).ok_or("GlyphBank decoded size overflow")?;
|
||||
|
||||
if entry.size != serialized_size as u64 {
|
||||
return Err(format!(
|
||||
@@ -1213,11 +1212,9 @@ impl AssetManager {
|
||||
let logical_pixels = width * height;
|
||||
let packed_pixels = &buffer[0..packed_pixel_bytes];
|
||||
let pixel_indices = Self::unpack_glyph_bank_pixels(packed_pixels, logical_pixels);
|
||||
let palette_data =
|
||||
&buffer[packed_pixel_bytes..packed_pixel_bytes + palette_bytes];
|
||||
let palette_data = &buffer[packed_pixel_bytes..packed_pixel_bytes + palette_bytes];
|
||||
|
||||
let mut palettes =
|
||||
vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||
for (c, slot) in pal.iter_mut().enumerate() {
|
||||
let offset = (p * 16 + c) * 4;
|
||||
@@ -1252,8 +1249,7 @@ impl AssetManager {
|
||||
.read_exact(&mut palette_data)
|
||||
.map_err(|_| "Buffer too small for GLYPHBANK".to_string())?;
|
||||
|
||||
let mut palettes =
|
||||
vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||
let mut palettes = vec![[Color::BLACK; GLYPH_BANK_COLORS_PER_PALETTE]; palette_count];
|
||||
for (p, pal) in palettes.iter_mut().enumerate() {
|
||||
for (c, slot) in pal.iter_mut().enumerate() {
|
||||
let offset = (p * 16 + c) * 4;
|
||||
@@ -1903,10 +1899,7 @@ mod tests {
|
||||
|
||||
fn test_glyph_asset_data_with_palette_count(palette_count: usize) -> Vec<u8> {
|
||||
let mut data = vec![0x11u8; 128];
|
||||
data.extend_from_slice(&vec![
|
||||
0u8;
|
||||
palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE
|
||||
]);
|
||||
data.extend_from_slice(&vec![0u8; palette_count * GLYPH_BANK_PALETTE_BYTES_PER_PALETTE]);
|
||||
data
|
||||
}
|
||||
|
||||
@@ -2109,8 +2102,8 @@ mod tests {
|
||||
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");
|
||||
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);
|
||||
@@ -2120,10 +2113,8 @@ mod tests {
|
||||
#[test]
|
||||
fn test_decode_glyph_bank_rejects_short_packed_buffer() {
|
||||
let entry = test_glyph_asset_entry("glyphs", 16, 16);
|
||||
let data = vec![
|
||||
0u8;
|
||||
expected_glyph_payload_size(16, 16, GLYPH_BANK_MAX_PALETTE_COUNT_V1) - 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) {
|
||||
Ok(_) => panic!("glyph decode should reject short buffer"),
|
||||
|
||||
@@ -142,10 +142,7 @@ fn test_glyph_asset_entry(asset_name: &str, data_len: usize) -> AssetEntry {
|
||||
|
||||
fn test_glyph_asset_data() -> Vec<u8> {
|
||||
let mut data =
|
||||
vec![
|
||||
0x11u8;
|
||||
test_glyph_payload_size(16, 16) - (GLYPH_BANK_MAX_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_MAX_PALETTE_COUNT_V1 * 16 * 4]);
|
||||
data
|
||||
}
|
||||
|
||||
@@ -2627,7 +2627,7 @@ mod tests {
|
||||
fn test_loader_hardening_unsupported_version() {
|
||||
let mut vm = VirtualMachine::default();
|
||||
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)
|
||||
|
||||
let res = vm.initialize(header);
|
||||
@@ -2635,16 +2635,16 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_loader_hardening_malformed_pbs_v0() {
|
||||
fn test_loader_hardening_malformed_pbx_v0() {
|
||||
let mut vm = VirtualMachine::default();
|
||||
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
|
||||
|
||||
let res = vm.initialize(header);
|
||||
match res {
|
||||
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.program.rom.len(), 2);
|
||||
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]
|
||||
@@ -3084,7 +3091,7 @@ mod tests {
|
||||
fn test_loader_hardening_missing_sysc_section() {
|
||||
let mut vm = VirtualMachine::default();
|
||||
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);
|
||||
|
||||
|
||||
@@ -83,30 +83,32 @@ impl VirtualMachine {
|
||||
self.scheduler = Scheduler::new();
|
||||
self.current_coro = None;
|
||||
|
||||
let program = if program_bytes.starts_with(b"PBS\0") {
|
||||
match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
||||
Ok(mut module) => {
|
||||
patch_module_hostcalls(&mut module, self.capabilities)
|
||||
.map_err(VmInitError::LoaderPatchFailed)?;
|
||||
let program = match prometeu_bytecode::BytecodeLoader::load(&program_bytes) {
|
||||
Ok(mut module) => {
|
||||
patch_module_hostcalls(&mut module, self.capabilities)
|
||||
.map_err(VmInitError::LoaderPatchFailed)?;
|
||||
|
||||
let max_stacks = Verifier::verify(&module.code, &module.functions)
|
||||
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
|
||||
let max_stacks = Verifier::verify(&module.code, &module.functions)
|
||||
.map_err(|e| VmInitError::VerificationFailed(format!("{:?}", e)))?;
|
||||
|
||||
let mut program = ProgramImage::from(module);
|
||||
let mut functions = program.functions.as_ref().to_vec();
|
||||
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
|
||||
func.max_stack_slots = max_stack;
|
||||
}
|
||||
program.functions = std::sync::Arc::from(functions);
|
||||
program
|
||||
let mut program = ProgramImage::from(module);
|
||||
let mut functions = program.functions.as_ref().to_vec();
|
||||
for (func, max_stack) in functions.iter_mut().zip(max_stacks) {
|
||||
func.max_stack_slots = max_stack;
|
||||
}
|
||||
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
||||
return Err(VmInitError::UnsupportedFormat);
|
||||
}
|
||||
Err(e) => return Err(VmInitError::ImageLoadFailed(e)),
|
||||
program.functions = std::sync::Arc::from(functions);
|
||||
program
|
||||
}
|
||||
} else {
|
||||
return Err(VmInitError::InvalidFormat);
|
||||
Err(prometeu_bytecode::LoadError::InvalidVersion) => {
|
||||
return Err(VmInitError::UnsupportedFormat);
|
||||
}
|
||||
Err(prometeu_bytecode::LoadError::InvalidMagic) => {
|
||||
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
|
||||
|
||||
@@ -2,8 +2,8 @@ use prometeu_vm::{VirtualMachine, VmInitError};
|
||||
|
||||
#[test]
|
||||
fn invalid_image_format_is_rejected_before_execution() {
|
||||
// Provide bytes that are not a valid PBS image. The VM must reject it with InvalidFormat.
|
||||
let program_bytes = b"NOT_PBS_IMAGE".to_vec();
|
||||
// Provide bytes that are not a valid PBX image. The VM must reject it with InvalidFormat.
|
||||
let program_bytes = b"NOT_PBX_IMAGE".to_vec();
|
||||
let mut vm = VirtualMachine::default();
|
||||
let result = vm.initialize(program_bytes);
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -130,7 +130,7 @@ mod tests {
|
||||
fn generated_program_is_pbx_module_with_expected_syscalls() {
|
||||
let bytes = build_program();
|
||||
|
||||
assert!(bytes.starts_with(b"PBS\0"));
|
||||
assert!(bytes.starts_with(&prometeu_bytecode::PBX_MAGIC));
|
||||
assert!(bytes.len() > 64);
|
||||
}
|
||||
|
||||
|
||||
@@ -275,8 +275,7 @@ fn build_glyph_asset() -> (AssetEntry, Vec<u8>) {
|
||||
bank_type: BankType::GLYPH,
|
||||
offset: 0,
|
||||
size: payload.len() as u64,
|
||||
decoded_size: (8 * 8
|
||||
+ GLYPH_BANK_MAX_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,
|
||||
codec: AssetCodec::None,
|
||||
metadata: serde_json::json!({
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{"type":"meta","next_id":{"DSC":47,"AGD":50,"DEC":42,"PLN":173,"LSN":56,"CLSN":1}}
|
||||
{"type":"meta","next_id":{"DSC":49,"AGD":52,"DEC":43,"PLN":174,"LSN":57,"CLSN":1}}
|
||||
{"type":"discussion","id":"DSC-0044","status":"done","ticket":"hub-suspended-game-kill-affordance","title":"Hub Suspended Game Kill Affordance","created_at":"2026-07-05","updated_at":"2026-07-05","tags":["hub","lifecycle","game","ui"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0054","file":"discussion/lessons/DSC-0044-hub-suspended-game-kill-affordance/LSN-0054-manual-hub-kill-must-share-game-termination-cleanup.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||
{"type":"discussion","id":"DSC-0043","status":"done","ticket":"system-os-cartridge-switch-orchestrator","title":"SystemOS Cartridge Switch Orchestrator","created_at":"2026-07-03","updated_at":"2026-07-05","tags":["runtime","os","lifecycle","game","cartridge","architecture"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0053","file":"discussion/lessons/DSC-0043-system-os-cartridge-switch-orchestrator/LSN-0053-game-switching-is-lifecycle-replacement-not-loader-work.md","status":"done","created_at":"2026-07-05","updated_at":"2026-07-05"}]}
|
||||
{"type":"discussion","id":"DSC-0039","status":"abandoned","ticket":"render-pipeline-family-and-future-3d","title":"Render Pipeline Family and Future 3D","created_at":"2026-06-04","updated_at":"2026-06-04","tags":["gfx","renderer","runtime","architecture","pipeline"],"agendas":[{"id":"AGD-0039","file":"AGD-0039-render-pipeline-family-and-future-3d.md","status":"abandoned","created_at":"2026-06-04","updated_at":"2026-06-04","_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}],"decisions":[],"plans":[],"lessons":[],"_override_reason":"User explicitly chose to close this agenda without a new decision because DSC-0038 already established enough architecture for future extension, and 3D is intentionally deferred."}
|
||||
@@ -45,3 +45,5 @@
|
||||
{"type":"discussion","id":"DSC-0036","status":"done","ticket":"prometeu-hub-ui-direction","title":"Agenda - Prometeu Hub UI Direction","created_at":"2026-05-15","updated_at":"2026-05-22","tags":["hub","ui","shell","system-apps","lifecycle","design-system"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0045","file":"discussion/lessons/DSC-0036-prometeu-hub-ui-direction/LSN-0045-hub-ui-slices-should-prove-os-boundaries.md","status":"done","created_at":"2026-05-22","updated_at":"2026-05-22"}]}
|
||||
{"type":"discussion","id":"DSC-0037","status":"done","ticket":"rgba8888-framebuffer-and-pixel-format-direction","title":"Agenda - RGBA8888 Framebuffer and Pixel Format Direction","created_at":"2026-05-22","updated_at":"2026-05-23","tags":["gfx","framebuffer","rgb565","rgba8888","renderer","assets","host","backend"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0046","file":"discussion/lessons/DSC-0037-rgba8888-framebuffer-and-pixel-format-direction/LSN-0046-pixel-format-contracts-must-move-as-one-surface.md","status":"done","created_at":"2026-05-23","updated_at":"2026-05-23"}]}
|
||||
{"type":"discussion","id":"DSC-0046","status":"done","ticket":"runtime-owned-variable-glyph-bank-palette-protocol","title":"Runtime-Owned Variable Glyph Bank Palette Protocol","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["runtime","gfx","assets","glyph-bank","palette-serialization","protocol"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0055","file":"discussion/lessons/DSC-0046-runtime-owned-variable-glyph-bank-palette-protocol/LSN-0055-runtime-owned-asset-protocols-must-align-payload-residency-and-lookup.md","status":"done","created_at":"2026-07-14","updated_at":"2026-07-14"}]}
|
||||
{"type":"discussion","id":"DSC-0047","status":"open","ticket":"portable-host-backend-strategy","title":"Portable Host Backend Strategy","created_at":"2026-07-14","updated_at":"2026-07-14","tags":["host","desktop","portable","sdl","backend","rendering","input","audio","linux","android","handheld"],"agendas":[{"id":"AGD-0050","file":"AGD-0050-portable-host-backend-strategy.md","status":"open","created_at":"2026-07-14","updated_at":"2026-07-14"}],"decisions":[],"plans":[],"lessons":[]}
|
||||
{"type":"discussion","id":"DSC-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"}]}
|
||||
|
||||
+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.
|
||||
@@ -0,0 +1,138 @@
|
||||
---
|
||||
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?
|
||||
- [ ] 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.
|
||||
|
||||
## Resolution
|
||||
@@ -65,6 +65,12 @@ dedicated `System` profile ABI and stdlib/framework.
|
||||
|
||||
## 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:
|
||||
|
||||
```
|
||||
|
||||
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user