feat(host): expose memcard controls and qualify process persistence
Intrepid/Prometeu/Runtime/pipeline/head This commit looks good

This commit is contained in:
2026-10-30 10:10:07 +00:00
parent dcf6561ea7
commit a4bec5bc45
42 changed files with 4778 additions and 100 deletions
+14 -3
View File
@@ -13,7 +13,8 @@ fn io_error(e: std::io::Error) -> Error {
use std::io::ErrorKind as K;
match e.kind() {
K::NotFound => Error::Unavailable,
K::PermissionDenied => Error::ReadOnly,
K::PermissionDenied => Error::AccessDenied,
K::AlreadyExists => Error::AlreadyExists,
K::StorageFull => Error::NoSpace,
K::InvalidInput | K::UnexpectedEof => Error::InvalidRange,
K::Unsupported => Error::Unsupported,
@@ -21,8 +22,15 @@ fn io_error(e: std::io::Error) -> Error {
}
}
impl FileMemcard {
fn lock(file: &File) -> Result<(), Error> {
file.try_lock().map_err(|error| match error {
std::fs::TryLockError::WouldBlock => Error::Busy,
std::fs::TryLockError::Error(error) => io_error(error),
})
}
pub fn open(path: &Path, read_only: bool) -> Result<Self, Error> {
let file = OpenOptions::new().read(true).write(!read_only).open(path).map_err(io_error)?;
Self::lock(&file)?;
let length = file.metadata().map_err(io_error)?.len();
Ok(Self { file, length, read_only })
}
@@ -47,7 +55,9 @@ impl FileMemcard {
.create_new(true)
.open(&temporary)
.map_err(io_error)?;
let mut published = false;
let result = (|| {
Self::lock(&file)?;
let mut card = Self { file, length, read_only: false };
let zeros = [0u8; 65_536];
let mut offset = 0;
@@ -64,6 +74,7 @@ impl FileMemcard {
card.sync()?;
// hard_link publishes without replacing a user file; parent sync makes the name durable.
std::fs::hard_link(&temporary, path).map_err(io_error)?;
published = true;
File::open(parent).and_then(|f| f.sync_all()).map_err(io_error)?;
Ok(card)
})();
@@ -71,10 +82,10 @@ impl FileMemcard {
std::fs::remove_file(&temporary).and_then(|()| File::open(parent)?.sync_all());
match result {
Ok(card) => {
cleanup.map_err(io_error)?;
cleanup.map_err(|_| Error::Indeterminate)?;
Ok(card)
}
Err(e) => Err(e),
Err(e) => Err(if published { Error::Indeterminate } else { e }),
}
}
#[cfg(not(unix))]
@@ -48,6 +48,25 @@ impl LoadCartridgeStep {
pub fn needs_memcard_choice(&self) -> bool {
self.awaiting_memcard && !self.preparing_memcard
}
/// Typed host and UI admission share this single policy boundary.
pub fn choose_memcard(
&mut self,
os: &mut prometeu_system::SystemOS,
choice: prometeu_system::memcard::admission::Choice,
created_at: u64,
) -> prometeu_system::memcard::image::Result<()> {
if !self.needs_memcard_choice() {
return Err(prometeu_system::memcard::image::Error::InvalidState);
}
os.memcard().choose_for_game(
self.cartridge.app_id,
self.cartridge.memcard_slots.unwrap() as usize,
choice,
created_at,
)?;
self.preparing_memcard = true;
Ok(())
}
pub fn new_game_switch(cartridge: Cartridge) -> Self {
Self { failure_recovery: LoadCartridgeFailureRecovery::ReturnToHub, ..Self::new(cartridge) }
@@ -128,13 +147,8 @@ impl LoadCartridgeStep {
Choice::MemoryExisting
};
let created_at = ctx.platform.wall_clock().utc_unix_seconds();
match ctx.os.memcard().choose_for_game(
self.cartridge.app_id,
self.cartridge.memcard_slots.unwrap() as usize,
choice,
created_at,
) {
Ok(()) => self.preparing_memcard = true,
match self.choose_memcard(ctx.os, choice, created_at) {
Ok(()) => {}
Err(error) => self.memcard_message = Self::preparation_message(error),
}
}
@@ -6,6 +6,10 @@ pub enum MemcardIoError {
InvalidRange,
NoSpace,
Unsupported,
Busy,
AccessDenied,
AlreadyExists,
Indeterminate,
IoError,
}
@@ -64,6 +64,14 @@ impl SystemOS {
pub fn memcard(&mut self) -> &mut MemcardService {
&mut self.memcard
}
/// A successful return confirms the shared worker has stopped and joined.
pub fn stop_background_io(&mut self) -> Result<(), crate::AsyncWorkLaneError> {
if let Some(controller) = &mut self.io_controller {
controller.stop()?;
}
self.io_controller = None;
Ok(())
}
/// Host/player operations are admitted only while gameplay is suspended.
pub fn replace_memcard(
@@ -2,6 +2,7 @@
//! shared IO worker owns storage during a publication. Legacy per-slot files are
//! intentionally neither read nor migrated by this service.
pub mod admission;
pub mod diagnostics;
pub mod guest;
pub mod image;
pub mod session;
@@ -37,6 +37,7 @@ pub struct Admission {
pub state: PreparationState,
pub snapshot_budget: usize,
faulted: bool,
replacement_observation: Option<super::diagnostics::SessionDiagnostics>,
}
impl Default for Admission {
fn default() -> Self {
@@ -48,10 +49,26 @@ impl Default for Admission {
state: PreparationState::Idle,
snapshot_budget: DEFAULT_SNAPSHOT_BUDGET,
faulted: false,
replacement_observation: None,
}
}
}
impl MemcardService {
pub fn session_diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
self.admission.replacement_observation.clone().unwrap_or_else(|| self.session.diagnostics())
}
pub fn preparation_active(&self) -> bool {
self.admission.receiver.is_some()
}
pub fn installed_card_id(&self) -> Option<[u8; 16]> {
self.admission.installed.as_ref().map(|c| c.current().card_id)
}
pub fn cancel_pending(&mut self) {
self.session.cancel_pending();
if let Some(control) = &self.admission.control {
control.cancel();
}
}
pub fn host_faulted(&self) -> bool {
self.admission.faulted || self.session.host_faulted()
}
@@ -60,7 +77,11 @@ impl MemcardService {
}
pub fn installed_health(&self) -> Option<(bool, bool, bool)> {
self.admission.installed.as_ref().map(|card| {
(card.recovered, card.degraded, card.write_blocked || card.storage_read_only())
(
card.recovered,
card.degraded,
card.write_blocked || card.storage_read_only() || card.uncertain,
)
})
}
pub fn card_has_game(&self, app_id: u32) -> bool {
@@ -135,6 +156,9 @@ impl MemcardService {
let owned =
card.catalog.games.iter().find(|g| g.app_id == app_id).map_or(0, |g| g.slots.len());
if choice == Choice::Persistent {
if card.uncertain {
return Err(Error::Indeterminate);
}
if card.storage_read_only() || card.write_blocked {
return Err(Error::ReadOnly);
}
@@ -171,6 +195,10 @@ impl MemcardService {
}
Choice::Persistent => {
let mut card = card.take().unwrap();
if card.uncertain {
session.retain_idle_card(card);
return Err(Error::Indeterminate);
}
if card.storage_read_only() || card.write_blocked {
session.retain_idle_card(card);
return Err(Error::ReadOnly);
@@ -256,9 +284,24 @@ impl MemcardService {
&mut self,
storage: Box<dyn MemcardStorage>,
load_existing: bool,
) -> Result<()> {
self.replace_card_job(move |session, control| {
session.replace_storage(storage, load_existing, control)
})
}
pub fn reconcile_card_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn MemcardStorage>> + Send + 'static,
) -> Result<()> {
self.replace_card_job(move |session, control| session.reconcile_storage_with(open, control))
}
fn replace_card_job(
&mut self,
operation: impl FnOnce(&mut Session, &PublicationControl) -> Result<()> + Send + 'static,
) -> Result<()> {
if self.admission.receiver.is_some()
|| self.session.has_in_flight()
|| self.session.io_active()
|| self.session.has_deferred_write()
|| self.session.is_boot_active()
{
return Err(Error::Busy);
@@ -266,6 +309,7 @@ impl MemcardService {
if self.admission.faulted {
return Err(Error::ReadOnly);
}
self.admission.replacement_observation = Some(self.session.diagnostics());
let handoff = Arc::new(Mutex::new(Some(std::mem::take(&mut self.session))));
let worker = handoff.clone();
let control = Arc::new(PublicationControl::default());
@@ -275,13 +319,14 @@ impl MemcardService {
.lane
.submit_memcard_commit_write(move |_| {
let mut session = worker.lock().unwrap().take().unwrap();
let result = session.replace_storage(storage, load_existing, &worker_control);
let result = operation(&mut session, &worker_control);
let _ = tx.send(Prepared::Replacement(session, result));
crate::AsyncWorkJobOutcome::Completed
})
.is_err()
{
self.session = handoff.lock().unwrap().take().unwrap();
self.admission.replacement_observation = None;
return Err(Error::InvalidState);
}
self.admission.control = Some(control);
@@ -331,6 +376,7 @@ impl MemcardService {
}
self.admission.receiver = None;
self.admission.control = None;
self.admission.replacement_observation = None;
}
Err(mpsc::TryRecvError::Disconnected) => {
self.admission.state = PreparationState::Failed(Error::InvalidState);
@@ -361,3 +407,37 @@ impl MemcardService {
}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
use prometeu_drivers::memcard::FileMemcard;
use prometeu_hal::memcard::MemcardIoError;
#[test]
fn idle_uncertain_media_remains_blocked_before_another_persistent_admission() {
let path = std::env::temp_dir().join(format!(
"memcard-uncertain-idle-{}-{}",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
));
let io = FileMemcard::create(&path, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
})
.unwrap();
let mut card = Card::mount(Box::new(io)).unwrap();
card.uncertain = true;
let mut service = MemcardService::new();
// An ended session returns its backend to the same installed-card state.
service.admission.installed = Some(card);
assert_eq!(service.installed_health(), Some((false, false, true)));
assert_eq!(
service.choose_for_game(42, 1, Choice::Persistent, 0),
Err(Error::Indeterminate)
);
assert!(service.card_installed());
assert_eq!(service.lane.pending_depth(), 0);
service.uninstall_card().unwrap();
std::fs::remove_file(path).unwrap();
}
}
@@ -0,0 +1,31 @@
//! Read-only native observations. These do not consume the guest request entry.
use super::{
image::Error,
session::{Mode, RequestResult},
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RequestDiagnostics {
pub result: RequestResult,
pub storage_error: Option<Error>,
pub slot: Option<usize>,
pub operation: &'static str,
pub retained: bool,
pub io_active: bool,
pub deferred: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SessionDiagnostics {
pub app_id: Option<u32>,
pub card_id: Option<[u8; 16]>,
pub epoch: u64,
pub mode: Option<Mode>,
pub health: (bool, bool, bool),
pub dirty_slots: Vec<usize>,
pub request: Option<RequestDiagnostics>,
pub io_active: bool,
pub removal_pending: bool,
pub reconciliation_required: bool,
pub restart_required: bool,
}
@@ -31,12 +31,14 @@ pub fn status(e: Error) -> i64 {
use prometeu_hal::memcard::MemcardIoError as I;
match e {
Error::NoSpace | Error::Io(I::NoSpace) => 3,
Error::AccessDenied => 4,
Error::AccessDenied
| Error::IdentityMismatch
| Error::Io(I::AccessDenied | I::AlreadyExists) => 4,
Error::Corrupt => 5,
Error::Indeterminate => 6,
Error::Indeterminate | Error::Io(I::Indeterminate) => 6,
Error::Io(I::Unavailable) => 7,
Error::InvalidState | Error::Canceled => 8,
Error::Busy => 9,
Error::Busy | Error::Io(I::Busy) => 9,
Error::ReadOnly | Error::CounterExhausted | Error::Io(I::ReadOnly) => 10,
Error::InvalidRange | Error::Io(I::InvalidRange) => 11,
Error::Unsupported | Error::Io(I::Unsupported) => 12,
@@ -29,6 +29,7 @@ pub enum Error {
OutOfMemory,
AccessDenied,
InvalidState,
IdentityMismatch,
}
impl From<MemcardIoError> for Error {
fn from(e: MemcardIoError) -> Self {
@@ -71,12 +71,14 @@ struct Request {
job: AsyncWorkJobId,
released: bool,
saves_payload: bool,
worker_returned: bool,
}
/// Main-lane control; the Card moves into the single worker while its source is protected.
#[derive(Default)]
pub struct Session {
card_id: Option<[u8; 16]>,
uncertain_target: Option<Map>,
known_card_exclusions: Option<([u8; 16], [bool; BLOCK_COUNT])>,
health: (bool, bool, bool),
context: u64,
epoch: u64,
@@ -100,6 +102,82 @@ pub struct Session {
deferred: Option<(u64, usize, u64, Instant)>,
}
impl Session {
/// IO ownership, independent of a completed result retained for guest release.
pub fn io_active(&self) -> bool {
self.request.as_ref().is_some_and(|r| !r.worker_returned)
}
pub fn has_deferred_write(&self) -> bool {
self.deferred.is_some()
}
pub fn cancel_pending(&mut self) {
if let Some(r) = &self.request {
r.control.cancel();
}
if let Some((id, local, ..)) = self.deferred.take() {
self.slots[local].protected = false;
self.memory_result = Some(RequestResult {
id,
state: RequestState::Failure,
reason: RequestReason::Storage(Error::Canceled),
});
}
}
pub fn diagnostics(&self) -> super::diagnostics::SessionDiagnostics {
use super::diagnostics::{RequestDiagnostics, SessionDiagnostics};
let request = if let Some((id, local, ..)) = self.deferred {
Some(RequestDiagnostics {
result: RequestResult {
id,
state: RequestState::Pending,
reason: RequestReason::None,
},
storage_error: None,
slot: Some(local),
operation: "commit",
retained: true,
io_active: false,
deferred: true,
})
} else if let Some(r) = &self.request {
Some(RequestDiagnostics {
result: r.result,
storage_error: r.worker_error,
slot: r.saves_payload.then_some(r.local),
operation: if r.saves_payload { "commit" } else { "presentation" },
retained: !r.released,
io_active: self.io_active(),
deferred: false,
})
} else {
self.memory_result.map(|result| RequestDiagnostics {
result,
storage_error: None,
slot: None,
operation: "commit",
retained: true,
io_active: false,
deferred: false,
})
};
SessionDiagnostics {
app_id: self.mode.map(|_| self.app_id),
card_id: self.card_id,
epoch: self.epoch,
mode: self.mode,
health: self.health(),
dirty_slots: self
.slots
.iter()
.enumerate()
.filter_map(|(i, s)| s.data.read().ok().filter(|s| s.dirty).map(|_| i))
.collect(),
request,
io_active: self.io_active(),
removal_pending: self.removal_pending,
reconciliation_required: self.reconcile_blocked,
restart_required: self.faulted,
}
}
pub fn context(&self) -> u64 {
self.context
}
@@ -531,6 +609,7 @@ impl Session {
job,
released: !saves_payload,
saves_payload,
worker_returned: false,
});
Ok(())
}
@@ -674,6 +753,7 @@ impl Session {
job,
released: false,
saves_payload: true,
worker_returned: false,
});
Ok(id)
}
@@ -692,6 +772,7 @@ impl Session {
let Some(r) = &mut self.request else { return };
match r.receiver.try_recv() {
Ok(completion) => {
r.worker_returned = true;
r.worker_error = completion.result.error;
let current =
self.mode.is_some() && r.session == self.context && r.epoch == self.epoch;
@@ -819,7 +900,7 @@ impl Session {
return Err(Error::Busy);
}
r.released = true;
if self.card.is_some() {
if r.worker_returned {
self.request = None;
}
Ok(())
@@ -833,7 +914,7 @@ impl Session {
r.control.cancel();
r.released = true;
}
if self.card.is_some() {
if !self.io_active() {
self.request = None;
}
self.removal_pending = false;
@@ -869,7 +950,23 @@ impl Session {
load_existing: bool,
control: &PublicationControl,
) -> Result<()> {
if self.has_in_flight() || self.boot_active || self.mode.is_none() {
self.replace_storage_with(move || Ok(storage), load_existing, false, control)
}
pub(super) fn reconcile_storage_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
control: &PublicationControl,
) -> Result<()> {
self.replace_storage_with(open, false, true, control)
}
fn replace_storage_with(
&mut self,
open: impl FnOnce() -> Result<Box<dyn prometeu_hal::memcard::MemcardStorage>>,
load_existing: bool,
same_only: bool,
control: &PublicationControl,
) -> Result<()> {
if self.io_active() || self.deferred.is_some() || self.boot_active || self.mode.is_none() {
return Err(Error::Busy);
}
if self.icon.is_empty()
@@ -882,11 +979,18 @@ impl Session {
{
self.uncertain_target = card.attempted_publication.clone();
}
let known = self.card.as_ref().map(|c| (c.current().card_id, c.known_exclusions()));
if let Some(card) = &self.card {
self.known_card_exclusions = Some((card.current().card_id, card.known_exclusions()));
}
let known = self.known_card_exclusions;
self.card.take(); // Release the old scratch before mounting another image.
self.scratch = None;
self.reconcile_blocked = true;
self.card = Some(Card::mount(storage)?);
let candidate = Card::mount(open()?)?;
if same_only && self.card_id != Some(candidate.current().card_id) {
return Err(Error::IdentityMismatch);
}
self.card = Some(candidate);
let card = self.card.as_mut().unwrap();
let same = self.card_id == Some(card.current().card_id);
if let Some((id, known)) = known
@@ -973,14 +1077,15 @@ impl Session {
Ok(())
}
pub fn detach(&mut self) -> Result<()> {
if self.deferred.is_some()
|| self
.request
.as_ref()
.is_some_and(|r| r.result.state == RequestState::Pending || self.card.is_none())
{
if self.deferred.is_some() || self.io_active() {
return Err(Error::Busy);
}
if self.card.is_none() && self.scratch.is_none() {
let mut scratch = Vec::new();
scratch.try_reserve_exact(SLOT_BYTES).map_err(|_| Error::OutOfMemory)?;
scratch.resize(SLOT_BYTES, 0);
self.scratch = Some(scratch);
}
self.mode = Some(Mode::MemoryOnly);
self.removal_pending = false;
self.reconcile_blocked = false;
@@ -107,4 +107,5 @@ mod tests {
}
}
pub mod memcard_fixture;
pub mod program;
@@ -0,0 +1,141 @@
//! Neutral PBX/ABI fixture. No source-language frontend or compiler is involved.
use crate::program::{TestProgram, scalar_catalog};
use prometeu_bytecode::{
assembler::assemble,
model::{ConstantPoolEntry, SyscallDecl},
registry::*,
};
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
pub enum MemcardFixture {
Write,
Read,
Dirty,
}
#[derive(Default)]
struct Code {
bytes: Vec<u8>,
labels: BTreeMap<&'static str, u32>,
fixups: Vec<(usize, &'static str)>,
}
impl Code {
fn emit(&mut self, text: &str) {
self.bytes.extend(assemble(text).expect("fixture assembly"));
}
fn mark(&mut self, name: &'static str) {
self.labels.insert(name, self.bytes.len() as u32);
}
fn jump(&mut self, op: &str, name: &'static str) {
self.fixups.push((self.bytes.len() + 2, name));
self.emit(&format!("{op} 0"));
}
fn check(&mut self, value: i64, int32: bool) {
self.emit(&format!("PUSH_{} {value}\nEQ", if int32 { "I32" } else { "I64" }));
let resume = self.bytes.len() + 8; // conditional jump followed by a terminal trap
self.emit(&format!("JMP_IF_TRUE {resume}\nTRAP"));
}
fn finish(mut self) -> Vec<u8> {
for (offset, label) in self.fixups {
self.bytes[offset..offset + 4].copy_from_slice(&self.labels[label].to_le_bytes());
}
self.bytes
}
}
/// Stack oracle at a completed frame: 100 pending, 101 durable SUCCESS,
/// 104 MEMORY_ONLY, 201 exact existing readback, 301 dirty/uncommitted RAM.
/// Read never writes or submits a commit; a missing/wrong payload traps.
pub fn memcard_program(kind: MemcardFixture) -> Vec<u8> {
let mut main = Code::default();
main.emit("HOSTCALL 0");
main.check(0, true);
main.emit("PUSH_I64 4\nARRAY_NEW 9\nSET_GLOBAL 1");
if matches!(kind, MemcardFixture::Read) {
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL 1");
main.check(4, false);
main.check(0, false);
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nARRAY_GET 9"));
main.check(value, true);
}
main.mark("done");
main.emit("PUSH_I64 201\nFRAME_SYNC\nPOP_N 1");
main.jump("JMP", "done");
} else {
for (i, value) in [0, 127, 128, 255].into_iter().enumerate() {
main.emit(&format!("GET_GLOBAL 1\nPUSH_I64 {i}\nPUSH_I32 {value}\nARRAY_SET 9"));
}
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nPUSH_I32 0\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 4\nHOSTCALL 2");
main.check(4, false);
main.check(0, false);
if matches!(kind, MemcardFixture::Dirty) {
main.mark("done");
main.emit("PUSH_I64 301\nFRAME_SYNC\nPOP_N 1");
main.jump("JMP", "done");
} else {
main.emit("GET_GLOBAL 0\nPUSH_I32 0\nHOSTCALL 3\nSET_GLOBAL 2");
main.check(0, false);
main.mark("query");
main.emit("GET_GLOBAL 0\nGET_GLOBAL 2\nHOSTCALL 4\nPOP_N 1\nSET_GLOBAL 3");
main.check(0, false);
main.emit("GET_GLOBAL 3\nPUSH_I64 100\nADD\nFRAME_SYNC\nPOP_N 1");
main.jump("JMP", "query");
}
}
main.mark("error");
main.emit("TRAP");
let mut code = main.finish();
let main_len = code.len() as u32;
let hook = if matches!(kind, MemcardFixture::Read) {
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I32 0\nRET").unwrap()
} else {
assemble("GET_LOCAL 0\nSET_GLOBAL 0\nPUSH_I64 560\nARRAY_NEW 9\nSET_GLOBAL 1\nGET_LOCAL 0\nPUSH_CONST 0\nPUSH_I64 1\nPUSH_I32 1\nPUSH_I32 1\nGET_GLOBAL 1\nPUSH_I32 0\nPUSH_I32 560\nHOSTCALL 1\nPOP_N 1\nPUSH_I32 0\nRET").unwrap()
};
let hook_len = hook.len() as u32;
code.extend(hook);
let mut types = scalar_catalog();
types.push(TypeDecl { name: None, kind: TypeKind::Array(TypeId(1)) });
let mut imports = vec![("bootstrap", 0, 1)];
if !matches!(kind, MemcardFixture::Read) {
imports.push(("presentation", 8, 1));
}
match kind {
MemcardFixture::Read => imports.push(("slot_read", 6, 2)),
MemcardFixture::Dirty => imports.push(("slot_write", 6, 2)),
MemcardFixture::Write => {
imports.extend([("slot_write", 6, 2), ("slot_commit", 2, 2), ("query", 2, 3)])
}
}
let syscalls = imports
.into_iter()
.map(|(name, arg_slots, ret_slots)| SyscallDecl {
module: "mem".into(),
name: name.into(),
version: 1,
arg_slots,
ret_slots,
})
.collect();
TestProgram {
const_pool: vec![ConstantPoolEntry::String("Neutral persistence fixture".into())],
code,
functions: vec![
FunctionDecl { code_len: main_len, max_stack_slots: 32, ..Default::default() },
FunctionDecl {
lifecycle_role: LifecycleRole::MemcardBoot,
code_offset: main_len,
code_len: hook_len,
max_stack_slots: 32,
signature: Signature {
parameters: vec![NamedType { type_id: TypeId(0), name: None }],
results: vec![TypeId(1)],
},
..Default::default()
},
],
syscalls,
..Default::default()
}
.serialize_with_types(types)
}
@@ -63,10 +63,13 @@ impl TestProgram {
}
}
pub fn serialize(&self) -> Vec<u8> {
self.serialize_with_types(scalar_catalog())
}
pub fn serialize_with_types(&self, types: Vec<TypeDecl>) -> Vec<u8> {
let mut budget = LoadBudget::new(Default::default());
let registry = Registry::resolve(
RegistryDeclarations {
types: scalar_catalog(),
types,
functions: self.functions.clone(),
implementations: vec![],
},
@@ -2,7 +2,7 @@
mod wire;
pub use wire::Limits;
use crate::{AdvanceFrameOutcome, HeadlessHost};
use crate::{AdvanceFrameOutcome, HeadlessHost, PendingWrites, TeardownPolicy};
use serde_json::{Value, json};
use std::io::{self, BufRead, Write};
use std::sync::{Arc, Mutex, mpsc};
@@ -16,7 +16,8 @@ struct Control {
}
enum Job {
Work(String, Command),
Work(String, Command, bool),
Shutdown(String, TeardownPolicy, bool, mpsc::Sender<bool>),
Stop(Option<String>),
ReadError(io::Error),
}
@@ -104,6 +105,7 @@ fn read_commands<R: BufRead, W: Write>(
limits: &Limits,
) -> io::Result<()> {
let mut initialized = false;
let mut memcard = false;
loop {
let bytes = match read_line(&mut input, limits.max_command_bytes)? {
Line::Eof => break,
@@ -142,11 +144,26 @@ fn read_commands<R: BufRead, W: Write>(
continue;
}
};
if let Command::Shutdown = command {
let mut c = control.lock().unwrap();
c.canceled = true;
sender.send(Job::Stop(Some(id))).map_err(|_| io::Error::other("execution stopped"))?;
return Ok(());
if command.needs_memcard() && !memcard {
output.reply(
Some(&id),
Err(WireError::new(
"unsupported_capability",
"negotiate minor 1.1 and require memcard first",
)),
)?;
continue;
}
if let Command::Shutdown(params) = command {
control.lock().unwrap().canceled = true;
let (tx, rx) = mpsc::channel();
sender
.send(Job::Shutdown(id, params.policy(), memcard, tx))
.map_err(|_| io::Error::other("execution stopped"))?;
if rx.recv().map_err(|_| io::Error::other("execution stopped"))? {
return Ok(());
}
continue;
}
if let Command::Initialize(params) = command {
let result = if initialized {
@@ -159,9 +176,17 @@ fn read_commands<R: BufRead, W: Write>(
.any(|c| !CAPABILITIES.contains(&c.as_str()))
{
Err(WireError::new("unsupported_capability", "required capability unavailable"))
} else if params.protocol_version.minor == 0
&& params.required_capabilities.iter().any(|c| c == "memcard")
{
Err(WireError::new("incompatible_version", "memcard requires protocol minor >= 1"))
} else {
initialized = true;
Ok(json!({"protocolVersion":{"major":1,"minor":0},"capabilities":CAPABILITIES}))
memcard = params.protocol_version.minor >= 1
&& params.required_capabilities.iter().any(|c| c == "memcard");
Ok(
json!({"protocolVersion":{"major":1,"minor":params.protocol_version.minor.min(1)},"capabilities":CAPABILITIES}),
)
};
output.reply(Some(&id), result)?;
continue;
@@ -197,7 +222,9 @@ fn read_commands<R: BufRead, W: Write>(
c.active = Some(id.clone());
c.advancing = matches!(command, Command::Advance(_));
c.canceled = false;
sender.send(Job::Work(id, command)).map_err(|_| io::Error::other("execution stopped"))?;
sender
.send(Job::Work(id, command, memcard))
.map_err(|_| io::Error::other("execution stopped"))?;
}
let mut c = control.lock().unwrap();
c.canceled = true;
@@ -210,14 +237,39 @@ fn execute<W: Write>(
id: &str,
output: &Output<W>,
control: &Mutex<Control>,
memcard: bool,
) -> io::Result<Result<Value, WireError>> {
Ok(match command {
Command::Boot(p) => {
host.boot(p.path).map(|()| wire::state(host.get_state())).map_err(wire::host_error)
let result = if let Some(choice) = p.memcard_choice {
host.boot_with_memcard_choice(p.path, choice.into())
} else {
host.boot(p.path)
};
result.map(|()| wire::state(host.get_state())).map_err(wire::host_error)
}
Command::Reset => {
host.reset();
Ok(wire::state(host.get_state()))
Command::Reset(params) => host
.reset_with_policy(params.policy())
.map(|snapshot| {
let mut state = wire::state(host.get_state());
if memcard {
state["memcard"] = json!(snapshot);
}
state
})
.map_err(wire::host_error),
Command::MemcardMount(p) => {
host.mount_memcard(p).map(|s| json!(s)).map_err(wire::host_error)
}
Command::MemcardUnmount => {
host.unmount_memcard().map(|s| json!(s)).map_err(wire::host_error)
}
Command::GetMemcardState => Ok(json!(host.get_memcard_state())),
Command::MemcardReconcile => {
host.reconcile_memcard().map(|s| json!(s)).map_err(wire::host_error)
}
Command::MemcardContinueInMemory => {
host.continue_memcard_in_memory().map(|s| json!(s)).map_err(wire::host_error)
}
Command::SetInput(p) => {
host.set_input(p.into());
@@ -254,6 +306,10 @@ fn execute<W: Write>(
result["stop"] = json!("terminated");
break;
}
Ok(AdvanceFrameOutcome::ActionRequired) => {
result["stop"] = json!("action_required");
break;
}
Err(error) => {
result["stop"] = json!("host_error");
result["error"] = serde_json::to_value(wire::host_error(error))?;
@@ -283,7 +339,7 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
let output =
Arc::new(Output { writer: Mutex::new(writer), session, limit: limits.max_response_bytes });
output.send(
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":0},
json!({"type":"hello","sessionId":output.session,"protocolVersion":{"major":1,"minor":1},
"runtimeVersion":runtime_version,"capabilities":CAPABILITIES,"limits":limits}),
)?;
let control = Arc::new(Mutex::new(Control::default()));
@@ -298,18 +354,58 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
}
});
let mut host = HeadlessHost::new();
while let Ok(job) = receiver.recv() {
loop {
host.poll_memcard();
let job = match receiver.recv_timeout(std::time::Duration::from_millis(5)) {
Ok(job) => job,
Err(mpsc::RecvTimeoutError::Timeout) => continue,
Err(mpsc::RecvTimeoutError::Disconnected) => break,
};
match job {
Job::Work(id, command) => {
let result = execute(&mut host, command, &id, &output, &control)?;
Job::Work(id, command, memcard) => {
let result = match execute(&mut host, command, &id, &output, &control, memcard) {
Ok(result) => result,
Err(error) => {
cleanup_after_loss(&mut host);
return Err(error);
}
};
// Release authority under the same lock as response publication:
// a client reacting to this reply cannot race a stale busy flag.
let mut c = control.lock().unwrap();
output.reply(Some(&id), result)?;
if let Err(error) = output.reply(Some(&id), result) {
drop(c);
cleanup_after_loss(&mut host);
return Err(error);
}
c.active = None;
c.advancing = false;
}
Job::Shutdown(id, policy, memcard, ack) => match host.shutdown(policy) {
Ok(snapshot) => {
drop(host);
let mut value = json!({"closed":true});
if memcard {
value["memcard"] = json!(snapshot);
}
output.reply(Some(&id), Ok(value))?;
let _ = ack.send(true);
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
return Ok(());
}
Err(error) => {
if let Err(error) = output.reply(Some(&id), Err(wire::host_error(error))) {
cleanup_after_loss(&mut host);
return Err(error);
}
let _ = ack.send(false);
}
},
Job::Stop(id) => {
let _ = host.shutdown(TeardownPolicy {
discard_unsaved: true,
pending_writes: PendingWrites::Cancel,
});
drop(host);
if let Some(id) = id {
output.reply(Some(&id), Ok(json!({"closed":true})))?;
@@ -317,13 +413,24 @@ pub fn serve<R: BufRead + Send + 'static, W: Write + Send + 'static>(
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
return Ok(());
}
Job::ReadError(error) => return Err(error),
Job::ReadError(error) => {
let _ = host.shutdown(TeardownPolicy {
discard_unsaved: true,
pending_writes: PendingWrites::Cancel,
});
return Err(error);
}
}
}
reader.join().map_err(|_| io::Error::other("input reader panicked"))?;
Ok(())
}
fn cleanup_after_loss(host: &mut HeadlessHost) {
let _ = host
.shutdown(TeardownPolicy { discard_unsaved: true, pending_writes: PendingWrites::Cancel });
}
#[cfg(test)]
mod tests {
use super::*;
@@ -369,7 +476,7 @@ mod tests {
"../../../../../devtools/headless-protocol/requests.json"
))
.unwrap();
assert_eq!(requests.len(), 11);
assert_eq!(requests.len(), 21);
for request in requests {
wire::parse(serde_json::from_value(request).unwrap()).unwrap();
}
@@ -8,7 +8,10 @@ use std::io;
#[cfg(test)]
mod fault_tests;
use crate::{CapturedFrame, HostError, HostExecutionStatus, HostState};
use crate::{
CapturedFrame, HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction,
MemcardChoice, MemcardMount, PendingWrites, TeardownPolicy,
};
pub const CAPABILITIES: &[&str] = &[
"boot",
@@ -21,6 +24,12 @@ pub const CAPABILITIES: &[&str] = &[
"get_fault",
"cancel",
"shutdown",
"memcard",
"memcard_mount",
"memcard_unmount",
"get_memcard_state",
"memcard_reconcile",
"memcard_continue_in_memory",
];
#[derive(Clone, Debug, Serialize)]
@@ -95,6 +104,33 @@ pub(super) struct Initialize {
#[serde(deny_unknown_fields)]
pub(super) struct Boot {
pub path: String,
#[serde(default, rename = "memcardChoice", deserialize_with = "present")]
pub memcard_choice: Option<MemcardChoice>,
}
fn present<'de, D: serde::Deserializer<'de>, T: Deserialize<'de>>(
d: D,
) -> Result<Option<T>, D::Error> {
T::deserialize(d).map(Some)
}
#[derive(Debug, Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
pub(super) struct Teardown {
#[serde(deserialize_with = "present")]
pub discard_unsaved: Option<bool>,
#[serde(deserialize_with = "present")]
pub pending_writes: Option<PendingWrites>,
}
impl Teardown {
pub fn explicit(&self) -> bool {
self.discard_unsaved.is_some() || self.pending_writes.is_some()
}
pub fn policy(&self) -> TeardownPolicy {
TeardownPolicy {
discard_unsaved: self.discard_unsaved.unwrap_or(false),
pending_writes: self.pending_writes.unwrap_or_default(),
}
}
}
#[derive(Debug, Deserialize)]
@@ -155,7 +191,12 @@ impl From<Input> for InputSignals {
pub(super) enum Command {
Initialize(Initialize),
Boot(Boot),
Reset,
Reset(Teardown),
MemcardMount(MemcardMount),
MemcardUnmount,
GetMemcardState,
MemcardReconcile,
MemcardContinueInMemory,
SetInput(Input),
ClearInput,
Advance(Advance),
@@ -163,7 +204,21 @@ pub(super) enum Command {
GetState,
GetFault,
Cancel(Cancel),
Shutdown,
Shutdown(Teardown),
}
impl Command {
pub fn needs_memcard(&self) -> bool {
match self {
Self::MemcardMount(_)
| Self::MemcardUnmount
| Self::GetMemcardState
| Self::MemcardReconcile
| Self::MemcardContinueInMemory => true,
Self::Boot(p) => p.memcard_choice.is_some(),
Self::Reset(p) | Self::Shutdown(p) => p.explicit(),
_ => false,
}
}
}
fn params<T: serde::de::DeserializeOwned>(value: Value) -> Result<T, WireError> {
@@ -192,6 +247,17 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
Command::Boot(p)
}
"advance" => Command::Advance(params(req.params)?),
"reset" => Command::Reset(params(req.params)?),
"shutdown" => Command::Shutdown(params(req.params)?),
"memcard_mount" => {
let p: MemcardMount = params(req.params)?;
if p.path.trim().is_empty()
|| matches!((p.action, p.access), (MediaAction::Create, MediaAccess::ReadOnly))
{
return Err(WireError::new("invalid_params", "invalid media path/action/access"));
}
Command::MemcardMount(p)
}
"set_input" => Command::SetInput(params(req.params)?),
"cancel" => {
let p: Cancel = params(req.params)?;
@@ -200,15 +266,25 @@ pub(super) fn parse(req: Request) -> Result<(String, Command), WireError> {
}
Command::Cancel(p)
}
"reset" | "clear_input" | "capture" | "get_state" | "get_fault" | "shutdown" => {
"clear_input"
| "capture"
| "get_state"
| "get_fault"
| "memcard_unmount"
| "get_memcard_state"
| "memcard_reconcile"
| "memcard_continue_in_memory" => {
empty(&req.params)?;
match req.command.as_str() {
"reset" => Command::Reset,
"memcard_unmount" => Command::MemcardUnmount,
"get_memcard_state" => Command::GetMemcardState,
"memcard_reconcile" => Command::MemcardReconcile,
"memcard_continue_in_memory" => Command::MemcardContinueInMemory,
"clear_input" => Command::ClearInput,
"capture" => Command::Capture,
"get_state" => Command::GetState,
"get_fault" => Command::GetFault,
_ => Command::Shutdown,
_ => unreachable!(),
}
}
_ => return Err(WireError::new("unknown_command", "unknown command")),
@@ -231,6 +307,9 @@ impl WireError {
pub(super) fn host_error(error: HostError) -> WireError {
let (code, details) = match &error {
HostError::Memcard(e) => {
("memcard_error", json!({"operation":e.operation,"reason":e.reason,"state":e.state}))
}
HostError::AlreadyBooted => ("already_booted", json!({})),
HostError::BootFailed { reason, report } => {
("boot_failed", json!({"reason":reason,"fault":report.as_deref().map(fault)}))
+91 -19
View File
@@ -11,6 +11,12 @@ use prometeu_hal::{
RuntimePlatform, TelemetryPlatform, WallClock,
};
use prometeu_system::{CrashReport, LatestRenderFrameStore};
#[path = "memcard.rs"]
mod memcard;
pub use memcard::{
MediaAccess, MediaAction, MemcardChoice, MemcardFailure, MemcardMount, MemcardState,
PendingWrites, TeardownPolicy,
};
const BOOT_TICK_LIMIT: usize = 5000;
const HOST_FRAME_ADVANCE_TICK_LIMIT: usize = 100_000;
@@ -46,6 +52,7 @@ pub enum AdvanceFrameOutcome {
FrameCompleted { logical_frame_index: u64, frame_id: FrameId },
Faulted(CrashReport),
Terminated,
ActionRequired,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -53,6 +60,7 @@ pub enum AdvanceFramesStop {
Completed,
Faulted(CrashReport),
Terminated,
ActionRequired,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -64,6 +72,7 @@ pub struct AdvanceFramesOutcome {
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum HostError {
Memcard(Box<MemcardFailure>),
AlreadyBooted,
BootFailed { reason: String, report: Option<Box<CrashReport>> },
InvalidState { operation: &'static str, status: HostExecutionStatus },
@@ -75,6 +84,7 @@ pub enum HostError {
impl fmt::Display for HostError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Memcard(error) => write!(f, "{}: {}", error.operation, error.reason),
Self::AlreadyBooted => write!(f, "boot requires reset before another attempt"),
Self::BootFailed { reason, .. } => write!(f, "boot failed: {reason}"),
Self::InvalidState { operation, status } => {
@@ -104,6 +114,7 @@ pub struct HeadlessHost {
boot_attempted: bool,
last_completed_frame: Option<CompletedFrame>,
controlled_wall_clock: Option<Arc<ControlledWallClock>>,
media: memcard::MediaSelection,
}
#[derive(Debug, Clone, Copy)]
@@ -153,6 +164,7 @@ impl HeadlessHost {
boot_attempted: false,
last_completed_frame: None,
controlled_wall_clock,
media: Default::default(),
}
}
@@ -189,15 +201,20 @@ impl HeadlessHost {
return Err(HostError::AlreadyBooted);
}
self.boot_attempted = true;
self.media.choice = choice;
self.media.boot_phase = "loading";
let path = path.into();
self.firmware.boot_target = BootTarget::Cartridge { path, debug: false, debug_port: 7777 };
let boot_deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
let mut choice_submitted = false;
for _ in 0..BOOT_TICK_LIMIT {
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
self.media.boot_phase = "running";
return Ok(());
}
if matches!(self.firmware.state, FirmwareState::AppCrashes(_)) {
self.media.boot_phase = "failed";
let report = self.get_fault();
let reason = report
.as_ref()
@@ -206,33 +223,55 @@ impl HeadlessHost {
return Err(HostError::BootFailed { reason, report: report.map(Box::new) });
}
if matches!(self.firmware.state, FirmwareState::HubHome(_)) {
self.media.boot_phase = "failed";
return Err(HostError::BootFailed {
reason: "cartridge did not load".to_string(),
report: None,
});
}
let progress = self.firmware.os.memcard().lane.progress_stamp();
if let FirmwareState::LoadCartridge(step) = &self.firmware.state
&& step.cartridge.memcard_slots.is_none()
&& choice.is_some()
{
self.media.boot_phase = "failed";
return Err(self.memcard_error("boot", "invalid_state"));
}
if choice_submitted
&& let prometeu_system::memcard::admission::PreparationState::Failed(error) =
self.firmware.os.memcard().admission.state
{
self.media.boot_phase = "failed";
return Err(self.memcard_error("boot", memcard::error_name(error)));
}
let waiting = matches!(&self.firmware.state,FirmwareState::LoadCartridge(step) if step.needs_memcard_choice());
if waiting {
let Some(choice) = choice else {
return Err(HostError::BootFailed {
reason: "Memory-card choice required; use boot_with_memcard_choice".into(),
report: None,
});
self.media.boot_phase = "choice_required";
return Err(self.memcard_error("boot", "choice_required"));
};
self.signals = InputSignals::default();
self.tick_once();
self.signals = match choice {
prometeu_system::memcard::admission::Choice::Persistent => {
InputSignals { a_signal: true, ..Default::default() }
}
prometeu_system::memcard::admission::Choice::MemoryFresh => {
InputSignals { x_signal: true, ..Default::default() }
}
prometeu_system::memcard::admission::Choice::MemoryExisting => {
InputSignals { y_signal: true, ..Default::default() }
if self.firmware.os.memcard().preparation_active() {
self.poll_memcard();
self.firmware
.os
.memcard()
.lane
.wait_for_progress(progress, std::time::Duration::from_millis(5));
continue;
}
let created_at = self.platform.wall_clock().utc_unix_seconds();
let result = match &mut self.firmware.state {
FirmwareState::LoadCartridge(step) => {
step.choose_memcard(&mut self.firmware.os, choice, created_at)
}
_ => unreachable!(),
};
if let Err(error) = result {
self.media.boot_phase = "failed";
return Err(self.memcard_error("boot", memcard::error_name(error)));
}
choice_submitted = true;
self.media.boot_phase = "preparing";
}
self.tick_once();
self.signals = InputSignals::default();
@@ -251,6 +290,7 @@ impl HeadlessHost {
if matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
Ok(())
} else {
self.media.boot_phase = "failed";
Err(HostError::BootFailed {
reason: "boot did not reach the game".to_string(),
report: self.get_fault().map(Box::new),
@@ -258,7 +298,10 @@ impl HeadlessHost {
}
}
pub fn reset(&mut self) {
pub fn reset(&mut self) -> Result<(), HostError> {
self.reset_with_policy(TeardownPolicy::default()).map(|_| ())
}
fn reset_inner(&mut self) {
self.signals = InputSignals::default();
self.firmware.change_state(
FirmwareState::Reset(ResetStep),
@@ -296,7 +339,11 @@ impl HeadlessHost {
return Ok(AdvanceFrameOutcome::Faulted(report));
}
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
return Ok(AdvanceFrameOutcome::Terminated);
return Ok(if self.host_action_required() {
AdvanceFrameOutcome::ActionRequired
} else {
AdvanceFrameOutcome::Terminated
});
}
let start = self.firmware.os.vm().logical_frame_index();
@@ -305,6 +352,11 @@ impl HeadlessHost {
self.firmware.os.vm().request_debug_step();
for _ in 0..HOST_FRAME_ADVANCE_TICK_LIMIT {
// A controlled lifecycle slice can consume the runtime step marker
// without closing a logical frame. This operation still owns the
// request until its first frame or an explicit stop boundary.
self.firmware.os.vm().set_paused(false);
self.firmware.os.vm().request_debug_step();
self.tick_once();
if let Some(report) = self.get_fault() {
self.finish_frame_advance();
@@ -312,7 +364,11 @@ impl HeadlessHost {
}
if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
self.finish_frame_advance();
return Ok(AdvanceFrameOutcome::Terminated);
return Ok(if self.host_action_required() {
AdvanceFrameOutcome::ActionRequired
} else {
AdvanceFrameOutcome::Terminated
});
}
let logical_frame_index = self.firmware.os.vm().logical_frame_index();
@@ -360,6 +416,13 @@ impl HeadlessHost {
stop: AdvanceFramesStop::Terminated,
});
}
AdvanceFrameOutcome::ActionRequired => {
return Ok(AdvanceFramesOutcome {
requested: count,
completed,
stop: AdvanceFramesStop::ActionRequired,
});
}
}
}
Ok(AdvanceFramesOutcome { requested: count, completed, stop: AdvanceFramesStop::Completed })
@@ -416,6 +479,8 @@ impl HeadlessHost {
fn execution_status(&mut self) -> HostExecutionStatus {
if self.fault_is_visible() {
HostExecutionStatus::Faulted
} else if self.host_action_required() {
HostExecutionStatus::Paused
} else if !matches!(self.firmware.state, FirmwareState::GameRunning(_)) {
HostExecutionStatus::Terminated
} else if self.firmware.os.vm().paused() {
@@ -432,7 +497,9 @@ impl HeadlessHost {
fn require_active(&mut self, operation: &'static str) -> Result<(), HostError> {
let status = self.execution_status();
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused) {
if matches!(status, HostExecutionStatus::Running | HostExecutionStatus::Paused)
&& !self.host_action_required()
{
Ok(())
} else {
Err(HostError::InvalidState { operation, status })
@@ -463,6 +530,11 @@ impl RenderSubmissionSink for HeadlessPlatform {
let frame_id = submission.frame_id;
let ownership = submission.ownership;
self.hardware.submit_render_submission(submission)?;
// Host dialogs use their own producer and may reuse FrameId::ZERO.
// Capture/advance observe only canonical game publications.
if ownership.app_mode != prometeu_hal::app_mode::AppMode::Game {
return Ok(());
}
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)
@@ -11,5 +11,6 @@ mod host;
pub use host::{
AdvanceFrameOutcome, AdvanceFramesOutcome, AdvanceFramesStop, CapturedFrame, HeadlessHost,
HostError, HostExecutionStatus, HostState,
HostError, HostExecutionStatus, HostState, MediaAccess, MediaAction, MemcardChoice,
MemcardFailure, MemcardMount, MemcardState, PendingWrites, TeardownPolicy,
};
@@ -0,0 +1,480 @@
//! Public native host controls; all image policy stays in the shared system service.
use super::{HeadlessHost, HostError};
use prometeu_drivers::memcard::FileMemcard;
use prometeu_firmware::FirmwareState;
use prometeu_hal::memcard::{MemcardIoError, MemcardStorage};
use prometeu_system::memcard::{
admission::{Choice, PreparationState},
image::{Error, IMAGE_BYTES},
session::{Mode, RequestReason, RequestState},
transaction::Card,
};
use serde::{Deserialize, Serialize};
use std::{
path::PathBuf,
time::{Duration, Instant},
};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MediaAction {
Open,
Create,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum MediaAccess {
ReadWrite,
ReadOnly,
}
#[derive(Debug, Clone, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct MemcardMount {
pub path: String,
pub action: MediaAction,
pub access: MediaAccess,
}
#[derive(Debug, Clone, Copy, Default, Deserialize, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PendingWrites {
#[default]
Wait,
Cancel,
}
#[derive(Debug, Clone, Copy, Default, Deserialize)]
#[serde(default, deny_unknown_fields, rename_all = "camelCase")]
pub struct TeardownPolicy {
pub discard_unsaved: bool,
pub pending_writes: PendingWrites,
}
#[derive(Debug, Clone, Copy, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MemcardChoice {
Persistent,
MemoryFresh,
MemoryExisting,
}
impl From<MemcardChoice> for Choice {
fn from(c: MemcardChoice) -> Self {
match c {
MemcardChoice::Persistent => Self::Persistent,
MemcardChoice::MemoryFresh => Self::MemoryFresh,
MemcardChoice::MemoryExisting => Self::MemoryExisting,
}
}
}
pub(super) fn choice_name(c: Choice) -> &'static str {
match c {
Choice::Persistent => "persistent",
Choice::MemoryFresh => "memory_fresh",
Choice::MemoryExisting => "memory_existing",
}
}
pub(super) fn error_name(e: Error) -> &'static str {
match e {
Error::Io(e) => match e {
MemcardIoError::Unavailable => "unavailable",
MemcardIoError::ReadOnly => "read_only",
MemcardIoError::InvalidRange => "invalid_range",
MemcardIoError::NoSpace => "no_space",
MemcardIoError::Unsupported => "unsupported",
MemcardIoError::Busy => "busy",
MemcardIoError::AccessDenied => "access_denied",
MemcardIoError::AlreadyExists => "already_exists",
MemcardIoError::Indeterminate => "indeterminate",
MemcardIoError::IoError => "io_error",
},
Error::Corrupt => "corrupt",
Error::Unsupported => "unsupported",
Error::NoSpace => "no_space",
Error::InvalidRange => "invalid_range",
Error::CounterExhausted => "counter_exhausted",
Error::ReadOnly => "read_only",
Error::Indeterminate => "indeterminate",
Error::Busy => "busy",
Error::Canceled => "canceled",
Error::OutOfMemory => "out_of_memory",
Error::AccessDenied => "access_denied",
Error::InvalidState => "invalid_state",
Error::IdentityMismatch => "identity_mismatch",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MemcardState {
pub media: MediaState,
pub session: SessionState,
pub dirty: bool,
pub dirty_slots: Vec<usize>,
pub request: Option<RequestObservation>,
pub io: IoState,
pub recovery: RecoveryState,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct MediaState {
pub path: Option<PathBuf>,
pub card_id: Option<String>,
pub access: Option<MediaAccess>,
pub mount_epoch: String,
pub preparation: &'static str,
pub error: Option<&'static str>,
pub recovered: bool,
pub degraded: bool,
pub write_blocked: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SessionState {
pub app_id: Option<u32>,
pub choice: Option<&'static str>,
pub mode: Option<&'static str>,
pub boot_attempted: bool,
pub boot_phase: &'static str,
pub resident: bool,
pub action_required: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestObservation {
pub id: String,
pub state: &'static str,
pub reason: &'static str,
pub storage_error: Option<&'static str>,
pub operation: &'static str,
pub slot: Option<usize>,
pub retained: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct IoState {
pub active: bool,
pub deferred: bool,
pub phase: &'static str,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RecoveryState {
pub removal_pending: bool,
pub reconciliation_required: bool,
pub restart_required: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MemcardFailure {
pub operation: &'static str,
pub reason: &'static str,
pub state: MemcardState,
}
#[derive(Default)]
pub(super) struct MediaSelection {
path: Option<PathBuf>,
access: Option<MediaAccess>,
card_id: Option<[u8; 16]>,
error: Option<&'static str>,
pub choice: Option<Choice>,
pub boot_phase: &'static str,
shutdown_failed: bool,
}
impl HeadlessHost {
/// Poll only native work. This does not tick firmware or execute guest code.
pub fn poll_memcard(&mut self) {
self.firmware.os.poll_background_io(&mut self.platform);
}
pub(super) fn memcard_error(
&mut self,
operation: &'static str,
reason: &'static str,
) -> HostError {
HostError::Memcard(Box::new(MemcardFailure {
operation,
reason,
state: self.get_memcard_state(),
}))
}
pub fn get_memcard_state(&mut self) -> MemcardState {
let resident = self.firmware.os.lifecycle().resident_game_task().is_some();
let service = self.firmware.os.memcard();
let d = service.session_diagnostics();
let preparation = service.preparation_active();
let host_faulted = service.host_faulted() || self.media.shutdown_failed;
let (state, error) = match service.admission.state {
PreparationState::Idle => ("idle", None),
PreparationState::Pending => ("pending", None),
PreparationState::Ready => ("ready", None),
PreparationState::Failed(e) => ("failed", Some(error_name(e))),
};
let id = d.card_id.or(service.installed_card_id()).or(self.media.card_id);
let health = if d.mode.is_some() {
d.health
} else {
service.installed_health().unwrap_or((false, false, false))
};
let phase = if preparation {
"preparing"
} else if d.request.as_ref().is_some_and(|r| r.deferred) {
"deferred"
} else if d.io_active {
if service.lane.telemetry().active_job_id == service.session.pending_job() {
"running"
} else {
"queued"
}
} else if d.request.is_some() {
"returned"
} else {
"idle"
};
MemcardState {
media: MediaState {
path: self.media.path.clone(),
access: self.media.access,
card_id: id.map(|id| id.iter().map(|v| format!("{v:02x}")).collect()),
mount_epoch: d.epoch.to_string(),
preparation: state,
error: error.or(self.media.error),
recovered: health.0,
degraded: health.1,
write_blocked: health.2,
},
session: SessionState {
app_id: d.app_id,
choice: self.media.choice.map(choice_name),
mode: d.mode.map(|m| match m {
Mode::Persistent => "persistent",
Mode::MemoryOnly => "memory_only",
}),
boot_attempted: self.boot_attempted,
boot_phase: if self.media.boot_phase.is_empty() {
"idle"
} else {
self.media.boot_phase
},
resident,
action_required: d.mode.is_some()
&& resident
&& (d.removal_pending
|| host_faulted
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_))),
},
dirty: !d.dirty_slots.is_empty(),
dirty_slots: d.dirty_slots,
request: d.request.map(|r| RequestObservation {
id: r.result.id.to_string(),
state: match r.result.state {
RequestState::Pending => "pending",
RequestState::Success => "success",
RequestState::Failure => "failure",
RequestState::Indeterminate => "indeterminate",
RequestState::MemoryOnly => "memory_only",
},
reason: match r.result.reason {
RequestReason::None => "none",
RequestReason::Timeout => "timeout",
RequestReason::RestartRequired => "restart_required",
RequestReason::Storage(e) => error_name(e),
},
storage_error: r.storage_error.map(error_name),
operation: r.operation,
slot: r.slot,
retained: r.retained,
}),
io: IoState {
active: preparation || d.io_active,
deferred: phase == "deferred",
phase,
},
recovery: RecoveryState {
removal_pending: d.removal_pending,
reconciliation_required: d.reconciliation_required,
restart_required: host_faulted,
},
}
}
pub fn mount_memcard(&mut self, options: MemcardMount) -> Result<MemcardState, HostError> {
self.poll_memcard();
if self.firmware.os.lifecycle().resident_game_task().is_some() {
return Err(self.memcard_error("memcard_mount", "invalid_state"));
}
if options.path.trim().is_empty()
|| matches!(
(options.action, options.access),
(MediaAction::Create, MediaAccess::ReadOnly)
)
{
return Err(self.memcard_error("memcard_mount", "invalid_state"));
}
let path = std::path::absolute(&options.path)
.map_err(|_| self.memcard_error("memcard_mount", "unavailable"))?;
// Do not change selection when admission is refused as busy.
let open_path = path.clone();
let result = self.firmware.os.memcard().mount_card_with(move || {
let io = match options.action {
MediaAction::Open => {
FileMemcard::open(&open_path, options.access == MediaAccess::ReadOnly)?
}
MediaAction::Create => FileMemcard::create(&open_path, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
})?,
};
Ok(Box::new(io) as Box<dyn MemcardStorage>)
});
result.map_err(|e| self.memcard_error("memcard_mount", error_name(e)))?;
self.media.path = Some(path);
self.media.access = Some(options.access);
self.media.error = None;
self.media.card_id = None;
if let Err(error) = self.wait_preparation("memcard_mount") {
if let HostError::Memcard(e) = &error {
self.media.error = Some(e.reason);
}
return Err(error);
}
self.media.card_id = self.firmware.os.memcard().installed_card_id();
Ok(self.get_memcard_state())
}
pub fn unmount_memcard(&mut self) -> Result<MemcardState, HostError> {
self.poll_memcard();
if self.firmware.os.lifecycle().resident_game_task().is_some() {
return Err(self.memcard_error("memcard_unmount", "invalid_state"));
}
self.firmware
.os
.memcard()
.uninstall_card()
.map_err(|e| self.memcard_error("memcard_unmount", error_name(e)))?;
self.media = MediaSelection { boot_phase: self.media.boot_phase, ..Default::default() };
Ok(self.get_memcard_state())
}
fn wait_preparation(&mut self, operation: &'static str) -> Result<(), HostError> {
let deadline = Instant::now() + Duration::from_secs(2);
loop {
self.poll_memcard();
match self.firmware.os.memcard().admission.state {
PreparationState::Ready => return Ok(()),
PreparationState::Failed(e) => {
let reason = if self.firmware.os.memcard().host_faulted() {
"restart_required"
} else {
error_name(e)
};
return Err(self.memcard_error(operation, reason));
}
_ => {}
}
if Instant::now() >= deadline {
return Err(self.memcard_error(operation, "restart_required"));
}
let lane = self.firmware.os.memcard().lane.clone();
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
}
}
pub fn prepare_teardown(
&mut self,
policy: TeardownPolicy,
operation: &'static str,
) -> Result<MemcardState, HostError> {
self.poll_memcard();
if matches!(policy.pending_writes, PendingWrites::Cancel) {
self.firmware.os.memcard().cancel_pending();
}
let deadline = Instant::now() + Duration::from_secs(2);
loop {
self.poll_memcard();
let state = self.get_memcard_state();
if !state.io.active && !state.io.deferred {
break;
}
if state.recovery.restart_required || Instant::now() >= deadline {
return Err(self.memcard_error(operation, "restart_required"));
}
let lane = self.firmware.os.memcard().lane.clone();
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
}
if self.get_memcard_state().dirty && !policy.discard_unsaved {
return Err(self.memcard_error(operation, "unsaved_changes"));
}
Ok(self.get_memcard_state())
}
pub fn reset_with_policy(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
self.prepare_teardown(policy, "reset")?;
self.reset_inner();
self.media.choice = None;
self.media.boot_phase = "idle";
self.poll_memcard();
Ok(self.get_memcard_state())
}
pub fn shutdown(&mut self, policy: TeardownPolicy) -> Result<MemcardState, HostError> {
let state = self.prepare_teardown(policy, "shutdown")?;
if self.firmware.os.stop_background_io().is_err() {
self.media.shutdown_failed = true;
return Err(self.memcard_error("shutdown", "restart_required"));
}
self.firmware.os.memcard().session.end_session();
self.firmware.os.memcard().poll(Instant::now());
self.firmware
.os
.memcard()
.uninstall_card()
.map_err(|e| self.memcard_error("shutdown", error_name(e)))?;
Ok(state)
}
pub fn reconcile_memcard(&mut self) -> Result<MemcardState, HostError> {
self.poll_memcard();
if !self.suspended_for_memcard() {
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
}
let path = self
.media
.path
.clone()
.ok_or_else(|| self.memcard_error("memcard_reconcile", "invalid_state"))?;
let read_only = self.media.access == Some(MediaAccess::ReadOnly);
self.firmware
.os
.memcard()
.reconcile_card_with(move || {
Ok(Box::new(FileMemcard::open(&path, read_only)?) as Box<dyn MemcardStorage>)
})
.map_err(|e| self.memcard_error("memcard_reconcile", error_name(e)))?;
self.wait_preparation("memcard_reconcile")?;
self.media.error = None;
if !self.firmware.resume_resident_game_from_home() {
return Err(self.memcard_error("memcard_reconcile", "invalid_state"));
}
Ok(self.get_memcard_state())
}
pub fn continue_memcard_in_memory(&mut self) -> Result<MemcardState, HostError> {
self.poll_memcard();
if !self.suspended_for_memcard() {
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
}
self.firmware
.os
.detach_memcard()
.map_err(|e| self.memcard_error("memcard_continue_in_memory", error_name(e)))?;
if !self.firmware.resume_resident_game_from_home() {
return Err(self.memcard_error("memcard_continue_in_memory", "invalid_state"));
}
Ok(self.get_memcard_state())
}
fn suspended_for_memcard(&mut self) -> bool {
let Some(task) = self.firmware.os.lifecycle().resident_game_task() else { return false };
self.firmware.os.lifecycle().task_state(task)
== Some(prometeu_system::task::TaskState::Suspended)
&& (self.firmware.os.memcard().session.removal_pending()
|| self.firmware.os.memcard().session.diagnostics().reconciliation_required
|| self.firmware.os.memcard().session.host_faulted())
}
pub(super) fn host_action_required(&mut self) -> bool {
self.firmware.os.memcard().session.mode().is_some()
&& self.firmware.os.lifecycle().resident_game_task().is_some()
&& (self.firmware.os.memcard().session.removal_pending()
|| self.firmware.os.memcard().host_faulted()
|| !matches!(self.firmware.state, FirmwareState::GameRunning(_)))
}
}
#[cfg(test)]
#[path = "memcard_tests.rs"]
mod tests;
@@ -0,0 +1,209 @@
use super::*;
use crate::{AdvanceFrameOutcome, HostExecutionStatus};
use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program};
use std::{fs, sync::mpsc};
struct Fixture {
root: PathBuf,
image: PathBuf,
cart: PathBuf,
}
impl Fixture {
fn new(kind: MemcardFixture) -> Self {
let root = std::env::temp_dir().join(format!(
"native-memcard-{}-{}",
std::process::id(),
std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_nanos()
));
let cart = root.join("cart");
fs::create_dir_all(&cart).unwrap();
fs::write(cart.join("program.pbx"), memcard_program(kind)).unwrap();
fs::write(cart.join("manifest.json"),r#"{"magic":"PMTU","cartridge_version":1,"app_id":42,"title":"Native memcard","app_version":"1","app_mode":"Game","capabilities":["memcard"],"memcard_slots":1}"#).unwrap();
let image = root.join("save.pmc");
Self { root, image, cart }
}
fn mount(&self, host: &mut HeadlessHost) {
host.mount_memcard(MemcardMount {
path: self.image.to_string_lossy().into_owned(),
action: MediaAction::Create,
access: MediaAccess::ReadWrite,
})
.unwrap();
host.boot_with_memcard_choice(self.cart.to_string_lossy(), Choice::Persistent).unwrap();
}
}
impl Drop for Fixture {
fn drop(&mut self) {
let _ = fs::remove_dir_all(&self.root);
}
}
fn settle(host: &mut HeadlessHost) {
let deadline = Instant::now() + Duration::from_secs(3);
loop {
host.poll_memcard();
if !host.get_memcard_state().io.active {
break;
}
assert!(Instant::now() < deadline, "IO did not cease");
let lane = host.firmware.os.memcard().lane.clone();
lane.wait_for_progress(lane.progress_stamp(), Duration::from_millis(5));
}
}
fn pause_for_media(host: &mut HeadlessHost) {
let task = host.firmware.os.lifecycle().resident_game_task().unwrap();
host.firmware.os.lifecycle().suspend_task(task).unwrap();
assert_eq!(
host.firmware.os.lifecycle().task_state(task),
Some(prometeu_system::task::TaskState::Suspended)
);
}
#[test]
fn same_media_recovery_rejects_replacement_and_preserves_ram_continuation() {
let f = Fixture::new(MemcardFixture::Dirty);
let mut host = HeadlessHost::new();
f.mount(&mut host);
assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. }));
settle(&mut host);
let context = host.firmware.os.memcard().session.context();
host.firmware.os.memcard().session.notify_removal();
pause_for_media(&mut host);
assert_eq!(host.get_state().status, HostExecutionStatus::Paused);
assert_eq!(host.advance_frame().unwrap(), AdvanceFrameOutcome::ActionRequired);
let old = f.root.join("old.pmc");
fs::rename(&f.image, &old).unwrap();
let replacement = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
})
.unwrap();
drop(replacement);
let error = host.reconcile_memcard().unwrap_err();
assert!(matches!(error,HostError::Memcard(e) if e.reason=="identity_mismatch"));
let mut bytes = [0; 4];
host.firmware.os.memcard().session.read(context, 0, 0, &mut bytes).unwrap();
assert_eq!(bytes, [0, 127, 128, 255]);
fs::rename(&f.image, f.root.join("other.pmc")).unwrap();
fs::rename(&old, &f.image).unwrap();
let restored = host.reconcile_memcard().unwrap();
assert!(restored.dirty);
assert!(!restored.recovery.reconciliation_required);
assert_eq!(host.firmware.os.memcard().session.context(), context);
assert!(matches!(host.advance_frame().unwrap(), AdvanceFrameOutcome::FrameCompleted { .. }));
assert_eq!(host.get_state().stack_top.last(), Some(&prometeu_bytecode::Value::Int64(301)));
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
}
#[test]
fn explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot() {
let f = Fixture::new(MemcardFixture::Dirty);
let mut host = HeadlessHost::new();
f.mount(&mut host);
host.advance_frame().unwrap();
settle(&mut host);
let context = host.firmware.os.memcard().session.context();
host.firmware.os.memcard().session.notify_removal();
pause_for_media(&mut host);
let ram = host.continue_memcard_in_memory().unwrap();
assert_eq!(ram.session.mode, Some("memory_only"));
assert!(ram.dirty);
assert_eq!(host.firmware.os.memcard().session.context(), context);
host.advance_frame().unwrap();
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
}
struct GateStore {
file: FileMemcard,
inside_publication: bool,
payload_seen: bool,
fired: bool,
entered: mpsc::Sender<()>,
continue_io: mpsc::Receiver<()>,
}
impl MemcardStorage for GateStore {
fn len(&self) -> Result<u64, MemcardIoError> {
self.file.len()
}
fn read_only(&self) -> bool {
false
}
fn read_at(&mut self, o: u64, b: &mut [u8]) -> Result<(), MemcardIoError> {
self.file.read_at(o, b)
}
fn sync(&mut self) -> Result<(), MemcardIoError> {
self.file.sync()
}
fn write_at(&mut self, o: u64, b: &[u8]) -> Result<(), MemcardIoError> {
let payload = o >= prometeu_system::memcard::image::DATA_OFFSET;
self.payload_seen |= payload;
let publication = self.payload_seen && (o == 8192 || o == 12288);
if !self.fired && if self.inside_publication { publication } else { payload } {
self.fired = true;
if self.inside_publication {
self.file.write_at(o, b)?;
}
self.entered.send(()).unwrap();
self.continue_io.recv_timeout(Duration::from_secs(10)).unwrap();
return Err(MemcardIoError::IoError);
}
self.file.write_at(o, b)
}
}
#[test]
fn unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile() {
for inside_publication in [false, true] {
let f = Fixture::new(MemcardFixture::Write);
let file = FileMemcard::create(&f.image, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
})
.unwrap();
let (entered_tx, entered) = mpsc::channel();
let (continue_io, release_rx) = mpsc::channel();
let mut host = HeadlessHost::new();
host.media.path = Some(f.image.clone());
host.media.access = Some(MediaAccess::ReadWrite);
host.install_memcard(Box::new(GateStore {
file,
inside_publication,
payload_seen: false,
fired: false,
entered: entered_tx,
continue_io: release_rx,
}))
.unwrap();
host.boot_with_memcard_choice(f.cart.to_string_lossy(), Choice::Persistent).unwrap();
host.advance_frame().unwrap();
entered.recv_timeout(Duration::from_secs(3)).unwrap();
host.firmware.os.memcard().poll(Instant::now() + Duration::from_secs(2));
let before = host.get_memcard_state();
assert!(before.io.active);
assert!(before.recovery.restart_required);
assert_eq!(
before.request.as_ref().unwrap().state,
if inside_publication { "indeterminate" } else { "failure" }
);
assert!(
matches!(host.shutdown(TeardownPolicy{discard_unsaved:true,..Default::default()}),Err(HostError::Memcard(e)) if e.reason=="restart_required")
);
assert!(matches!(FileMemcard::open(&f.image, false), Err(MemcardIoError::Busy)));
continue_io.send(()).unwrap();
settle(&mut host);
let returned = host.get_memcard_state().request;
let original = before.request.as_ref().unwrap();
let late = returned.as_ref().unwrap();
assert_eq!(
(&late.id, late.state, late.reason),
(&original.id, original.state, original.reason),
"late completion cannot rewrite the original result"
);
assert_eq!(late.storage_error, Some("io_error"));
pause_for_media(&mut host);
let restored = host.reconcile_memcard().unwrap();
assert_eq!(
restored.request, returned,
"recovery must not consume or rewrite the guest result"
);
assert!(!restored.recovery.restart_required);
host.shutdown(TeardownPolicy { discard_unsaved: true, ..Default::default() }).unwrap();
}
}
@@ -61,7 +61,7 @@ fn thousand_reset_reload_cycles_release_session_owners_and_preserve_controls() {
));
assert_eq!(&*host.get_state().stack_top, &[Value::Int32(73)]);
assert!(host.get_fault().is_none());
host.reset();
host.reset().expect("reset");
assert_eq!(host.firmware.os.sessions().vm_session_count(), 0);
assert_eq!(
observer.diagnostic_snapshot().used,
@@ -37,7 +37,7 @@ fn controlled_civil_time_is_independent_of_frames_pause_and_reset() {
host.controlled_wall_clock().unwrap().set(10);
host.advance_frame().expect("frame after clock adjustment");
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
host.reset();
host.reset().expect("reset");
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
host.boot(&cartridge).expect("reboot");
assert_eq!(host.wall_clock().utc_unix_seconds(), 10);
@@ -57,7 +57,7 @@ fn injected_civil_clock_remains_the_runtime_source_across_lifecycle() {
assert_eq!(host.wall_clock().utc_unix_seconds(), u64::MAX);
clock.set(42);
assert_eq!(host.wall_clock().utc_unix_seconds(), 42);
host.reset();
host.reset().expect("reset");
clock.advance(3);
assert_eq!(host.wall_clock().utc_unix_seconds(), 45);
}
@@ -290,7 +290,7 @@ fn two_runs_match_oracle() {
fn reset_matches_fresh_host() {
let mut host = boot_color();
let _ = run_on(&mut host);
host.reset();
host.reset().expect("reset");
assert_eq!(host.get_state().status, HostExecutionStatus::Terminated);
assert_eq!(host.capture_frame(), Err(HostError::NoFrameAvailable));
host.boot(color_cartridge()).expect("reboot");
@@ -357,7 +357,7 @@ fn batch_stops_early_on_fault_and_reports_partial_progress() {
#[test]
fn advance_after_reset_reports_termination_without_ticking() {
let mut host = boot_color();
host.reset();
host.reset().expect("reset");
let before = host.get_state().tick_index;
assert_eq!(host.advance_frame().expect("termination outcome"), AdvanceFrameOutcome::Terminated);
+22
View File
@@ -2,6 +2,28 @@
use clap::Args;
use prometeu_host_headless::automation::Limits;
#[derive(Args, Debug)]
pub struct DesktopMediaArgs {
/// Explicit memory-card image used by the desktop host.
#[arg(long, value_name = "PATH")]
pub memcard: Option<String>,
/// Create a new image; never replace an existing destination.
#[arg(long, requires = "memcard")]
pub create_memcard: bool,
}
impl DesktopMediaArgs {
pub fn forwarded_args(&self) -> Vec<String> {
let mut args = Vec::new();
if let Some(path) = &self.memcard {
args.extend(["--memcard".into(), path.clone()]);
}
if self.create_memcard {
args.push("--create-memcard".into());
}
args
}
}
#[derive(Args, Debug)]
pub struct HeadlessArgs {
/// Use the versioned JSONL stdin/stdout protocol (required).
+14 -8
View File
@@ -25,6 +25,8 @@ enum Commands {
Run {
/// Path to the cartridge (directory or .pmc file).
cart: String,
#[command(flatten)]
media: prometeu_cli::DesktopMediaArgs,
},
/// Executes a cartridge in Assisted Mode (Debug).
/// The runtime will wait for a DevTools connection before starting.
@@ -34,6 +36,8 @@ enum Commands {
/// TCP port for the DevTools server (default: 7777).
#[arg(long, default_value_t = 7777)]
port: u16,
#[command(flatten)]
media: prometeu_cli::DesktopMediaArgs,
},
}
@@ -72,15 +76,17 @@ fn main() {
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
dispatch(&exe_dir, "prometeu-headless", &borrowed);
}
Some(Commands::Run { cart }) => {
dispatch(&exe_dir, "prometeu-runtime", &["--run", &cart]);
Some(Commands::Run { cart, media }) => {
let mut args = vec!["--run".into(), cart];
args.extend(media.forwarded_args());
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
}
Some(Commands::Debug { cart, port }) => {
dispatch(
&exe_dir,
"prometeu-runtime",
&["--debug", &cart, "--port", &port.to_string()],
);
Some(Commands::Debug { cart, port, media }) => {
let mut args = vec!["--debug".into(), cart, "--port".into(), port.to_string()];
args.extend(media.forwarded_args());
let borrowed: Vec<&str> = args.iter().map(String::as_str).collect();
dispatch(&exe_dir, "prometeu-runtime", &borrowed);
}
None => {
use clap::CommandFactory;
@@ -16,6 +16,8 @@ use std::sync::{
mpsc,
};
use std::time::{Duration, Instant};
#[path = "support/memcard_process.rs"]
mod memcard_process;
struct TempDir(PathBuf);
impl TempDir {
@@ -241,7 +243,7 @@ fn png_bytes(capture: &Value) -> Vec<u8> {
fn handshake_versions_capabilities_and_limits_are_explicit() {
let mut c = Client::new(&["--stdio"]);
assert_eq!(c.hello["runtimeVersion"], env!("CARGO_PKG_VERSION"));
assert_eq!(c.hello["protocolVersion"], json!({"major":1,"minor":0}));
assert_eq!(c.hello["protocolVersion"], json!({"major":1,"minor":1}));
assert_eq!(
c.hello["limits"],
json!({"maxFrames":600,"maxCommandBytes":65536,"maxResponseBytes":33554432,
@@ -267,7 +269,7 @@ fn handshake_versions_capabilities_and_limits_are_explicit() {
"initialize",
json!({"protocolVersion":{"major":1,"minor":42},"requiredCapabilities":[]})
)["protocolVersion"]["minor"],
0
1
);
assert_eq!(
c.call(
@@ -0,0 +1,355 @@
use super::*;
use prometeu_test_support::memcard_fixture::{MemcardFixture, memcard_program};
fn card(kind: MemcardFixture, version: &str) -> TempDir {
let dir = TempDir::new();
fs::write(dir.0.join("program.pbx"), memcard_program(kind)).unwrap();
fs::write(
dir.0.join("manifest.json"),
serde_json::to_vec(&json!({
"magic":"PMTU","cartridge_version":1,"app_id":4294967295u32,
"title":"Neutral persistence","app_version":version,"app_mode":"Game",
"capabilities":["memcard"],"memcard_slots":1
}))
.unwrap(),
)
.unwrap();
dir
}
fn start_at(binary: &Path) -> Client {
let mut c = Client::spawn(binary, &["headless", "--stdio"], Some(&std::env::temp_dir()));
c.ok(
"initialize",
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
);
c
}
fn start() -> Client {
start_at(Path::new(env!("CARGO_BIN_EXE_prometeu")))
}
fn mount(c: &mut Client, path: &Path, action: &str, access: &str) -> Value {
c.ok("memcard_mount", json!({"path":path,"action":action,"access":access}))
}
fn launch(c: &mut Client, dir: &TempDir, choice: &str) {
c.ok("boot", json!({"path":dir.0,"memcardChoice":choice}));
}
fn oracle(c: &mut Client, expected: i64) {
let deadline = Instant::now() + Duration::from_secs(5);
loop {
let advance = c.ok("advance", json!({"frames":1}));
assert_eq!(
advance["stop"],
"completed",
"{advance}; state={}; mem={}; fault={}",
c.ok("get_state", json!({})),
c.ok("get_memcard_state", json!({})),
c.ok("get_fault", json!({}))
);
let state = c.ok("get_state", json!({}));
let top = state["stackTop"].as_array().unwrap();
if top.last().and_then(|v| v["value"].as_str()) == Some(&expected.to_string()) {
return;
}
assert!(Instant::now() < deadline, "oracle {expected} not reached: {state}");
}
}
fn reason(c: &mut Client, command: &str, params: Value, expected: &str) -> Value {
let error = c.call(command, params)["error"].clone();
assert_eq!(error["code"], "memcard_error", "{error}");
assert_eq!(error["details"]["reason"], expected, "{error}");
error["details"]["state"].clone()
}
fn persistence(binary: &Path) {
let root = TempDir::new();
let image = root.0.join("save.pmc");
let write = card(MemcardFixture::Write, "1");
let mut first = start_at(binary);
let mounted = mount(&mut first, &image, "create", "read_write");
assert_eq!(mounted["media"]["cardId"].as_str().unwrap().len(), 32);
launch(&mut first, &write, "persistent");
oracle(&mut first, 101);
let saved = first.ok("get_memcard_state", json!({}));
assert_eq!(saved["request"]["state"], "success");
assert_eq!(saved["request"]["retained"], true);
assert_eq!(saved["dirty"], false);
assert_eq!(saved["io"]["active"], false);
first.close();
let bytes = fs::read(&image).unwrap();
for version in ["1", "2"] {
let read = card(MemcardFixture::Read, version);
let mut next = start_at(binary);
mount(&mut next, &image, "open", "read_write");
launch(&mut next, &read, "persistent");
oracle(&mut next, 201);
assert_eq!(next.ok("get_state", json!({}))["appId"], 4294967295u32);
assert_eq!(
next.ok("get_memcard_state", json!({}))["request"],
Value::Null,
"reader must not submit a save"
);
next.close();
assert!(fs::read(&image).unwrap() == bytes, "readback must not rewrite the image");
}
let read = card(MemcardFixture::Read, "2");
let mut memory = start_at(binary);
mount(&mut memory, &image, "open", "read_only");
reason(&mut memory, "boot", json!({"path":read.0,"memcardChoice":"persistent"}), "read_only");
memory.ok("reset", json!({}));
launch(&mut memory, &read, "memory_existing");
oracle(&mut memory, 201);
assert_eq!(memory.ok("get_memcard_state", json!({}))["session"]["mode"], "memory_only");
memory.close();
assert!(fs::read(&image).unwrap() == bytes);
}
#[test]
fn memcard_public_distinct_process_save_readback_and_version_identity() {
persistence(Path::new(env!("CARGO_BIN_EXE_prometeu")));
}
#[test]
#[ignore = "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive"]
fn packaged_memcard_process_persistence() {
let installation = PathBuf::from(
std::env::var_os("PROMETEU_PROTOCOL_TEST_INSTALL").expect("extracted distribution"),
);
persistence(&installation.join("prometeu"));
}
#[test]
fn memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save() {
let dirty = card(MemcardFixture::Dirty, "1");
let mut c = start();
launch(&mut c, &dirty, "memory_fresh");
oracle(&mut c, 301);
for command in ["shutdown", "reset"] {
let state = reason(&mut c, command, json!({}), "unsaved_changes");
assert_eq!(state["dirty"], true);
assert_eq!(state["session"]["resident"], true);
assert_eq!(c.ok("get_state", json!({}))["appId"], 4294967295u32);
}
let reset = c.ok("reset", json!({"discardUnsaved":true,"pendingWrites":"cancel"}));
assert_eq!(reset["memcard"]["dirty"], false);
let write = card(MemcardFixture::Write, "1");
launch(&mut c, &write, "memory_fresh");
oracle(&mut c, 104);
let state = c.ok("get_memcard_state", json!({}));
assert_eq!(state["request"]["state"], "memory_only");
assert_eq!(state["dirty"], true);
assert_eq!(state["io"]["active"], false);
assert_eq!(state["media"]["path"], Value::Null);
c.ok("shutdown", json!({"discardUnsaved":true}));
c.wait_exit();
}
#[test]
fn memcard_media_errors_and_negotiation_never_select_a_fallback() {
let root = TempDir::new();
let missing = root.0.join("missing.pmc");
let mut old = Client::new(&["--stdio"]);
old.initialize();
assert_eq!(
old.call("memcard_mount", json!({"path":missing,"action":"create","access":"read_write"}))
["error"]["code"],
"unsupported_capability"
);
assert!(!missing.exists());
old.close();
let mut c = Client::new(&["--stdio"]);
assert_eq!(
c.call(
"initialize",
json!({"protocolVersion":{"major":1,"minor":0},"requiredCapabilities":["memcard"]})
)["error"]["code"],
"incompatible_version"
);
c.ok(
"initialize",
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
);
reason(
&mut c,
"memcard_mount",
json!({"path":missing,"action":"open","access":"read_write"}),
"unavailable",
);
assert!(!missing.exists());
let cart = card(MemcardFixture::Write, "1");
reason(&mut c, "boot", json!({"path":cart.0}), "choice_required");
assert_eq!(c.ok("get_state", json!({}))["logicalFrameIndex"], 0);
c.ok("reset", json!({}));
let corrupt = root.0.join("corrupt.pmc");
let mut bytes = vec![0; 5_259_264];
bytes[..8].copy_from_slice(b"PMCARD1\0");
bytes[8] = 1;
fs::write(&corrupt, &bytes).unwrap();
reason(
&mut c,
"memcard_mount",
json!({"path":corrupt,"action":"open","access":"read_write"}),
"corrupt",
);
assert!(fs::read(&corrupt).unwrap() == bytes);
assert_eq!(c.ok("get_memcard_state", json!({}))["session"]["mode"], Value::Null);
c.close();
}
#[cfg(unix)]
#[test]
fn memcard_process_ownership_covers_aliases_readers_and_release() {
let root = TempDir::new();
let image = root.0.join("save.pmc");
let hard = root.0.join("hard.pmc");
let sym = root.0.join("sym.pmc");
let mut owner = start();
mount(&mut owner, &image, "create", "read_write");
fs::hard_link(&image, &hard).unwrap();
std::os::unix::fs::symlink(&image, &sym).unwrap();
let bytes = fs::read(&image).unwrap();
let mut contender = start();
for path in [&image, &hard, &sym] {
for access in ["read_only", "read_write"] {
reason(
&mut contender,
"memcard_mount",
json!({"path":path,"action":"open","access":access}),
"busy",
);
}
}
reason(
&mut contender,
"memcard_mount",
json!({"path":image,"action":"create","access":"read_write"}),
"already_exists",
);
assert!(fs::read(&image).unwrap() == bytes);
owner.ok("memcard_unmount", json!({}));
mount(&mut contender, &image, "open", "read_only");
reason(
&mut owner,
"memcard_mount",
json!({"path":image,"action":"open","access":"read_only"}),
"busy",
);
contender.close();
mount(&mut owner, &image, "open", "read_write");
owner.close();
}
#[cfg(unix)]
#[test]
fn memcard_creation_race_and_process_death_release_real_ownership() {
let root = TempDir::new();
let image = root.0.join("race.pmc");
// Kill the actual storage-owning process rather than its dispatcher parent.
let mut a = Client::new(&["--stdio"]);
let mut b = Client::new(&["--stdio"]);
for c in [&mut a, &mut b] {
c.ok(
"initialize",
json!({"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}),
);
}
let params = json!({"path":image,"action":"create","access":"read_write"});
let aid = a.send("memcard_mount", params.clone());
let bid = b.send("memcard_mount", params);
let ar = a.response(&aid);
let br = b.response(&bid);
assert_ne!(
ar.get("result").is_some(),
br.get("result").is_some(),
"exactly one creator must win"
);
let (winner, loser, error) =
if ar.get("result").is_some() { (&mut a, &mut b, br) } else { (&mut b, &mut a, ar) };
assert_eq!(error["error"]["details"]["reason"], "already_exists");
let before = fs::read(&image).unwrap();
winner.child.kill().unwrap();
winner.child.wait().unwrap();
mount(loser, &image, "open", "read_write");
loser.close();
assert!(fs::read(&image).unwrap() == before);
}
#[cfg(unix)]
#[test]
fn memcard_access_denial_is_typed_and_does_not_create_or_modify_media() {
use std::os::unix::fs::PermissionsExt;
let root = TempDir::new();
let image = root.0.join("denied.pmc");
let mut creator = start();
mount(&mut creator, &image, "create", "read_write");
creator.close();
let before = fs::read(&image).unwrap();
fs::set_permissions(&image, fs::Permissions::from_mode(0o0)).unwrap();
let mut c = start();
reason(
&mut c,
"memcard_mount",
json!({"path":image,"action":"open","access":"read_write"}),
"access_denied",
);
c.close();
fs::set_permissions(&image, fs::Permissions::from_mode(0o600)).unwrap();
assert!(fs::read(&image).unwrap() == before);
}
#[cfg(unix)]
#[test]
fn desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy() {
use std::os::unix::fs::PermissionsExt;
let installation = TempDir::new();
let dispatcher = installation.0.join("prometeu");
fs::copy(env!("CARGO_BIN_EXE_prometeu"), &dispatcher).unwrap();
let runtime = installation.0.join("prometeu-runtime");
fs::write(&runtime, "#!/bin/sh\nprintf '%s\\n' \"$@\"\n").unwrap();
fs::set_permissions(&runtime, fs::Permissions::from_mode(0o755)).unwrap();
for command in ["run", "debug"] {
let output = Command::new(&dispatcher)
.args([command, "cartridge", "--memcard", "image with spaces.pmc", "--create-memcard"])
.output()
.unwrap();
assert!(output.status.success());
let actual = String::from_utf8(output.stdout).unwrap();
let mut expected = vec![format!("--{command}"), "cartridge".into()];
if command == "debug" {
expected.extend(["--port".into(), "7777".into()]);
}
expected.extend([
"--memcard".into(),
"image with spaces.pmc".into(),
"--create-memcard".into(),
]);
assert_eq!(actual.lines().collect::<Vec<_>>(), expected);
}
assert!(
!Command::new(&dispatcher)
.args(["run", "cartridge", "--create-memcard"])
.output()
.unwrap()
.status
.success()
);
}
#[test]
fn memcard_idle_observation_never_advances_guest_counters() {
let root = TempDir::new();
let image = root.0.join("save.pmc");
let cart = card(MemcardFixture::Write, "1");
let mut c = start();
mount(&mut c, &image, "create", "read_write");
launch(&mut c, &cart, "persistent");
c.ok("advance", json!({"frames":1}));
let before = c.ok("get_state", json!({}));
let deadline = Instant::now() + Duration::from_secs(3);
loop {
let state = c.ok("get_memcard_state", json!({}));
if !state["io"]["active"].as_bool().unwrap() {
assert_eq!(state["request"]["state"], "success");
break;
}
assert!(Instant::now() < deadline);
}
let after = c.ok("get_state", json!({}));
for field in ["pc", "logicalFrameIndex", "tickIndex", "stackTop"] {
assert_eq!(before[field], after[field], "{field}");
}
c.close();
}
@@ -45,5 +45,59 @@
"requestId": "null-params",
"command": "get_state",
"params": null
},
{
"requestId": "bad-mem-8",
"command": "memcard_mount",
"params": {
"path": "x",
"action": "create",
"access": "read_only"
}
},
{
"requestId": "bad-mem-9",
"command": "memcard_mount",
"params": {
"path": "x",
"action": "open"
}
},
{
"requestId": "bad-mem-10",
"command": "boot",
"params": {
"path": "x",
"memcardChoice": null
}
},
{
"requestId": "bad-mem-11",
"command": "boot",
"params": {
"path": "x",
"memcardChoice": "auto"
}
},
{
"requestId": "bad-mem-12",
"command": "shutdown",
"params": {
"discardUnsaved": null
}
},
{
"requestId": "bad-mem-13",
"command": "reset",
"params": {
"pendingWrites": "save"
}
},
{
"requestId": "bad-mem-14",
"command": "get_memcard_state",
"params": {
"anything": true
}
}
]
+135 -3
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://prometeu.dev/headless/v1/request.schema.json",
"title": "Prometeu Headless v1 Request",
"title": "Prometeu Headless v1.1 Request",
"type": "object",
"additionalProperties": false,
"required": [
@@ -65,6 +65,13 @@
"type": "string",
"minLength": 1,
"pattern": "\\S"
},
"memcardChoice": {
"enum": [
"persistent",
"memory_fresh",
"memory_existing"
]
}
}
}
@@ -129,7 +136,19 @@
},
"params": {
"type": "object",
"maxProperties": 0
"properties": {
"discardUnsaved": {
"type": "boolean"
},
"pendingWrites": {
"enum": [
"wait",
"cancel"
]
}
},
"required": [],
"additionalProperties": false
}
}
},
@@ -184,7 +203,120 @@
},
"params": {
"type": "object",
"maxProperties": 0
"properties": {
"discardUnsaved": {
"type": "boolean"
},
"pendingWrites": {
"enum": [
"wait",
"cancel"
]
}
},
"required": [],
"additionalProperties": false
}
}
},
{
"properties": {
"command": {
"const": "memcard_mount"
},
"params": {
"type": "object",
"properties": {
"path": {
"type": "string",
"minLength": 1,
"pattern": "\\S"
},
"action": {
"enum": [
"open",
"create"
]
},
"access": {
"enum": [
"read_write",
"read_only"
]
}
},
"required": [
"path",
"action",
"access"
],
"additionalProperties": false,
"not": {
"properties": {
"action": {
"const": "create"
},
"access": {
"const": "read_only"
}
},
"required": [
"action",
"access"
]
}
}
}
},
{
"properties": {
"command": {
"const": "memcard_unmount"
},
"params": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
}
}
},
{
"properties": {
"command": {
"const": "get_memcard_state"
},
"params": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
}
}
},
{
"properties": {
"command": {
"const": "memcard_reconcile"
},
"params": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
}
}
},
{
"properties": {
"command": {
"const": "memcard_continue_in_memory"
},
"params": {
"type": "object",
"properties": {},
"required": [],
"additionalProperties": false
}
}
}
+74
View File
@@ -74,5 +74,79 @@
"params": {
"targetRequestId": "advance"
}
},
{
"requestId": "mem-11",
"command": "initialize",
"params": {
"protocolVersion": {
"major": 1,
"minor": 1
},
"requiredCapabilities": [
"memcard"
]
}
},
{
"requestId": "mem-12",
"command": "memcard_mount",
"params": {
"path": "/save.pmc",
"action": "open",
"access": "read_only"
}
},
{
"requestId": "mem-13",
"command": "memcard_mount",
"params": {
"path": "/new.pmc",
"action": "create",
"access": "read_write"
}
},
{
"requestId": "mem-14",
"command": "boot",
"params": {
"path": "/cartridge",
"memcardChoice": "memory_existing"
}
},
{
"requestId": "mem-15",
"command": "get_memcard_state",
"params": {}
},
{
"requestId": "mem-16",
"command": "memcard_unmount",
"params": {}
},
{
"requestId": "mem-17",
"command": "memcard_reconcile",
"params": {}
},
{
"requestId": "mem-18",
"command": "memcard_continue_in_memory",
"params": {}
},
{
"requestId": "mem-19",
"command": "reset",
"params": {
"discardUnsaved": true,
"pendingWrites": "cancel"
}
},
{
"requestId": "mem-20",
"command": "shutdown",
"params": {
"pendingWrites": "wait"
}
}
]
+400 -7
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"title": "Prometeu headless server messages v1.0",
"$comment": "requestId additionally has a 128 UTF-8-byte bound; uint counters require lossless decoding. v1.0 producers are checked strictly. Consumers must allow compatible minor extensions.",
"title": "Prometeu headless server messages v1.1",
"$comment": "Producer schema for supported 1.0/1.1 shapes. Consumers permit compatible minor additions; 64-bit identities require lossless decoding.",
"oneOf": [
{
"type": "object",
@@ -167,12 +167,18 @@
"properties": {
"closed": {
"const": true
},
"memcard": {
"$ref": "#/$defs/memcard"
}
},
"required": [
"closed"
],
"additionalProperties": false
},
{
"$ref": "#/$defs/memcard"
}
]
}
@@ -222,7 +228,42 @@
"message",
"details"
],
"additionalProperties": false
"additionalProperties": false,
"allOf": [
{
"if": {
"properties": {
"code": {
"const": "memcard_error"
}
}
},
"then": {
"properties": {
"details": {
"type": "object",
"properties": {
"operation": {
"type": "string"
},
"reason": {
"$ref": "#/$defs/memcardReason"
},
"state": {
"$ref": "#/$defs/memcard"
}
},
"required": [
"operation",
"reason",
"state"
],
"additionalProperties": false
}
}
}
}
]
},
"stack": {
"oneOf": [
@@ -271,8 +312,24 @@
"const": "heap_ref"
},
"value": {
"type": "integer",
"minimum": 0
"type": "object",
"properties": {
"index": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
"generation": {
"type": "integer",
"minimum": 0,
"maximum": 4294967295
}
},
"required": [
"index",
"generation"
],
"additionalProperties": false
}
},
"required": [
@@ -347,6 +404,9 @@
"terminated",
"faulted"
]
},
"memcard": {
"$ref": "#/$defs/memcard"
}
},
"required": [
@@ -694,7 +754,8 @@
"faulted",
"terminated",
"canceled",
"host_error"
"host_error",
"action_required"
]
},
"fault": {
@@ -952,7 +1013,7 @@
"DuplicateFn",
"StructuralTypeCycle",
"CaptureIndex",
"CaptureCount",
"CaptureCount",
"CapturedDirectCall",
"RemovedOpcode",
"ArrayCycle",
@@ -1368,6 +1429,338 @@
"additionalProperties": false
}
]
},
"memcardReason": {
"enum": [
"choice_required",
"unavailable",
"corrupt",
"unsupported",
"read_only",
"access_denied",
"already_exists",
"busy",
"no_space",
"out_of_memory",
"invalid_state",
"invalid_range",
"counter_exhausted",
"identity_mismatch",
"unsaved_changes",
"indeterminate",
"restart_required",
"io_error",
"canceled"
]
},
"memcard": {
"type": "object",
"properties": {
"media": {
"type": "object",
"properties": {
"path": {
"anyOf": [
{
"type": "string"
},
{
"type": "null"
}
]
},
"cardId": {
"anyOf": [
{
"type": "string",
"pattern": "^[0-9a-f]{32}$"
},
{
"type": "null"
}
]
},
"access": {
"anyOf": [
{
"enum": [
"read_write",
"read_only"
]
},
{
"type": "null"
}
]
},
"mountEpoch": {
"type": "string",
"pattern": "^(0|[1-9][0-9]*)$"
},
"preparation": {
"enum": [
"idle",
"pending",
"ready",
"failed"
]
},
"error": {
"anyOf": [
{
"$ref": "#/$defs/memcardReason"
},
{
"type": "null"
}
]
},
"recovered": {
"type": "boolean"
},
"degraded": {
"type": "boolean"
},
"writeBlocked": {
"type": "boolean"
}
},
"required": [
"path",
"cardId",
"access",
"mountEpoch",
"preparation",
"error",
"recovered",
"degraded",
"writeBlocked"
],
"additionalProperties": false
},
"session": {
"type": "object",
"properties": {
"appId": {
"anyOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 4294967295
},
{
"type": "null"
}
]
},
"choice": {
"anyOf": [
{
"enum": [
"persistent",
"memory_fresh",
"memory_existing"
]
},
{
"type": "null"
}
]
},
"mode": {
"anyOf": [
{
"enum": [
"persistent",
"memory_only"
]
},
{
"type": "null"
}
]
},
"bootAttempted": {
"type": "boolean"
},
"bootPhase": {
"enum": [
"idle",
"loading",
"choice_required",
"preparing",
"running",
"failed"
]
},
"resident": {
"type": "boolean"
},
"actionRequired": {
"type": "boolean"
}
},
"required": [
"appId",
"choice",
"mode",
"bootAttempted",
"bootPhase",
"resident",
"actionRequired"
],
"additionalProperties": false
},
"dirty": {
"type": "boolean"
},
"dirtySlots": {
"type": "array",
"items": {
"type": "integer",
"minimum": 0,
"maximum": 63
},
"uniqueItems": true,
"maxItems": 64
},
"request": {
"anyOf": [
{
"type": "object",
"properties": {
"id": {
"type": "string",
"pattern": "^(0|[1-9][0-9]*)$"
},
"state": {
"enum": [
"pending",
"success",
"failure",
"indeterminate",
"memory_only"
]
},
"reason": {
"anyOf": [
{
"$ref": "#/$defs/memcardReason"
},
{
"enum": [
"none",
"timeout"
]
}
]
},
"storageError": {
"anyOf": [
{
"$ref": "#/$defs/memcardReason"
},
{
"type": "null"
}
]
},
"operation": {
"enum": [
"commit",
"presentation"
]
},
"slot": {
"anyOf": [
{
"type": "integer",
"minimum": 0,
"maximum": 63
},
{
"type": "null"
}
]
},
"retained": {
"type": "boolean"
}
},
"required": [
"id",
"state",
"reason",
"storageError",
"operation",
"slot",
"retained"
],
"additionalProperties": false
},
{
"type": "null"
}
]
},
"io": {
"type": "object",
"properties": {
"active": {
"type": "boolean"
},
"deferred": {
"type": "boolean"
},
"phase": {
"enum": [
"idle",
"preparing",
"deferred",
"queued",
"running",
"returned"
]
}
},
"required": [
"active",
"deferred",
"phase"
],
"additionalProperties": false
},
"recovery": {
"type": "object",
"properties": {
"removalPending": {
"type": "boolean"
},
"reconciliationRequired": {
"type": "boolean"
},
"restartRequired": {
"type": "boolean"
}
},
"required": [
"removalPending",
"reconciliationRequired",
"restartRequired"
],
"additionalProperties": false
}
},
"required": [
"media",
"session",
"dirty",
"dirtySlots",
"request",
"io",
"recovery"
],
"additionalProperties": false
}
}
}
@@ -0,0 +1,128 @@
---
id: LSN-0073
ticket: memcard-public-host-persistence
title: Public persistence is a process and ownership contract
created: 2026-10-30
tags: [memcard, persistence, headless, host, ownership]
---
## Context
The runtime now exposes media preparation, three explicit boot choices, native
observation, protected teardown and same-media recovery through its installed
headless protocol. The file backend has a single owner across compatible hosts,
including read-only opens. Runtime tests remain neutral PBX/ABI programs and do
not depend on a source-language frontend or another application's build.
Historical source: accepted decision DEC-0068, executed through PLN-0199 from
AGD-0071. Their workflow files are disposable. The published contracts are
[Save Memory and MEMCARD](../../../docs/specs/runtime/08-save-memory-and-memcard.md)
and [Headless Automation](../../../docs/specs/runtime/11a-headless-automation-protocol.md#memcard-controls).
This lesson explains those published results rather than defining new behavior.
## A native API is not an installed integration surface
Injecting storage into an in-process host is useful for controlled faults, but
does not establish that a consumer can configure the distributed executable.
Media preparation and player choice therefore became explicit operations of
the existing transport. The negotiated minor and capability identify support;
an executable version string alone does not. A client without the extension
continues using the original non-memcard shapes.
Preparing media separately from boot lets missing, corrupt, read-only and busy
files produce native domain errors before game initialization. Opening is not
creation. A persistent choice does not turn into fresh RAM after a failure.
These distinctions belong to the provider so every consumer sees the same
storage and admission policy.
## Result knowledge, RAM state and resource lifetime are separate
A retained terminal result is a statement about an attempt. It is not evidence
that a worker still owns the source, and absence of a mounted backend is not
evidence that the worker is active. In particular, reacquisition can fail after
the previous IO safely returned. An explicit worker-return observation separates
that case from an outstanding operation.
This distinction also matters after watchdog escalation. A late completion can
provide the original worker error and return its resources without rewriting the
terminal result already exposed to the game. Same-card reconciliation keeps that
original result available until guest release. It does not consume the result
to make media operations easier. Controlled tests exercise both a refusal before
publication and an uncertain attempt inside metadata publication.
Ending a session does not establish media health. An installed image with an
indeterminate publication stays write-blocked after reset, and a new persistent
admission cannot bypass the need for explicit revalidation.
RAM has its own state. A memory-only commit completes without a durability claim
and leaves modified RAM dirty. Teardown first waits for or cancels already
admitted IO, then reevaluates RAM. It can avoid an unnecessary discard prompt if
the save completes cleanly during that wait. If dirty data remains, refusal keeps
the process, session and channel available for a later explicit decision.
## A process boundary makes file ownership visible
Serializing one runtime's transactions does not exclude another process that
opened the same image from making decisions against an older map. The shared
file backend now attaches an exclusive OS lock to the open file, including
read-only access. Hardlink and symlink tests exercise identity rather than path
string equality. Creation locks its new file before publishing a non-replacing
name. Resource ownership continues through cancellation, result release and
blocked teardown until IO actually ceases or the owner process dies.
Recovery has to account for the lock held by the same host. Opening another
descriptor before relinquishing the safely quiescent backend can conflict with
that host's own lock. The recovery boundary transfers ownership, validates the
expected card identity before mutation and preserves local RAM on failure.
The selected path containing a different card is an identity error, not implicit
permission to register or load a replacement game record.
## Deterministic guest progress and asynchronous observation coexist
The headless owner polls native IO between commands. Completion and deadlines
can become observable while guest PC, stack, tick and frame remain unchanged.
Driving IO does not require inventing game frames or restarting initialization.
Two integration details were exposed by the first real memcard frame. A
controlled bootstrap slice can consume the runtime's step marker before a logical
frame closes; the host retains its requested advancement until the frame or an
explicit stop boundary. Also, a host dialog can reuse frame ID zero. Its producer
is excluded from canonical game capture, so an initial game frame is neither
mistaken for the dialog nor rejected merely for sharing that numeric ID.
A resident game waiting for external media action is paused rather than
terminated. Recovery preserves its continuation and admitted RAM. It does not
call bootstrap again. Explicit continuation in RAM uses the existing SO choice
and remains distinct from restarting a game with fresh memory.
## A readback oracle should be unable to save its own answer
The neutral writer stores bytes 0, 127, 128 and 255 and exposes the guest query
SUCCESS through public state inspection. A different process runs a reader with
no save or presentation import. It checks each prior byte, traps on a wrong or
missing payload and exposes a separate readback result. The entire image remains
unchanged by that reader. A further process changes app_version while retaining
the same uint32 app_id. Read-only loading into RAM is qualified independently.
The same process oracle runs through the public dispatcher from another working
directory against a real extracted archive produced by the distribution workflow.
That establishes something stronger than reopening a native object in one test
process or copying target/debug binaries into a directory labeled as an install.
Archive, binary, schema and source fingerprints identify the evidence precisely
even while the implementation is an uncommitted checkout.
## Evidence and ownership boundary
[Qualification evidence](evidence/summary.json) records 1,107 passing workspace
tests, 73 passing release tests, strict formatter/clippy checks, and both extracted
distribution tests passing. The generic workspace gate has 14 ignored manual or
installation tests; the two installation tests were separately run successfully.
Execution was qualified on macOS arm64. This is not a physical power-cut,
cross-target or storage-latency qualification.
The runtime delivery prepares a supported contract and its independent evidence.
No consumer source, configuration, SDK, workflow or tests were changed or run.
Future client/frontend integration uses the published surface and has its own
acceptance criteria. Its completion is neither claimed nor required to close
this provider work. This boundary prevents a provider plan from absorbing another
domain merely because that consumer originally discovered the missing interface.
@@ -0,0 +1,6 @@
Checking prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
Checking prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
Checking prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
Checking prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
Checking prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
Finished `dev` profile [unoptimized + debuginfo] target(s) in 5.02s
@@ -0,0 +1,44 @@
Generated VERSION.txt with version 0.1.0
Preparing dist-staging...
Preparing dist-staging/stable (existing archives are retained)...
building artifacts:
prometeu-cli-aarch64-apple-darwin.zip
prometeu-cli-aarch64-apple-darwin.zip.sha256
prometeu-host-desktop-winit-aarch64-apple-darwin.zip
prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
pbxgen-dummy-boy-aarch64-apple-darwin.zip
pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
pbxgen-stress-aarch64-apple-darwin.zip
pbxgen-stress-aarch64-apple-darwin.zip.sha256
building aarch64-apple-darwin target, using cargo profile dist --workspace)
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
Finished `dist` profile [optimized] target(s) in 39.63s
announcing v0.1.0
prometeu-cli 0.1.0
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip
[bin] prometeu
[bin] prometeu-headless
[bin] prometeu-runtime
[misc] 11a-headless-automation-protocol.md, LICENSE, README.md, headless-protocol
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-cli-aarch64-apple-darwin.zip.sha256
prometeu-host-desktop-winit 0.1.0
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip
[bin] prometeu-host-desktop-winit
[misc] LICENSE, README.md, VERSION.txt
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/prometeu-host-desktop-winit-aarch64-apple-darwin.zip.sha256
pbxgen-dummy-boy 0.1.0
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip
[bin] pbxgen-dummy-boy
[misc] LICENSE, README.md
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-dummy-boy-aarch64-apple-darwin.zip.sha256
pbxgen-stress 0.1.0
/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip
[bin] pbxgen-stress
[misc] LICENSE, README.md
[checksum] /Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/target/distrib/pbxgen-stress-aarch64-apple-darwin.zip.sha256
Copying target/distrib content to dist-staging/stable...
@@ -0,0 +1,3 @@
# Historical baseline investigation
These files record the diagnosis at revision `dcf6561ea73446e0a3e1cf1c73eda20923b38df0`, before the public memcard interface and exclusive backend locking were implemented. The probe intentionally tests the old behavior and is not a current conformance runner. Current qualification, commands, artifact fingerprints and limits are recorded in [the provider evidence summary](../summary.json).
@@ -0,0 +1,95 @@
import json
from pathlib import Path
import subprocess
import tempfile
root = Path.cwd()
scratch = Path(tempfile.mkdtemp(prefix="runtime-memcard-review-"))
source = scratch / "image_access.rs"
source.write_text(r'''
use prometeu_drivers::memcard::FileMemcard;
use prometeu_hal::memcard::MemcardIoError;
use prometeu_system::memcard::{image::IMAGE_BYTES, transaction::Card};
fn main() {
let args: Vec<_> = std::env::args().collect();
let path = std::path::Path::new(&args[1]);
if args.get(2).is_some() {
let second = FileMemcard::open(path, false)
.map_err(|e| format!("{e:?}"))
.and_then(|io| Card::mount(Box::new(io)).map_err(|e| format!("{e:?}")));
match second {
Ok(card) => {
println!("second_process_rw_mount_accepted");
drop(card);
}
Err(error) => println!("second_process_rw_mount_rejected:{error}"),
}
return;
}
let io = FileMemcard::create(path, IMAGE_BYTES, |io, id| {
Card::format(io, id).map_err(|_| MemcardIoError::IoError)
}).expect("create private probe image");
let first_card = Card::mount(Box::new(io)).expect("first mount");
let output = std::process::Command::new(std::env::current_exe().unwrap())
.arg(path).arg("child").output().expect("child process");
assert!(output.status.success());
print!("{}", String::from_utf8(output.stdout).unwrap());
drop(first_card);
}
''')
binary = scratch / "image-access"
command = ["rustc", "--edition=2024", str(source), "-o", str(binary),
"-L", "dependency=" + str(root / "target/debug/deps")]
for crate in ("prometeu_drivers", "prometeu_hal", "prometeu_system"):
rlib = max((root / "target/debug/deps").glob("lib" + crate + "-*.rlib"),
key=lambda p: p.stat().st_mtime_ns)
command += ["--extern", crate + "=" + str(rlib)]
subprocess.run(command, check=True, capture_output=True, text=True)
access = subprocess.run([str(binary), str(scratch / "probe.pmc")],
check=True, capture_output=True, text=True)
process = subprocess.Popen([str(root / "target/debug/prometeu"), "headless", "--stdio"],
stdin=subprocess.PIPE, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, text=True)
hello = json.loads(process.stdout.readline())
def request(identity, command, params):
process.stdin.write(json.dumps({"requestId": identity, "command": command, "params": params}) + "\n")
process.stdin.flush()
return json.loads(process.stdout.readline())
required = request("probe-capability", "initialize", {
"protocolVersion": {"major": 1, "minor": 0}, "requiredCapabilities": ["memcard"]})
initialized = request("init", "initialize", {
"protocolVersion": {"major": 1, "minor": 0}, "requiredCapabilities": []})
invalid = request("probe-field", "boot", {"path": str(scratch), "memcard": {}})
state = request("state", "get_state", {})
shutdown = request("stop", "shutdown", {})
process.stdin.close()
process.wait(timeout=10)
assert process.returncode == 0
assert required["error"]["code"] == "unsupported_capability"
assert invalid["error"]["code"] == "invalid_params"
assert shutdown["result"] == {"closed": True}
report = {
"runtime_revision": subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip(),
"scope": "read-only diagnosis using checkout debug binaries and isolated disposable image; no installed-process persistence qualification",
"scratch_directory": str(scratch),
"file_access_probe": {
"backend": "FileMemcard + Card::mount on a valid freshly created image",
"first_process_holds_rw_card": True,
"second_process_result": access.stdout.strip(),
"payload_writes": False,
},
"wire_probe": {
"capabilities": hello["capabilities"],
"required_capability_memcard": required["error"],
"unknown_boot_field_memcard": invalid["error"],
"get_state_fields": sorted(state["result"]),
"shutdown": shutdown["result"],
"note": "The memcard capability/field names are intentionally unsupported test input, not a proposed public contract.",
},
}
report_path = scratch / "summary.json"
report_path.write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
print("report_path=" + str(report_path))
@@ -0,0 +1,68 @@
{
"runtime_revision": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0",
"scope": "read-only diagnosis using checkout debug binaries and isolated disposable image; no installed-process persistence qualification",
"scratch_directory": "/var/folders/0t/tfsqc14j5wbgh9h4s4dytwb00000gq/T/runtime-memcard-review-qa13v648",
"file_access_probe": {
"backend": "FileMemcard + Card::mount on a valid freshly created image",
"first_process_holds_rw_card": true,
"second_process_result": "second_process_rw_mount_accepted",
"payload_writes": false
},
"wire_probe": {
"capabilities": [
"boot",
"reset",
"set_input",
"clear_input",
"advance",
"capture",
"get_state",
"get_fault",
"cancel",
"shutdown"
],
"required_capability_memcard": {
"code": "unsupported_capability",
"details": {},
"message": "required capability unavailable"
},
"unknown_boot_field_memcard": {
"code": "invalid_params",
"details": {},
"message": "unknown field `memcard`, expected `path`"
},
"get_state_fields": [
"appId",
"logicalFrameIndex",
"pc",
"stackTop",
"status",
"tickIndex"
],
"shutdown": {
"closed": true
},
"note": "The memcard capability/field names are intentionally unsupported test input, not a proposed public contract."
},
"date": "2026-10-29",
"platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
"studio_revision": "3a3417eb44c2e99ca183ce6f3fbbfff738b70f87",
"reproduction": [
"cargo test -p prometeu-cli --test automation_process -- --test-threads=1",
"python3 discussion/workflow/agendas/AGD-0071-evidence/review_probe.py"
],
"automation_process_tests": {
"passed": 12,
"failed": 0,
"ignored": 1,
"ignored_test": "packaged_installation_smoke",
"ignored_reason": "requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive",
"covers_memcard": false
},
"qualification_limits": [
"No Studio Gradle/native memcard suite was rerun; its summary was inspected as existing evidence.",
"No configured installed-runtime memcard persistence test was performed.",
"Two simultaneous valid RW mounts were accepted; no concurrent payload publication was attempted.",
"No product code, normative specs or Studio files were modified."
]
}
@@ -0,0 +1,13 @@
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
Finished `test` profile [unoptimized + debuginfo] target(s) in 6.37s
Running tests/automation_process.rs (target/debug/deps/automation_process-018fadef87e61183)
running 2 tests
test memcard_process::packaged_memcard_process_persistence ... ok
test packaged_installation_smoke ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 20 filtered out; finished in 1.27s
@@ -0,0 +1,140 @@
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
Compiling prometeu-firmware v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-firmware)
Compiling prometeu-host-headless v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-headless)
Compiling prometeu-host-desktop-winit v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/host/prometeu-host-desktop-winit)
Compiling prometeu-cli v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/tools/prometeu-cli)
Finished `release` profile [optimized] target(s) in 39.83s
Running unittests src/lib.rs (target/release/deps/prometeu_cli-a2a569acb4d2123a)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/main.rs (target/release/deps/prometeu-233bd0c6f7dfd1c0)
running 4 tests
test tests::child_exit_code_preserves_non_zero_one ... ok
test tests::child_exit_code_preserves_non_zero_other ... ok
test tests::child_exit_code_preserves_zero ... ok
test tests::child_exit_code_rejects_status_without_numeric_code ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/bin/prometeu-headless.rs (target/release/deps/prometeu_headless-891734b93133c22e)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running unittests src/bin/prometeu-runtime.rs (target/release/deps/prometeu_runtime-2d42636990523667)
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/automation_process.rs (target/release/deps/automation_process-48ae7cde6854c255)
running 22 tests
test malformed_fragmented_and_oversized_commands_do_not_desynchronize ... ok
test handshake_versions_capabilities_and_limits_are_explicit ... ok
test conflicting_work_is_rejected_and_cancellation_reports_partial_progress ... ok
test faults_and_boot_failures_are_structured_not_log_parsing ... ok
test lifecycle_and_capture_match_the_in_process_canonical_oracle ... ok
test idle_eof_and_truncated_eof_close_the_process ... ok
test dispatcher_works_from_a_relocated_installation_and_other_cwd ... ok
test memcard_process::packaged_memcard_process_persistence ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
test independent_processes_match_pixels_ids_state_and_fault ... ok
test packaged_installation_smoke ... ignored, requires PROMETEU_PROTOCOL_TEST_INSTALL pointing to an extracted dist archive
test memcard_process::desktop_dispatch_forwards_explicit_media_without_interpreting_player_policy ... ok
test memcard_process::memcard_creation_race_and_process_death_release_real_ownership ... ok
test memcard_process::memcard_access_denial_is_typed_and_does_not_create_or_modify_media ... ok
test memcard_process::memcard_media_errors_and_negotiation_never_select_a_fallback ... ok
test memcard_process::memcard_dirty_refusal_retains_channel_and_explicit_ram_has_no_save ... ok
test schemas_and_distributed_request_fixtures_are_consistent ... ok
test memcard_process::memcard_idle_observation_never_advances_guest_counters ... ok
test shutdown_and_eof_interrupt_active_work_without_resuming_it ... ok
test missing_binary_and_invalid_cli_limits_fail_explicitly ... ok
test memcard_process::memcard_process_ownership_covers_aliases_readers_and_release ... ok
test partial_guest_fault_and_host_watchdog_are_distinct_outcomes ... ok
test memcard_process::memcard_public_distinct_process_save_readback_and_version_identity ... ok
test result: ok. 20 passed; 0 failed; 2 ignored; 0 measured; 0 filtered out; finished in 0.66s
Running tests/registry_fault_schema.rs (target/release/deps/registry_fault_schema-2274560704287ef1)
running 2 tests
test published_load_schema_requires_tag_context_and_the_matching_init_payload ... ok
test published_schema_accepts_structured_resource_fields_and_rejects_unknown_or_negative_values ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.05s
Running unittests src/lib.rs (target/release/deps/prometeu_host_headless-751195d1585cd278)
running 13 tests
test automation::tests::bounded_lines_accept_fragmentation_and_recover_after_oversize ... ok
test automation::tests::response_limit_counts_the_complete_envelope_and_keeps_correlation ... ok
test automation::tests::input_snapshot_is_replacement_and_rejects_unknown_fields ... ok
test automation::tests::distributed_request_fixtures_are_accepted_by_the_actual_parser ... ok
test automation::wire::fault_tests::resource_trap_wire_preserves_native_fields_and_source_span ... ok
test automation::tests::capture_preserves_independent_ids_and_excludes_padding_without_channel_loss ... ok
test automation::wire::fault_tests::load_failure_wire_uses_shared_structured_serializer_and_no_runtime_pc ... ok
test automation::wire::fault_tests::executed_closure_quota_refusal_reaches_wire_with_machine_fields ... ok
test automation::wire::fault_tests::active_host_native_type_fault_preserves_wire_machine_fields ... ok
test host::tests::termination_during_frame_advance_clears_host_step_control ... ok
test host::memcard::tests::explicit_continue_in_ram_preserves_dirty_snapshot_and_uses_no_new_boot ... ok
test host::memcard::tests::same_media_recovery_rejects_replacement_and_preserves_ram_continuation ... ok
test host::memcard::tests::unceased_io_retains_lock_and_terminal_result_survives_late_return_and_reconcile ... ok
test result: ok. 13 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.09s
Running tests/deterministic_control.rs (target/release/deps/deterministic_control-98e9b0ea3dcb6c52)
running 25 tests
test headless_source_has_no_timing_wait_or_interactive_backend_dependency ... ok
test lifecycle_state_and_preconditions_are_structural ... ok
test instruction_step_fault_remains_structured ... ok
test batch_stops_early_on_fault_and_reports_partial_progress ... ok
test end_of_rom_completes_a_logical_frame ... ok
test advance_after_reset_reports_termination_without_ticking ... ok
test audio_play_does_not_need_a_device ... ok
test clear_input_drops_right ... ok
test injected_civil_clock_remains_the_runtime_source_across_lifecycle ... ok
test normalized_touch_edges_and_coordinates_use_the_same_input_surface ... ok
test one_frame_returns_and_captures_the_exact_published_frame ... ok
test normalized_button_press_hold_release_and_clear_are_observable ... ok
test right_hold_then_release_changes_pixels ... ok
test step_does_not_complete_a_logical_frame ... ok
test controlled_civil_time_is_independent_of_frames_pause_and_reset ... ok
test one_logical_frame_may_span_multiple_internal_ticks ... ok
test trap_is_structured ... ok
test stepping_frame_sync_is_not_a_fault_or_completed_runtime_frame ... ok
test vm_init_failure_is_returned_as_structured_boot_failure ... ok
test zero_frames_is_an_explicit_noop ... ok
test reset_matches_fresh_host ... ok
test two_runs_match_oracle ... ok
test three_hundred_frames_complete_without_realtime_pacing ... ok
test outer_frame_limit_is_a_host_error_and_finishes_paused ... ok
test audio_controls_quota_and_multiple_frames_are_device_independent ... ok
test result: ok. 25 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.18s
Running tests/input_queries.rs (target/release/deps/input_queries-2ee1672fd0295c9d)
running 4 tests
test catalogue_has_exact_names_ids_signatures_and_no_endpoint_aliases ... ok
test every_known_query_faults_when_unavailable_and_rejects_arguments ... ok
test vm_queries_charge_one_cycle_each_and_allocate_no_guest_objects ... ok
test every_button_uses_its_own_snapshot_and_queries_do_not_advance_frames ... ok
test result: ok. 4 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s
Running tests/typed_runtime.rs (target/release/deps/typed_runtime-e31573f60bd59e2a)
running 5 tests
test typed_native_argument_fault_inside_callback_reaches_active_host ... ok
test active_host_preserves_removed_opcode_load_context_and_null_fn_trap ... ok
test sync_in_callee_or_closure_resumes_next_pc_with_locals_and_init_once ... ok
test budget_exhaustion_inside_fn_keeps_the_same_open_logical_frame ... ok
test regenerated_cartridges_run_six_complete_frames_on_production_host ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.07s
@@ -0,0 +1,157 @@
{
"date": "2026-10-30",
"scope": "runtime/host provider readiness only; no consumer modifications/builds/tests/configuration updates",
"baseline_revision": "dcf6561ea73446e0a3e1cf1c73eda20923b38df0",
"working_tree": "uncommitted implementation; identified by per-file SHA256 and combined source fingerprint",
"source_files_sha256": {
"crates/console/prometeu-drivers/src/memcard.rs": "cc0326c89033cca97d1798e7725f2bf52115c8592a12dab39146c9d3dcb19769",
"crates/console/prometeu-firmware/src/firmware/firmware_step_load_cartridge.rs": "3177c16ab016d45424b54e9b3bbf1746f9113db8ec607a2819cabc412202a4fb",
"crates/console/prometeu-hal/src/memcard.rs": "263d609d336d6e37b62fa4604d2be5ab98df26c45ec7c611557b0abfb8916bee",
"crates/console/prometeu-system/src/os/system_os.rs": "cbca29127df9ca28b6ed84bd5fa3f926b410a34f360c33bfce0456292cf4340b",
"crates/console/prometeu-system/src/services/memcard.rs": "a58517232ceef657d005da2f28fbc0cd484398bd407b2340b0d3571d083e53c5",
"crates/console/prometeu-system/src/services/memcard/admission.rs": "ecec0b0642da3aba3a38941ce25afdb35dc8d42b15f34d9da6ac9d06f765f741",
"crates/console/prometeu-system/src/services/memcard/diagnostics.rs": "99699c14c43090c8eb72624967e96846a99400a5809301a8dcc2564d8164ab61",
"crates/console/prometeu-system/src/services/memcard/guest.rs": "507913dc29ed07ab2a4ac6ec93583e935a73e35ec8f16798de0a5b55d392dd98",
"crates/console/prometeu-system/src/services/memcard/image.rs": "c4aedb43b050989ef95f8efbd5d0994b23928a16dd49358361ecd96ffed3811d",
"crates/console/prometeu-system/src/services/memcard/session.rs": "f6990ddac2f0cd2f2643d4323be6e18eef0e349ea1494c6dfd216cb5e2105d4a",
"crates/dev/prometeu-test-support/src/lib.rs": "4cf14e6065e40ec5bc84fdc20f653babee26e1d60c97687b1e68edfda9b1a219",
"crates/dev/prometeu-test-support/src/memcard_fixture.rs": "f63fd0c6dff5b862d228709d9160b38ab9edc1a90e62b051eb6540706977bd0f",
"crates/dev/prometeu-test-support/src/program.rs": "d6c2f720fb405355ea2d3648a5c08e7fa96f5fc8cfd289be0cfb17f911907696",
"crates/host/prometeu-host-headless/src/automation/mod.rs": "7d72c0eddf23b769047812e9a96746380f58dc18d5ef560188999160aee17c68",
"crates/host/prometeu-host-headless/src/automation/wire.rs": "0a1e3c786810499857f54d8d1795fded417ed809b17c4a03d1b39941b0d4dd28",
"crates/host/prometeu-host-headless/src/host.rs": "fc75f6c9dd842ec241e95f4389935d8edf619ed3c7c5134733d25b6dd58cbb2f",
"crates/host/prometeu-host-headless/src/lib.rs": "3b29775d61a26a6098562e2e4e98fba1d43580a36979be43682f44ce5f8655c8",
"crates/host/prometeu-host-headless/src/memcard.rs": "a32fcfc9cb30ddf18a2eb848101c34583a215817bf6e185124084a46f22ad329",
"crates/host/prometeu-host-headless/src/memcard_tests.rs": "66f566a8291014524a4ef0d5952252adf64d3f8c68b50bd9251f4482664e2f39",
"crates/host/prometeu-host-headless/src/resource_qualification_tests.rs": "243f51eadc91c30ef5895d34525574349dbad45ee7b77cb88bee25c7fd2e66a4",
"crates/host/prometeu-host-headless/tests/deterministic_control.rs": "5fe3f48575e0fd5f4f2640c76145603baa2571b67ad619de21caadf1ce35aa1b",
"crates/tools/prometeu-cli/src/lib.rs": "944840ef6e14400b98cc1dc659c95ba5eb6e7ef8a4cd4d28d37ba70392e7e2d6",
"crates/tools/prometeu-cli/src/main.rs": "2c956bc90756e31bc38cd6811933a717b3c49d1f0ab501ed39f5869e6b3d8c92",
"crates/tools/prometeu-cli/tests/automation_process.rs": "230dea8a6cabede2e168c35938284903fa41614eaa2619626bb6560a9527640f",
"crates/tools/prometeu-cli/tests/support/memcard_process.rs": "0a8581fb129238f39605a6e9485e813e58b639e7a2131e3cf06e9c390cce2bed",
"devtools/headless-protocol/invalid-requests.json": "f0f0a9a21735c7f90180e816093a884350c07303ea887ebe89a534fc6c8a7b3a",
"devtools/headless-protocol/request.schema.json": "d7e5b39917f0973e0cb697815937e21574bec7f24ebcab8c9a72ca3c05dca553",
"devtools/headless-protocol/requests.json": "5821af6fecb51a7b85e502fd27d22e046e140d417982bbb561fd260b9023ddf2",
"devtools/headless-protocol/response.schema.json": "0040bb288226eb2f34d4028d8a5f3f8a708d754d51d8f62eaa7e64b0da5c69a8",
"docs/specs/runtime/08-save-memory-and-memcard.md": "7ead27a4039a3451909e7319f8624ec37c62602fee4615f6766e4435b0f411d7",
"docs/specs/runtime/11a-headless-automation-protocol.md": "526e6aae664ffc5661289150410599fb3494e1a1665ba334fe802b0d69e46313"
},
"source_fingerprint_sha256": "87474a7172e3e233a9144c97202a40001892ea0e8a6c814b47581b67527c2575",
"platform": "macOS-27.0.1-arm64-arm-64bit-Mach-O",
"architecture": "arm64",
"rustc": "rustc 1.98.1 (48a229cea 2026-09-01)",
"cargo": "cargo 1.98.1 (797e8a9bc 2026-08-05)",
"cargo_lock_sha256": "cffad9ed62f38a591538abd81dd39270d6022397342c8189f4ac6c7baaa8e795",
"protocol": {
"major": 1,
"minor": 1,
"capability": "memcard",
"schema_sha256": {
"invalid-requests.json": "f0f0a9a21735c7f90180e816093a884350c07303ea887ebe89a534fc6c8a7b3a",
"request.schema.json": "d7e5b39917f0973e0cb697815937e21574bec7f24ebcab8c9a72ca3c05dca553",
"requests.json": "5821af6fecb51a7b85e502fd27d22e046e140d417982bbb561fd260b9023ddf2",
"response.schema.json": "0040bb288226eb2f34d4028d8a5f3f8a708d754d51d8f62eaa7e64b0da5c69a8"
}
},
"checks": {
"workspace_all_targets_all_features": {
"passed": 1107,
"failed": 0,
"ignored": 14,
"suites": 60
},
"release_cli_headless": {
"passed": 73,
"failed": 0,
"ignored": 2,
"suites": 10
},
"extracted_distribution": {
"passed": 2,
"failed": 0,
"ignored": 0,
"suites": 1
},
"clippy_all_targets_all_features": "passed; warnings denied",
"format": "passed",
"git_diff_check": "passed",
"docs_workflow_reference_scan": "no matches",
"edited_specification_links": "all resolve",
"uncertain_installed_media_admission": {
"passed": 1,
"failed": 0,
"ignored": 0,
"suites": 1
}
},
"commands": [
"cargo test --workspace --all-targets --all-features --no-fail-fast",
"cargo test --release -p prometeu-host-headless -p prometeu-cli --lib --tests",
"cargo clippy --workspace --all-targets --all-features -- -D warnings",
"cargo fmt --all -- --check",
"./scripts/local-dist.sh --artifacts local --target aarch64-apple-darwin --allow-dirty",
"PROMETEU_PROTOCOL_TEST_INSTALL=<isolated extraction> cargo test -p prometeu-cli --test automation_process packaged_ -- --ignored --test-threads=1"
],
"distribution": {
"builder": "cargo-dist 0.30.3 via existing local-dist workflow",
"target": "aarch64-apple-darwin",
"profile": "dist (inherits release, LTO)",
"archive": "target/distrib/prometeu-cli-aarch64-apple-darwin.zip",
"archive_sha256": "a6f66e814e0e9254cc4bba5e4a4307c9ec8a9963f8332f2f64a283a376d93b7c",
"extracted_to": "/tmp/pln199-install-0x57zot6",
"binary_sha256": {
"prometeu": "182e4d9a4d32201c8ad892a11c297de7059dcc0a837660bdd173be44808b9906",
"prometeu-headless": "7703190f63844d91fa125ba3a322b5e771db79a282b3cfbb3480eef76422b6ef",
"prometeu-runtime": "0e8e692395cedea799b6d555b416e40536dcabf3a98a2061327d2010c478e446"
},
"included_schemas_and_spec": "byte-identical to current checkout",
"qualification_harness_profile": "dev harness invokes only extracted dist executables"
},
"neutral_fixture": {
"producer": "runtime TestProgram / Registry writer / assembler; no frontend input or dependency",
"source": "crates/dev/prometeu-test-support/src/memcard_fixture.rs",
"source_sha256": "f63fd0c6dff5b862d228709d9160b38ab9edc1a90e62b051eb6540706977bd0f",
"save_bytes": [
0,
127,
128,
255
],
"app_id": 4294967295,
"versions": [
"1",
"2"
],
"oracles": {
"101": "guest query SUCCESS",
"104": "MEMORY_ONLY, remains dirty",
"201": "exact prior readback, reader has no save/presentation import",
"301": "dirty RAM, no commit"
},
"readback_checks": "separate public-dispatcher processes; exact bytes, no retained reader request and unchanged entire image; repeated across app_version and read-only memory-existing"
},
"additional_qualification": [
"minor/capability/schema parsing and 1.0 regression",
"dirty shutdown/reset refusal keeps session/channel; explicit discard and memory-only",
"missing/corrupt/read-only/access-denied errors, no fallback",
"cross-process RW/RO/hardlink/symlink exclusion, non-replacing creation race, actual owner process-death release",
"native controlled failures before/inside publication; lock retained with unceased IO; immutable original result and late worker error",
"same-card revalidation preserves RAM/continuation/original request; wrong identity rejected; explicit RAM detach",
"idle IO observation leaves guest PC/stack/tick/frame unchanged",
"desktop dispatcher forwards explicit options without launching a GUI",
"uncertain installed media remains write-blocked after session teardown; persistent readmission is refused pending explicit revalidation"
],
"limits": [
"Execution qualified on this macOS arm64 host, not other targets or storage devices.",
"No physical power-cut or latency claim.",
"14 unrelated/manual tests are ignored by the generic workspace gate; the two packaged tests are separately executed and passed.",
"Future frontend/client integration remains external and is not claimed."
],
"implementation_findings": [
"Lifecycle bootstrap can consume a debug step marker before the requested logical frame; headless retains its active advance until frame/stop.",
"Host dialogs may reuse FrameId zero; canonical capture excludes their producer.",
"Worker return is tracked separately from retained results and presence of a backend after failed reacquisition.",
"Ending a session does not clear uncertain publication; installed-media health and admission must preserve the write block."
],
"historical_investigation": "investigation/summary.json records the earlier baseline diagnosis, not the implemented protocol"
}
@@ -0,0 +1,8 @@
Compiling prometeu-system v0.1.0 (/Users/niltonconstantino/personal/workspace.personal/intrepid/prometeu/runtime/crates/console/prometeu-system)
Finished `test` profile [unoptimized + debuginfo] target(s) in 3.55s
Running unittests src/lib.rs (target/debug/deps/prometeu_system-5bd0bf863c9e944e)
running 1 test
test services::memcard::admission::tests::idle_uncertain_media_remains_blocked_before_another_persistent_admission ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 231 filtered out; finished in 0.05s
@@ -328,6 +328,40 @@ ordinary storage failures are domain results.
## Host integration
### Public host controls
The installed headless interface is the negotiated memcard surface of
[Headless Automation](11a-headless-automation-protocol.md#memcard-controls).
Media selection belongs to the host instance, never the cartridge manifest.
Opening, creation and the three boot choices are explicit. Missing, corrupt,
inaccessible or read-only media never silently select fresh RAM or create a file.
File hosts acquire a nonblocking exclusive OS lock, including for read-only
access, before validating the opened image. The lock follows file identity and
therefore covers aliases across desktop/headless processes. Contention is BUSY;
unsupported locking is an explicit refusal. Creation locks the new file before
publishing its name and never replaces an existing destination. Locks and native
buffers remain owned until actual IO cessation, independently of result release,
discard consent and timeout. Inspection through a second mounted reader is not
supported while an owner holds the image.
Native observation distinguishes dirty RAM, retained terminal results and actual
IO ownership. Reset/shutdown wait for admitted IO, or request cancellation when
explicitly selected, then reevaluate dirty RAM. Remaining dirty RAM requires
explicit discard consent; refusal preserves the resident session. Neither wait,
cancel nor discard starts a save or proves rollback. Unconfirmed cessation blocks
reset/closure confirmation and requires restart supervision. EOF/transport loss
attempts bounded cancellation/cleanup without saving or resuming the guest.
An installed image with an indeterminate publication remains write-blocked after
reset; another persistent admission requires explicit revalidation first.
The headless owner polls IO/deadlines while idle without advancing VM instructions,
input, ticks or frames. A resident game awaiting media action is paused, not
terminated. Explicit reconciliation reopens only the selected card identity after
safe cessation, preserves RAM/continuation and the original retained request
result, and never reruns bootstrap. Different-card switching is not part of this
public host surface.
The desktop host accepts `--memcard PATH` for an existing image and
`--memcard PATH --create-memcard` for explicit creation. Creation never replaces
an existing file. File creation, opening, mount validation and save IO execute
@@ -30,7 +30,7 @@ and may terminate the process tree. There is no transport replay or durable queu
## Handshake and compatibility
The server first emits a `hello` object with `sessionId`, `protocolVersion`
(`major: 1, minor: 0`), real `runtimeVersion`, `capabilities` and `limits`.
(`major: 1, minor: 1`), real `runtimeVersion`, `capabilities` and `limits`.
Session identity is opaque and process-local, excluded from deterministic oracles.
Before work, the client sends `initialize` with `protocolVersion` and an array
@@ -130,6 +130,8 @@ if the process dies. The final response is authoritative when delivered.
Shutdown/EOF requests cancellation, waits for the active work to reach its boundary,
drops the host and exits; explicit shutdown receives its response after cleanup.
Negotiated memcard shutdown may refuse with native state and keep the channel
available, as specified in [Memcard controls](#memcard-controls).
Disconnect never starts/resumes execution. A failed process requires a new explicit
session, not replay. Host session loss does not implicitly release Studio authority.
@@ -175,6 +177,106 @@ structured faults, progress on partial failure and retained desktop run/debug.
Neither Studio UI nor an AI model is required. See `tests/automation_process.rs`
in prometeu-cli and the in-process deterministic-control tests in the headless crate.
## Memcard controls
Protocol minor 1.1 adds capability `memcard`. Initialize negotiates the lesser
minor. These commands and parameters require minor >= 1 and `memcard` in
requiredCapabilities; unsupported use fails before mutation. Clients negotiating
1.0 keep the previous command/result shapes. No executable-version inference,
default image, alternate transport or headless media startup flags are defined.
| Command | Parameters | Meaning |
| --- | --- | --- |
| memcard_mount | path, action: open/create, access: read_write/read_only | prepare explicit media before boot; bounded result |
| memcard_unmount | empty object | release idle media outside a resident session |
| get_memcard_state | empty object | coherent native observation, without guest execution |
| boot | path, optional memcardChoice: persistent/memory_fresh/memory_existing | explicit player choice required for a memcard cartridge |
| memcard_reconcile | empty object | recover selected same-card identity while suspended |
| memcard_continue_in_memory | empty object | explicit safe SO detach, preserving RAM |
| reset / shutdown | optional discardUnsaved (false), pendingWrites: wait/cancel (wait) | controlled teardown; no autosave |
Mount requires no resident game or outstanding IO. Create/read_only is invalid.
Paths are resolved relative to process cwd, reported absolutely; parent directories
must exist. Open does not create; create never replaces, converts or repairs media.
Persistent requires writable coherent media; memory_existing requires a readable
record for the cartridge appId. No error changes that choice automatically.
After an admitted boot attempt, retry requires explicit reset; parsing and
negotiation failures do not admit boot. Reset preserves selected media/lock.
State has closed objects `media`, `session`, `io`, `recovery`, a nullable `request`,
`dirty` and `dirtySlots`. Media reports path/cardId/access/preparation/error/health;
session reports identity/choice/mode/boot phase/residency/action requirement.
Requests report original identity, operation, local slot, state, deadline reason,
storage error and retention, independently of IO activity. cardId is 32 lowercase
hex digits; request IDs and mount epochs are decimal strings. Unknown values are
null, never invented outcomes. Schemas distributed with the installation specify
all fields. Inspection never releases requests or exposes private save payloads.
Domain failures use `memcard_error` with `details.operation`, `details.reason`
and `details.state`. Reasons include choice_required, unavailable, corrupt,
unsupported, read_only, access_denied, already_exists, busy, no_space,
out_of_memory, invalid_state, invalid_range, counter_exhausted, identity_mismatch,
unsaved_changes, indeterminate and restart_required. Human messages are not codes.
Original worker error, deadline cause and durable result are separate observations.
Shutdown stops an active advance at its existing frame boundary, then evaluates
IO and dirty RAM. Wait/cancel only concern already admitted work. After IO ceases,
remaining dirty RAM without discard consent returns unsaved_changes and leaves
the session/channel usable. Terminal results retained by the guest alone do not
block closure. Unconfirmed IO cessation never returns closed:true or permits
resource/lock release. Successful negotiated reset adds `memcard` to the state
result; shutdown returns closed:true and its final `memcard` snapshot, after checked
cleanup. EOF/output loss attempts bounded cancellation without save/resumption;
process death does not establish publication outcome.
An advance stopped for resident media action returns stop:action_required with
known completed progress. Resident state is paused; a host dialog is not counted
as a game frame. Idle IO polling leaves guest counters/input unchanged. Reconcile
accepts no replacement path, validates expected identity before changes, preserves
RAM/continuation/original retained results and does not rerun initialization.
Runtime qualification uses neutral PBX/ABI fixtures, real distinct processes and
an isolated extracted distribution. It proves SUCCESS, termination, exact readback
without resave and stable appId across cartridge versions. Consumer source-language
compilation and client adaptation are separate work; the provider has no frontend
build dependency. No global installation or consumer configuration update is needed.
### Integration sequence
Start `prometeu headless --stdio` from the selected installation and consume its
hello before sending work. Require the capability explicitly:
```json
{"requestId":"init","command":"initialize","params":{"protocolVersion":{"major":1,"minor":1},"requiredCapabilities":["memcard"]}}
{"requestId":"media","command":"memcard_mount","params":{"path":"/absolute/save.pmc","action":"open","access":"read_write"}}
{"requestId":"boot","command":"boot","params":{"path":"/absolute/cartridge","memcardChoice":"persistent"}}
{"requestId":"step","command":"advance","params":{"frames":1}}
{"requestId":"save-state","command":"get_memcard_state","params":{}}
{"requestId":"close","command":"shutdown","params":{"pendingWrites":"wait"}}
```
Each request above follows the successful response to the preceding one. Creating
new media requires a deliberate `action:create`; do not retry an open failure
with create. Memory choices are `memory_fresh` and `memory_existing`. No client
may replace a failed persistent choice with either automatically.
If closure reports unsaved_changes, keep the process/session and expose that
native state to the caller. A later explicit choice may send
`{"discardUnsaved":true,"pendingWrites":"cancel"}`; do not infer that consent
from a UI stop, timeout or process error. A successful commit is the guest/native
request state `success`, independently of its reason; neither an advance response
nor closed:true proves that a save occurred.
On reopening, launch a different process, open the same image and choose the
appropriate mode explicitly. The neutral process oracle verifies exact prior
bytes without resaving and repeats with a changed cartridge version and unchanged
appId. Run `cargo test -p prometeu-cli --test automation_process
memcard_public_distinct_process_save_readback_and_version_identity`; add
`--release` to qualify that profile independently. For an extracted archive,
set `PROMETEU_PROTOCOL_TEST_INSTALL` and run the ignored
`packaged_memcard_process_persistence` test. It invokes the installed dispatcher
from another cwd without modifying any consumer project or installation.
## Program Registry integration
When exposing initialization failures, retain the [structured load error](02c-program-registry-and-pbx-v0.md#errors-and-publication) code, typed reason and available context. Human-readable messages are not a parsing contract; a load error has no fabricated runtime PC. Failed loads must not publish executable sessions. Existing protocol request names and transport behavior are unchanged.