feat(studio): integrate memcard persistence and headless controls
Test / Tests and coverage
Intrepid/Prometeu/Studio/pipeline/pr-master This commit looks good

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.
This commit is contained in:
2026-10-30 11:01:02 +00:00
parent 3a3417eb44
commit 1d8b8c2101
110 changed files with 6502 additions and 85 deletions
@@ -206,9 +206,16 @@ See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%
## Guest hook marker identity
LifecycleMarker explicitly distinguishes NONE, INIT, FRAME, BEFORE_PAUSE and
BEFORE_RESUME. Preserve marker attributes and source spans alongside the marker;
BEFORE_RESUME and MEMCARD_BOOT. Preserve marker attributes and source spans alongside the marker;
never reconstruct the role from a function name or an import alias. Invalid
attribute targets/combinations MUST be diagnosed rather than silently treated
as ordinary functions. Generic substitution/import processing MUST preserve
canonical source identity and marker metadata. No MemcardBoot marker is defined
by this surface.
canonical source identity and marker metadata. The additional MEMCARD_BOOT marker follows the dedicated memcard contract.
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -283,3 +283,11 @@ MUST preserve bodies and metadata. Common code consumes neutral typed roles,
never PBS ASTs/names. The ordinary assembled entry remains physical FunctionId
zero; hook targets are nonzero after deterministic linking. Common Registry/PBX
validation and production runtime admission remain mandatory defenses.
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -0,0 +1,153 @@
# 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>).
@@ -80,7 +80,7 @@ Rules:
- Attributes are not first-class values and are not reflectable in v1 core.
- Attributes do not automatically survive into runtime or bytecode artifacts.
- An attribute affects runtime artifacts only when another specification defines an explicit lowering for its semantic effect.
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `BeforePause`, `BeforeResume`, `InitAllowed`, and `Doc`.
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `BeforePause`, `BeforeResume`, `MemcardBoot`, `InitAllowed`, and `Doc`.
- `Host` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
- `Capability` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
- `AssetLowering` is valid only on a host method signature declared directly inside a reserved stdlib/interface-module `declare host` body.
@@ -858,3 +858,11 @@ Direct calls remain normal calls and do not request an OS transition or create
a controlled invocation. Runtime FunctionId zero is reserved for the ordinary
entry; physical hook IDs are validated after linking. Init/Frame requirements
and their frontend/common assembly remain unchanged.
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -570,3 +570,11 @@ See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md).
Generic struct/function barrels export declarations and ordered parameters, including complete function signatures, rather than enumerated specializations. Imports and aliases preserve nominal origins and definition-scoped bodies/private helpers. Specializations are shared across equivalent uses and do not export private dependencies. SDK and program sources use the same language machinery.
See [Concrete generic structs and free functions](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.md).
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -252,3 +252,11 @@ The current temporary contract is:
6. PBX `SYSC` declares required host bindings, not authority.
7. Loader validation fails if PBX host requirements exceed granted cartridge capabilities.
8. `manifest.json` is not entrypoint authority for PBS v1 boot.
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -411,4 +411,12 @@ effects. Fatal traps/host failures and unfinished fuel exhaustion fail the
session, block gameplay and retain the existing crash envelope, without retry,
rollback or compensation. HALT is OS termination, not successful hook return.
Existing capability/service rules apply, without auto-save, flush, disk wait,
transition veto or reason argument. MemcardBoot and persistence are separate.
transition veto or reason argument. MemcardBoot and persistence follow the dedicated memcard chapter.
## Memcard integration
The [Memcard Bootstrap and SDK contract](<26. Memcard Bootstrap and SDK Specification.md>)
defines the additional [MemcardBoot] marker, exact signature, neutral once-only
bootstrap, project identity/slot validation and complete installed mem ABI.
Its requirements apply in addition to this chapter; pause/resume remain independent.
@@ -202,3 +202,5 @@ IDs returned by project context. The alias catalog is generated by the frontend
build from this single source directory. It does not read a second spec tree.
The internal resource path is `pbs-knowledge/specs/<numbered filename>.md`;
reference clients resolve IDs through the catalog instead of constructing paths.
- [Memcard Bootstrap and SDK](<26. Memcard Bootstrap and SDK Specification.md>): opt-in persistence producer and runtime-consumer boundaries.