feat(pbs): add explicit guest lifecycle hooks

This commit is contained in:
2026-10-28 09:12:48 +00:00
parent eb7d6a2398
commit 9504f4694a
41 changed files with 1209 additions and 24 deletions
@@ -265,3 +265,16 @@ BudgetExhausted and debugger pauses can occur between instructions and resume at
the current PC; they neither roll back nor complete a method. No atomic observation
of source operations by host/debugger is promised. SDK methods introduce no user
callbacks or explicit suspension during the updates that complete their invariants.
## Producer-selected guest hook roots
BeforePause/BeforeResume role targets and their transitive dependencies MUST
remain in the executable set even without ordinary callers. Preserve typed
metadata through merge, lifecycle assembly, optimization and linking. Names,
exports and frontend ASTs MUST NOT become a common role-selection mechanism.
Common emission validates unique nonzero roles, empty pause/resume signatures
and capture lists, and final hook FunctionIds other than zero. The ordinary
entry and synthetic Init/Frame assembly keep role None. Calling a hook as an
ordinary function does not request an OS transition. PBS marker syntax belongs
to its frontend; MemcardBoot selection/bootstrap is a separate producer scope.
@@ -76,7 +76,7 @@ Mandatory declaration metadata on required declaration nodes includes:
2. declared signature/surface when applicable (parameters/return),
3. declaration-level syntactic flags/attributes required by later phases,
4. stable `file/start/end` attribution,
5. lifecycle-marker metadata when a declaration carries `[Init]` or `[Frame]`,
5. lifecycle-marker metadata when a declaration carries `[Init]`, `[Frame]`, `[BeforePause]` or `[BeforeResume]`,
6. documentation attribute metadata when a declaration carries `[Doc(markdown = """...""")]`.
Missing required attribution or metadata on mandatory nodes is non-conformant.
@@ -110,6 +110,7 @@ Lifecycle-observable declarations must preserve marker metadata explicitly:
- top-level `fn` marked with `[Init]`,
- top-level `fn` marked with `[Frame]`,
- top-level `fn` marked with `[BeforePause]` or `[BeforeResume]`,
- and host method signatures marked with `[InitAllowed]`.
Documentation-observable declarations must preserve `Doc` metadata explicitly on every accepted named API declaration surface that carries `[Doc(markdown = """...""")]`.
@@ -196,3 +197,14 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Structs and free functions preserve ordered parameter declarations and spans. Explicit applied function references preserve type arguments and their source span. Implements preserves its binder, full applied owner and target. Substitution rewrites every field, signature, annotation and executable body/capture position with a declaration-local environment. Concrete application provenance retains original declaration, canonical logical arguments and requesting use; it is not an executable runtime template.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
## Guest hook marker identity
LifecycleMarker explicitly distinguishes NONE, INIT, FRAME, BEFORE_PAUSE and
BEFORE_RESUME. 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.
@@ -320,3 +320,26 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Generic diagnostics distinguish duplicate/unbound parameters, exact arity, raw or improperly inferred application, unjustified symbolic capabilities, invalid substituted positions, constructor errors, collapsed overloads, invalid bound owners, overlap and bounded expansion. Preserve declaration and requesting-use locations with a short instantiation chain. Editor projections retain symbolic parameter, concrete argument and generic origin identities. Generated instance names and host stacks do not replace source explanations.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
## Guest lifecycle diagnostics and conformance
Invalid target, marker arguments and combinations are source-anchored syntax or
reserved-attribute diagnostics. Nongeneric empty signatures use
`E_SEM_INVALID_LIFECYCLE_SIGNATURE`; generic-instantiation admission may also
report the existing generic lifecycle error. `E_SEM_DUPLICATE_LIFECYCLE_ROLE`
identifies the role, conflicting declarations and their source locations across
the project graph; import order MUST NOT select a winner. Source diagnostics do
not guess physical FunctionIds. Typed handoff/PBX validation rejects duplicate
roles, captures, invalid signatures and physical entry-zero targets separately
from runtime load failures and executed traps.
Conformance MUST include both/one/no-hook cases, arbitrary names, imported and
repeated-import targets, invalid source surfaces, valid globals/closures,
optimized targets with no callers and ordinary direct calls. Execute generated
production PBX through production runtime/host Home/resume, observing ordered
effects, retained PC/state/init guard and gameplay frame/tick counters. Trap,
fuel exhaustion across slices and direct/transitive FRAME_SYNC are required;
sync fixtures use synthetic common IR because PBS exposes no sync construct.
Record revisions, platform/configuration, commands, scenarios, oracles and
results. Existing runtime tests alone are not producer integration evidence.
@@ -229,7 +229,7 @@ For executable PBS frontends, PBS lowering MUST emit a typed `IRLifecycleDeclara
At frontend `IRBackend` emission time:
1. PBS MUST retain marker admission for `[Init]`, `[Frame]`, and `InitAllowed`,
1. PBS MUST retain marker admission for `[Init]`, `[Frame]`, `[BeforePause]`, `[BeforeResume]`, and `InitAllowed`,
2. PBS MUST emit typed references for:
- file-init fragments that include global materialization and non-project `[Init]`,
- the optional project-init callable, which is the `[Init]` colocated with `[Frame]`,
@@ -262,3 +262,20 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Instantiate structs, free functions and owner-bound implementations within PBS before publishing executable descriptors. Registry receives concrete fields, signatures, bodies, capture groups and targets. Specialized free-function references use existing empty-environment Closure values; Fn remains structural. Preserve receiver identity, implementation zero, singletons, rooting, GC, ownership, evaluation/fault order and quotas. No generic Dynamic/boxing ABI, opcode, descriptor category or runtime instantiation engine is introduced.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
## Lowering optional runtime hook roles
Map BEFORE_PAUSE/BEFORE_RESUME to `IRRegistry.Role.BEFORE_PAUSE` (1) /
`BEFORE_RESUME` (2) in typed FunctionMetadata. Preserve the declaration/callable
identity, empty signature and capture list; no hidden receiver or parameter is
introduced. INIT/FRAME and ordinary functions retain role None (0). Function
names/exports/manifests are not role binding mechanisms. No MemcardBoot role is
inferred or emitted by these markers.
Each role target and its dependencies are externally entered retention roots,
even without source callers. Merge, lifecycle assembly, linking and optimization
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.
@@ -253,7 +253,7 @@ Rules:
- An attribute attaches syntactic metadata to the declaration surface that immediately follows it.
- Attributes do not introduce values, types, callables, or modules by themselves.
- In v1 core, ordinary user-authored modules MUST reject attributes unless another specification explicitly permits them.
- Ordinary userland source MAY use `[Init]` and `[Frame]` only on top-level `fn` declarations.
- Ordinary userland source MAY use `[Init]`, `[Frame]`, `[BeforePause]` and `[BeforeResume]` only on top-level `fn` declarations.
- Ordinary userland source MAY use `[Doc(markdown = """...""")]` on named API declarations where the static semantics specification permits documentation.
- Reserved stdlib/toolchain interface modules MAY use attributes where explicitly allowed by syntax and semantics.
- Reserved stdlib/toolchain interface modules MAY additionally use `[InitAllowed]` only on `declare host` method signatures where another specification explicitly permits it.
@@ -1218,3 +1218,22 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Struct and module-level free-function declarations and their barrel items accept ordered type parameters. Explicit function applications are reference expressions; calls use existing parentheses/apply. Generic construction supports explicit arguments and contextual diamond/omission. Owner-bound `implements` accepts its own parameter binder and a full applied owner. Independent method parameters, function diamond/inference and polymorphic Fn remain invalid. The owner specification defines exact arity, comparison disambiguation and recovery.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
## Controlled guest lifecycle marker syntax
`[BeforePause]` and `[BeforeResume]` select optional runtime lifecycle hooks:
```pbs
[BeforePause]
fn preparePause() -> void {}
[BeforeResume]
fn prepareResume() -> void {}
```
These markers accept no arguments and MUST NOT combine with another lifecycle
marker (`Init`, `Frame`, `BeforePause`, `BeforeResume`). Existing `[Doc]` metadata
may accompany them. Targets MUST be nongeneric top-level userland functions;
methods, lambdas, host/interface declarations and other declaration kinds are
invalid targets. Function names are arbitrary and do not select runtime roles.
PBS exposes no sync statement, lifecycle syscall or termination marker.
@@ -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`, `InitAllowed`, and `Doc`.
- In v1 core, the normative reserved attributes are `Host`, `Capability`, `AssetLowering`, `BuiltinType`, `BuiltinConst`, `IntrinsicCall`, `Init`, `Frame`, `BeforePause`, `BeforeResume`, `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.
@@ -837,3 +837,23 @@ See [PBS generic contracts](../../../compiler/pbs/specs/generic-contracts.md).
Templates are checked symbolically in definition scope. Required concrete owners validate all methods and constructors, including unused methods. Substitute complete bodies and applied Self; preserve position restrictions, invariant nominal/phantom identity and logical groups. Explicit function applications filter generic overloads by type arity; ordinary calls never infer them. Bound owner implementations require complete exact signatures and symbolic overlap rejection before use. Finite recursive applications are anchored; expanding type/body families are bounded errors.
See [Concrete generic structs and free functions](../../../compiler/pbs/specs/generic-structs-and-free-functions.md).
## Controlled guest lifecycle admission
`[BeforePause]` and `[BeforeResume]` targets MUST be nongeneric top-level
userland functions with explicit unit signature `fn name() -> void`, zero
parameters, zero logical results and zero captures. Marker arguments and
combinations with any other lifecycle marker are invalid; `[Doc]` remains
allowed. Globals are not captures. Normal calls and closure creation/use inside
the body remain subject to ordinary PBS rules.
Each role is independently optional and has at most one distinct target across
the compiled graph/image, including imported modules. Targets may be in any
compiled userland file, without colocation with `[Frame]`. Repeated imports of
the same source declaration MUST NOT manufacture duplicate targets; distinct
declarations for one role MUST produce a deterministic conflict diagnostic.
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.
@@ -382,3 +382,30 @@ The [PBS input and value alignment contract](../../../compiler/pbs/specs/input-a
## Typed arrays and optional execution extension
The [typed arrays and optional execution specification](../../../compiler/pbs/specs/typed-arrays-and-optional-execution.md) defines array types/construction/indexing, contextual literals, optional bindings and runtime storage. Its rules extend this specification, including source typing, complete groups, Struct/contract execution and diagnostics.
## Controlled pause and resume hooks
Source-selected BeforePause/BeforeResume functions lower to existing runtime
roles 1/2. Runtime owns invocation ordering, continuation, fuel and failures.
Home's existing handoff precedes BeforePause; suspension completes after normal
hook return. Reactivation precedes BeforeResume; no normal gameplay instruction
is eligible until that hook returns. Direct suspension and Shell handoff follow
the runtime contract without an additional gameplay reaction tick. Missing
hooks preserve existing transitions.
Controlled calls retain the same VM stacks, suspended values, environments,
globals and heap roots, restoring the continuation on outer return and handing
control immediately to the OS. Mutations persist. They MUST NOT reprepare entry,
repeat Init, reset the boot guard, or add gameplay ticks/logical frames. Ordinary
calls to marked functions do not themselves acquire controlled-call semantics.
Each controlled invocation has 1,500,000 virtual cycles total, sliced at at most
250,000 admitted cycles per host update, with the runtime's whole-instruction
overshoot rule. Slices/debugger stops do not renew fuel. There is no wall-clock
deadline. FRAME_SYNC, including in a callee, traps before frame/GC/publication
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.
@@ -153,3 +153,18 @@ This document is ready to move beyond temporary status only when:
2. service and module runtime lifecycle assumptions are explicit enough to remove the remaining TODO items,
3. execution lifecycle boundaries are aligned with dynamic semantics and runtime authority,
4. and the document no longer relies on unresolved TODO items for ordinary v1 runtime startup behavior.
## Optional controlled runtime hooks
Producer-selected BeforePause/BeforeResume metadata MUST survive lifecycle
assembly without joining the init sequence or replacing the frame root/entry.
BeforePause runs after the existing gameplay handoff and before suspension;
BeforeResume runs after reactivation and before any normal gameplay instruction.
Missing hooks preserve transitions. Controlled calls preserve PC/stacks/roots,
globals and init guard; outer return restores continuation and yields to the OS
without another gameplay tick/frame or reinitialization. Direct calls remain
ordinary calls. Runtime owns the independent bounded fuel, transitive sync
prohibition, debugger behavior and failure envelope. There is no termination
hook, new syscall or automatic persistence. See the runtime's controlled
lifecycle contract and common typed Registry/PBX specification.
@@ -216,3 +216,15 @@ This specification MUST NOT be read as authorizing:
- or reopening lifecycle-assembly ownership.
Platform validators MUST NOT depend on types from the PBS frontend module (`prometeu-frontend-pbs`). The package `p.studio.compiler.pbs` is not the complete boundary; facades shipped by that module remain PBS-owned. Platform validators MUST NOT discover roles from `__pbs.` prefixes.
## Guest hook verification boundary
Frontend diagnostics validate source marker targets/signatures and image-wide
uniqueness. Common typed validation MUST independently reject duplicate roles,
pause/resume parameters/results/captures and final FunctionId-zero targets.
These producer defenses do not replace runtime loading/admission. Assembly and
optimization MUST preserve hook metadata and externally entered bodies/callees.
Regression tests MUST inspect production PBX from source and execute it through
the production runtime. Source errors, common emission errors, loader failures
and executed traps retain distinct diagnostics; preserve the runtime envelope.
@@ -289,3 +289,15 @@ This document is healthy when:
4. common backend obligations are not described as owned by PBS,
5. frontend-specific lowering specs only own emission into `IRBackend`,
6. and scope boundaries with optimization/emission specs are explicit.
## Preserving optional runtime hook metadata
Typed FunctionMetadata roles are frontend-neutral executable input. Lowering,
function ordering and optimization MUST retain externally entered role targets,
their dependencies and exact signature/capture/role metadata even without
ordinary CALL edges. Physical entry zero remains ordinary; deterministic linking
assigns other IDs to hooks. PBX emission consumes the existing role byte and
validates final targets, without role inference from function names or frontend
ASTs. Synthetic Init/Frame assembly is unchanged. FRAME_SYNC fixtures used to
test controlled-call rejection do not introduce frontend sync syntax.