feat(runtime): implement shared transactional memcard with async saves
Intrepid/Prometeu/Runtime/pipeline/pr-master This commit looks good

This commit is contained in:
2026-10-13 15:24:01 +01:00
parent 0af8b2b1fe
commit 6c2a07e579
65 changed files with 6222 additions and 985 deletions
@@ -89,17 +89,20 @@ Code offsets are relative to Code. Local and temporary counts widen from current
## Optional lifecycle roles
The executable Function record carries one role byte before its optional name:
`0=None`, `1=BeforePause`, `2=BeforeResume`. Zero means an ordinary function,
`0=None`, `1=BeforePause`, `2=BeforeResume`, `3=MemcardBoot`. Zero means an ordinary function,
not a callable hook. Unknown values reject with InvalidRegistry/LifecycleRole.
Each nonzero role has at most one target; duplicates reject with
InvalidRegistry/DuplicateLifecycleRole. Targets MUST NOT be FunctionId 0 and
MUST have zero parameters, results and captures; violations reject with
MUST have zero captures. Pause/resume roles have zero parameters and results;
MemcardBoot has exactly one Int64 parameter and one Int32 result. Violations reject with
InvalidEntrypoint/LifecycleSignature. Preserve function/section context and the
wire offset when decoding an invalid role. Resolve optional FunctionIds once
in the immutable Registry. Names, exports, manifests and trait Method records
are not the binding mechanism.
Either hook may be absent. Additional roles require a future contract; there is
Pause/resume hooks may be absent. MemcardBoot is required for a cartridge with
the memcard capability and is invoked only at its explicit bootstrap gate.
Additional roles require a future contract; there is
no termination role. PBX remains version 1, with no old-layout fallback or
external-artifact compatibility. Producers MUST regenerate their images and
emit this byte for every function, including zero for ordinary functions.
+277 -92
View File
@@ -3,138 +3,323 @@
Domain: virtual hardware: save memory
Function: normative
Didactic companion: [`../learn/mental-model-save-memory-and-memcard.md`](../runtime/learn/mental-model-save-memory-and-memcard.md)
The runtime implements image transactions, per-game RAM snapshots, a shared
asset/IO worker and an explicit guest bootstrap gate. Host latency and durability
qualification apply to the concrete host and storage device.
## 1 Scope
## 1. Ownership and capacity
This chapter defines the `game` persistence surface in PROMETEU.
A runtime has at most one installed card. A card contains 64 shared logical slots,
each holding 0..65,536 private bytes, and 68 physical blocks of 65,536 bytes.
There are four nominal rotating spares when all logical slots contain data; all
healthy unprotected blocks participate in the pool. Physical IDs are never game
slot IDs. Each of at most 64 game records owns at least one logical slot.
MEMCARD is a runtime-owned service layered on top of the runtime filesystem.
The cartridge declares a `memcard_slots` count in 1..64 together with the memcard
capability. Allocation and growth are all-or-nothing. A smaller declaration uses
the prefix of the prior allocation and retains excess slots/data. The authorized
`app_id` is the cartridge's uint32 identity. Guest indices are local 0..N-1.
Newly assigned slots expose no residual bytes. Game clear retains ownership;
external administration removes the entire game and all its metadata/slots.
There is no external single-slot deletion. Space management/card switching is
an explicit player action outside gameplay.
Games do not get broad path-based filesystem access for saves. They use slot operations only.
## 2. Image encoding
## 2 Profile Contract (`game`)
All integers are unsigned little-endian unless stated otherwise. There is no
filesystem inside the image. Every reserved byte is zero. Readers reject unknown
versions, malformed lengths, overlapping/out-of-range references and unknown
flags before following references. Creation allocates the entire 5,259,264-byte
image physically, including currently unused regions, and publishes the file's
namespace durably. Sparse length extension alone is insufficient.
The v1 contract is fixed:
| Region | Offset | Length |
| --- | ---: | ---: |
| Identity A | 0 | 4,096 |
| Identity B | 4,096 | 4,096 |
| Map A | 8,192 | 4,096 |
| Map B | 12,288 | 4,096 |
| Catalog A | 16,384 | 131,072 |
| Icons A | 147,456 | 262,144 |
| Catalog B | 409,600 | 131,072 |
| Icons B | 540,672 | 262,144 |
| Physical blocks 0..67 | 802,816 | 4,456,448 |
- `32` slots per game (`slot_index: 0..31`);
- each slot has up to `32KB` payload;
- ownership is isolated by `app_id`;
- persistence is explicit through `slot_commit`;
- copy/export/import is a Hub/OS responsibility (outside game userland).
Each identity page contains: magic `PMCARD1\0` at0 (8 bytes), version1:u32
at8, image length:u32 at12, host-generated random cardId:[u8;16] at16,
zero padding32..4092 and CRC32C:u32 at4092. CRC covers bytes0..4092 (exclusive
of the CRC). Either valid identity is sufficient; two valid differing identities
are inconsistent. A degraded single identity must be reported.
## 3 Slot Identity and Metadata
CRC32C uses reflected Castagnoli polynomial0x82f63b78, initial0xffffffff,
final xor0xffffffff, reflected byte input/output. Empty input produces0;
ASCII `123456789` produces0xe3069283. Payload CRC covers exactly used bytes.
Catalog and icon CRCs cover exactly the declared used region. Administrative
page CRC covers all bytes preceding its last4-byte checksum, including padding.
Each slot has runtime-owned metadata:
Each map page contains:
- `app_id` owner;
- `slot_index`;
- `save_uuid`;
- `generation`;
- `checksum`;
- `payload_size`;
- `state`.
State values:
- `0 = EMPTY`
- `1 = STAGED`
- `2 = COMMITTED`
- `3 = CORRUPT`
`generation` and `checksum` are not manually controlled by game code:
- `generation` increments on successful `slot_commit`;
- `checksum` is recalculated by runtime for committed payload integrity.
## 4 Host ABI Surface (v1)
Canonical module: `mem` (version `1`).
| Operation | Signature |
| Offset | Field |
| --- | --- |
| `slot_count` | `mem.slot_count() -> (status:int, count:int)` |
| `slot_stat` | `mem.slot_stat(slot:int) -> (status:int, state:int, used_bytes:int, generation:int, checksum:int)` |
| `slot_read` | `mem.slot_read(slot:int, offset:int, max_bytes:int) -> (status:int, payload_hex:string, bytes_read:int)` |
| `slot_write` | `mem.slot_write(slot:int, offset:int, payload_hex:string) -> (status:int, bytes_written:int)` |
| `slot_commit` | `mem.slot_commit(slot:int) -> status:int` |
| `slot_clear` | `mem.slot_clear(slot:int) -> status:int` |
| 0 | magic `PMMAP1\0\0`, 8 bytes |
| 8 | publication sequence:u64, positive |
| 16 | public-copy selector:u32, 0 or1 |
| 20 | catalog used length:u32, <=131072 |
| 24 | catalog CRC32C:u32 |
| 28 | icons used length:u32, <=262144 |
| 32 | icons CRC32C:u32 |
| 36 | cardId:[u8;16], equal to identity |
| 52 | 12 reserved zero bytes |
| 64 | rotation order: permutation of physical IDs0..67, 68 bytes |
| 132 | quarantine flags: 68 bytes, each0 or1 |
| 200 | 56 reserved zero bytes |
| 256 | 64 slot descriptors, each40 bytes |
| 2816 | zero padding through4091 |
| 4092 | page CRC32C:u32 |
`status` is always the first return slot.
A slot descriptor has state:u8 at0 (0 unassigned,1 EMPTY,2 payload), physical
ID:u8 at1 (255 unless payload), zero:u16 at2, used bytes:u32 at4,
generation:u64 at8, update_at:u64 at16, payload CRC32C:u32 at24 and12 zero
bytes at28. Unassigned is canonical except physical ID255. EMPTY has no physical
block, zero used bytes/CRC, but can have a save generation/time. Payload requires
1..65536 used bytes, physical ID0..67 and positive generation. A physical block
has at most one owner per map and cannot also be quarantined. Assigned descriptor
IDs must equal the union of catalog assignments.
### 4.1 Byte transport note (v1)
Generation0 means never saved, with canonical timestamp0; first persistent commit
is1, including empty commits. Later commits/clear increment it. With positive
generation, timestamp0 is a valid epoch date. Sequence and generation never wrap;
a required increment at uint64 maximum refuses publication. Equal sequence only
permits byte-identical map content; differing content is corruption.
Current ABI transport for memcard payload is `payload_hex:string`.
## 3. Public catalog and icons
This is a temporary transport form until VM-owned bytes (`HeapRef<Bytes>`) is exposed in the host ABI path.
Each catalog is UTF-8 JSON, schema version1, maximum depth8, closed objects and no
duplicate keys. Integers are exact unsigned values in their declared range (no
floating-point conversion). Unknown fields, wrong types and invalid Unicode are
rejected. The root has exactly `metadataVersion` (1) and `games` (array, <=64).
Each game has exactly:
## 5 Operation Semantics
- `app_id`: uint32, unique and authorized by the runtime;
- `title`: nonblank UTF-8 string, <=128 decoded bytes, reject rather than truncate;
- `dataFormatVersion`: uint32, game-defined including0;
- `created_at`: uint64 UTC Unix seconds for first registration;
- `slots`: nonempty array of distinct logical IDs0..63, exclusive across games;
- `icon`: object with `offset`:uint32, `frames`:1..4, `duration`:uint16,
`crc32c`:uint32. Offset is relative to the selected public icon region.
### `slot_count`
An icon contains a48-byte palette in RGB order (16 opaque RGB888 colors), followed
by512 bytes per32x32 frame, row-major, first pixel in the high nibble. All16
indices are ordinary opaque colors. Its length is48+512*frames. Icon ranges must
not overlap and CRC covers palette and all frames. `duration` is1..65535 units of
1/30 second, shared by all animated frames. Static icons use canonical duration1.
A consumer cycles frames while visible using its SO/Hub clock; rendering or a
save-management application is not part of the game runtime.
- returns slot capacity visible to game profile (`32`);
- does not depend on slot content.
The maximum icon payload is64*2096=134144 bytes, within262144. Even charging768
bytes per escaped128-byte title, maximal decimal integers, every logical-slot ID
and field punctuation, a canonical game record is bounded by2048 bytes; the
actual maximum catalog must fit131072 including its root. Producers use compact
serialization and validate final length; readers never allocate from an unchecked
length or require both public copies/icons in RAM.
### `slot_stat`
Ordinary slot commits do not rewrite JSON. created_at survives updates, but a
removed/recreated record obtains a new date. Slot update_at/generation/CRC live
only in binary descriptors. The game's last-save date is derived as max update_at
over positive generations; no such slots means never saved. Public readers can
locate slot bytes and check CRC without interpreting the private payload.
- returns current state and integrity/version metadata for one slot.
## 4. Publication, retirement and recovery
### `slot_read`
Before overwriting any block/public region, protect the union of references from
both usable maps. Retire an older map by overwriting its full page with zero,
syncing and verifying it is no longer a usable map; only then may references held
exclusively by it be reused. The current coherent map remains untouched. A failed
retirement stops that operation; no referenced data is overwritten speculatively.
- reads from staged content when present, otherwise committed content;
- returns empty payload with success when offset is beyond current payload end.
A nonempty commit freezes its RAM source, chooses a healthy unprotected block,
writes payload, syncs and verifies readback CRC. Then it writes the inactive map
with next sequence/descriptor, syncs and verifies that map before SUCCESS. Empty
commit publishes EMPTY without a data block. Former blocks join the end of the
rotation queue when eligible; they are not erased after commit.
### `slot_write`
Catalog changes prepare the inactive public copy, sync/readback-verify it, and
publish its reference together with allocation/descriptors in a new map. Retire
any old map referencing that destination before overwriting it. Registration,
growth, whole-game removal and presentation update are coherent administrative
publications. Payload is never saved automatically. dataFormatVersion changes do
not migrate data or promise atomic migration of multiple slots.
- writes into slot staging buffer (does not persist directly);
- supports offset writes;
- does not allow resulting payload above `32KB`.
Mount validates candidate maps, catalog and all referenced payload CRCs; select
the newest coherent publication. A page checksum alone is insufficient. Report
recovery from an older map explicitly; never silently roll back confirmed saves.
No coherent map means corruption, not empty media. Persist quarantine exclusions;
known exclusions survive recovery of an older map. If exclusion cannot be made
durable safely, block writes until revalidation. Reintegration requires explicit
verification, never merely remount. Transient timeout does not prove block damage.
Mount state and health/write permission are separate: DEGRADED may write with a
safe candidate; READ_ONLY still permits valid reads.
### `slot_commit`
Durable result codes are SUCCESS=1, FAILURE=2, INDETERMINATE=3. PENDING=0 and
MEMORY_ONLY=4 are request states/results without a durability claim. FAILURE
requires proof of no publication; write/sync errors may have partial effects.
The uncertain window begins when publication-capable metadata is attempted.
Retain attempt cardId/slot/target sequence/generation/CRC for same-card
reconciliation before more writes. Confirmed success survives cleanup failure.
- persists staged payload for one slot;
- commit is atomic at slot operation level (all-or-error, no silent partial success).
## 5. RAM and guest operations
### `slot_clear`
Before boot reserve N*65536 bytes of actual snapshot capacity, one 65536-byte
scratch and bounded metadata/backend overhead. Memory-only mode has the same
requirement. Insufficient RAM prevents admission with a diagnostic. Existing
saves are validated and loaded, never replaced with empty on integrity error.
Only the game's declared prefix is resident, not other games' payloads.
- clears staged content and removes committed slot payload.
Read/write/clear are bounded RAM operations. Write zero-fills gaps and rejects
end offsets beyond65536. Clear makes used length0 and retains ownership; commit
persists that clear. During an in-flight commit the source slot rejects mutations
with BUSY, but remains readable; other slots/gameplay continue. No duplicate full
source snapshot is allowed. Protect its storage until the host ceases all use.
## 6 Status Codes (Domain-Owned)
The mem module uses a session-bound Int64 context and local slot indices. Byte
transport is Array<Int32>, values 0..255, at most 4096 bytes per guest call. Validate
array type, element values, range/overflow, ownership and all output capacity
before copying or mutating. Charge array storage (four bytes per element) and
copy work. Host IO maximum remains 65536. A native array reference cannot escape
the bounded call into asynchronous work; async source is the native snapshot.
Minimum status catalog:
The [guest ABI](#guest-abi) fixes domain status and request result encodings.
Request identity is separate from status and durable result. All queries validate
session/mount/request identity. Only one request/result entry exists, retained
until explicit release; release never frees in-flight resources. No payload queue.
- `0 = OK`
- `1 = EMPTY`
- `2 = NOT_FOUND`
- `3 = NO_SPACE`
- `4 = ACCESS_DENIED`
- `5 = CORRUPT`
- `6 = CONFLICT`
- `7 = UNAVAILABLE`
- `8 = INVALID_STATE`
## 6. Bootstrap and producer contract
## 7 Fault Classification
The Registry role 3 is MemcardBoot(context:Int64)->Int32, no captures, unique and
never FunctionId 0. Role number is not FunctionId. Capability requires that binding;
absence of capability skips snapshot and hook. Roles 0/1/2 are unchanged.
MEMCARD follows `16a`:
The producer emits an explicit memcard bootstrap boundary after its initialization
and before its first frame. Runtime recognizes a bootstrap phase, not FE concepts
such as Init/Frame. Snapshot/preload is ready before that boundary; the hook runs
once on the main lane, preserving continuation, with1,500,000 total cycles and
250,000-cycle slices outside frame accounting. READY=0 or INCONSISTENT=1 returns
with a bounded diagnostic (up to1024 UTF-8 bytes) set via the service. Invalid
return/trap/budget exhaustion blocks admission and reports through SO/Hub.
- `Trap`: structural violations (invalid slot index, invalid call shape, invalid window value type/range);
- `status`: operational domain conditions;
- `Panic`: runtime invariant break only.
New records/slots are provisional while the hook provides presentation. A commit
may be submitted during the hook; it remains pending until READY and coherent
catalog publication. The hook must return rather than wait for that dependent
commit; normal frames may later query its result. This uses the one existing
request entry, not a second queue. INCONSISTENT invalidates provisional admission
and never publishes its payload. IO wait and guest cycle budgets are separate.
Retries/remount/resume never automatically rerun the hook or main initialization.
Silent no-op is forbidden for operations with operational failure paths.
## 7. Executor, host and deadlines
## 8 Runtime Layering and Storage Mapping
Host implements complete-or-error read_at/write_at of up to 64 KiB, sync and
bounded cancellation/recovery or fault escalation. Partial transfers are normalized
inside host bounds; failure may have changed storage. Runtime owns all logical
mapping, checksums, publication and request policy. Deliver file backend and fault
backend; raw flash requires separate qualification.
MEMCARD is a domain layer over runtime FS.
Use one shared async_work lane with assets. Save has highest priority; an asset
finishes a bounded safe step, retains its progress and yields to the whole save,
then resumes from that point. Retained save result does not retain the worker.
No extra worker or waiting inside the only worker implements yielding.
Runtime host mapping for v1 is namespace-isolated by `app_id`, for example:
Measure from admission with monotonic time: start within one nominal frame
(~16.7ms), healthy target 100ms, initiate cancellation at 500ms, stop or escalate
and notify by 1s. Deadline control runs outside potentially blocked IO. Coordinate
cancel with publication entry; no retries after deadline. Timeout is a reason,
not proof of rollback. If cessation is unconfirmed, isolate mount/resources,
block new work and retain source/scratch. Late completion belongs to original
reconciliation. Never kill threads unsafely, free buffers in use or create a
replacement worker. Report restart requirement when host recovery is impossible.
Fast-profile claims require measurements under asset load, including tail latency.
`/user/games/<app_id>/memcard/slot_<NN>.pmem`
## 8. Player choice and lifecycle
The exact host-side file naming is internal to runtime/host as long as ownership and isolation guarantees are preserved.
The player chooses PERSISTENT or MEMORY_ONLY through SO/Hub. No required/optional
mode is imposed by the game. Memory-only commit performs no IO and makes no
persistence claim or hidden temporary save. With a readable existing save, offer
load-to-RAM or clean start explicitly. RAM survives pause/resume and removal;
warn before discarding unsaved changes when ending the session.
## 9 Explicit Persistence Rule
Removal uses existing OS pause and external choices to restore/switch card,
continue in RAM or exit. Same-card reinsertion reconciles with a new mount epoch
without overwriting RAM. Different card requires validation/allocation and explicit
keep-local/load-existing choice. No automatic upload, reload, save or reinit.
BeforePause can submit and return without waiting for disk; BeforeResume can query.
Session termination retains resources used by outstanding IO until safe cessation.
PROMETEU does not auto-save slot staging data.
The legacy per-slot file format is unsupported by this image codec. Preserve
legacy files; do not migrate or delete them automatically. Internal fixtures are
regenerated; removal of the old runtime path follows validated integration.
Without `slot_commit`, writes remain staged and are not guaranteed as persisted committed state.]
## Guest ABI
All entries use module `mem`, version 1 and capability `memcard` (bit 9).
Context and request IDs are positive Int64 values. Other numeric domain results
use Int64; `dirty`, `new`, and health flags use Bool. Unsigned 64-bit generations
and timestamps use the Int64 bit pattern without changing their unsigned meaning.
Guest indices/ranges may use Int32 or Int64 and must be nonnegative.
Error results carry the leading status and Null for unused payload positions.
| ID | Operation | Results in declaration order |
| --- | --- | --- |
| 0x4200 | bootstrap() | hook result: Int32 (0 READY, 1 INCONSISTENT) |
| 0x4201 | slot_count(context) | status, count |
| 0x4202 | slot_stat(context, slot) | status, has_payload, RAM used_bytes, generation, update_at, CRC32C, dirty |
| 0x4203 | slot_read(context, slot, offset, array, array_offset, count) | status, bytes_read |
| 0x4204 | slot_write(context, slot, offset, array, array_offset, count) | status, bytes_written |
| 0x4205 | slot_commit(context, slot) | status, request |
| 0x4206 | slot_clear(context, slot) | status |
| 0x4207 | query(context, request) | status, state, reason |
| 0x4208 | release(context, request) | status |
| 0x4209 | info(context) | status, mode, new, recovered, degraded, write_blocked |
| 0x420A | metadata(context) | status, title, dataFormatVersion, created_at |
| 0x420B | presentation(context, title, dataFormatVersion, frames, duration, array, offset, count) | status |
| 0x420C | diagnostic(context, message) | status |
| 0x420D | publish_presentation(context) | status, request |
`slot_stat` reports the durable descriptor alongside RAM length/dirty state;
CRC32C does not pretend that uncommitted RAM is already durable. `presentation`
sets the game-owned public fields; initial boot publishes them after READY.
Subsequent explicit `publish_presentation` uses the same one-request slot.
Icon bytes include the 48-byte RGB888 palette followed by packed frames.
Diagnostics are UTF-8 strings bounded to 1024 bytes.
Status values: 0 OK, 3 NO_SPACE, 4 ACCESS_DENIED, 5 CORRUPT,
6 INDETERMINATE, 7 UNAVAILABLE, 8 INVALID_STATE/CANCELED, 9 BUSY,
10 READ_ONLY/COUNTER_EXHAUSTED, 11 INVALID_RANGE, 12 UNSUPPORTED,
13 IO_ERROR, 16 OUT_OF_MEMORY. Query states: 0 PENDING, 1 SUCCESS,
2 FAILURE, 3 INDETERMINATE, 4 MEMORY_ONLY. Query reason uses the status
catalog, plus 15 for deadline/restart escalation. Mode 0 is PERSISTENT and
1 is MEMORY_ONLY. Type/heap/range violations at the array carrier are VM traps;
ordinary storage failures are domain results.
## Host integration
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
on the shared worker. Unsupported hosts must reject physical-allocation claims.
The headless host accepts an injected `MemcardStorage` through `install_memcard`
and an explicit player policy through `boot_with_memcard_choice`. Its boot loop
waits for actual worker progress with a bounded watchdog timeout; frame execution
remains independent of real-time pacing.
Before guest boot, firmware presents persistent, fresh-memory-only and (when
available) existing-save-memory-only choices. Choosing no card does not bypass
snapshot reservation. Leaving a resident game with dirty RAM requires an explicit
discard decision. A blocked host operation produces a restart dialog by 1 second;
it does not free in-flight buffers or create another worker.
Native administrative operations run outside gameplay. Whole-game removal,
explicit card revalidation and explicit reintegration use the shared worker.
Revalidation preserves known quarantined blocks; reintegration separately tests
and durably clears one exclusion. Same-card replacement preserves RAM and advances
the mount epoch. Different-card replacement takes an explicit keep-RAM or
load-existing choice and never invokes initialization or bootstrap again.
@@ -80,8 +80,8 @@ flush, disk-completion wait, guest event queue or reason argument is added.
Host-owned in-flight work keeps its ownership until the service/host safely
releases it; lifecycle failure does not simulate cancellation or free borrowed
buffers. Native calls must return promptly: VM fuel only bounds bytecode and
cannot preempt a blocked native/host call. Existing FS read/write and the current
memcard commit backend are synchronous interfaces, so this implementation does
not promise a wall-time bound for them. The new asynchronous memcard backend
must expose bounded submission/polling independently; hooks can then submit an
explicit commit without waiting for disk completion.
cannot preempt a blocked native/host call. Existing FS read/write interfaces remain synchronous. Memcard commits use
bounded admission and query calls on the shared asset/IO lane. BeforePause can
submit a commit and return immediately; BeforeResume can query the retained
result. The independent 500ms cancellation and 1s host escalation deadlines are
defined by [save memory](08-save-memory-and-memcard.md).
+11
View File
@@ -35,6 +35,7 @@ The runtime currently expects the following manifest fields:
Additional manifest-supported fields include:
- `capabilities`
- `memcard_slots`: a count in 1..64, required exactly when the memcard capability is declared
## 3 Required Fields
@@ -63,6 +64,7 @@ The current loader validates:
- `cartridge_version == 1`
- manifest parse validity
- capability normalization
- memcard capability and slot-count consistency
- presence of `program.pbx`
- when `Asset` capability is declared, presence of valid `assets.pa` before asset bootstrap
@@ -88,6 +90,15 @@ This means:
- firmware/runtime loads the cartridge and starts execution from `func_id = 0`;
- nominal exports may exist for linking or introspection, but they do not hold boot authority.
A cartridge declaring memcard support also supplies the unique Registry role 3
`MemcardBoot(context: Int64) -> Int32` binding, with no captures and a nonzero
FunctionId. Its producer emits the explicit `mem.bootstrap` boundary after its
initialization and before its first frame. The runtime prepares the selected
persistent or memory-only snapshot and asset preload before this optional hook;
normal frame execution waits for successful bootstrap and registration. See
[Save Memory and Memcard](08-save-memory-and-memcard.md) for admission, the guest
contract, and publication semantics.
## 5.1 Runtime Profiles
`Game` and `System` are distinct runtime profiles.
+8 -20
View File
@@ -187,27 +187,15 @@ Return shape must also follow the transversal status-first policy in [`16a-sysca
### MEMCARD game surface (`mem`, v1)
The game memcard profile uses module `mem` with status-first return shapes.
`mem` is a domain layer backed by runtime `fs` (it is not a separate storage backend).
The game surface requires `memcard` capability and an admitted RAM snapshot.
Its native host owns disk IO through `MemcardStorage`; guest code only accesses
its own logical slots. Payload transport is bounded `Array<Int32>` with checked
byte values, never hex strings or retained guest heap references.
The `mem` module is a game profile surface. It is not the public storage model
for `System` profile apps.
Durable memcard data is keyed by `app_id` according to the save-memory
contract. Runtime handles, open file tables, pending lifecycle delivery, and
other mutable VM-facing syscall context are scoped to the owning VM session and
MUST NOT be used as durable app identity.
Canonical operations in v1 are:
- `mem.slot_count() -> (status, count)`
- `mem.slot_stat(slot) -> (status, state, used_bytes, generation, checksum)`
- `mem.slot_read(slot, offset, max_bytes) -> (status, payload_hex, bytes_read)`
- `mem.slot_write(slot, offset, payload_hex) -> (status, bytes_written)`
- `mem.slot_commit(slot) -> status`
- `mem.slot_clear(slot) -> status`
Semantics and domain status catalog are defined by [`08-save-memory-and-memcard.md`](08-save-memory-and-memcard.md).
`mem.bootstrap()` invokes the Registry MemcardBoot role at the producer's explicit
post-initialization gate. Ordinary domain calls use an opaque session context,
status-first results and one retained asynchronous request. See the complete
[ABI table and storage contract](08-save-memory-and-memcard.md#guest-abi).
### Asset surface (`asset`, v1)
+6 -3
View File
@@ -100,14 +100,17 @@ Example groups:
- `gfx`
- `audio`
- `asset`
- `fs` (includes game memcard module `mem` in v1)
- `fs`
- `memcard` (game module `mem`, bit 9)
Capability checks exist to constrain which host-managed surfaces a cartridge may use.
Input in v1 is VM-owned intrinsic surface and is not capability-gated through syscall policy.
Game memcard operations (`mem.*`) are status-first and use `fs` capability in v1.
`mem` remains layered on runtime `fs`; no parallel persistence channel is introduced.
Game memcard operations (`mem.*`) require the separate `memcard` capability
and a manifest `memcard_slots` count in 1..64. Domain operations are status-first;
`mem.bootstrap()` is a controlled-call boundary returning the hook result.
Storage is a host-owned region backend, independent of runtime `fs`.
Domain surface, status catalog and slot semantics are defined in [`08-save-memory-and-memcard.md`](08-save-memory-and-memcard.md).
Asset backlog operations are status-first. `queued`, `active`, `ready`,
+37 -10
View File
@@ -17,7 +17,8 @@ reference boundaries. The separate render frame scheduler remains active.
Fn values, frame-owned capture environments, typed indirect calls and receiver-first
trait dispatch use [the function-value contract](../specs/runtime/02b-vm-function-values-and-closures.md).
FRAME_SYNC resumes next PC; successful root RET permits recurring entry preparation.
New strings/bytes/save APIs, long-run stress and representative-game headroom require
The memcard byte carrier and bootstrap use the [save-memory contract](../specs/runtime/08-save-memory-and-memcard.md).
General string/byte APIs, long-run stress and representative-game headroom require
separate technical contracts and workloads.
The external Studio handoff targets are the build-pipeline
@@ -38,7 +39,7 @@ fallback. Use the canonical chapter's field order and UTF-8 rules, not Rust layo
TypeId, FunctionId and ImplementationId are independent image-local table indices;
zero is valid. BuiltinIds are imports, not local TypeIds. Function records contain
optional name, ordered named parameters, ordered result TypeIds, code offset/length,
a lifecycle-role byte followed by optional name, ordered named parameters, ordered result TypeIds, code offset/length,
extra local slots and maximum temporary slots. Names are independent of debug.
Widths are derived from TypeIds; serialize no parameter/result width caches.
`max_stack_slots = 0` is a literal zero limit. Boot authority remains FunctionId 0.
@@ -55,22 +56,48 @@ module/name/version and exact ABI counts; every declaration must be used. Loadin
binds it to SYSCALL after capability/ABI validation. Raw SYSCALL in producer PBX,
unknown declarations, invalid indices and unused declarations are rejected.
## Memcard and controlled-call lowering
Emit role 0 for ordinary functions, role 1 for optional BeforePause and role 2
for optional BeforeResume. Both lifecycle hooks have no parameters, results or
captures. A memcard-enabled cartridge declares capability `memcard`, a manifest
`memcard_slots` count in 1..64, and exactly one role 3 function with signature
`(Int64 context) -> Int32`, no captures, and a FunctionId different from zero.
The compiler chooses source-level spelling; the runtime binds only the role.
After frontend-owned initialization and before the first frame, emit the declared
`mem.bootstrap` HOSTCALL (0 arguments, 1 Int32 result). The runtime invokes role 3
on the same VM, then resumes the producer continuation after READY and coherent
registration. The producer must not directly call the role as a substitute for
this gate. Use 0 READY or 1 INCONSISTENT, with bounded `mem.diagnostic` text when
needed. This function executes once per boot with controlled-call fuel, outside
frame accounting; Init and Frame remain frontend concepts.
Declare the exact [mem ABI](../specs/runtime/08-save-memory-and-memcard.md#guest-abi).
Use concrete `Array<Int32>` storage for bytes 0..255, transfer at most 4096 bytes
per call, and preserve the session context for subsequent calls. The array's
storage charge is four bytes per element. Save requests return an opaque ID;
query reports durable success/failure/indeterminate or memory-only completion,
and explicit release frees the retained result. Hooks may submit/query; they
must not busy-wait for disk. Initial commits are held until READY so registration
and payload publication cannot deadlock each other.
## Independent binary oracles
The manually specified minimal executable in
`crates/console/prometeu-bytecode/tests/registry_v1.rs::minimal_bytes` is 193 bytes.
`crates/console/prometeu-bytecode/tests/registry_v1.rs::minimal_bytes` is 194 bytes.
Its directory begins at 32; eight entries end at 128:
| Kind | Offset | Length | Payload |
| --- | ---: | ---: | --- |
| constants | 128 | 4 | count 0 |
| functions | 132 | 29 | one unnamed zero-parameter/result function, offset 0, length 2, locals/max 0 |
| code | 161 | 2 | `01 00` (HALT) |
| exports | 163 | 4 | count 0 |
| syscalls | 167 | 4 | count 0 |
| types | 171 | 10 | one unnamed Bool import, BuiltinId `0x0013` |
| implementations | 181 | 4 | count 0 |
| captures | 185 | 8 | function count 1; empty environment |
| functions | 132 | 30 | role 0, one unnamed zero-parameter/result function, offset 0, length 2, locals/max 0 |
| code | 162 | 2 | `01 00` (HALT) |
| exports | 164 | 4 | count 0 |
| syscalls | 168 | 4 | count 0 |
| types | 172 | 10 | one unnamed Bool import, BuiltinId `0x0013` |
| implementations | 182 | 4 | count 0 |
| captures | 186 | 8 | function count 1; empty environment |
The independent multi-slot fixture in the same suite declares `fn(vec2)->vec2`
with TypeId 0, no serialized widths, no extra locals and max 2. Its fourteen code