# PBS Diagnostics Specification Status: Draft v1 Applies to: deterministic diagnostics emitted by PBS-facing tooling across parsing, static analysis, manifest/import resolution, linking, host-admission checks, and load-facing validation surfaces ## 1. Purpose This document defines the PBS diagnostics baseline for v1. Its purpose is to make diagnostics stable enough that: - conforming tools report failures in the same phases, - users receive deterministic and actionable source-facing feedback, - diagnostics remain machine-identifiable even when rendered in different locales, - conformance can validate rejection class and attribution, - and frontend, linking, manifest, and load-facing validation remain aligned. ## 2. Scope The installed `pbs:example:game:1:production/GUIDE.md` reference maps global initializer, visibility, malformed project-address and unresolved-import diagnostics to their normative rules and complete positive/negative examples. Codes retain their existing identity; a bounds fault remains an execution outcome rather than a fabricated compile-time diagnostic. Blank quoted project names are source errors, not internal `ModuleReference` construction exceptions. Existing explanation payloads have no navigable reference-ID field for these mappings. Tools MUST preserve that limitation and use the explicit installed guide rather than infer rules from rendered messages or expand a public schema. This document defines: - the required external diagnostic phases, - the minimum machine-readable identity of a PBS-facing diagnostic, - the minimum source-facing payload and attribution baseline, - the boundary between normative diagnostic fields and implementation-defined rendering, - the boundary between PBS-facing diagnostics and artifact/tooling failures, - and the warning/cost-diagnostics boundary for v1. This document does not define: - a full runtime trap catalog, - UI presentation or IDE styling, - one exact localized sentence for every diagnostic, - one transport-specific schema such as LSP field mapping, - one standardized source-map or artifact-offset format, - or profiling/reporting formats. ## 3. Authority and Precedence Normative precedence: 1. `1. Language Charter.md` 2. `3. Core Syntax Specification.md` 3. `4. Static Semantics Specification.md` 4. `5. Manifest, Stdlib, and SDK Resolution Specification.md` 5. `6.2. Host ABI Binding and Loader Resolution Specification.md` 6. `7. Cartridge Manifest and Runtime Capabilities Specification.md` 7. `9. Dynamic Semantics Specification.md` 8. `10. Memory and Lifetime Specification.md` 9. `13. Lowering IRBackend Specification.md` 10. This document If a diagnostic rule here contradicts a normative acceptance/rejection rule in a higher-precedence document, the higher-precedence document wins. ## 4. Normative Inputs This document depends on, at minimum: - `3. Core Syntax Specification.md` - `4. Static Semantics Specification.md` - `5. Manifest, Stdlib, and SDK Resolution Specification.md` - `6.2. Host ABI Binding and Loader Resolution Specification.md` - `7. Cartridge Manifest and Runtime Capabilities Specification.md` - `9. Dynamic Semantics Specification.md` - `10. Memory and Lifetime Specification.md` - `13. Lowering IRBackend Specification.md` Relevant backend-facing integration points also include: - `docs/specs/compiler/15. Bytecode and PBX Mapping Specification.md` - `docs/specs/compiler/16. Runtime Execution and Initialization Specification.md` - `docs/specs/compiler/19. Verification and Safety Checks Specification.md` ## 5. Already-Settled Inputs The following inputs are already fixed elsewhere and must not be contradicted here: - The syntax specification already enumerates minimum required syntax diagnostics. - The static semantics specification already enumerates minimum required static diagnostics. - Manifest/import resolution failures are required to be deterministic compile-time errors. - Loader failures around malformed or unauthorized host usage are required to be deterministic. - Stable source span metadata is required at the token level and must remain useful to later diagnostics. - Traps are fatal runtime outcomes rather than a recoverable userland diagnostic flow. - Qualitative cost facts such as retention-bearing operations and host-boundary crossings are normative, but quantitative performance metrics are not. - PBS requires deterministic diagnostics for source-form globals, lifecycle markers, and init admission. - Published-wrapper, boot-guard, synthetic-origin, and invalid-lifecycle-declaration failures are compiler-general. See `docs/specs/compiler/19. Verification and Safety Checks Specification.md` section 11 and `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`. ## 6. Required Diagnostic Phases PBS-facing tooling must distinguish at least the following external diagnostic phases: 1. `syntax`, 2. `static semantics`, 3. `manifest/import resolution`, 4. `linking`, 5. `host-binding/capability admission`, 6. `load-facing rejection` when directly attributable to malformed or unauthorized PBS-facing artifact usage. `linking` is a first-class phase in the external diagnostics contract and must not be collapsed away into a generic resolution bucket. The `host-binding/capability admission` phase covers the source shape of `[Host]` and `[Capability]`. Canonical host-binding identity and capability consistency over `IRReservedMetadata` are platform-owned and are not moved by this specification. This document does not require one finer-grained public phase split for verifier internals, artifact offsets, or transport-specific backend stages beyond what is stated here. ## 7. Required Diagnostic Identity, Payload, and Attribution Every PBS-facing diagnostic must expose a stable machine-readable identity. At minimum, every required source-facing diagnostic must include: 1. `diagnostic code`, 2. `severity`, 3. `phase`, 4. `primary file`, 5. `primary span/location`, 6. `message template id`, 7. stable named placeholders for that template when applicable, 8. and a rendered human-readable message. The stable identity of a diagnostic is carried primarily by: - `diagnostic code`, - stable phase attribution, - `message template id`, - primary attribution, - and the rejection-class semantics represented by the code/template pair. Human wording alone is not the identity of the diagnostic. Conformance assertions must key diagnostics by stable machine fields (`code`, `phase`, `message template id`, attribution), not by localized rendered sentence text. ## 8. Cross-File Attribution, Notes, and Hint Surface Cross-file attribution follows an action-first rule. Rules: - import failures must point primarily to the importing site, - barrel failures must point primarily to the barrel site or entry that triggered the failure, - linking and cross-module lookup failures must point primarily to the use or reference site that could not be resolved, - related sites may be attached when known, - and `duplicate` or `conflict` diagnostics must include at least one related site. `notes` are optional by default in v1 except where another rule explicitly requires related-location reporting. The stable visible categories currently reserved are: - `error`, - `warning`, - `note`, - `hint`. `hint` is part of the diagnostics model in v1, but hint content is not mandatory. ## 9. Wording, Templates, and Localization Rendered wording does not need to be byte-for-byte identical across implementations or locales. However: - the rendered message must preserve the same normative rejection meaning, - the rendered message must not contradict the governing spec rule, - and the code/template/placeholder contract must remain stable. This allows implementations to localize diagnostics while preserving conformance-friendly identity. Human-readable messages may be rendered from locale-specific templates, but template/token identity remains stable across locales. Implementations should preserve the ability to render an English default or fallback message for future interoperability-oriented transports such as a possible LSP integration, even when the local product surface renders another language by default. Examples in this specification are illustrative unless explicitly marked normative. `help` or guided remediation is outside the minimum mandatory contract in v1. ## 10. Required Diagnostic Coverage and Backend-Originated Failures At minimum, the PBS diagnostics baseline must cover: 1. syntax errors already required by `3. Core Syntax Specification.md`, 2. static-semantics errors already required by `4. Static Semantics Specification.md`, 3. deterministic manifest and import-resolution failures required by `5. Manifest, Stdlib, and SDK Resolution Specification.md`, 4. linking failures required by source-level name-resolution and module-linking rules, 5. malformed, unauthorized, or capability-rejected host usage required by `6.2. Host ABI Binding and Loader Resolution Specification.md` and `7. Cartridge Manifest and Runtime Capabilities Specification.md`, 6. source-attributable backend-originated failures that remain user-actionable under normative lowering or load-facing rules. 7. dependency-scoped fail-fast admission at frontend boundary: when one module is rejected, modules that import it (directly or transitively) must not be emitted, while diagnostics collection for independent modules must continue. 8. lifecycle-marker and source-form global diagnostics, including: - `global initializer uses unsupported form`, - `global dependency cycle detected`, - `global import must resolve through a global barrel entry`, - `imported symbol shadows existing visible symbol; alias required`, - `init function must have signature fn name() -> void`, - `frame function must have signature fn name() -> void`, - `multiple module init functions detected`, - `multiple project init functions detected`, - `multiple frame functions detected`, - `missing frame function for executable project`, - `project init must be colocated with frame`, - `Init attribute target invalid`, - `InitAllowed is valid only on SDK host methods`, - `host call not allowed during init`. 9. compiler-general lifecycle-assembly and IRVM-precondition failures, which this PBS catalog MUST NOT claim as PBS required coverage; see `docs/specs/compiler/19. Verification and Safety Checks Specification.md` section 11 and `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`. 10. symbolic asset-reference diagnostics required by backend-owned `Addressable` resolution, including: - unresolved terminal asset reference, - namespace-versus-terminal asset misuse, - structurally invalid symbolic asset path admitted by source syntax but rejected by semantic surface rules. 11. ignored-value diagnostics for expression statements, including: - a stable warning when a materialized value is produced and then ignored, - and no warning for unit-like expression statements. Reserved-attribute diagnostics for host-backed asset lowering must also cover: - duplicate `AssetLowering` declarations on the same host signature, - missing or malformed `AssetLowering(param = N)` arguments, - out-of-range `AssetLowering.param` indexes, - and `AssetLowering` targets whose selected parameter is not statically typed as `Addressable`. Documentation attribute diagnostics must cover: - unterminated documentation text block syntax, - `Doc` used without the required `markdown` argument, - `Doc` with extra or unknown arguments, - `Doc` with a non-documentation-text-block payload, - duplicate `Doc` on the same declaration, - `Doc` applied to a parameter or other non-documentable surface, - normalized empty or whitespace-only documentation payload, - and rejected aliases or alternate forms such as `text`, positional arguments, `html`, `format`, `Document`, `Documentation`, or `md"""..."""`. Diagnostics for duplicate `Doc` attributes must be static semantic diagnostics and should include a related site for the conflicting declaration attribute when available. At minimum, host-admission diagnostics must cover missing or malformed host capability metadata and unknown or undeclared capability names. Only backend-originated failures that remain source-attributable and user-actionable belong to the PBS-facing diagnostics contract. This means: - lowering failures remain in scope when they reflect a normative source-facing lowering rule or impossibility, - verifier or loader failures remain in scope when they are directly attributable to malformed or unauthorized PBS-facing artifact usage already within the PBS contract, - and purely internal compiler exceptions, artifact corruption, or backend-internal failures with no stable user-facing source attribution remain outside the PBS-facing diagnostics contract. When a backend-originated failure remains in scope for PBS-facing diagnostics, v1 requires at least one source location but does not require one standardized source-map, artifact-offset, or verifier-trace format. For backend-owned symbolic asset surfaces: - diagnostics SHOULD point primarily to the symbolic reference site in source; - the frontend MAY use backend-provided surface context to improve earlier diagnostics; - backend ownership of final validation does not remove the requirement for deterministic source-facing diagnostics when validation fails. Dynamic-semantics traps are not source-level recoverable diagnostics in the ordinary PBS userland model. This document therefore does not require a compile-time diagnostic surface for every possible fatal runtime trap. Dependency-scoped fail-fast admission is not equivalent to global build abort. When failures exist, implementations must still preserve deterministic diagnostic identity and attribution for unaffected independent modules processed in the same build. ## 11. Cost Diagnostics and Warning Policy Warnings are supported in v1, and one warning is mandatory for PBS core: ignored materialized values in expression statements. The mandatory warning identity for this rule is `W_SEM_IGNORED_VALUE`. Tooling may surface qualitative cost facts as warnings or notes, especially for: - retention-bearing explicit closure captures, - observable copy-versus-alias semantics, - and host-boundary crossings. The choice between `warning` and `note` is implementation-defined in v1. This document does not make a detailed warning taxonomy normative and does not require a warning at every such site. Quantitative metrics such as exact byte counts, exact allocation counts, collector timing, or performance ranking remain outside the diagnostics contract and belong to profiling/tooling rather than to language conformance. ## 12. Current Limits The v1 diagnostics contract intentionally leaves the following items outside the currently standardized surface: - transport-specific wire formats, - one exact source-map format, - one exact verifier/loader internal reporting shape, - one mandatory warning catalog, - and one mandatory remediation/help-content policy. These are not licenses to weaken the required external fields defined above. ## 13. Non-Goals - Mandating one UI or IDE presentation style. - Freezing one exact localization strategy or locale set. - Turning every optimization hint into a normative diagnostic. - Replacing the acceptance/rejection rules already defined elsewhere. - Standardizing profiler output as if it were language law. ## 14. Exit Criteria This document is ready to move beyond temporary status only when: 1. every required rejection in the current spec set is mapped to a diagnostic phase, 2. diagnostic identity, metadata, and attribution rules are explicit enough for conformance, including locale-agnostic token/template identity, 3. the backend-originated failure boundary is explicit enough that PBS-facing diagnostics can be distinguished from internal tool failures, 4. and cost/warning expectations are explicit where they are intended to be normative for v1. ## Existing values and input runtime alignment The [PBS input and value alignment contract](18.%20Input%20and%20Existing%20Type%20Runtime%20Alignment%20Specification.md) governs int/Int32, long/Int64, exact builtin carriers, the Pad/Button/LowPad and Touch API, named-argument evaluation order, migration diagnostics and executable conformance. It supersedes older input-object and untyped executable-lowering descriptions. ## Typed arrays and optional execution extension The [Array owner chapter](14.%20Typed%20Arrays%20and%20Optional%20Execution%20Specification.md) defines the complete type, optional-flow and storage contract. This chapter owns diagnostic classification and source attribution; the owner chapter defines which Array forms are rejected. Array spelling and construction are owned by [Core Syntax](3.%20Core%20Syntax%20Specification.md) and the Array chapter; AST, diagnostics and lowering MUST consume that same syntax. ## Parameterized contracts Parameterized contract diagnostics distinguish exact arity (E_SEM_CONTRACT_ARITY), undeclared/duplicate parameters (E_SEM_CONTRACT_PARAMETER), invalid applications (E_SEM_CONTRACT_ARGUMENT), incompatible or incomplete implementations (E_SEM_CONTRACT_SIGNATURE), duplicate pairs (E_SEM_CONTRACT_DUPLICATE_IMPLEMENTATION), invalid owners/modules (E_SEM_CONTRACT_OWNER / E_SEM_CONTRACT_OWNER_MODULE), invalid coercions (E_SEM_CONTRACT_COERCION), and bounded expansion/resource exhaustion (E_SEM_CONTRACT_EXPANSION). Barrel parameter disagreement uses E_LINK_CONTRACT_PARAMETERS. Existing invalid Array/Fn/optional/Self diagnostics also apply after substitution. See [PBS generic contracts](16.%20Generic%20Contracts%20Specification.md). ## Concrete generic structs and free functions 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](17.%20Generic%20Structs%20and%20Free%20Functions%20Specification.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. ## Deterministic explanations and observed semantic context PBS diagnostics retain their original code/message/template and add a detector-specific checkId, owner explanation and immutable semanticContext. This instrumentation MUST NOT change resolution, visibility, typing, lowering acceptance or source language rules. An observed resolution constraint is evidence about the implementation's lookup, not a declaration that the language requires that constraint. | Check | Observed context | | --- | --- | | pbs.lowering.call-resolution | Requested call, receiver/type, argument count, declared candidates, enclosing return type and actual expected-type constraint. | | pbs.lowering.structured-overload | Structured call, actual owner lookup key, parameter/return lookup types and observed lookup result. | | pbs.flow.call-target | Applied symbol/construction, callable classification, argument/constraint, candidates and scope. | | pbs.flow.assignment-target | Assignment symbol/construction, binding classification and scope. | | pbs.lowering.stack-shape | Executable function, declared result slots, instruction count and recorded stack-check condition; known internal failure remains distinct from unsupported source construction. | Each semantic fact has {value,availability,reason}. Known null differs from not-recorded/unavailable/not-applicable. Keep declaredTypes, expressionTypes and resolutionConstraints distinct. Unknown module/dependency/expression information is marked not-recorded; source identity is available separately in the origin/input map. Related declarations/candidates are included only when actually recorded. Generic-instantiation diagnostic reconstruction MUST preserve the complete context and reported phase. The unchanged frozen cases F1-direct/F1-two-calls/F1-service-this, F3-function/F3-global/F3-service and F4-same-dependency/F4-same-direct qualify these mechanisms through real LSP analysis and Studio build/MCP. F3-service demonstrates that the shared unsupported-lowering code can represent distinct structured-overload and stack-shape checks. The original rejected observations are retained in the Studio diagnostic lesson. Following the production corrections, those eight valid sources MUST compile without their former false rejection; invalid file-private access remains a source rejection. Existing detector IDs, source attribution and operation-failure semantics remain unchanged. ## Production correction regressions The compiler must no longer emit the received false call-resolution, peer-binding or nominal-owner rejections for the eight valid production cases. Negative visibility controls still return structured source errors, independently from loader/infrastructure/guest failures. Diagnostics remain producer-owned; a compiler correctness fix does not weaken source attribution or reinterpret callable completion as approval. PbsFacadeDiagnosticTest uses the unchanged F3-file-private negative fixture, and StructuredDiagnosticsIntegrationTest now verifies the corrected positive corpus plus that negative control. The earlier rejection evidence remains immutable.