Files
prometeu-studio/docs/specs/compiler-languages/pbs/26. Memcard Bootstrap and SDK Specification.md
bquarkz 1d8b8c2101
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good
feat(studio): integrate memcard persistence and headless controls
Persist cartridge identity and slot configuration, add MemcardBoot and the MemcardBuffer SDK, and consume the runtime's negotiated memcard host controls with protected teardown.

Qualify save/reopen and version upgrades through distinct configured runtime processes. Include specs, examples, regression evidence and the consolidated discussion lesson.
2026-10-30 11:01:02 +00:00

154 lines
8.5 KiB
Markdown

# Memcard Bootstrap and SDK Specification
Owner: compiler/pbs; propagation to compiler/general and studio.
## Source configuration and identity
`prometeu.json` accepts numeric integral `app_id` (uint32, 0..4294967295) and
optional integral `memcard_slots` (1..64). Strings, booleans, Null, fractions and
out-of-range values MUST fail validation. Memcard opt-in MUST have exactly one
role 3 target, capability memcard and a bootstrap boundary. Memcard imports without
that complete declaration MUST fail before launch; ordinary projects remain unchanged.
Studio persists an explicit initial app_id for new projects and adopts the
legacy generated value once for an older project before shipping. Adoption MUST
preserve unrelated manifest fields and existing explicit IDs. Rename, version,
language and stdlib changes MUST NOT derive a new ID. A copied manifest is the
same game; a distinct game needs an explicitly different identity. The source
identity is propagated losslessly to build/manifest.json, with slots only when
memcard is enabled. Media path and session policy are local host configuration.
## Marker and lifecycle boundary
```pbs
[MemcardBoot]
fn restore(context: long) -> int {
// Inspect admitted RAM and provide presentation through @sdk:mem.
return 0;
}
```
The marker MUST select a nongeneric top-level user function of exact signature
(long)->int with no captures. It accepts no arguments and MUST NOT combine with
another lifecycle marker. Doc metadata, global access and internal closures remain
allowed. Uniqueness is per compiled image and canonical source identity, including
imports and reexports. Names and normal direct calls do not grant lifecycle authority.
The target and its dependencies MUST survive optimization without source callers.
Registry role is 3 and physical FunctionId MUST NOT be zero.
PBS contributes an explicit neutral host-bootstrap request through serializable
common lifecycle declarations. Common assembly emits mem.bootstrap@1 HOSTCALL
with 0 arguments/1 Int32 result after all file/module/project initialization,
inside the once-per-boot guard and before the first Frame. It discards the gate
result after runtime admission. It MUST NOT directly invoke the role, inspect
PBS names or teach the runtime Init/Frame concepts. Ordinary images emit no gate.
READY=0 and INCONSISTENT=1, diagnostic text (at most 1024 UTF-8 bytes), continuation,
budget/trap behavior and provisional registration follow the runtime contract.
A commit submitted in the hook stays pending until READY/coherent registration;
the hook MUST return rather than await it. Resume/remount does not rerun Init or
bootstrap. BeforePause may submit/return and BeforeResume may query across frames.
## MemcardBuffer
`@sdk:mem` exports the nongeneric opaque source type MemcardBuffer. Construct
`new MemcardBuffer(capacity)` with int capacity in 0..4096. Storage is fixed length
and zero initialized; `capacity() -> int`, `read(index: int) -> int` and
`write(index: int, value: int) -> void` provide checked access. Reads always return
an int, with no vacancy/optional representation. Values MUST be in 0..255;
invalid capacity/index/value traps before mutation. Copies alias the same buffer.
The compiler MUST identify the origin-verified SDK declaration, not its spelling,
and lower it directly to concrete Array<Int32> in common Registry/PBX. There is
no Struct wrapper, Dynamic boxing, automatic conversion from ordinary arrays,
copying adapter, new runtime BuiltinId or syscall. Allocation and work obey the
existing VM limits and element charge (four bytes per element). Ordinary PBS
arrays retain their existing vacancy and optional-read semantics.
The same carrier serves slot_read, slot_write and presentation. Successful reads
mutate the same buffer only over the returned range. The buffer owns guest RAM,
not a persistent logical slot or the runtime's asynchronous snapshot.
## Installed SDK
`import {Mem} from @sdk:mem;` selects the forwarding facade. LowMem contains the
exact module mem/version 1/capability memcard host bindings. Bootstrap is compiler
owned; a game MUST NOT manually substitute a direct hook call or bootstrap call.
All numeric domain results/context/request use long, except the Int32 bootstrap
result. Flags are bool; text is str; ranges/local slots are int; presentation
format version is long to represent uint32. Byte transport is MemcardBuffer, each
value 0..255, at most 4096 per transfer; slot capacity is 65536 private bytes.
| Native ID | Binding | Arguments | Results (native order) |
| --- | --- | ---: | --- |
| 0x4200 | bootstrap | 0 | int readiness |
| 0x4201 | slot_count | 1 | status, count |
| 0x4202 | slot_stat | 2 | status, has_payload, used_bytes, generation, update_at, crc32c, dirty |
| 0x4203 | slot_read | 6 | status, bytes_read |
| 0x4204 | slot_write | 6 | status, bytes_written |
| 0x4205 | slot_commit | 2 | status, request |
| 0x4206 | slot_clear | 2 | status |
| 0x4207 | query | 2 | status, state, reason |
| 0x4208 | release | 2 | status |
| 0x4209 | info | 1 | status, mode, is_new, recovered, degraded, write_blocked |
| 0x420A | metadata | 1 | status, title, data_format_version, created_at |
| 0x420B | presentation | 8 | status |
| 0x420C | diagnostic | 2 | status |
| 0x420D | publish_presentation | 1 | status, request |
slot_stat.has_payload is numeric 0/1; dirty/info health flags are bool.
The PBS source tuple groups generation/update_at/crc32c under `stat.durable`;
recursive flattening preserves all seven native results and their exact types/order,
without increasing the language's six-field tuple bound. CRC/generation/timestamp
are durable descriptor data; used_bytes/dirty describe RAM. Unsigned 64-bit values
retain their bit pattern in long. This SDK introduces no general save codec.
The installed facade uses origin-checked exact host forwarding. Its callsites
emit the native operation directly, preserving error Null payloads until the
caller checks status; an intermediate typed-return wrapper MUST NOT turn an
ordinary domain error into a VM type trap. Argument order and evaluation are
preserved. The private HostForward binding accepts only a single exact host
return of unchanged positional parameters and matching result ABI.
Every operation checks status before using payload. Error payload positions are
Null and MUST remain unobserved on a failed status. Status 0 is 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. Type/heap/carrier violations are VM traps.
Submitting a commit does not establish persistence. Query state 0 pending,
1 success, 2 failure, 3 indeterminate, 4 memory-only is independent of reason.
Reason 15 is deadline/restart; Success/15 is valid. Only one request/result is
retained until release. Release MUST NOT free in-flight resources. A source slot
is readable but rejects writes/clear with BUSY while committing; other slots
continue. Clear changes RAM and requires explicit commit. No implicit retries,
autosave or disk waits are hidden by the facade.
## Provider boundary and qualification
Runtime owns hosts/headless/storage, explicit persistent/fresh-RAM/load-existing-RAM
choices, concurrent image access, discard confirmation and reconciliation. Studio
uses supported public configuration/operations/diagnostics of its configured
installation. Missing/failed media MUST NOT silently choose memory-only. Image
creation is explicit and never overwrites a file. The development image location
is .studio/memcard.pmc, outside build output; shared images require explicit choice.
Transport loss/timeout/forced termination cannot prove rollback or durable failure.
A missing provider surface is an explicit external dependency, never invented flags,
a second host or a duplicated SO/Hub UI. RAM survives pause/resume.
The installed opt-in `memcard/` subproject demonstrates presentation, status-first
read/write, query and release separately from the ordinary example. Qualification
MUST distinguish source/PBX, native production-host and configured-process evidence.
Complete persistence proof requires SUCCESS, process termination, a new process on
the same image, exact bytes, and the same result after a project-version change.
Record provider revision, OS/architecture, runtime dev/release and PBS optimizer
variants. Native injection is useful contract evidence but never substitutes for
that process proof.
## References
- [Runtime memcard contract](../../../../../runtime/docs/specs/runtime/08-save-memory-and-memcard.md).
- [Common Registry](<../../compiler/25. Typed Registry and PBX v0 Specification.md>).