This commit is contained in:
bQUARKz 2026-03-30 10:05:44 +01:00
parent 4c334c573a
commit bd989eab32
Signed by: bquarkz
SSH Key Fingerprint: SHA256:Z7dgqoglWwoK6j6u4QC87OveEq74WOhFN+gitsxtkf8
9 changed files with 82 additions and 1293 deletions

View File

@ -1,9 +1,9 @@
{"type":"meta","next_id":{"DSC":9,"AGD":9,"DEC":7,"PLN":9,"LSN":24,"CLSN":1}}
{"type":"meta","next_id":{"DSC":9,"AGD":9,"DEC":7,"PLN":9,"LSN":25,"CLSN":1}}
{"type":"discussion","id":"DSC-0001","status":"done","ticket":"studio-docs-import","title":"Import docs/studio into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0001","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0001-assets-workspace-execution-wave-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0002","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0002-bank-composition-editor-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0003","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0003-mental-model-asset-mutations-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0004","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0004-mental-model-assets-workspace-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0005","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0005-mental-model-studio-events-and-components-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0006","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0006-mental-model-studio-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0007","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0007-pack-wizard-shell-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0008","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0008-project-scoped-state-and-activity-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0016","file":"discussion/lessons/DSC-0001-studio-docs-import/LSN-0016-studio-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0002","status":"open","ticket":"palette-management-in-studio","title":"Palette Management in Studio","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["studio","legacy-import","palette-management","tile-bank","packer-boundary"],"agendas":[{"id":"AGD-0002","file":"AGD-0002-palette-management-in-studio.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0003","status":"done","ticket":"packer-docs-import","title":"Import docs/packer into discussion-framework artifacts","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","migration","discussion-framework","docs-import"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0009","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0009-mental-model-packer-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0010","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0010-asset-identity-and-runtime-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0011","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0011-foundations-workspace-runtime-and-build-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0012","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0012-runtime-ownership-and-studio-boundary-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0013","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0013-metadata-convergence-and-runtime-sink-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0014","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0014-pack-wizard-summary-validation-and-pack-execution-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0015","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0015-tile-bank-packing-contract-legacy.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"},{"id":"LSN-0017","file":"discussion/lessons/DSC-0003-packer-docs-import/LSN-0017-packer-docs-import-pattern.md","status":"done","created_at":"2026-03-26","updated_at":"2026-03-26"}]}
{"type":"discussion","id":"DSC-0004","status":"open","ticket":"tilemap-and-metatile-runtime-binary-layout","title":"Tilemap and Metatile Runtime Binary Layout","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tilemap","metatile","runtime-layout"],"agendas":[{"id":"AGD-0004","file":"AGD-0004-tilemap-and-metatile-runtime-binary-layout.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0005","status":"open","ticket":"variable-tile-bank-palette-serialization","title":"Variable Tile Bank Palette Serialization","created_at":"2026-03-26","updated_at":"2026-03-26","tags":["packer","legacy-import","tile-bank","palette-serialization","versioning"],"agendas":[{"id":"AGD-0005","file":"AGD-0005-variable-tile-bank-palette-serialization.md","status":"open","created_at":"2026-03-26","updated_at":"2026-03-26"}],"decisions":[],"plans":[],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"open","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[{"id":"AGD-0006","file":"AGD-0006-pbs-game-facing-asset-refs-and-call-result-discard.md","status":"accepted","created_at":"2026-03-27","updated_at":"2026-03-27"}],"decisions":[{"id":"DEC-0005","file":"DEC-0005-pbs-asset-address-surface-and-be-lowering.md","status":"accepted","created_at":"2026-03-27","updated_at":"2026-03-27","ref_agenda":"AGD-0006"},{"id":"DEC-0006","file":"DEC-0006-pbs-ignored-values-lowering-and-warning.md","status":"accepted","created_at":"2026-03-27","updated_at":"2026-03-27","ref_agenda":"AGD-0006"}],"plans":[{"id":"PLN-0005","file":"PLN-0005-pbs-asset-address-surface-spec-propagation.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27","ref_decisions":["DEC-0005"]},{"id":"PLN-0006","file":"PLN-0006-pbs-asset-address-surface-implementation.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27","ref_decisions":["DEC-0005"]},{"id":"PLN-0007","file":"PLN-0007-pbs-ignored-values-warning-implementation.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27","ref_decisions":["DEC-0006"]},{"id":"PLN-0008","file":"PLN-0008-pbs-assetlowering-host-metadata-and-callsite-rewrite.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27","ref_decisions":["DEC-0005"]}],"lessons":[]}
{"type":"discussion","id":"DSC-0006","status":"done","ticket":"pbs-game-facing-asset-refs-and-call-result-discard","title":"PBS Game-Facing Asset References and Ignored Call Result Lowering","created_at":"2026-03-27","updated_at":"2026-03-30","tags":["compiler","pbs","ergonomics","lowering","runtime","asset-identity","expression-statements"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0024","file":"discussion/lessons/DSC-0006-pbs-game-facing-asset-refs-and-call-result-discard/LSN-0024-addressable-surface-host-metadata-and-ignored-value-discipline.md","status":"done","created_at":"2026-03-30","updated_at":"2026-03-30"}]}
{"type":"discussion","id":"DSC-0007","status":"done","ticket":"pbs-learn-to-discussion-lessons-migration","title":"Migrate PBS Learn Documents into Discussion Lessons","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","migration","discussion-framework","lessons","learn-prune"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0018","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0018-pbs-ast-and-parser-contract-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0019","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0019-pbs-name-resolution-and-linking-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0020","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0020-pbs-runtime-values-identity-memory-boundaries-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0021","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0021-pbs-diagnostics-and-conformance-governance-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"},{"id":"LSN-0022","file":"discussion/lessons/DSC-0007-pbs-learn-to-discussion-lessons-migration/LSN-0022-pbs-globals-lifecycle-and-published-entrypoint-legacy.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}
{"type":"discussion","id":"DSC-0008","status":"done","ticket":"pbs-low-level-asset-manager-surface","title":"PBS Low-Level Asset Manager Surface for Runtime AssetManager","created_at":"2026-03-27","updated_at":"2026-03-27","tags":["compiler","pbs","runtime","asset-manager","host-abi","stdlib","asset"],"agendas":[],"decisions":[],"plans":[],"lessons":[{"id":"LSN-0023","file":"discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md","status":"done","created_at":"2026-03-27","updated_at":"2026-03-27"}]}

View File

@ -0,0 +1,80 @@
---
id: LSN-0024
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: Addressable Surface, Host Metadata, and Ignored-Value Discipline
created: 2026-03-30
tags: [compiler, pbs, asset-surface, lowering, diagnostics, runtime, host-metadata, ergonomics]
---
## Context
PBS needed to close two related gaps at the boundary between ergonomic game code and executable lowering.
Asset references needed an author-facing symbolic surface that did not fall back to unstable `asset_name` lookup or couple the frontend directly to packer internals.
At the same time, expression statements that produce values needed an explicit discard rule so backend stack discipline would not leak into source authoring.
The resulting implementation spans specs, frontend API models, backend lowering metadata, stdlib host surfaces, and compiler diagnostics.
## Key Decisions
### Keep Asset Authoring Symbolic But Backend-Owned
**What:**
PBS now treats `assets...` as a hierarchical compile-time namespace whose terminal leaves are `Addressable` values supplied through a backend-owned `FESurfaceContext`.
The v1 surface carries `List<Addressable(address, asset_id)>`.
**Why:**
This preserves natural source authoring while keeping the backend as the owner of operational asset identity and final `address -> asset_id` lowering.
The frontend gets enough structure for semantics, typing, and tooling without querying packer services directly.
**Trade-offs:**
Rename or move operations now change the canonical symbolic address and can break compile-time references.
That is stricter than a loose name-based model, but the breakage is explicit and deterministic instead of becoming late runtime ambiguity.
### Put Asset-Aware Lowering On Host Metadata, Not Service Bodies
**What:**
Asset-aware host calls now declare `[AssetLowering(param = N)]`, and backend lowering uses that metadata to rewrite the selected `Addressable` argument into runtime-facing `asset_id`.
**Why:**
This keeps lowering ownership on the host-backed contract surface instead of burying special behavior in wrapper services or generic expression shortcuts.
The lowering path stays aligned with `LowAssets`, and the compiler knows exactly which parameter is asset-facing.
**Trade-offs:**
Host-backed signatures must be validated more strictly, and metadata propagation has to remain consistent across extraction, indexing, and lowering.
That adds infrastructure, but it prevents the normative path from becoming implicit or drifting between layers.
### Treat Ignored Materialized Values As A General Language Rule
**What:**
Any PBS expression statement that produces a materialized value now triggers two things: a warning diagnostic and explicit discard lowering.
**Why:**
This keeps authoring simple without silently relying on backend stack behavior.
The language remains honest about ignored results while still allowing expression statements to execute.
**Trade-offs:**
The compiler now distinguishes unit-like results from materialized values in both semantics and lowering.
That is more work than silently discarding everything, but it yields a stable, testable language rule instead of API-specific exceptions.
## Patterns and Algorithms
- Use a backend-to-frontend surface contract when the frontend needs semantic visibility but must not own operational truth. `FESurfaceContext` is intentionally small and deduplicated by canonical address.
- Model symbolic assets as a namespace tree with terminal leaves only. Intermediate namespaces are not values, and terminal paths cannot also behave as namespace prefixes.
- Carry executable special cases as reserved host metadata. `[AssetLowering(param = N)]` is the authoritative marker for backend callsite rewriting.
- Make lowering side effects explicit when a source form hides operational cost. Ignored expression results are not silently tolerated; they lower to discard behavior and emit a warning.
- Pin cross-layer contracts in specs, stdlib surfaces, and compiler tests together. That prevents the PBS surface, host metadata, and runtime lowering path from drifting apart.
## Pitfalls
- Do not reintroduce `asset_name` as the operational compile-time identity. The symbolic surface is the canonical address derived from the asset root.
- Do not let the frontend query packer services directly for visible assets. It must consume the backend-owned surface contract.
- Do not bypass host metadata with generic expression rewriting for asset-aware calls. The normative path is host-backed `AssetLowering`.
- Do not treat intermediate `assets...` namespaces as terminal values, and do not allow terminal-vs-namespace collisions in asset roots.
- Do not silently drop ignored materialized values. If the compiler materializes a value in statement position, the discard path and warning are both part of the language contract.
## Takeaways
- PBS asset authoring is symbolic and hierarchical, but operational asset identity remains backend-owned and runtime-aligned through `asset_id`.
- Asset-aware lowering belongs to the host contract through reserved metadata, not to ad hoc wrapper logic.
- Ignored values are now a general PBS language rule: warn in semantics, discard explicitly in lowering.
- The durable pattern is consistent boundary ownership: frontend surfaces stay ergonomic, backend lowering stays authoritative, and the runtime contract remains explicit.

View File

@ -1,373 +0,0 @@
---
id: AGD-0006
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: PBS Game-Facing Asset References and Ignored Call Result Lowering
status: accepted
created: 2026-03-27
resolved: 2026-03-27
decision: DEC-0005, DEC-0006
tags: [compiler, pbs, ergonomics, lowering, runtime, asset-identity, expression-statements]
---
## Pain
PBS ainda tem dois atritos abertos na fronteira entre ergonomia de código de jogo e lowering executável:
1. referências a assets continuam centradas em `asset_name` no código-fonte, enquanto packer/runtime já convergiram para identidade estável por `asset_id`;
2. `expression statements` com retorno materializado ainda precisam de política explícita de descarte, para não vazar regra de stack do backend para o código de usuário.
Os dois temas pertencem à mesma discussão porque tratam da mesma pergunta arquitetural:
Como PBS deve preservar uma superfície de autoria natural sem sacrificar determinismo no lowering e no runtime?
## Context
Esta agenda consolida dois tópicos legados do domínio PBS:
- `18.4. Asset References in Game Code - Names vs Compile-Time Lowering`
- `18.5. Ignored Call Results in Executable Lowering`
Os pontos estáveis já conhecidos são:
- packer/runtime tratam `asset_id` como identidade estável;
- `asset_name` ainda é a superfície mais natural para autoria e tooling;
- o packer já mantém um `PackerRuntimeSnapshot` coerente em memória como projeção operacional do workspace ativo;
- Studio já consome leituras normais a partir desse snapshot operacional em vez de reconstituir a verdade diretamente do filesystem a cada interação;
- o pipeline executável hoje já exige disciplina explícita de stack;
- a família `19` reforçou a direção de compiler-owned lowering e publication protocol, reduzindo espaço para ambiguidades “aceitas pelo frontend, rejeitadas mais tarde”.
Isso sugere um princípio comum:
- a linguagem pode continuar amigável na superfície,
- mas o compiler precisa assumir explicitamente o trabalho de normalizar essa superfície para um contrato executável estável.
O novo ponto importante é que, para referências a asset, essa “superfície amigável” não precisa nascer de nomes soltos escritos manualmente nem de arquivos tipados gerados sem owner claro.
Ela pode ser tratada como uma projeção simbólica derivada da autoridade operacional já existente no packer:
- `PackerRuntimeSnapshot` como fonte operacional coerente do conjunto de assets visíveis;
- backend/compiler como owner de uma `FESurfaceContext` derivada desse snapshot, sem expor o snapshot bruto ao frontend;
- Studio como IDE que consome e exibe essa superfície, mas não a possui normativamente;
- PBS como consumidor frontend dessa superfície tipada;
- backend/compiler como responsável final por validar e lowerar essa superfície para identidade estável de runtime.
O entendimento atual desta discussão mudou um ponto importante do modelo anterior:
- `asset_name` não parece justificar existência como campo operacional separado;
- o dado estrutural realmente útil já está no root do asset dentro de `assets/`;
- portanto a superfície simbólica candidata pode ser o próprio address normatizado derivado do diretório, e não um nome livre fornecido pelo autor.
Exemplo de direção:
- asset root em disco: `assets/some/dir/maluco/asset/asset.json`
- superfície simbólica projetada para código/tooling: `assets.some.dir.maluco.asset`
Na direção atual, essa superfície não deve ser tratada como enum flat simples.
O modelo preferido é:
- `assets` como árvore hierárquica sintetizada de compile;
- nós intermediários como namespaces de compile;
- apenas folhas correspondentes a asset roots reais como valores terminais do tipo `Addressable`.
Exemplo:
- `assets.ui` pode ser apenas namespace;
- `assets.ui.borders` pode ser apenas namespace;
- `assets.ui.borders.panel` pode ser uma folha `Addressable`.
Isso implica uma regra estrutural importante:
- um asset terminal não pode ocupar um prefixo que também precise funcionar como namespace para outros assets.
Exemplo inválido:
- existir asset terminal em `assets/ui`
- e também existir asset terminal em `assets/ui/borders/panel`
porque `assets.ui` não pode ser simultaneamente `Addressable` terminal e namespace.
Operational note:
- Studio should prevent creation of a new asset root when that path would collide with an existing asset terminal/namespace boundary.
- In practice, if an asset already exists at a path, Studio should not allow creating descendant assets under that same terminal path.
- Likewise, if descendants already exist, Studio should not allow creating a new asset at their prefix path.
- This must become an explicit Studio-side creation and move constraint, not just a compiler-side validation concern.
Nesse modelo:
- Studio mostra o address normatizado do asset, não um `asset_name` livre;
- packer não precisa mais ler nem escrever `asset_name` como variável operacional em `asset.json`;
- packer apenas reconhece, normaliza e publica o address derivado do root do asset sem persistir esse address como estado redundante em disco;
- `asset_id` permanece como primary key operacional estável do asset dentro do packer/runtime;
- o `address` passa a ser a identidade simbólica usada pelos compiladores para referenciar o asset em superfícies de autoria/compile;
- renomear ou mover diretório muda o address e quebra referências em compile time;
- tooling de rename/move pode existir para amortecer esse custo, mas a quebra deixa de ser ambígua e passa a ser explícita.
Com esse contexto, o coração real da discussão de asset references não é mais “nome versus `asset_id`”.
O ponto central passa a ser:
- como PBS/SDK transforma um `address` autoral em `asset_id` operacional.
Exemplo de shape ainda ilustrativo:
```pbs
fn load(addressable: Addressable, bankRef: BankRef) -> LoadError
```
A dúvida principal não é o nome exato da API, mas o lugar da resolução:
- a função do SDK recebe um símbolo/valor addressable e resolve internamente para `asset_id`;
- ou o próprio `Addressable` já é uma declaração/superfície sintetizada a partir do modelo vindo do backend, carregando a resolução necessária antes mesmo de entrar na função;
- ou ainda existe uma terceira forma híbrida em que a superfície autoral é simbólica, mas o lowering do compiler reescreve a chamada para a variante já normalizada em `asset_id`.
Essa decisão é o núcleo arquitetural da agenda porque define:
- o quanto a API pública do SDK continua “asset-address-first”;
- o quanto o compiler participa do lowering antes da chamada;
- e qual parte do sistema é owner da ponte entre identidade simbólica de compile e identidade operacional de runtime.
O modelo que hoje parece mais coerente com PBS não é colocar essa resolução no corpo de um `declare service`.
O desenho mais alinhado com a linguagem atual é:
- `declare service` público continua sendo wrapper ergonômico normal;
- a metadata reservada de lowering fica no `declare host`, junto do próprio contrato host-backed;
- o compiler consome essa metadata ao baixar a chamada host-backed;
- o parâmetro marcado como asset-facing é resolvido de `Addressable` para `asset_id` durante o lowering.
Exemplo ilustrativo:
```pbs
declare host low_assets {
[Host(module = "assets", name = "preload", version = 1)]
[AssetLowering(param = 0)]
fn preload(addressable: Addressable, bank_id: int) -> LoadError;
}
declare service Assets {
fn load(addressable: Addressable, bank: BankRef) -> LoadError {
return low_assets.preload(addressable, bank.id());
}
}
```
Neste desenho:
- o `service` não contém lógica especial de resolução;
- ele só encaminha a chamada de forma autoral/ergonômica;
- a assinatura host-backed explicita qual parâmetro sofre asset-lowering;
- o compiler sabe exatamente onde injetar o `asset_id` porque a própria assinatura `declare host` carrega o contrato;
- o lowering ocorre antes da forma final host/syscall, sem exigir placeholder artificial no corpo do `service`.
Outro limite arquitetural precisa ficar explícito:
- `asset` não é a superfície correta para endereçamento de recursos internos;
- o `asset` entra como unidade de instalação/publicação/carregamento;
- o acesso a internos só faz sentido depois que o conteúdo foi instalado em um `bank` de runtime;
- portanto, members internos pertencem à superfície do `bank` e não à superfície do `asset`.
Isso impede uma confusão comum:
- `assets.foo.bar` parece sugerir que `bar` é membro estável do asset em si;
- mas, neste modelo, `bar` só deve existir como símbolo depois que um `bank` específico expõe esse espaço de endereçamento.
Como diferentes bancos têm semânticas distintas (`tile bank`, `sound bank`, e futuros bancos), o endereçamento de internos é family-specific e provavelmente pertence a uma spec transversal de runtime/banks, não à política básica de asset references.
Tambem surge uma separação importante entre pipeline de compile e runtime packer:
- o frontend PBS não deveria consultar o packer diretamente para descobrir a superfície de assets;
- o backend deve expor ao frontend uma `FESurfaceContext` mínima, derivada da autoridade operacional já existente no packer;
- essa `FESurfaceContext` não é o `PackerRuntimeSnapshot` nem transfere ownership da resolução para o frontend;
- o frontend usa a superfície para semântica e tooling locais, enquanto o backend continua responsável por validar o valor concreto e realizar o lowering final;
- essa mesma porta abre precedente para outras estruturas futuras entrarem no frontend por um contrato estável de surface, sem acoplá-lo diretamente a serviços externos.
For the current agenda scope, the initial `FESurfaceContext` asset payload is intentionally small:
- `List<Addressable>`
- `address`
- `asset_id`
No richer asset payload is required yet for this policy discussion.
For PBS specifically, the frontend-facing fake/public type may also be named `Addressable`, as a homonymous language surface over the backend-owned `FESurfaceContext` payload.
Outro recorte importante:
- preload já existe e não é o objeto principal desta agenda;
- ele pode ser citado como contexto de integração;
- mas a discussão aqui não é “como preload funciona”;
- a discussão é “como asset references em PBS/SDK se resolvem até o ponto em que o caminho low-level já opera com `asset_id`”.
## Open Questions
- [ ] Quais outras estruturas além de assets podem, no futuro, seguir esse mesmo padrão de `FESurfaceContext` BE -> FE?
## Options
### Option A - Keep Surface Simple, Keep Runtime Rules Visible
- **Approach:** manter `asset_name` como referência de longo prazo e exigir consumo explícito de retornos quando houver valor materializado.
- **Pro:** modelo simples e pouco invasivo.
- **Con:** vaza custo operacional e detalhe de lowering para código-fonte; mantém fragilidade de rename e lookup tardio.
- **Maintainability:** baixa a média, porque o autor continua negociando diretamente com limites do backend/runtime.
### Option B - Preserve Surface Ergonomics, Normalize in the Compiler
- **Approach:** manter superfície amigável (`asset_name`, `foo();`) e explicitar no compiler as normalizações necessárias, como lowering para identidade estável quando possível e descarte automático de resultados ignorados em `expression statement`.
- **Pro:** separa melhor autoria de protocolo executável; fica alinhado com a direção já adotada na família `19`.
- **Con:** aumenta responsabilidade do compiler e exige regras claras de quando a normalização pode ou não ocorrer.
- **Maintainability:** alta, porque o contrato passa a ficar onde ele deveria estar: no compiler e nas specs de lowering.
### Option C - Introduce Rich Resource and Effect Surfaces
- **Approach:** criar abstrações mais fortes para recursos e resultados descartáveis, com novos tipos/superfícies na linguagem.
- **Pro:** potencialmente o modelo mais explícito e expressivo no longo prazo.
- **Con:** escopo bem maior; mistura redesign de linguagem com problemas que talvez possam ser resolvidos por lowering.
- **Maintainability:** incerta no curto prazo; só compensa se PBS quiser investir em abstrações novas, não apenas fechar lacunas atuais.
## Discussion
As duas agendas legadas apontam para a mesma direção recomendada:
- preservar ergonomia de autoria;
- e mover o peso de normalização para o compiler.
Isso não significa “magia implícita sem limite”.
Significa assumir, de forma normativa, que a superfície PBS pode ser mais estável e legível do que o protocolo executável final.
O ponto central desta discussão é definir o limite dessa política:
- quando PBS só normaliza lowering,
- e quando precisa criar uma abstração nova de linguagem.
Com o contexto atual do packer, a pergunta fica mais precisa:
- a autoria PBS deve continuar apontando para identificadores “humanos” sem owner operacional claro;
- ou deve consumir uma superfície simbólica derivada do snapshot coerente que o packer já mantém para o projeto?
Se a segunda direção for adotada, o enum sintético de assets não é só ergonomia de editor.
Ele passa a ser a projeção tipada, em domínio PBS, de uma autoridade operacional já existente no packer.
Isso desloca a discussão de “nome versus `asset_id`” para uma formulação melhor:
- qual é a superfície simbólica correta para o jogo autorar;
- quem é owner dessa superfície;
- e como essa superfície é lowered para a identidade estável final.
Também desloca uma segunda discussão para fora do escopo imediato:
- a agenda atual pode fechar como o jogo referencia o `asset` enquanto unidade instalável/publicável;
- mas não deve colapsar isso com o addressing dos internos expostos por `banks`.
O modelo mais correto parece ser:
1. o jogo referencia um asset por uma superfície simbólica derivada da autoridade operacional do packer;
2. esse asset é instalado/publicado em um `bank` de runtime;
3. somente o `bank` passa a expor o espaço de endereçamento de recursos internos;
4. esse espaço de endereçamento é específico da família do banco e merece contrato próprio.
Ao mesmo tempo, a discussão de root references passa a ter três frentes explícitas:
1. `Studio`
- como o asset é exibido e selecionado na UI;
- se o address derivado do root substitui o `asset_name` como identidade visível;
- como impedir criação/move que faça um path atuar ao mesmo tempo como asset terminal e namespace;
2. `packer`
- como o snapshot operacional publica o address normatizado;
- se `asset.json` deixa de carregar `asset_name` como dado relevante;
- como moves/renames impactam o address e a invalidade de referências;
3. `compiler/pbs`
- como a projeção de assets entra no compile;
- como o frontend PBS consome essa projeção sem consultar o packer diretamente;
- como o lowering converte `assets.foo.bar` para identidade estável de runtime;
- em que ponto da superfície SDK/PBS a ponte `address -> asset_id` realmente acontece.
No momento, a direção técnica mais forte para essa ponte é:
- `Addressable` permanece como a surface simbólica de autoria do PBS;
- a `FESurfaceContext` mínima de assets carrega uma `List<Addressable>`, cujas entradas são compostas por `address` e `asset_id`;
- o frontend PBS usa um tipo fake homônimo `Addressable` para consumir essa surface de forma editorial e tipada;
- `declare host` asset-backed recebe metadata reservada como `[AssetLowering(param = N)]`;
- o backend continua validando o valor concreto e resolve esse parâmetro durante o lowering da chamada host-backed;
- `declare service` público permanece apenas como wrapper ergonômico sobre esse contrato.
Additional convergence already accepted in this discussion:
1. the v1 `FESurfaceContext` asset shape is limited to `List<Addressable(address, asset_id)>`;
2. ignored call results in `expression statement` follow a general lowering rule in v1 and SHOULD also emit a warning in the first version;
3. asset-facing references should be resolved at compile time whenever possible; no runtime-dynamic exception is currently required for this policy;
4. future editorial refinement may tune warning policy severity or suppression rules, but the baseline v1 direction already includes an `ignored values` warning.
## Resolution
Accepted on 2026-03-27.
This agenda now resolves into two sibling decisions:
1. `DEC-0005` for PBS asset address surface, `FESurfaceContext`, and backend-owned `Addressable` lowering.
2. `DEC-0006` for ignored values general lowering and warning policy.
What is now locked:
1. PBS asset-facing authoring is symbolic and based on `Addressable`.
2. The backend exposes a minimal `FESurfaceContext` with `List<Addressable(address, asset_id)>`.
3. The backend remains owner of final validation and lowering to runtime-facing `asset_id`.
4. Ignored values in `expression statement` follow a general lowering rule and emit a warning in v1.
Direção recomendada por enquanto:
1. tratar os dois temas como uma única discussão de política de surface-versus-lowering em PBS;
2. preferir a direção **Option B** como baseline;
3. tratar a política de asset references como discussão entre três camadas explícitas:
- `PackerRuntimeSnapshot` como autoridade operacional do conjunto de assets;
- superfície simbólica sintetizada para consumo em PBS;
- lowering compiler-owned para identidade estável de runtime;
4. explorar explicitamente a remoção de `asset_name` como variável operacional em favor do address derivado do root relativo em `assets/`;
5. tratar como requisito arquitetural que a projeção de assets chegue ao frontend PBS pelo backend/orquestração do compile, não por consulta direta do frontend ao packer;
6. tratar como questão central da agenda o ponto exato em que a superfície PBS/SDK converte `address` em `asset_id`;
7. fechar depois duas decisões derivadas:
- política de asset references para código de jogo, agora incluindo owner, forma do address canônico e contrato de entrada BE -> FE da projeção de assets;
- política de descarte de retorno ignorado em `expression statement`;
8. registrar explicitamente que addressing de recursos internos instalados em `banks` não pertence ao contrato básico de `asset references` e deve seguir discussão/spec própria, provavelmente em superfície transversal de runtime/banks;
9. evitar introduzir nova abstração de linguagem antes de esgotar a via de normalização no compiler e a via de superfície simbólica derivada da autoridade operacional já existente no packer.
### Current preferred technical shape
Sem fechar ainda a decision final, a forma técnica hoje preferida nesta agenda é:
1. `declare host` asset-backed carrega `[AssetLowering(param = ...)]`;
2. o parâmetro marcado usa `Addressable` como surface autoral;
3. `declare service` público chama normalmente esse host wrapper;
4. o compiler resolve `address -> asset_id` ao baixar a chamada host-backed;
5. o runtime final continua vendo apenas o contrato operacional por `asset_id`.
Related shape for the synthetic asset surface:
1. `assets` is a hierarchical compile-time tree, not a flat enum;
2. intermediate nodes are namespaces only;
3. terminal asset leaves are typed as `Addressable`;
4. compile-time projection currently needs only `address` and `asset_id`;
5. Studio/runtime-tooling must reject terminal/namespace path collisions;
6. Studio should not allow creating or moving assets in ways that would make the same path act as both terminal asset and namespace prefix.
Example:
```pbs
declare host low_assets {
[Host(module = "assets", name = "preload", version = 1)]
[AssetLowering(param = 0)]
fn preload(addressable: Addressable, bank_id: int) -> LoadError;
}
declare service Assets {
fn load(addressable: Addressable, bank: BankRef) -> LoadError {
return low_assets.preload(addressable, bank.id());
}
}
```
In this example:
- the author-facing API remains `Assets.load(addressable, bank)`;
- `low_assets.preload(...)` is the host-backed contract surface;
- `[AssetLowering(param = 0)]` tells the compiler that parameter `0` must be resolved from symbolic `Addressable` to operational `asset_id`;
- the service body remains ordinary PBS code;
- the special behavior lives in reserved lowering metadata on the `declare host` signature.

View File

@ -1,147 +0,0 @@
---
id: DEC-0005
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: PBS Asset Address Surface and Backend-Lowered Addressable Resolution
status: accepted
created: 2026-03-27
accepted: 2026-03-27
agenda: AGD-0006
plans: [PLN-0005, PLN-0006]
tags: [compiler, pbs, ergonomics, lowering, runtime, asset-identity, asset-surface, be-fe-contract]
---
## Context
PBS precisava fechar a superfície author-facing de referência a assets depois que `DSC-0008` fixou a base low-level em `LowAssets` e no contrato runtime `asset_id + slot`.
O ponto restante já não era o ABI low-level.
O ponto restante era como a autoria em PBS referencia assets de forma ergonômica sem reintroduzir lookup tardio por `asset_name`, sem acoplar o frontend diretamente ao packer, e sem mover para o frontend a ownership do lowering final.
O estado aceito desta discussão também reconhece que:
- o packer continua sendo a autoridade operacional do conjunto de assets;
- o backend do compiler expõe ao frontend apenas uma surface derivada, não o `PackerRuntimeSnapshot` bruto;
- o backend permanece owner da validação final do valor concreto e do lowering `address -> asset_id`.
## Decision
PBS SHALL adotar uma superfície author-facing baseada em `Addressable` e em addresses canônicos derivados do path relativo do asset root dentro de `assets/`.
O shape canônico da autoria PBS SHALL seguir uma árvore hierárquica:
- `assets` como namespace raiz;
- namespaces intermediários para prefixos estruturais;
- folhas terminais representando assets reais como valores `Addressable`.
O address simbólico SHALL ser derivado do path relativo do asset root e SHALL substituir `asset_name` como identidade operacional de referência para compile-time asset lookup.
O compiler backend SHALL expor ao frontend uma `FESurfaceContext` derivada da surface operacional do backend.
Para v1, essa `FESurfaceContext` SHALL carregar apenas:
- `List<Addressable>`
em que cada entrada `Addressable` contém:
- `address`
- `asset_id`
O frontend PBS MAY usar um tipo fake/public homônimo `Addressable` como surface editorial e de semântica local.
Esse tipo frontend-owned MUST NOT transferir ao frontend a responsabilidade de validação final ou de lowering operacional.
O backend SHALL continuar responsável por:
- validar o valor concreto referenciado no programa;
- resolver `address -> asset_id`;
- realizar o lowering final para o contrato low-level já fixado em `LowAssets`.
PBS asset-facing APIs SHOULD permanecer simbólicas na surface pública.
Quando uma chamada exigir lowering asset-aware, o contrato host-backed SHALL carregar metadata reservada de lowering, e o backend SHALL usar essa metadata para reescrever a chamada para a forma operacional em `asset_id`.
PBS MUST NOT consultar o packer diretamente a partir do frontend para descobrir assets visíveis.
PBS MUST NOT tratar `asset` como superfície de addressing de membros internos carregados em runtime.
O contrato de members expostos por `bank` SHALL permanecer separado da política de asset references.
Asset-facing references SHOULD be resolved at compile time whenever possible.
For the current policy, no runtime-dynamic exception is required.
## Rationale
Essa decisão preserva três fronteiras importantes ao mesmo tempo:
1. ergonomia de autoria no source;
2. autoridade operacional no backend;
3. lowering final alinhado ao runtime já consolidado.
Ela evita o pior dos dois extremos:
- um frontend cego que não consegue oferecer semântica/tooling razoáveis;
- ou um frontend acoplado ao packer e responsável por decisões que pertencem ao backend.
O uso de `Addressable` como nome em ambos os lados é aceitável porque:
- no backend, ele representa a entrada da `FESurfaceContext`;
- no PBS, ele representa a surface editorial/fake type consumida pelo frontend.
O nome é homônimo, mas a ownership continua explícita:
- a surface chega do backend;
- a validação final e o lowering permanecem no backend.
## Technical Specification
### 1. Canonical Authoring Surface
- PBS SHALL treat `assets` as a compile-time hierarchical namespace root.
- A terminal asset root SHALL map to a terminal `Addressable` leaf.
- Intermediate namespace nodes MUST NOT be treated as terminal assets.
- A terminal asset path MUST NOT also act as a namespace prefix for descendant assets.
### 2. Canonical Address Identity
- The canonical symbolic identity SHALL be the normalized address derived from the asset root path under `assets/`.
- `asset_name` MUST NOT remain the operational compile-time identity for asset lookup.
- Rename or move operations MAY change the canonical address and thereby invalidate compile-time references.
### 3. Backend-To-Frontend Surface Contract
- The backend SHALL expose a `FESurfaceContext` to the frontend.
- The v1 asset slice of that context SHALL be `List<Addressable(address, asset_id)>`.
- The frontend MAY use this surface for parsing-adjacent semantics, typing, diagnostics, and tooling.
- The frontend MUST NOT be treated as the canonical resolver of operational asset identity.
### 4. Lowering Ownership
- Asset-aware lowering metadata SHALL be carried on the host-backed declaration surface.
- The backend SHALL validate the referenced `Addressable` value against the backend-owned surface.
- The backend SHALL lower the symbolic asset reference to the runtime-facing `asset_id`.
- The resulting low-level call SHALL target the `LowAssets` contract already fixed by `DEC-0004`.
### 5. Scope Boundary
This decision covers:
- symbolic asset references in PBS source;
- the minimal backend-to-frontend surface contract for assets;
- backend ownership of final validation and lowering.
This decision does NOT cover:
- bank-internal member addressing;
- richer future `FESurfaceContext` structures beyond assets;
- suppression or editorial warning policy for rename fragility;
- the low-level `LowAssets` ABI itself, already fixed elsewhere.
## Constraints
- The frontend MUST NOT query packer services directly for asset discovery.
- The backend MUST NOT expose the raw `PackerRuntimeSnapshot` as the frontend contract.
- The backend-to-frontend contract MUST remain small and explicitly extensible.
- The source-level `Addressable` surface MUST preserve the backend as owner of executable semantics.
- Any future richer asset APIs MUST still lower into backend-resolved `asset_id` before the final `LowAssets` host call.
## Revision Log
- 2026-03-27: Initial accepted decision from AGD-0006.
- 2026-03-27: Locked `FESurfaceContext` v1 asset shape to `List<Addressable(address, asset_id)>`.
- 2026-03-27: Locked backend ownership of final `Addressable` validation and lowering.

View File

@ -1,88 +0,0 @@
---
id: DEC-0006
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: PBS Ignored Values Lowering and Warning Policy
status: accepted
created: 2026-03-27
accepted: 2026-03-27
agenda: AGD-0006
plans: [PLN-0007]
tags: [compiler, pbs, ergonomics, lowering, diagnostics, expression-statements, warnings]
---
## Context
PBS ainda precisava fixar o comportamento de `expression statements` cujo valor produzido não é consumido.
Sem essa decisão, a disciplina de stack do backend continua vazando para a surface do autor:
- alguns callsites com retorno materializado ficam semanticamente ambíguos;
- a política de descarte pode ficar implícita demais ou inconsistente entre passes;
- o usuário não recebe feedback claro quando ignora um valor que a linguagem materializou.
Essa discussão não exige uma exceção por API específica.
Ela exige uma regra geral de linguagem com lowering e diagnóstico previsíveis.
## Decision
PBS SHALL adotar uma regra geral para ignored values em `expression statement`.
Quando uma expressão usada como statement produzir um valor materializado que não seja consumido, o compiler SHALL:
1. lowerar explicitamente o descarte desse valor;
2. emitir um warning na v1.
Essa política SHALL ser geral, e não uma exceção localizada para certos callsites ou certas superfícies de API.
O warning inicial SHALL existir como baseline diagnóstica da linguagem.
Refinamentos futuros de severidade, suppressions ou subcategorias MAY acontecer depois, mas não bloqueiam esta decisão.
## Rationale
Essa regra resolve a tensão principal da agenda:
- a autoria continua simples, porque o usuário pode escrever uma expressão como statement;
- o protocolo executável continua explícito, porque o compiler assume o descarte;
- a linguagem continua honesta, porque o usuário recebe um warning quando ignora um valor material.
Isso é superior a duas alternativas piores:
- exigir consumo explícito de todo valor sempre, empurrando ruído operacional para o source;
- ou descartar silenciosamente tudo, removendo feedback útil em situações potencialmente equivocadas.
## Technical Specification
### 1. General Rule
- Any PBS `expression statement` that produces a materialized value and does not consume it SHALL trigger ignored-value handling.
- Ignored-value handling SHALL consist of:
- explicit lowering for value discard;
- a warning diagnostic.
### 2. Scope
- The rule SHALL apply generally across expression statements.
- The rule MUST NOT be restricted to asset-facing APIs, host-backed calls, or any single subsystem.
- The rule MAY apply equally to pure or impure expressions if the language surface materializes a value that is then ignored.
### 3. Lowering Ownership
- The compiler backend SHALL remain responsible for the executable lowering that discards the value.
- Frontend diagnostics MAY identify the situation earlier if architecture permits, but the normative executable behavior remains compiler-owned.
### 4. Diagnostic Policy
- The baseline v1 diagnostic level SHALL be warning.
- Future work MAY define suppression mechanisms, lint categories, escalation rules, or context-sensitive exemptions.
- No such refinement is required to consider this decision accepted.
## Constraints
- PBS MUST keep the rule general and easy to explain.
- PBS MUST NOT depend on backend stack discipline leaking into source-level author decisions.
- PBS MUST NOT require API-by-API bespoke ignored-value semantics as the baseline language policy.
## Revision Log
- 2026-03-27: Initial accepted decision from AGD-0006.
- 2026-03-27: Locked ignored values as a general lowering rule with warning severity in v1.

View File

@ -1,152 +0,0 @@
---
id: PLN-0005
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: Propagate DEC-0005 Asset Address Surface into Compiler, Packer, and Studio Specs
status: done
created: 2026-03-27
completed: 2026-03-27
tags: [compiler, pbs, packer, studio, specs, addressable, asset-identity, be-fe-contract]
---
## Objective
Propagate `DEC-0005` into the normative documentation so PBS asset authoring, backend-owned `FESurfaceContext`, and the separation between `asset` and `bank` become explicit, cross-domain, and implementation-ready.
## Background
`DEC-0005` locks the symbolic authoring surface for assets around:
- hierarchical `assets...` addressing;
- `Addressable` as the public/editorial PBS type shape;
- `FESurfaceContext` as a backend-owned contract delivered to the frontend;
- `List<Addressable(address, asset_id)>` as the v1 asset slice;
- backend-owned validation and lowering from symbolic address to runtime-facing `asset_id`;
- explicit separation between asset references and bank-internal addressing.
The repository already documents:
- packer ownership of `asset_id`;
- Studio ownership of asset workspace UX;
- PBS low-level runtime asset access through `LowAssets`.
What is still missing is the normative bridge between these surfaces.
## Scope
### Included
- Update PBS language specs to define the symbolic asset address model and the backend-to-frontend contract.
- Update packer specs to state how the operational snapshot projects canonical asset addresses without turning `asset_name` into a first-class operational identity.
- Update Studio specs to state that UI-facing asset identity aligns with the canonical address surface and namespace collision rules.
- Add or update compiler-level specs so backend-owned asset lowering and `FESurfaceContext` ownership are normatively visible.
### Excluded
- Implementing parser, semantic, lowering, or diagnostics code.
- Designing bank-internal member addressing.
- Defining richer future `FESurfaceContext` slices beyond assets.
- Introducing rename-fragility warnings or LSP-only UX refinements.
## Execution Steps
### Step 1 - Update PBS Normative Surface Documents
**What:**
Document the symbolic PBS surface for asset references and the `Addressable` model.
**How:**
Revise the PBS specs so they state:
- `assets` is a compile-time namespace root;
- leaves correspond to terminal `Addressable` values;
- the canonical symbolic identity is the normalized asset-root-derived address;
- `asset_name` is not the operational compile-time identity;
- the PBS frontend may use a fake/editorial `Addressable` type while the backend remains the owner of executable semantics.
**File(s):**
- `docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md`
- `docs/specs/compiler-languages/pbs/5. Manifest, Stdlib, and SDK Resolution Specification.md`
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
### Step 2 - Update Backend Contract and Lowering Specs
**What:**
Make the backend-owned `FESurfaceContext` and asset-lowering ownership explicit in compiler-wide specs.
**How:**
Add or revise sections that state:
- the frontend receives a minimal backend-derived surface, not the raw packer snapshot;
- v1 assets arrive as `List<Addressable(address, asset_id)>`;
- backend validation and final lowering ownership remain backend-only;
- symbolic asset references lower into the already-accepted `LowAssets` contract before runtime execution.
**File(s):**
- `docs/specs/compiler/18. Standard Library Surface Specification.md`
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
- optional conformance/matrix sync if needed: `docs/specs/compiler/22. Backend Spec-to-Test Conformance Matrix.md`
### Step 3 - Update Packer And Studio Domain Specs
**What:**
Align packer and Studio domain specs with the symbolic address model and namespace rules.
**How:**
Revise the specs so they state:
- packer remains owner of operational asset identity and derives canonical addresses from asset roots;
- `asset_name` is not required as an operational registry field;
- Studio should expose canonical address identity in UX where appropriate;
- Studio must prevent terminal-vs-namespace collisions on asset root creation and moves.
**File(s):**
- `docs/specs/packer/2. Workspace, Registry, and Asset Identity Specification.md`
- `docs/specs/packer/5. Diagnostics, Operations, and Studio Integration Specification.md`
- `docs/specs/studio/4. Assets Workspace Specification.md`
### Step 4 - Cross-Check Decision Boundaries
**What:**
Verify that the edited specs preserve the intended scope split between `DEC-0004`, `DEC-0005`, and bank-specific addressing.
**How:**
Check that:
- `DEC-0004` still owns only the low-level `LowAssets` ABI;
- `DEC-0005` owns the symbolic authoring and backend-owned surface contract;
- no updated document accidentally defines bank-internal member addressing or future richer `FESurfaceContext` slices.
**File(s):**
- `discussion/workflow/decisions/DEC-0004-pbs-low-level-asset-manager-surface.md` if restored for reference, otherwise use `discussion/lessons/DSC-0008-pbs-low-level-asset-manager-surface/LSN-0023-lowassets-runtime-aligned-sdk-surface.md`
- `discussion/workflow/decisions/DEC-0005-pbs-asset-address-surface-and-be-lowering.md`
## Test Requirements
### Unit Tests
- None required for the editorial plan itself.
### Integration Tests
- None required for the editorial plan itself.
### Manual Verification
- Read updated specs together and verify the same terminology is used for `Addressable`, canonical address, `asset_id`, and `FESurfaceContext`.
- Verify no document reintroduces `asset_name` as the normative compile-time identity.
- Verify no document collapses `asset` references with bank-internal addressing.
## Acceptance Criteria
- [ ] PBS specs describe hierarchical asset addressing and `Addressable` as the symbolic authoring surface.
- [ ] Compiler specs state that the backend exposes a minimal `FESurfaceContext` and retains final validation/lowering ownership.
- [ ] Packer specs state that canonical asset addresses are derived operationally without promoting `asset_name` back to first-class identity.
- [ ] Studio specs state the namespace-collision rule for asset root creation and moves.
- [ ] Updated docs preserve the scope boundary between low-level `LowAssets` ABI and symbolic asset references.
## Dependencies
- `DEC-0005-pbs-asset-address-surface-and-be-lowering`
- Existing `DEC-0004` low-level `LowAssets` contract
## Risks
- Cross-domain wording may drift if compiler, packer, and Studio specs are updated independently.
- Over-documenting future `FESurfaceContext` expansion now would make the contract harder to keep stable.
- It is easy to accidentally reintroduce `asset_name` as an editorial convenience unless the operational/authoring distinction stays explicit.

View File

@ -1,184 +0,0 @@
---
id: PLN-0006
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: Implement DEC-0005 Addressable Surface, FESurfaceContext, and Backend Asset Lowering
status: done
created: 2026-03-27
completed: 2026-03-27
tags: [compiler, pbs, implementation, addressable, lowering, be-fe-contract, asset-identity]
---
## Objective
Implement the executable and semantic infrastructure required by `DEC-0005` so PBS can consume a backend-owned asset surface, type symbolic asset references as `Addressable`, and lower them to runtime-facing `asset_id` before the final `LowAssets` call path.
## Background
`DEC-0005` locks:
- `assets...` as the symbolic compile-time surface;
- `Addressable` as the PBS editorial/public type shape;
- `FESurfaceContext` as a backend-owned contract delivered to the frontend;
- `List<Addressable(address, asset_id)>` as the v1 asset payload;
- backend-owned validation and final lowering to `asset_id`.
The repository already has:
- `LowAssets` in stdlib and tests;
- `FrontendPhaseContext` as the frontend request surface;
- `PBSFrontendPhaseService` as the main orchestration point for PBS frontend compilation;
- executable lowering infrastructure that can already carry host-binding metadata.
What is missing is the symbolic asset surface and the backend-owned path from frontend-visible `Addressable` to low-level `asset_id`.
## Scope
### Included
- Extend frontend API models to carry a minimal asset `FESurfaceContext`.
- Thread the new surface through PBS frontend compilation entrypoints.
- Introduce or adapt PBS semantic handling for `Addressable` and asset namespace resolution.
- Add backend-owned validation and lowering hooks for asset-aware callsites.
- Add or update tests for compile surface ingestion, semantic acceptance, and lowering behavior.
### Excluded
- Designing richer future `FESurfaceContext` slices beyond assets.
- Implementing bank-internal member addressing.
- Designing rename/move tooling or LSP UX beyond what is needed for compile surface wiring.
- Changing the already accepted low-level `LowAssets` ABI.
## Execution Steps
### Step 1 - Add Frontend API Surface Models For Assets
**What:**
Introduce the minimal backend-to-frontend asset surface contract.
**How:**
Add new API models so the frontend request context can carry:
- a `FESurfaceContext`;
- an asset slice represented as `List<Addressable>`;
- `Addressable(address, asset_id)` entries.
Keep the contract intentionally small and backend-owned.
Avoid leaking raw packer snapshot structures into the frontend API.
**File(s):**
- `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/FrontendPhaseContext.java`
- new companion model files under `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/messages/`
- tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/`
### Step 2 - Thread FESurfaceContext Through PBS Frontend Orchestration
**What:**
Make `PBSFrontendPhaseService` and related assembly services consume the backend-provided asset surface.
**How:**
Propagate the new context data through the PBS frontend pipeline so semantic and lowering phases can read the v1 asset list without querying packer services directly.
Keep ownership clear: the frontend consumes the surface, but the backend still owns final validation and lowering.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PBSFrontendPhaseService.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsModuleAssemblyService.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/services/PbsImportedSemanticContextService.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PBSFrontendPhaseServiceTest.java`
### Step 3 - Implement PBS Symbolic Addressable Semantics
**What:**
Teach PBS semantics and binding layers how to recognize the symbolic asset surface and treat terminal asset leaves as `Addressable`.
**How:**
Add semantic support for:
- hierarchical `assets...` namespace resolution;
- terminal asset leaves typed as `Addressable`;
- rejection of unresolved or structurally invalid asset references;
- preventing intermediate namespace nodes from being treated as terminal addressable values.
Do not move operational validation ownership out of the backend; semantic handling should remain a frontend-facing interpretation of backend-provided surface data.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsNamespaceBinder.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowExpressionAnalyzer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStructuralExpressionAnalyzer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java`
- parser/AST files only if the current source form requires parser changes
- tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/`
### Step 4 - Add Backend-Owned Asset Lowering Hooks
**What:**
Implement final backend validation and lowering from symbolic `Addressable` references to runtime-facing `asset_id`.
**How:**
Extend lowering metadata and executable lowering so asset-aware callsites can:
- identify which argument is asset-facing;
- validate that the referenced value maps to a backend-owned `Addressable`;
- lower the symbolic reference to the numeric `asset_id`;
- continue into the already-existing `LowAssets` low-level host path.
Keep this logic backend-owned rather than embedding operational resolution inside frontend-only semantics or service wrapper bodies.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableCallsiteEmitter.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableMetadataIndexFactory.java`
- tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/`
### Step 5 - Add Conformance And Regression Coverage
**What:**
Pin the new contract with tests that cover both frontend surface consumption and backend lowering behavior.
**How:**
Add tests that prove:
- `FESurfaceContext` asset data is visible to the PBS frontend;
- symbolic asset references resolve only when present in the backend-provided list;
- invalid namespace collisions or unresolved terminal references are rejected deterministically;
- valid asset-facing callsites lower to the same low-level `asset_id` path expected by `LowAssets`.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PBSFrontendPhaseServiceTest.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsFrontendCompilerTest.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUStdlibCompileTest.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsGateUSdkInterfaceConformanceTest.java`
## Test Requirements
### Unit Tests
- Semantics tests for `Addressable` terminals, intermediate namespace rejection, and unresolved symbolic asset references.
- Metadata/lowering tests for asset-aware callsites and `asset_id` substitution.
### Integration Tests
- `PBSFrontendPhaseService` tests that compile a project with a supplied `FESurfaceContext`.
- End-to-end frontend compilation tests that import the low-level `@sdk:asset` surface and confirm the final lowering path stays aligned with `LowAssets`.
### Manual Verification
- Inspect the new frontend API types and verify they expose only `List<Addressable(address, asset_id)>` for v1.
- Verify no frontend code path queries packer services directly.
- Re-run targeted PBS frontend test suites after implementation.
## Acceptance Criteria
- [ ] `FrontendPhaseContext` or equivalent frontend API entrypoints can carry a backend-owned asset `FESurfaceContext`.
- [ ] PBS can interpret terminal symbolic asset references as `Addressable` values using backend-provided surface data.
- [ ] Backend lowering validates symbolic asset references and resolves them to runtime-facing `asset_id`.
- [ ] Valid asset-facing calls still lower into the `LowAssets` contract from `DEC-0004`.
- [ ] Missing or structurally invalid symbolic asset references fail deterministically with stable diagnostics.
## Dependencies
- `DEC-0005-pbs-asset-address-surface-and-be-lowering`
- Existing `DEC-0004` low-level asset surface
- Existing frontend request and lowering infrastructure in `prometeu-compiler`
## Risks
- The current frontend API may need more structural changes than expected to pass backend-owned surface data cleanly.
- If `Addressable` is introduced inconsistently across semantics and lowering, the frontend may accept states the backend cannot lower.
- Mixing frontend convenience with backend ownership could accidentally reintroduce direct packer coupling unless boundaries are enforced carefully.

View File

@ -1,151 +0,0 @@
---
id: PLN-0007
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: Implement DEC-0006 Ignored Values Lowering and Warning
status: done
created: 2026-03-27
completed: 2026-03-27
tags: [compiler, pbs, implementation, diagnostics, lowering, expression-statements, warnings]
---
## Objective
Implement `DEC-0006` so ignored materialized values in PBS `expression statement` positions are always explicitly discarded during lowering and also emit a warning in v1.
## Background
`DEC-0006` locks a general language rule:
- `expression statement` forms that produce a materialized value must not silently leak backend stack discipline into source semantics;
- the compiler must lower explicit discard behavior;
- the compiler must also emit a warning in v1.
The current lowering path already lowers expression statements as plain expression evaluation.
The existing executable stack analyzer already understands `POP`, but expression-statement lowering does not yet make discard behavior explicit.
## Scope
### Included
- Update PBS specs and diagnostics docs for ignored-value behavior.
- Add a warning diagnostic contract for ignored materialized values.
- Implement explicit discard lowering for expression statements that leave a materialized value.
- Add frontend and lowering tests covering both the warning and the discard behavior.
### Excluded
- Suppression syntax, lint categories, or configurable severity policy.
- API-specific special cases for ignored values.
- Non-PBS frontend work.
## Execution Steps
### Step 1 - Propagate The Rule Into PBS Specs
**What:**
Make the ignored-values rule explicit in PBS normative docs.
**How:**
Update the specs so they state:
- `expression statement` may produce a value;
- if that value is materialized and not consumed, the compiler must lower an explicit discard;
- the v1 diagnostic policy is warning.
**File(s):**
- `docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md`
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
- optional compiler-wide sync if needed: `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
### Step 2 - Add A Stable Warning Diagnostic Contract
**What:**
Define the PBS diagnostic identity for ignored values.
**How:**
Add a stable warning code and wire it through the diagnostics contract so tests can assert identity, phase, severity, and attribution.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsDiagnosticsContractTest.java`
- semantics tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/`
### Step 3 - Emit Ignored-Value Warnings During Semantics
**What:**
Detect ignored materialized values at the statement-analysis boundary and emit the new warning.
**How:**
Use the existing flow/statement analyzers to identify expression statements whose resulting type is materialized rather than unit-like, and emit the warning without blocking lowering.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowBodyAnalyzer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowStatementAnalyzer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsFlowExpressionAnalyzer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/PbsSemanticsOptionalResultTest.java`
- new focused test file if needed for ignored-value warnings
### Step 4 - Lower Explicit Discard Operations
**What:**
Make expression-statement lowering explicitly discard ignored values rather than implicitly leaving them to backend behavior.
**How:**
Update executable lowering so expression statements that produce materialized values emit the appropriate discard instruction sequence, then verify stack accounting remains correct.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableStackAnalyzer.java`
- lowering tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/`
### Step 5 - Add Regression And Contract Coverage
**What:**
Pin both the warning and the executable discard behavior with tests.
**How:**
Add tests that cover:
- pure expression statements returning a value;
- call expressions returning a value that is ignored;
- unit-returning expression statements that must not warn;
- executable lowering shape and stack behavior after explicit discard insertion.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/semantics/`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsFrontendCompilerTest.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PBSFrontendPhaseServiceTest.java`
## Test Requirements
### Unit Tests
- Semantics tests for warning emission on ignored non-unit values.
- Negative tests ensuring unit-valued expression statements do not warn.
- Lowering tests verifying discard instruction emission and stack balance.
### Integration Tests
- End-to-end frontend compilation tests showing warning emission without turning the program into an error.
- Targeted pipeline tests proving explicit discard lowering survives later executable lowering phases.
### Manual Verification
- Inspect diagnostics and confirm ignored-value reports are warnings, not errors.
- Inspect lowered instruction streams for representative ignored-value cases and confirm explicit discard behavior.
- Re-run targeted PBS frontend and lowering test suites.
## Acceptance Criteria
- [ ] PBS emits a stable warning diagnostic for ignored materialized values in expression statements.
- [ ] Unit-like expression statements do not emit the ignored-value warning.
- [ ] Executable lowering emits explicit discard behavior for ignored materialized values.
- [ ] Stack analysis remains valid after the discard instruction path is added.
- [ ] The rule applies generally and is not limited to one API family.
## Dependencies
- `DEC-0006-pbs-ignored-values-lowering-and-warning`
- Existing PBS flow semantics and executable lowering infrastructure
## Risks
- The current semantics/lowering split may make it easy to warn in one place but forget to lower explicit discard in another.
- If the implementation does not distinguish unit-like from materialized values carefully, it may over-warn or under-warn.
- Later severity/suppression refinements may require reshaping the diagnostics API, so the first version should keep the contract minimal and stable.

View File

@ -1,196 +0,0 @@
---
id: PLN-0008
ticket: pbs-game-facing-asset-refs-and-call-result-discard
title: Implement Mandatory AssetLowering Host Metadata and Backend Callsite Rewrite
status: done
created: 2026-03-27
completed: 2026-03-27
tags: [compiler, pbs, implementation, assetlowering, host-metadata, backend-lowering, correction]
---
## Objective
Complete the missing normative part of `DEC-0005` by implementing mandatory host-backed `AssetLowering` metadata and using it to rewrite `Addressable` arguments into runtime-facing `asset_id` at backend callsite lowering time.
## Background
`DEC-0005` did not only require:
- `FESurfaceContext = List<Addressable(address, asset_id)>`,
- symbolic `assets...` semantics,
- and backend ownership of final validation.
It also normatively locked a second requirement:
- asset-aware lowering metadata must live on the host-backed declaration surface;
- the backend must use that metadata to identify which host parameter is asset-facing;
- and host-backed lowering must rewrite the `Addressable` argument to operational `asset_id` before the final `LowAssets` path.
`PLN-0006` implemented the symbolic surface and direct symbolic-to-`asset_id` expression lowering, but it did not implement:
- reserved attribute `[AssetLowering(param = N)]`,
- reserved-metadata propagation for host bindings,
- host-signature validation for asset-lowered parameters,
- or host-callsite rewriting driven by parameter metadata.
This plan exists to correct that gap without reinterpreting `DEC-0005`.
## Scope
### Included
- Add `AssetLowering(param = N)` as a PBS reserved attribute on host-backed signatures.
- Validate the attribute shape and its admissible target surface.
- Extend backend host-binding metadata to carry asset-lowering parameter information.
- Rewrite host call lowering so asset-facing parameters consume symbolic `Addressable` values and lower them to `asset_id` according to host metadata.
- Align tests and specs so the normative path is explicit and covered.
- Correct any now-misleading tests or implementation shortcuts introduced by `PLN-0006`.
### Excluded
- Redesign of `DEC-0005`.
- Changes to the `LowAssets` ABI already fixed by `DEC-0004`.
- Generalization to non-asset metadata families beyond the exact `AssetLowering` rule.
- Runtime-dynamic asset lookup exceptions.
## Execution Steps
### Step 1 - Add Reserved Attribute Surface For AssetLowering
**What:**
Introduce `[AssetLowering(param = N)]` as a normative reserved attribute on host-backed callable surfaces.
**How:**
Extend the PBS reserved attribute extractor and declaration validation so:
- `AssetLowering` is recognized as reserved metadata;
- it is admitted only on supported host-backed callable declarations;
- `param` is mandatory and must be a valid zero-based parameter index;
- the targeted parameter must match the `Addressable` author-facing contract required by `DEC-0005`;
- duplicate or malformed declarations fail deterministically.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsDeclarationSemanticsValidator.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/PbsSemanticsErrors.java`
- tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/`
### Step 2 - Propagate AssetLowering Through Reserved Metadata
**What:**
Make host binding metadata carry the asset-lowering contract instead of relying on implicit expression-level lowering.
**How:**
Extend `IRReservedMetadata.HostMethodBinding` or the equivalent host-binding metadata shape so each binding can expose:
- whether asset lowering is required;
- which parameter index is asset-facing.
Update metadata construction, merging, indexing, and any downstream readers so the information survives all backend-facing frontend phases.
**File(s):**
- `prometeu-compiler/prometeu-frontend-api/src/main/java/p/studio/compiler/models/IRReservedMetadata.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/PbsReservedMetadataExtractor.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringModels.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableMetadataIndexFactory.java`
- metadata conformance tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/`
### Step 3 - Rewrite Host Calls Using AssetLowering Metadata
**What:**
Move final `Addressable -> asset_id` host-argument rewriting into the backend-owned host call path mandated by `DEC-0005`.
**How:**
Update executable lowering so:
- host callsites inspect `AssetLowering(param = N)` metadata from the resolved host binding;
- the backend validates that the selected argument is a terminal backend-known `Addressable`;
- the selected argument is lowered to operational `asset_id`;
- non-asset-facing arguments are lowered normally;
- the final emitted host call matches the already accepted `LowAssets` runtime path.
This step must remove reliance on the current shortcut where symbolic asset references are lowered generically without host-parameter ownership.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableBodyLowerer.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableCallsiteEmitter.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/PbsExecutableLoweringContext.java`
- related lowering metadata/index files
- targeted lowering tests under `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/`
### Step 4 - Realign Symbolic Expression Lowering With The Host-Metadata Contract
**What:**
Correct the partial implementation from `PLN-0006` so symbolic asset expressions support the normative host-metadata path instead of bypassing it.
**How:**
Review the current direct lowering of `assets...` expressions and keep only the behavior that remains valid under `DEC-0005`.
At minimum:
- standalone symbolic `Addressable` semantics must remain correct;
- host-backed `AssetLowering` callsites must no longer depend on an implicit generic shortcut;
- tests that previously “passed” through direct expression lowering must be updated to assert the host-metadata path explicitly.
If any `PLN-0006` behavior contradicts `DEC-0005`, correct the code and the tests rather than preserving the shortcut.
**File(s):**
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/semantics/`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/main/java/p/studio/compiler/pbs/lowering/`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/pbs/PbsFrontendCompilerTest.java`
- `prometeu-compiler/frontends/prometeu-frontend-pbs/src/test/java/p/studio/compiler/services/PBSFrontendPhaseServiceTest.java`
### Step 5 - Propagate And Pin The Contract In Specs And Tests
**What:**
Ensure the normative wording and regression coverage now match the corrected implementation.
**How:**
Update specs and tests so they explicitly cover:
- `AssetLowering(param = N)` as mandatory host-backed metadata for asset-aware lowering;
- the backend-owned rewrite from symbolic `Addressable` to operational `asset_id`;
- rejection of malformed attribute usage and invalid parameter targeting;
- a representative `LowAssets`-aligned host call path using the metadata-bearing surface.
**File(s):**
- `docs/specs/compiler-languages/pbs/4. Static Semantics Specification.md`
- `docs/specs/compiler-languages/pbs/12. Diagnostics Specification.md`
- `docs/specs/compiler-languages/pbs/13. Lowering IRBackend Specification.md`
- `docs/specs/compiler/20. IRBackend to IRVM Lowering Specification.md`
- targeted PBS frontend/compiler tests
## Test Requirements
### Unit Tests
- Reserved-attribute tests for valid and invalid `AssetLowering(param = N)` usage.
- Metadata tests proving host bindings preserve the asset-lowering parameter index.
- Negative tests for duplicate, malformed, or out-of-range `AssetLowering` declarations.
### Integration Tests
- End-to-end PBS frontend compilation tests where a host-backed asset API uses `Addressable` plus `[AssetLowering(param = N)]`.
- Lowering tests proving the backend rewrites the marked argument to `asset_id` before the final host call.
- Regression tests proving `LowAssets`-aligned callsites still lower correctly after removing the shortcut path.
### Manual Verification
- Inspect extracted reserved metadata and verify `AssetLowering` is carried on the host binding.
- Inspect lowered instruction streams for an asset-aware host call and verify the asset-facing argument becomes `asset_id`.
- Confirm malformed host metadata fails with deterministic source-facing diagnostics.
## Acceptance Criteria
- [ ] PBS supports `[AssetLowering(param = N)]` as a validated reserved attribute on the correct host-backed surface.
- [ ] Host binding metadata preserves the asset-lowering parameter contract through backend lowering preparation.
- [ ] Backend host-call lowering uses the metadata to rewrite the selected `Addressable` argument into runtime-facing `asset_id`.
- [ ] The final asset-aware host path remains aligned with `LowAssets` and no longer depends on a generic shortcut that bypasses host metadata.
- [ ] Tests and specs explicitly cover the normative `AssetLowering` path from `DEC-0005`.
## Dependencies
- `DEC-0005-pbs-asset-address-surface-and-be-lowering`
- `DEC-0004` low-level `LowAssets` contract
- existing `PLN-0006` implementation as the correction baseline
## Risks
- The current direct symbolic lowering path may overlap with the normative host-metadata path and require careful removal or restriction.
- Extending host metadata may require synchronized updates across multiple compiler layers, increasing the chance of partial propagation if done carelessly.
- If tests keep asserting the shortcut path instead of the normative path, the repository may regress into the same discrepancy again.